proxy.ts
This file
Path
src/proxy.ts
252 lines · 6.9 KiB · TypeScript
Last changed by
fix: #502Michel Weststratebefore adoption8d4f723
History of this fileTake it
feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 1why, one step back1"use strict"fix: #502Michel Weststratebefore adoption8d4f723
line 2why, one step back2import {each, has, is, isDraftable, shallowCopy, latest} from "./common"feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 3why, one step back3import {ImmerScope} from "./scope"feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 4–12why, one step back4import {5 AnyObject,6 Drafted,7 ImmerState,8 AnyArray,9 Objectish,10 ImmerBaseState,11 ProxyType12} from "./types"fix: #502Michel Weststratebefore adoption8d4f723
line 13why, one step back13import {DRAFT_STATE} from "./env"feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 14why, one step back14feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 15–24why, one step back15interface ProxyBaseState extends ImmerBaseState {16 assigned: {17 [property: string]: boolean18 }19 parent?: ImmerState20 drafts?: {21 [property: string]: Drafted<any, any>22 }23 revoke(): void24}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 25why, one step back25feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 26–31why, one step back26export interface ProxyObjectState extends ProxyBaseState {27 type: ProxyType.ProxyObject28 base: AnyObject29 copy: AnyObject | null30 draft: Drafted<AnyObject, ProxyObjectState>31}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 32why, one step back32feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 33–37why, one step back33export interface ProxyArrayState extends ProxyBaseState {34 type: ProxyType.ProxyArray35 base: AnyArray36 copy: AnyArray | null37 draft: Drafted<AnyArray, ProxyArrayState>feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 38–39why, one step back38}39feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 40–41why, one step back40type ProxyState = ProxyObjectState | ProxyArrayState41feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 42–46why, one step back42/**43 * Returns a new draft of the `base` object.44 *45 * The second argument is the parent draft-state (used internally).46 */feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 47why, one step back47export function createProxy<T extends Objectish>(feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 48why, one step back48 base: T,feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 49–53why, one step back49 parent?: ImmerState50): Drafted<T, ProxyState> {51 const isArray = Array.isArray(base)52 const state: ProxyState = {53 type: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 54why, one step back54 // Track which produce call this is associated with.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 55why, one step back55 scope: parent ? parent.scope : ImmerScope.current!,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 56–66why, one step back56 // True for both shallow and deep changes.57 modified: false,58 // Used during finalization.59 finalized: false,60 // Track which properties have been assigned (true) or deleted (false).61 assigned: {},62 // The parent draft state.63 parent,64 // The base state.65 base,66 // The base proxy.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 67why, one step back67 draft: null as any, // set belowfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 68–72why, one step back68 // Any property proxies.69 drafts: {},70 // The base copy with any updated values.71 copy: null,72 // Called by the `produce` function.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 73–74why, one step back73 revoke: null as any,74 isManual: falsefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 75–84why, one step back75 }7677 // the traps must target something, a bit like the 'real' base.78 // but also, we need to be able to determine from the target what the relevant state is79 // (to avoid creating traps per instance to capture the state in closure,80 // and to avoid creating weird hidden properties as well)81 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)82 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb83 let target: T = state as any84 let traps: ProxyHandler<object | Array<any>> = objectTrapsfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 85why, one step back85 if (isArray) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 86–89why, one step back86 target = [state] as any87 traps = arrayTraps88 }89feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 90–91why, one step back90 // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy91 // and administrate revoking ourselvesfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 92why, one step back92 const {revoke, proxy} = Proxy.revocable(target, traps)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 93why, one step back93 state.draft = proxy as anyfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 94why, one step back94 state.revoke = revokefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 95why, one step back95 return proxy as anyfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 96–100why, one step back96}9798/**99 * Object drafts100 */feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 101why, one step back101const objectTraps: ProxyHandler<ProxyState> = {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 102–107why, one step back102 get(state, prop) {103 if (prop === DRAFT_STATE) return state104 let {drafts} = state105106 // Check for existing draft in unmodified state.107 if (!state.modified && has(drafts, prop)) {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 108why, one step back108 return drafts![prop as any]feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 109–120why, one step back109 }110111 const value = latest(state)[prop]112 if (state.finalized || !isDraftable(value)) {113 return value114 }115116 // Check for existing draft in modified state.117 if (state.modified) {118 // Assigned values are never drafted. This catches any drafts we created, too.119 if (value !== peek(state.base, prop)) return value120 // Store drafts on the copy (when one exists).feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 121why, one step back121 // @ts-ignorefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 122–124why, one step back122 drafts = state.copy123 }124feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 125why, one step back125 return (drafts![prop as any] = state.scope.immer.createProxy(value, state))feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 126–132why, one step back126 },127 has(state, prop) {128 return prop in latest(state)129 },130 ownKeys(state) {131 return Reflect.ownKeys(latest(state))132 },feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 133why, one step back133 set(state, prop: string /* strictly not, but helps TS */, value) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 134–139why, one step back134 if (!state.modified) {135 const baseValue = peek(state.base, prop)136 // Optimize based on value's truthiness. Truthy values are guaranteed to137 // never be undefined, so we can avoid the `in` operator. Lastly, truthy138 // values may be drafts, but falsy values are never drafts.139 const isUnchanged = valuefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 140why, one step back140 ? is(baseValue, value) || value === state.drafts![prop]feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 141–142why, one step back141 : is(baseValue, value) && prop in state.base142 if (isUnchanged) return truefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 143why, one step back143 prepareCopy(state)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 144–146why, one step back144 markChanged(state)145 }146 state.assigned[prop] = truefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 147–148why, one step back147 // @ts-ignore148 state.copy![prop] = valuefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 149–150why, one step back149 return true150 },feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 151why, one step back151 deleteProperty(state, prop: string) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 152–154why, one step back152 // The `undefined` check is a fast path for pre-existing keys.153 if (peek(state.base, prop) !== undefined || prop in state.base) {154 state.assigned[prop] = falsefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 155why, one step back155 prepareCopy(state)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 156–160why, one step back156 markChanged(state)157 } else if (state.assigned[prop]) {158 // if an originally not assigned property was deleted159 delete state.assigned[prop]160 }feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 161why, one step back161 // @ts-ignorefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 162–171why, one step back162 if (state.copy) delete state.copy[prop]163 return true164 },165 // Note: We never coerce `desc.value` into an Immer draft, because we can't make166 // the same guarantee in ES5 mode.167 getOwnPropertyDescriptor(state, prop) {168 const owner = latest(state)169 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)170 if (desc) {171 desc.writable = truefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 172–173why, one step back172 desc.configurable =173 state.type !== ProxyType.ProxyArray || prop !== "length"feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 174–191why, one step back174 }175 return desc176 },177 defineProperty() {178 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore179 },180 getPrototypeOf(state) {181 return Object.getPrototypeOf(state.base)182 },183 setPrototypeOf() {184 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore185 }186}187188/**189 * Array drafts190 */191feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 192why, one step back192const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 193why, one step back193each(objectTraps, (key, fn) => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 194why, one step back194 // @ts-ignorefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 195–217why, one step back195 arrayTraps[key] = function() {196 arguments[0] = arguments[0][0]197 return fn.apply(this, arguments)198 }199})200arrayTraps.deleteProperty = function(state, prop) {201 if (isNaN(parseInt(prop as any))) {202 throw new Error("Immer only supports deleting array indices") // prettier-ignore203 }204 return objectTraps.deleteProperty!.call(this, state[0], prop)205}206arrayTraps.set = function(state, prop, value) {207 if (prop !== "length" && isNaN(parseInt(prop as any))) {208 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore209 }210 return objectTraps.set!.call(this, state[0], prop, value, state[0])211}212213/**214 * Map drafts215 */216217// Access a property without creating an Immer draft.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 218why, one step back218function peek(draft: Drafted, prop: PropertyKey): any {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 219–226why, one step back219 const state = draft[DRAFT_STATE]220 const desc = Reflect.getOwnPropertyDescriptor(221 state ? latest(state) : draft,222 prop223 )224 return desc && desc.value225}226feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 227why, one step back227export function markChanged(state: ImmerState) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 228–229why, one step back228 if (!state.modified) {229 state.modified = truefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 230–239why, one step back230 if (231 state.type === ProxyType.ProxyObject ||232 state.type === ProxyType.ProxyArray233 ) {234 const copy = (state.copy = shallowCopy(state.base))235 each(state.drafts!, (key, value) => {236 // @ts-ignore237 copy[key] = value238 })239 state.drafts = undefinedfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 240–241why, one step back240 }241feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 242–243why, one step back242 if (state.parent) {243 markChanged(state.parent)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 244–247why, one step back244 }245 }246}247feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 248–250why, one step back248function prepareCopy(state: ProxyState) {249 if (!state.copy) {250 state.copy = shallowCopy(state.base)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 251–252why, one step back251 }252}