TS type improvements
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent aeba1ff · Browse files · 11 files·+224 added−213 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+224 added−213 removed
- other:+224 added−213 removed
Provenance
- Commit
dd1808e- Tree
02b6979- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
aeba1ff
11 files changed+224 added−213 removed
modified:src/common.ts+57 added-9 removed
57 unmodified lines58 isSet(value)59 )60 }61 62-export function isPlainObject(value): value is AnyObject | AnyArray {62+export function isPlainObject(value: any): boolean {63 if (!value || typeof value !== "object") return false64 if (Array.isArray(value)) return true65 const proto = Object.getPrototypeOf(value)66 return !proto || proto === Object.prototype6 unmodified lines73 }74 // otherwise return undefined75 }76 77-export const ownKeys: (target) => PropertyKey[] =77+export const ownKeys: (target: AnyObject) => PropertyKey[] =78 typeof Reflect !== "undefined" && Reflect.ownKeys79 ? Reflect.ownKeys80 : typeof Object.getOwnPropertySymbols !== "undefined"81 ? obj =>4 unmodified lines86 87 export function each<T extends Objectish>(88 obj: T,89 iter: (key: string | number, value: any, source: T) => void90-)91-export function each(obj, iter) {90+): void91+export function each(obj: any, iter: any) {92 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {93- obj.forEach((entry, index) => iter(index, entry, obj))93+ obj.forEach((entry: any, index: any) => iter(index, entry, obj))94 } else if (obj && typeof obj === "object") {95 ownKeys(obj).forEach(key => iter(key, obj[key], obj))96 } else {97- throw new Error("Nope")97+ die()98 }99 }100 101 export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {102 const desc = Object.getOwnPropertyDescriptor(base, prop)103 return desc && desc.enumerable ? true : false104 }105 106+// TODO: use draft meta data if present?107+// make refelction methods to determine types?108 export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {109 return !thing110 ? false111 : isMap(thing)112 ? thing.has(prop)113 : Object.prototype.hasOwnProperty.call(thing, prop)114 }115 116+// TODO: use draft meta data if present?114-export function get(thing: ObjectishNoSet, prop: PropertyKey): any {115- return isMap(thing) ? thing.get(prop) : thing[prop]117+export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {118+ return isMap(thing) ? thing.get(prop) : thing[prop as any]119 }120 121+// TODO: measure fast vs slow path, use type switch instead122+export function set(parent: Drafted, prop: PropertyKey, value: any) {123+ // fast path switch on meta data124+ if (parent[DRAFT_STATE])125+ switch (parent[DRAFT_STATE].type) {126+ case "map":127+ parent.set(prop, value)128+ break129+ case "set":130+ parent.delete(prop)131+ parent.add(value)132+ break133+ default:134+ parent[prop] = value135+ }136+137+ // slow path138+ parent[prop] = value139+ if (isMap(parent)) {140+ parent.set(prop, value)141+ } else if (isSet(parent)) {142+ // In this case, the `prop` is actually a draft.143+ parent.delete(prop)144+ parent.add(value)145+ } else {146+ parent[prop] = value147+ }148+}149+150 export function is(x: any, y: any): boolean {151 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js152 if (x === y) {153 return x !== 0 || 1 / x === 1 / y23 unmodified lines177 export function shallowCopy<T extends AnyObject | AnyArray>(178 base: T,179 invokeGetters?: boolean180 ): T149-export function shallowCopy(base, invokeGetters = false) {181+export function shallowCopy(base: any, invokeGetters = false) {182 if (Array.isArray(base)) return base.slice()183 const clone = Object.create(Object.getPrototypeOf(base))184 ownKeys(base).forEach(key => {185 if (key === DRAFT_STATE) {36 unmodified lines222 223 function dontMutateFrozenCollections() {224 throw new Error("This object has been frozen and should not be mutated")225 }226+227+export function createHiddenProperty(228+ target: AnyObject,229+ prop: PropertyKey,230+ value: any231+) {232+ Object.defineProperty(target, prop, {233+ value: value,234+ enumerable: false,235+ writable: true236+ })237+}238+239+export function die(): never {240+ throw new Error("Illegal state, please file a bug")241+}modified:src/es5.ts+40 added-57 removed
8 unmodified lines9 isMap,10 isSet,11 shallowCopy,12 DRAFT_STATE,13- latest13+ latest,14+ createHiddenProperty15 } from "./common"16 17 import {ImmerScope} from "./scope"17-import {ImmerState, Drafted, AnyObject, AnyMap} from "./types"18+import {ImmerState, Drafted, AnyObject, AnyMap, Objectish} from "./types"19 19-// TODO: merge with ImmerState?20 interface ES5BaseState {21 scope: ImmerScope22 modified: boolean23 finalizing: boolean24 finalized: boolean25 assigned: {[key: string]: any}26 parent?: ImmerState27- drafts: AnyMap | null // TODO: don't use map?28- revoke()27+ revoke(): void28 revoked: boolean29 }30 31 export interface ES5ObjectState extends ES5BaseState {35 unmodified lines67 68 export function createES5Proxy<T>(69 base: T,70 parent?: ImmerState72-): Drafted<any, ES5ObjectState | ES5ArrayState> {71+): Drafted<T, ES5ObjectState | ES5ArrayState> {72 const isArray = Array.isArray(base)73 const draft = clonePotentialDraft(base)74 75 each(draft, prop => {9 unmodified lines85 assigned: {},86 parent,87 base,88 draft,90- drafts: null,89 copy: null,90 revoke,91 revoked: false // es5 only92 }5 unmodified lines98 function revoke(this: ES5BaseState) {99 this.revoked = true100 }101 104-// TODO: type these methods102 // Access a property without creating an Immer draft.106-function peek(draft, prop) {103+function peek(draft: Drafted, prop: PropertyKey) {104 const state = draft[DRAFT_STATE]105 if (state && !state.finalizing) {106 state.finalizing = true107 const value = draft[prop]2 unmodified lines110 }111 return draft[prop]112 }113 117-function get(state, prop) {114+function get(state: ES5State, prop: string | number) {115 assertUnrevoked(state)116 const value = peek(latest(state), prop)117 if (state.finalizing) return value118 // Create a draft if the value is unmodified.119 if (value === peek(state.base, prop) && isDraftable(value)) {120 prepareCopy(state)124- return (state.copy[prop] = state.scope.immer.createProxy(value, state))121+ return (state.copy![prop] = state.scope.immer.createProxy(value, state))122 }123 return value124 }125 129-function set(state: ES5State, prop, value) {126+function set(state: ES5State, prop: string | number, value: any) {127 assertUnrevoked(state)128 state.assigned[prop] = true129 if (!state.modified) {130 if (is(value, peek(latest(state), prop))) return2 unmodified lines133 }134 state.copy![prop] = value135 }136 140-export function markChangedES5(state) {137+export function markChangedES5(state: ImmerState) {138 if (!state.modified) {139 state.modified = true140 if (state.parent) markChangedES5(state.parent)141 }142 }143 147-function prepareCopy(state) {144+function prepareCopy(state: ES5State) {145 if (!state.copy) state.copy = clonePotentialDraft(state.base)146 }147 151-function clonePotentialDraft(base) {152- const state = base && base[DRAFT_STATE]148+function clonePotentialDraft(base: Objectish) {149+ const state = base && (base as any)[DRAFT_STATE]150 if (state) {151 state.finalizing = true152 const draft = shallowCopy(state.draft, true)153 state.finalizing = false3 unmodified lines157 }158 159 // property descriptors are recycled to make sure we don't create a get and set closure per property,160 // but share them all instead164-const descriptors = {}161+const descriptors: {[prop: string]: PropertyDescriptor} = {}162 166-function proxyProperty(draft, prop, enumerable) {163+function proxyProperty(164+ draft: Drafted<any, ES5State>,165+ prop: string | number,166+ enumerable: boolean167+) {168 let desc = descriptors[prop]169 if (desc) {170 desc.enumerable = enumerable171 } else {172 descriptors[prop] = desc = {173 configurable: true,174 enumerable,174- get() {175+ get(this: any) {176 return get(this[DRAFT_STATE], prop)177 },177- set(value) {178+ set(this: any, value) {179 set(this[DRAFT_STATE], prop, value)180 }181 }182 }183 Object.defineProperty(draft, prop, desc)184 }185 185-export function assertUnrevoked(state) {186+export function assertUnrevoked(state: ES5State) {187 if (state.revoked === true)188 throw new Error(189 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +190 JSON.stringify(latest(state))191 )192 }193 194 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.194-function markChangesSweep(drafts) {195+function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {196 // The natural order of drafts in the `scope` array is based on when they197 // were accessed. By processing drafts in reverse natural order, we have a198 // better chance of processing leaf nodes first. When a leaf node is known to199 // have changed, we can avoid any traversal of its ancestor nodes.200 for (let i = drafts.length - 1; i >= 0; i--) {201 const state = drafts[i][DRAFT_STATE]202 if (!state.modified) {202- if (Array.isArray(state.base)) {203- if (hasArrayChanges(state)) markChangedES5(state)204- } else if (isMap(state.base)) {205- // TODO: use switch206- continue207- } else if (isSet(state.base)) {208- continue209- } else if (hasObjectChanges(state)) {210- markChangedES5(state)203+ switch (state.type) {204+ case "es5_array":205+ if (hasArrayChanges(state)) markChangedES5(state)206+ break207+ case "es5_object":208+ if (hasObjectChanges(state)) markChangedES5(state)209+ break210 }211 }212 }213 }214 216-// TODO: refactor this to work per object-type217-// TODO: Set / Map shouldn't be ES specific218-function markChangesRecursively(object) {215+function markChangesRecursively(object: any) {216 if (!object || typeof object !== "object") return217 const state = object[DRAFT_STATE]218 if (!state) return222- const {base, draft, assigned} = state223- if (isSet(object) || isMap(object)) {224- // TODO: create switch here225- return226- } else if (!Array.isArray(object)) {219+ const {base, draft, assigned, type} = state220+ if (type === "es5_object") {221 // Look for added keys.228- // TODO: use each?229- Object.keys(draft).forEach(key => {222+ // TODO: looks quite duplicate to hasObjectChanges223+ each(draft, key => {224+ if ((key as any) === DRAFT_STATE) return225 // The `undefined` check is a fast path for pre-existing keys.226 if (base[key] === undefined && !has(base, key)) {232- // TODO: this code seems invalid for Maps!227 assigned[key] = true228 markChangedES5(state)229 } else if (!assigned[key]) {236- // TODO: === false ?230 // Only untouched properties trigger recursion.231 markChangesRecursively(draft[key])232 }233 })234 // Look for removed keys.242- // TODO: is this code needed?243- // TODO: use each?244- Object.keys(base).forEach(key => {235+ each(base, key => {236 // The `undefined` check is a fast path for pre-existing keys.237 if (draft[key] === undefined && !has(draft, key)) {238 assigned[key] = false239 markChangedES5(state)240 }241 })251- } else if (hasArrayChanges(state)) {242+ } else if (type === "es5_array" && hasArrayChanges(state)) {243 markChangedES5(state)244 assigned.length = true245 if (draft.length < base.length) {246 for (let i = draft.length; i < base.length; i++) assigned[i] = false6 unmodified lines253 }254 }255 }256 266-function hasObjectChanges(state) {257+function hasObjectChanges(state: ES5ObjectState) {258 const {base, draft} = state259 260 // Search for added keys and changed keys. Start at the back, because261 // non-numeric keys are ordered by time of definition on the object.20 unmodified lines282 // Compare key count to determine if keys were deleted.283 return keys.length !== Object.keys(base).length284 }285 295-function hasArrayChanges(state) {286+function hasArrayChanges(state: ES5ArrayState) {287 const {draft} = state288 if (draft.length !== state.base.length) return true289 // See #116290 // If we first shorten the length, our array interceptors will be removed.7 unmodified lines298 if (descriptor && !descriptor.get) return true299 // For all other cases, we don't have to compare, as they would have been picked up by the index setters300 return false301 }311-312-function createHiddenProperty(target, prop, value) {313- Object.defineProperty(target, prop, {314- value: value,315- enumerable: false,316- writable: true317- })318-}modified:src/finalize.ts+18 added-44 removed
10 unmodified lines11 isEnumerable,12 DRAFT_STATE,13 NOTHING,14 freeze,15- shallowCopy15+ shallowCopy,16+ set17 } from "./common"18 import {isDraft, isDraftable} from "./index"19 import {SetState} from "./set"19-import {generatePatches} from "./patches"20+import {generatePatches, PatchPath} from "./patches"21 21-type PatchPath = Array<string | number> | null22-22 export function processResult(immer: Immer, result: any, scope: ImmerScope) {23 const baseDraft = scope.drafts![0]24 const isReplaced = result !== undefined && result !== baseDraft25 immer.willFinalize(scope, result, isReplaced)3 unmodified lines29 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore30 }31 if (isDraftable(result)) {32 // Finalize the result in case it contains (or is) a subset of the draft.34- result = finalize(immer, result, null, scope)33+ result = finalize(immer, result, scope)34 maybeFreeze(immer, result)35 }36 if (scope.patches) {37 scope.patches.push({8 unmodified lines46 })47 }48 } else {49 // Finalize the base draft.51- result = finalize(immer, baseDraft, [], scope)50+ result = finalize(immer, baseDraft, scope, [])51 }52 scope.revoke()53 if (scope.patches) {54 scope.patchListener!(scope.patches, scope.inversePatches!)3 unmodified lines58 59 function finalize(60 immer: Immer,61 draft: Drafted,63- path: PatchPath,64- scope: ImmerScope62+ scope: ImmerScope,63+ path?: PatchPath64 ) {65 const state = draft[DRAFT_STATE]66 if (!state) {67 if (Object.isFrozen(draft)) return draft69- return finalizeTree(immer, draft, null, scope)68+ return finalizeTree(immer, draft, scope)69 }70 // Never finalize drafts owned by another scope.71 if (state.scope !== scope) {72 return draft3 unmodified lines76 return state.base77 }78 if (!state.finalized) {79 state.finalized = true81- finalizeTree(immer, state.draft, path, scope)80+ finalizeTree(immer, state.draft, scope, path)81 82 // We cannot really delete anything inside of a Set. We can only replace the whole Set.83 if (immer.onDelete && !isSet(state.base)) {84 // The `assigned` object is unreliable with ES5 drafts.2 unmodified lines87 each(assigned, (prop, exists) => {88 if (!exists) immer.onDelete?.(state, prop as any)89 })90 } else {92- // TODO: Figure it out for Maps and Sets if we need to support ES591 const {base, copy} = state92 each(base, prop => {93 if (!has(copy, prop)) immer.onDelete?.(state, prop as any)94 })18 unmodified lines113 114 function finalizeTree(115 immer: Immer,116 root: Drafted,119- rootPath: PatchPath,120- scope: ImmerScope117+ scope: ImmerScope,118+ rootPath?: PatchPath119 ) {120 const state = root[DRAFT_STATE]121 if (state) {124- // TODO: kill isMap / isSet here125- if (!immer.useProxies && !isMap(root) && !isSet(root)) {122+ if (state.type === "es5_object" || state.type === "es5_array") {123 // 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?124+ state.copy = shallowCopy(state.draft, true)125 }129-126 root = state.copy127 }132-128 const needPatches = !!rootPath && !!scope.patches134-129 each(root, (key, value) =>130 finalizeProperty(131 immer,132 root,15 unmodified lines148 root: ImmerState,149 state: ImmerState,150 prop: string | number,151 value: any,158- parent: ImmerState,152+ parent: Drafted,153 needPatches: boolean,154 scope: ImmerScope,161- rootPath: PatchPath155+ rootPath?: PatchPath156 ) {157 if (value === parent) {158 throw Error("Immer forbids circular references")159 }8 unmodified lines168 needPatches &&169 !isSetMember && // Set objects are atomic since they have no keys.170 !has((state as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.171 ? rootPath!.concat(prop)178- : null172+ : undefined173 174 // Drafts owned by `scope` are finalized here.181- value = finalize(immer, value, path, scope)182- replace(parent, prop, value)175+ value = finalize(immer, value, scope, path)176+ set(parent, prop, value)177 178 // Drafts from another scope must prevent auto-freezing.179 if (isDraft(value)) {180 scope.canAutoFreeze = false28 unmodified lines209 immer.onAssign(state, prop, value)210 }211 }212 219-function 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-}238-213 export function maybeFreeze(immer: Immer, value: any, deep = false) {214 if (immer.autoFreeze && !isDraft(value)) {215 freeze(value, deep)216 }1 unmodified linemodified:src/immer.ts+35 added-41 removed
1 import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2 import {createProxy, markChanged} from "./proxy"3 4-import {applyPatches, generatePatches} from "./patches"4+import {applyPatches} from "./patches"5 import {6 each,7- has,8- is,7 isDraft,8 isSet,11- get,9 isMap,10 isDraftable,14- isEnumerable,15- shallowCopy,11 DRAFT_STATE,12 NOTHING,18- freeze,13 isPlainObject,20- DRAFTABLE14+ DRAFTABLE,15+ die16 } from "./common"17 import {ImmerScope} from "./scope"18 import {19 ImmerState,5 unmodified lines25 Patch,26 Drafted27 } from "./types"28 import {proxyMap} from "./map"34-import {proxySet, SetState} from "./set"29+import {proxySet} from "./set"30 import {processResult, maybeFreeze} from "./finalize"31 32 function verifyMinified() {}33 8 unmodified lines42 : verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: null51-}46+} as const47 48 interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches17 unmodified lines68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {71 each(configDefaults, (key, value) => {77- this[key] = value72+ // @ts-ignore73+ this[key] = config?.[key] ?? value74 })79- config &&80- each(config, (key, value) => {81- this[key] = value82- })75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }16 unmodified lines95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */107- produce(base, recipe?, patchListener?) {99+ produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104 105 const self = this114- return function curriedProduce(this: any, base = defaultBase, ...args) {115- return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106+ return function curriedProduce(107+ this: any,108+ base = defaultBase,109+ ...args: any[]110+ ) {111+ return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore112 }113 }114 115 // prettier-ignore43 unmodified lines159 return result160 }161 }162 167- produceWithPatches(arg1, arg2?, arg3?): any {163+ produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {164 if (typeof arg1 === "function") {165 const self = this170- return (state, ...args) =>171- this.produceWithPatches(state, draft => arg1(draft, ...args))166+ return (state: any, ...args: any[]) =>167+ this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))168 }169 // non-curried form170 if (arg3)171 throw new Error("A patch listener cannot be passed to produceWithPatches")176- let patches, inversePatches177- const nextState = this.produce(arg1, arg2, (p, ip) => {172+ let patches: Patch[], inversePatches: Patch[]173+ const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {174 patches = p175 inversePatches = ip176 })181- return [nextState, patches, inversePatches]177+ return [nextState, patches!, inversePatches!]178 }179 184- createDraft<T extends Objectish>(base: T): Draft<T> {180+ createDraft<T extends Objectish>(base: T): Drafted<T> {181 if (!isDraftable(base)) {182 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore183 }184 const scope = ImmerScope.enter(this)185 const proxy = this.createProxy(base, undefined)186+ // @ts-ignore TODO: add to structures187 proxy[DRAFT_STATE].isManual = true188 scope.leave()189 return proxy190 }35 unmodified lines226 227 applyPatches(base: Objectish, patches: Patch[]) {228 // If a patch replaces the entire state, take that replacement as base229 // before applying patches233- let i230+ let i: number231 for (i = patches.length - 1; i >= 0; i--) {232 const patch = patches[i]233 if (patch.path.length === 0 && patch.op === "replace") {234 base = patch.value5 unmodified lines240 // N.B: never hits if some patch a replacement, patches are never drafts241 return applyPatches(base, patches)242 }243 // Otherwise, produce a copy of the base state.247- return this.produce(base, draft =>244+ return this.produce(base, (draft: Drafted) =>245 applyPatches(draft, patches.slice(i + 1))246 )247 }248 252- createProxy<T>(value: any, parent?: ImmerState) {253- if (!value || typeof value !== "object") return value254-249+ createProxy<T extends Objectish>(250+ value: T,251+ parent?: ImmerState252+ ): Drafted<T, ImmerState> {253 let draft: Drafted256-257- if (258- isPlainObject(value) ||259- Array.isArray(value) ||260- value[DRAFTABLE] ||261- value?.constructor?.[DRAFTABLE]262- ) {254+ // TODO: use switch + type discovery>255+ if (isMap(value)) draft = proxyMap(value, parent)256+ else if (isSet(value)) draft = proxySet(value, parent)257+ else {258+ // createProxy should be guarded by isDraftable, so we know we can safely draft259 draft = this.useProxies260 ? createProxy(value, parent)261 : createES5Proxy(value, parent)266- } else if (isMap(value)) draft = proxyMap(value, parent)267- else if (isSet(value)) draft = proxySet(value, parent)268- else return value262+ }263 264 const scope = parent ? parent.scope : ImmerScope.current!265 scope.drafts.push(draft)266 return draft2 unmodified lines269 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {270 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)271 }272 279- markChanged(state: any) {273+ markChanged(state: ImmerState) {274 if (this.useProxies) {275 markChanged(state)276 } else {277 markChangedES5(state)3 unmodified linesmodified:src/map.ts+15 added-19 removed
1234456786711891011123 unmodified lines1617181923242526272829202122232425262738282930313243333435363749 unmodified lines87888990101102919210410593949596979853 unmodified lines152153154155167156157158159160161162163164165import {isDraftable, DRAFT_STATE, latest} from "./common"
import {ImmerScope} from "./scope"import {AnyMap, Drafted} from "./types"import {AnyMap, Drafted, ImmerState} from "./types"
// TODO: create own states// TODO: clean up the maps and such from ES5 / Proxy states
export interface MapState { type: "map" parent: any // TODO: type parent?: ImmerState scope: ImmerScope modified: boolean finalizing: boolean finalized: boolean3 unmodified lines revoke(): void draft: Drafted<AnyMap, MapState>}
function prepareCopy(state: MapState) { if (!state.copy) { state.assigned = new Map() state.copy = new Map(state.base) }}
// Make sure DraftMap declarion doesn't die if Map is not avialable...const MapBase: MapConstructor = typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)
// TODO: fix types for drafts// TODO: assert unrevoked, use freeze for thatexport class DraftMap<K, V> extends MapBase implements Map<K, V> { [DRAFT_STATE]: MapState constructor(target, parent) { constructor(target: AnyMap, parent?: ImmerState) { super() this[DRAFT_STATE] = { type: "map", parent, scope: parent ? parent.scope : ImmerScope.current, scope: parent ? parent.scope : ImmerScope.current!, modified: false, finalized: false, finalizing: false, copy: undefined,49 unmodified lines } return state.copy!.clear() }
// @ts-ignore TODO: forEach(cb) { forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) { const state = this[DRAFT_STATE] latest(state).forEach((_value, key, _map) => { cb(this.get(key), key, this) latest(state).forEach((_value: V, key: K, _map: this) => { cb.call(thisArg, this.get(key), key, this) }) }
get(key: K): V /* TODO: Draft<V> */ {53 unmodified lines return this.entries() }}
export function proxyMap(target, parent) {export function proxyMap(target: AnyMap, parent?: ImmerState) { return new DraftMap(target, parent)}
function prepareCopy(state: MapState) { if (!state.copy) { state.assigned = new Map() state.copy = new Map(state.base) }}modified:src/patches.ts+13 added-9 removed
1-import {get, each, isMap, isSet, has} from "./common"1+import {get, each, isMap, isSet, has, die} from "./common"2 import {Patch, ImmerState} from "./types"3 import {SetState} from "./set"4 5+export type PatchPath = (string | number)[]6+7 export function generatePatches(8 state: ImmerState,7- basePath: (string | number)[],9+ basePath: PatchPath,10 patches: Patch[],11 inversePatches: Patch[]12 ) {13 // TODO: use a proper switch here7 unmodified lines21 }22 23 function generateArrayPatches(24 state: any, // TODO: type properly with ImmerState23- basePath: (string | number)[],25+ basePath: PatchPath,26 patches: Patch[],27 inversePatches: Patch[]28 ) {29 let {base, copy, assigned} = state54 unmodified lines84 85 // This is used for both Map objects and normal objects.86 function generatePatchesFromAssigned(87 state: any, // TODO: type properly with ImmerState86- basePath: (number | string)[],88+ basePath: PatchPath,89 patches: Patch[],90 inversePatches: Patch[]91 ) {92 const {base, copy} = state15 unmodified lines108 }109 110 function generateSetPatches(111 state: SetState,110- basePath: (number | string)[],112+ basePath: PatchPath,113 patches: Patch[],114 inversePatches: Patch[]115 ) {116 let {base, copy} = state37 unmodified lines154 export function applyPatches<T>(draft: T, patches: Patch[]): T {155 patches.forEach(patch => {156 const {path, op} = patch157 156- if (!path.length) throw new Error("Illegal state")158+ if (!path.length) die()159 160 let base = draft161 for (let i = 0; i < path.length - 1; i++) {162 base = get(base, path[i])13 unmodified lines176 } else {177 // if value is an object, then it's assigned by reference178 // in the following add or remove ops, the value field inside the patch will also be modifyed179 // so we use value from the cloned patch180+ // @ts-ignore181 base[key] = value182 }183 break184 case "add":6 unmodified lines191 : isMap(base)192 ? base.set(key, value)193 : isSet(base)194 ? base.add(value)192- : (base[key] = value)195+ : ((base as any)[key] = value)196 break197 case "remove":198 Array.isArray(base)199 ? base.splice(key as any, 1)200 : isMap(base)201 ? base.delete(key)202 : isSet(base)203 ? base.delete(patch.value)201- : delete base[key]204+ : delete (base as any)[key]205 break206 default:207 throw new Error("Unsupported patch operation: " + op)208 }4 unmodified lines213 214 // TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?215 // E.g. auto-draft when new objects from outside are assigned and modified?216 // (See failing test when deepClone just returns obj)214-function deepClonePatchValue(obj) {217+function deepClonePatchValue<T>(obj: T): T218+function deepClonePatchValue(obj: any) {219 if (!obj || typeof obj !== "object") return obj220 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)221 if (isMap(obj))222 return new Map(7 unmodified linesmodified:src/proxy.ts+17 added-9 removed
9 unmodified lines10 DRAFT_STATE,11 latest12 } from "./common"13 import {ImmerScope} from "./scope"14-import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"14+import {AnyObject, Drafted, ImmerState, AnyArray, Objectish} from "./types"15 16 interface ProxyBaseState {17 scope: ImmerScope18 modified: boolean21 unmodified lines40 copy: AnyArray | null41 draft: Drafted<AnyArray, ProxyArrayState>42 }43 44+type ProxyState = ProxyObjectState | ProxyArrayState45+46 /**47 * Returns a new draft of the `base` object.48 *49 * The second argument is the parent draft-state (used internally).50 */49-export function createProxy<T extends object>(51+export function createProxy<T extends Objectish>(52 base: T,53 parent?: ImmerState52-): Drafted<T, ProxyObjectState | ProxyArrayState> {54+): Drafted<T, ProxyState> {55 const isArray = Array.isArray(base)54- const state: ProxyObjectState | ProxyArrayState = {56+ const state: ProxyState = {57 type: isArray ? "proxy_array" : ("proxy_object" as any),58 // Track which produce call this is associated with.59 scope: parent ? parent.scope : ImmerScope.current!,60 // True for both shallow and deep changes.37 unmodified lines98 99 /**100 * Object drafts101 */100-const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {102+const objectTraps: ProxyHandler<ProxyState> = {103 get(state, prop) {104 if (prop === DRAFT_STATE) return state105 let {drafts} = state106 37 unmodified lines144 prepareCopy(state)145 markChanged(state)146 }147 state.assigned[prop] = true148+ // @ts-ignore149 state.copy![prop] = value150 return true151 },152 deleteProperty(state, prop: string) {5 unmodified lines158 } else if (state.assigned[prop]) {159 // if an originally not assigned property was deleted160 delete state.assigned[prop]161 }162+ // @ts-ignore163 if (state.copy) delete state.copy[prop]164 return true165 },166 // Note: We never coerce `desc.value` into an Immer draft, because we can't make23 unmodified lines190 */191 192 const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}193 each(objectTraps, (key, fn) => {194+ // @ts-ignore195 arrayTraps[key] = function() {196 arguments[0] = arguments[0][0]197 return fn.apply(this, arguments)198 }15 unmodified lines214 * Map drafts215 */216 217 // Access a property without creating an Immer draft.213-function peek(draft, prop) {218+function peek(draft: Drafted, prop: PropertyKey): any {219 const state = draft[DRAFT_STATE]220 const desc = Reflect.getOwnPropertyDescriptor(221 state ? latest(state) : draft,222 prop223 )224 return desc && desc.value225 }226 222-// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?223-export function markChanged(state) {227+export function markChanged(state: ImmerState) {228 if (!state.modified) {229 state.modified = true230+ // @ts-ignore TODO231 const {base, drafts, parent} = state232+ // TODO: get rid of isMap and isSet233 if (!isMap(base) && !isSet(base)) {234 // TODO: drop creating copies here?235 const copy = (state.copy = shallowCopy(base))236 each(drafts, (key, value) => {237+ // @ts-ignore238 copy[key] = value239 })240+ // @ts-ignore TODO241 state.drafts = null242 }243 244 if (parent) {1 unmodified line246 }247 }248 }249 242-function prepareCopy(state) {250+function prepareCopy(state: ProxyState) {251 if (!state.copy) {252 state.copy = shallowCopy(state.base)253 }254 }modified:src/scope.ts+2 added-2 removed
1 import {DRAFT_STATE} from "./common"2-import {Patch, PatchListener} from "./types"2+import {Patch, PatchListener, Drafted} from "./types"3 import {Immer} from "./immer"4 5 /** Each scope represents a `produce` call. */6 export class ImmerScope {47 unmodified lines54 return scope55 }56 }57 58-function revoke(draft) {58+function revoke(draft: Drafted) {59 draft[DRAFT_STATE].revoke()60 }modified:src/set.ts+25 added-21 removed
1-import {DRAFT_STATE, latest} from "./common"1+import {DRAFT_STATE, latest, isDraftable} from "./common"2 3 // TODO: kill:4 import {ImmerScope} from "./scope"5-import {AnySet, Drafted} from "./types"5+import {AnySet, Drafted, ImmerState} from "./types"6 7 // TODO: create own states8 // TODO: clean up the maps and such from ES5 / Proxy states9 10 export interface SetState {11 type: "set"12- parent: any // TODO: type12+ parent?: ImmerState13 scope: ImmerScope14 modified: boolean15 finalizing: boolean16 finalized: boolean17 copy: AnySet | undefined18 base: AnySet19- drafts: Map<any, any> // maps the original value to the draft value in the new set19+ drafts: Map<any, Drafted> // maps the original value to the draft value in the new set20 revoke(): void21 draft: Drafted<AnySet, SetState>22 }23 24-function prepareCopy(state: SetState) {25- if (!state.copy) {26- // create drafts for all entries to preserve insertion order27- state.copy = new Set()28- state.base.forEach(value => {29- const draft = state.scope.immer.createProxy(value, state)30- state.copy!.add(draft)31- state.drafts.set(value, draft)32- })33- }34-}35-24 // Make sure DraftSet declarion doesn't die if Map is not avialable...25 const SetBase: SetConstructor =26 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)27 28 // TODO: fix types for drafts29 // TODO: assert unrevoked, use freeze for that30 export class DraftSet<K, V> extends SetBase implements Set<V> {31 [DRAFT_STATE]: SetState44- constructor(target, parent) {32+ constructor(target: AnySet, parent?: ImmerState) {33 super()34 this[DRAFT_STATE] = {35 type: "set",36 parent,49- scope: parent ? parent.scope : ImmerScope.current,37+ scope: parent ? parent.scope : ImmerScope.current!,38 modified: false,39 finalized: false,40 finalizing: false,41 copy: undefined,77 unmodified lines119 [Symbol.iterator]() {120 return this.values()121 }122 135- forEach(cb, thisArg) {123+ forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {124 const state = this[DRAFT_STATE]125 const iterator = this.values()126 let result = iterator.next()127 while (!result.done) {140- cb.call(thisArg, result.value, result.value, state.draft)128+ cb.call(thisArg, result.value, result.value, this)129 result = iterator.next()130 }131 }132 }133 146-export function proxySet(target, parent) {134+export function proxySet(target: AnySet, parent?: ImmerState) {135 return new DraftSet(target, parent)136 }137+138+function prepareCopy(state: SetState) {139+ if (!state.copy) {140+ // create drafts for all entries to preserve insertion order141+ state.copy = new Set()142+ state.base.forEach(value => {143+ if (isDraftable(value)) {144+ const draft = state.scope.immer.createProxy(value, state)145+ state.drafts.set(value, draft)146+ state.copy!.add(draft)147+ } else {148+ state.copy!.add(value)149+ }150+ })151+ }152+}modified:src/types.ts+1 added-1 removed
3 unmodified lines4 import {ProxyObjectState, ProxyArrayState} from "./proxy"5 import {ES5ObjectState, ES5ArrayState} from "./es5"6 7 export type Objectish = AnyObject | AnyArray | AnyMap | AnySet8-8 export type ObjectishNoSet = AnyObject | AnyArray | AnyMap9 10 export type AnyObject = {[key: string]: any}11 export type AnyArray = Array<any>15 unmodified lines27 | ES5ArrayState28 | MapState29 | SetState30 31+// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)32 export type Drafted<Base = any, T extends ImmerState = ImmerState> = {33 [DRAFT_STATE]: T34 } & Base35 174 unmodified linesmodified:tsconfig.json+1 added-1 removed
5 unmodified lines6 "target": "ES6",7 "strict": true,8 "declaration": true,9 "importHelpers": false,10- "noImplicitAny": false, // TODO: true,10+ "noImplicitAny": true,11 "esModuleInterop": true12 }13 }