Skip to content
Myr

feat: support async recipes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Drafts won't be revoked until the returned promise is fulfilled or rejected.

authored by aleclarson · committed by aleclarson · parent 271cd1b · Browse files · 5 files+182 added−92 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+182 added−92 removed

  • tests:+31 added−1 removed
  • other:+151 added−91 removed

5 files+182 added−92 removed

modified:__tests__/base.js+31 added-1 removed
813 unmodified lines
814 })815 expect(next.obj).toBe(next.arr[0])816 })817818 it("can return an object with two references to any pristine draft", () => {818 it("can return an object with two references to an unmodified draft", () => {819 const base = {a: {}}820 const next = produce(base, d => {821 return [d.a, d.a]822 })
9 unmodified lines
832 }).toThrow("Immer forbids circular references")833 })834 })835836 describe("async recipe function", () => {837 it("can modify the draft", async () => {838 const base = {a: 0, b: 0}839 const res = await produce(base, async d => {840 d.a = 1841 await Promise.resolve()842 d.b = 1843 })844 expect(res).not.toBe(base)845 expect(res).toEqual({a: 1, b: 1})846 })847848 it("works with rejected promises", async () => {849 let draft850 const base = {a: 0, b: 0}851 const err = new Error("passed")852 try {853 await produce(base, async d => {854 draft = d855 draft.b = 1856 await Promise.reject(err)857 })858 throw "failed"859 } catch (e) {860 expect(e).toBe(err)861 expect(() => draft.a).toThrowError(/revoked/)862 }863 })864 })865866 it("throws when the draft is modified and another object is returned", () => {867 const base = {x: 3}868 expect(() => {869 produce(base, draft => {
312 unmodified lines
modified:src/es5.js+17 added-18 removed
1"use strict"2// @ts-check32import {3 each,4 has,5 is,
2 unmodified lines
8 isEnumerable,9 shallowCopy,10 DRAFT_STATE11} from "./common"12import {ImmerScope} from "./scope"1314const descriptors = {}1517// For nested produce calls:18export const scopes = []19export const currentScope = () => scopes[scopes.length - 1]2021export function willFinalize(result, baseDraft, needPatches) {22 const scope = currentScope()23 scope.forEach(state => (state.finalizing = true))24 if (result === undefined || result === baseDraft) {25 if (needPatches) markChangesRecursively(baseDraft)16export function willFinalize(scope, result, isReplaced) {17 scope.drafts.forEach(draft => {18 draft[DRAFT_STATE].finalizing = true19 })20 if (!isReplaced) {21 if (scope.patches) {22 markChangesRecursively(scope.drafts[0])23 }24 // This is faster when we don't care about which attributes changed.27 markChangesSweep(scope)25 markChangesSweep(scope.drafts)26 }27}2829export function createDraft(base, parent) {
3 unmodified lines
33 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))34 })3536 // See "proxy.js" for property documentation.37 const scope = parent ? parent.scope : ImmerScope.current38 const state = {40 scope: parent ? parent.scope : currentScope(),39 scope,40 modified: false,41 finalizing: false, // es5 only42 finalized: false,43 assigned: {},
5 unmodified lines
49 revoked: false // es5 only50 }5152 createHiddenProperty(draft, DRAFT_STATE, state)54 state.scope.push(state)53 scope.drafts.push(draft)54 return draft55}5657function revoke() {
75 unmodified lines
133 )134}135136// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.138function markChangesSweep(scope) {137function markChangesSweep(drafts) {138 // The natural order of drafts in the `scope` array is based on when they139 // were accessed. By processing drafts in reverse natural order, we have a140 // better chance of processing leaf nodes first. When a leaf node is known to141 // have changed, we can avoid any traversal of its ancestor nodes.143 for (let i = scope.length - 1; i >= 0; i--) {144 const state = scope[i]145 if (state.modified === false) {142 for (let i = drafts.length - 1; i >= 0; i--) {143 const state = drafts[i][DRAFT_STATE]144 if (!state.modified) {145 if (Array.isArray(state.base)) {146 if (hasArrayChanges(state)) markChanged(state)147 } else if (hasObjectChanges(state)) markChanged(state)148 }
85 unmodified lines
modified:src/immer.js+92 added-65 removed
11 unmodified lines
12 shallowCopy,13 DRAFT_STATE,14 NOTHING15} from "./common"16import {ImmerScope} from "./scope"1718function verifyMinified() {}1920const configDefaults = {
30 unmodified lines
51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }5354 let result54 // Only create proxies for plain objects/arrays.55 if (!isDraftable(base)) {56 result = recipe(base)57 if (result === undefined) return base58 }59 // The given value must be proxied.60 else {61 this.scopes.push([])5556 // Only plain objects, arrays, and "immerable classes" are drafted.57 if (isDraftable(base)) {58 const scope = ImmerScope.enter()59 const baseDraft = this.createDraft(base)60 try {61 result = recipe.call(baseDraft, baseDraft)65 this.willFinalize(result, baseDraft, !!patchListener)6667 // Never generate patches when no listener exists.68 var patches = patchListener && [],69 inversePatches = patchListener && []7071 // Finalize the modified draft...72 if (result === undefined || result === baseDraft) {73 result = this.finalize(74 baseDraft,75 [],76 patches,77 inversePatches78 )79 }80 // ...or use a replacement value.81 else {82 // Users must never modify the draft _and_ return something else.83 if (baseDraft[DRAFT_STATE].modified)84 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore8586 // Finalize the replacement in case it contains (or is) a subset of the draft.87 if (isDraftable(result)) result = this.finalize(result)8889 if (patchListener) {90 patches.push({91 op: "replace",92 path: [],93 value: result94 })95 inversePatches.push({96 op: "replace",97 path: [],98 value: base99 })62 } catch (error) {63 scope.revoke()64 throw error65 }66 scope.leave()67 if (result instanceof Promise) {68 return result.then(69 result => {70 scope.usePatches(patchListener)71 return this.processResult(result, scope)72 },73 error => {74 scope.revoke()75 throw error76 }101 }102 } finally {103 this.currentScope().forEach(state => state.revoke())104 this.scopes.pop()77 )78 }106 patchListener && patchListener(patches, inversePatches)79 scope.usePatches(patchListener)80 return this.processResult(result, scope)81 } else {82 result = recipe(base)83 if (result === undefined) return base84 return result !== NOTHING ? result : undefined85 }108 // Normalize the result.109 return result === NOTHING ? undefined : result86 }87 setAutoFreeze(value) {88 this.autoFreeze = value89 }
8 unmodified lines
98 }99 // Otherwise, produce a copy of the base state.100 return this.produce(base, draft => applyPatches(draft, patches))101 }102 /** @internal */103 processResult(result, scope) {104 const baseDraft = scope.drafts[0]105 const isReplaced = result !== undefined && result !== baseDraft106 this.willFinalize(scope, result, isReplaced)107 if (isReplaced) {108 if (baseDraft[DRAFT_STATE].modified) {109 scope.revoke()110 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore111 }112 if (isDraftable(result)) {113 // Finalize the result in case it contains (or is) a subset of the draft.114 result = this.finalize(result, null, scope)115 }116 if (scope.patches) {117 scope.patches.push({118 op: "replace",119 path: [],120 value: result121 })122 scope.inversePatches.push({123 op: "replace",124 path: [],125 value: baseDraft[DRAFT_STATE].base126 })127 }128 } else {129 // Finalize the base draft.130 result = this.finalize(baseDraft, [], scope)131 }132 scope.revoke()133 if (scope.patches) {134 scope.patchListener(scope.patches, scope.inversePatches)135 }136 return result !== NOTHING ? result : undefined137 }138 /**139 * @internal140 * Finalize a draft, returning either the unmodified base state or a modified141 * copy of the base state.142 */131 finalize(draft, path, patches, inversePatches) {143 finalize(draft, path, scope) {144 const state = draft[DRAFT_STATE]145 if (!state) {146 if (Object.isFrozen(draft)) return draft135 return this.finalizeTree(draft)147 return this.finalizeTree(draft, null, scope)148 }137 // Never finalize drafts owned by an outer scope.138 if (state.scope !== this.currentScope()) {149 // Never finalize drafts owned by another scope.150 if (state.scope !== scope) {151 return draft152 }141 if (!state.modified) return state.base153 if (!state.modified) {154 return state.base155 }156 if (!state.finalized) {157 state.finalized = true144 this.finalizeTree(state.draft, path, patches, inversePatches)158 this.finalizeTree(state.draft, path, scope)159160 if (this.onDelete) {161 // The `assigned` object is unreliable with ES5 drafts.162 if (this.useProxies) {163 const {assigned} = state
6 unmodified lines
170 if (!has(copy, prop)) this.onDelete(state, prop)171 })172 }173 }159 if (this.onCopy) this.onCopy(state)174 if (this.onCopy) {175 this.onCopy(state)176 }177178 // Nested producers must never auto-freeze their result,179 // because it may contain drafts from parent producers.163 if (this.autoFreeze && this.scopes.length === 1) {180 if (this.autoFreeze && !scope.parent) {181 Object.freeze(state.copy)182 }183167 if (patches) generatePatches(state, path, patches, inversePatches)184 if (path && scope.patches) {185 generatePatches(186 state,187 path,188 scope.patches,189 scope.inversePatches190 )191 }192 }193 return state.copy194 }195 /**196 * @internal197 * Finalize all drafts in the given state tree.198 */175 finalizeTree(root, path, patches, inversePatches) {199 finalizeTree(root, path, scope) {200 const state = root[DRAFT_STATE]201 if (state) {202 if (!this.useProxies) {203 state.finalizing = true
12 unmodified lines
216 // The only possible draft (in the scope of a `finalizeTree` call) is the `root` object.217 const inDraft = !!state && parent === root218219 if (isDraft(value)) {196 value =197 // Patches are never generated for assigned properties.198 patches && inDraft && !state.assigned[prop]199 ? this.finalize(value, path.concat(prop), patches, inversePatches) // prettier-ignore200 : this.finalize(value)220 const needPatches =221 inDraft && path && scope.patches && !state.assigned[prop]222223 value = this.finalize(224 value,225 needPatches ? path.concat(prop) : null,226 scope227 )228229 // Preserve non-enumerable properties.230 if (Array.isArray(parent) || isEnumerable(parent, prop)) {231 parent[prop] = value232 } else {
24 unmodified lines
modified:src/proxy.js+4 added-8 removed
added:src/scope.js+38 added