Skip to content
Myr

finalize.ts

This file

Path

src/core/finalize.ts

318 lines · 8.3 KiB · TypeScript

Last changed by

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 1–12why, one step back
1import {
2 ImmerScope,3 DRAFT_STATE,4 isDraftable,5 NOTHING,6 PatchPath,7 each,8 freeze,9 ImmerState,10 isDraft,11 SetState,12 set,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 13why, one step back
13 ArchType,

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 14–16why, one step back
14 getPlugin,
15 die,16 revokeScope,

Fix: freezing of Map values during finalization (#1150)Chetan Satputebefore adoptionb4f71a6

line 17why, one step back
17 isFrozen,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 18–22why, one step back
18 get,
19 Patch,20 latest,21 prepareCopy,22 getFinalValue,

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 23–24why, one step back
23 getValue,
24 ProxyArrayState

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 25–30why, one step back
25} from "../internal"
2627export function processResult(result: any, scope: ImmerScope) {28 scope.unfinalizedDrafts_ = scope.drafts_.length29 const baseDraft = scope.drafts_![0]30 const isReplaced = result !== undefined && result !== baseDraft

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 31why, one step back
31

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 32–40why, one step back
32 if (isReplaced) {
33 if (baseDraft[DRAFT_STATE].modified_) {34 revokeScope(scope)35 die(4)36 }37 if (isDraftable(result)) {38 // Finalize the result in case it contains (or is) a subset of the draft.39 result = finalize(scope, result)40 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 41–43why, one step back
41 const {patchPlugin_} = scope
42 if (patchPlugin_) {43 patchPlugin_.generateReplacementPatches_(

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 44–45why, one step back
44 baseDraft[DRAFT_STATE].base_,
45 result,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 46why, one step back
46 scope

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 47–50why, one step back
47 )
48 }49 } else {50 // Finalize the base draft.

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 51why, one step back
51 result = finalize(scope, baseDraft)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 52why, one step back
52 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 53–55why, one step back
53
54 maybeFreeze(scope, result, true)55

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 56–62why, one step back
56 revokeScope(scope)
57 if (scope.patches_) {58 scope.patchListener_!(scope.patches_, scope.inversePatches_!)59 }60 return result !== NOTHING ? result : undefined61}62

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 63why, one step back
63function finalize(rootScope: ImmerScope, value: any) {

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 64–68why, one step back
64 // Don't recurse in tho recursive data structures
65 if (isFrozen(value)) return value6667 const state: ImmerState = value[DRAFT_STATE]68 if (!state) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 69–74why, one step back
69 const finalValue = handleValue(value, rootScope.handledSet_, rootScope)
70 return finalValue71 }7273 // Never finalize drafts owned by another scope74 if (!isSameScope(state, rootScope)) {

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 75–76why, one step back
75 return value
76 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 77why, one step back
77

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 78–81why, one step back
78 // Unmodified draft, return the (frozen) original
79 if (!state.modified_) {80 return state.base_81 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 82why, one step back
82

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 83why, one step back
83 if (!state.finalized_) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 84–90why, one step back
84 // Execute all registered draft finalization callbacks
85 const {callbacks_} = state86 if (callbacks_) {87 while (callbacks_.length > 0) {88 const callback = callbacks_.pop()!89 callback(rootScope)90 }

fix: Preserve insertion order of Sets, fixes #819 (#976)jdipbefore adoptionb3eeb69

line 91why, one step back
91 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 92–93why, one step back
92
93 generatePatchesAndFinalize(state, rootScope)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 94why, one step back
94 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 95–96why, one step back
95
96 // By now the root copy has been fully updated throughout its tree

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 97–99why, one step back
97 return state.copy_
98}99

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 100–103why, one step back
100function maybeFreeze(scope: ImmerScope, value: any, deep = false) {
101 // we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects102 if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {103 freeze(value, deep)

feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce

line 104why, one step back
104 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 105why, one step back
105}

feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce

line 106why, one step back
106

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 107–136why, one step back
107function markStateFinalized(state: ImmerState) {
108 state.finalized_ = true109 state.scope_.unfinalizedDrafts_--110}111112let isSameScope = (state: ImmerState, rootScope: ImmerScope) =>113 state.scope_ === rootScope114115// A reusable empty array to avoid allocations116const EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []117118// Updates all references to a draft in its parent to the finalized value.119// This handles cases where the same draft appears multiple times in the parent, or has been moved around.120export function updateDraftInParent(121 parent: ImmerState,122 draftValue: any,123 finalizedValue: any,124 originalKey?: string | number | symbol125): void {126 const parentCopy = latest(parent)127 const parentType = parent.type_128129 // Fast path: Check if draft is still at original key130 if (originalKey !== undefined) {131 const currentValue = get(parentCopy, originalKey, parentType)132 if (currentValue === draftValue) {133 // Still at original location, just update it134 set(parentCopy, originalKey, finalizedValue, parentType)135 return136 }

feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce

line 137why, one step back
137 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 138–153why, one step back
138
139 // Slow path: Build reverse mapping of all children140 // to their indices in the parent, so that we can141 // replace all locations where this draft appears.142 // We only have to build this once per parent.143 if (!parent.draftLocations_) {144 const draftLocations = (parent.draftLocations_ = new Map())145146 // Use `each` which works on Arrays, Maps, and Objects147 each(parentCopy, (key, value) => {148 if (isDraft(value)) {149 const keys = draftLocations.get(value) || []150 keys.push(key)151 draftLocations.set(value, keys)152 }153 })

feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce

lines 154–155why, one step back
154 }
155

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 156–162why, one step back
156 // Look up all locations where this draft appears
157 const locations =158 parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT159160 // Update all locations161 for (const location of locations) {162 set(parentCopy, location, finalizedValue, parentType)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 163why, one step back
163 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 164–178why, one step back
164}
165166// Register a callback to finalize a child draft when the parent draft is finalized.167// This assumes there is a parent -> child relationship between the two drafts,168// and we have a key to locate the child in the parent.169export function registerChildFinalizationCallback(170 parent: ImmerState,171 child: ImmerState,172 key: string | number | symbol173) {174 parent.callbacks_.push(function childCleanup(rootScope) {175 const state: ImmerState = child176177 // Can only continue if this is a draft owned by this scope178 if (!state || !isSameScope(state, rootScope)) {

feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce

lines 179–180why, one step back
179 return
180 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 181–197why, one step back
181
182 // Handle potential set value finalization first183 rootScope.mapSetPlugin_?.fixSetContents(state)184185 const finalizedValue = getFinalValue(state)186187 // Update all locations in the parent that referenced this draft188 updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)189190 generatePatchesAndFinalize(state, rootScope)191 })192}193194function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {195 const shouldFinalize =196 state.modified_ &&197 !state.finalized_ &&

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 198–201why, one step back
198 (state.type_ === ArchType.Set ||
199 (state.type_ === ArchType.Array &&200 (state as ProxyArrayState).allIndicesReassigned_) ||201 (state.assigned_?.size ?? 0) > 0)

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 202–210why, one step back
202
203 if (shouldFinalize) {204 const {patchPlugin_} = rootScope205 if (patchPlugin_) {206 const basePath = patchPlugin_!.getPath(state)207208 if (basePath) {209 patchPlugin_!.generatePatches_(state, basePath, rootScope)210 }

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 211why, one step back
211 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 212–213why, one step back
212
213 markStateFinalized(state)

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 214–216why, one step back
214 }
215}216

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 217–242why, one step back
217export function handleCrossReference(
218 target: ImmerState,219 key: string | number | symbol,220 value: any221) {222 const {scope_} = target223 // Check if value is a draft from this scope224 if (isDraft(value)) {225 const state: ImmerState = value[DRAFT_STATE]226 if (isSameScope(state, scope_)) {227 // Register callback to update this location when the draft finalizes228229 state.callbacks_.push(function crossReferenceCleanup() {230 // Update the target location with finalized value231 prepareCopy(target)232233 const finalizedValue = getFinalValue(state)234235 updateDraftInParent(target, value, finalizedValue, key)236 })237 }238 } else if (isDraftable(value)) {239 // Handle non-draft objects that might contain drafts240 target.callbacks_.push(function nestedDraftCleanup() {241 const targetCopy = latest(target)242

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

lines 243–265why, one step back
243 // For Sets, check if value is still in the set
244 if (target.type_ === ArchType.Set) {245 if (targetCopy.has(value)) {246 // Process the value to replace any nested drafts247 handleValue(value, scope_.handledSet_, scope_)248 }249 } else {250 // Maps/objects251 if (get(targetCopy, key, target.type_) === value) {252 if (253 scope_.drafts_.length > 1 &&254 ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??255 false) === true &&256 target.copy_257 ) {258 // This might be a non-draft value that has drafts259 // inside. We do need to recurse here to handle those.260 handleValue(261 get(target.copy_, key, target.type_),262 scope_.handledSet_,263 scope_264 )265 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 266–268why, one step back
266 }
267 }268 })

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 269why, one step back
269 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 270–317why, one step back
270}
271272export function handleValue(273 target: any,274 handledSet: Set<any>,275 rootScope: ImmerScope276) {277 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {278 // optimization: if an object is not a draft, and we don't have to279 // deepfreeze everything, and we are sure that no drafts are left in the remaining object280 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.281 // This benefits especially adding large data tree's without further processing.282 // See add-data.js perf test283 return target284 }285286 // Skip if already handled, frozen, or not draftable287 if (288 isDraft(target) ||289 handledSet.has(target) ||290 !isDraftable(target) ||291 isFrozen(target)292 ) {293 return target294 }295296 handledSet.add(target)297298 // Process ALL properties/entries299 each(target, (key, value) => {300 if (isDraft(value)) {301 const state: ImmerState = value[DRAFT_STATE]302 if (isSameScope(state, rootScope)) {303 // Replace draft with finalized value304305 const updatedValue = getFinalValue(state)306307 set(target, key, updatedValue, target.type_)308309 markStateFinalized(state)310 }311 } else if (isDraftable(value)) {312 // Recursively handle nested values313 handleValue(value, handledSet, rootScope)314 }315 })316317 return target

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 318why, one step back
318}