Moving files into folders
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 67565dd · Browse files · 29 files·+1462 added−1458 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+1462 added−1458 removed
- other:+1462 added−1458 removed
Provenance
- Commit
ab49edc- Tree
ce656bf- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
67565dd
29 files changed+1462 added−1458 removed
added:src/core/finalize.ts+162 added
1+import {2+ ImmerScope,3+ DRAFT_STATE,4+ isDraftable,5+ NOTHING,6+ PatchPath,7+ each,8+ has,9+ freeze,10+ shallowCopy,11+ ImmerState,12+ isDraft,13+ SetState,14+ set,15+ is,16+ get,17+ ProxyTypeES5Object,18+ ProxyTypeES5Array,19+ ProxyTypeSet,20+ getPlugin,21+ die22+} from "../internal"23+24+export function processResult(result: any, scope: ImmerScope) {25+ scope.unfinalizedDrafts_ = scope.drafts_.length26+ const baseDraft = scope.drafts_![0]27+ const isReplaced = result !== undefined && result !== baseDraft28+ if (!scope.immer_.useProxies_)29+ getPlugin("es5").willFinalizeES5_(scope, result, isReplaced)30+ if (isReplaced) {31+ if (baseDraft[DRAFT_STATE].modified_) {32+ scope.revoke_()33+ die(4)34+ }35+ if (isDraftable(result)) {36+ // Finalize the result in case it contains (or is) a subset of the draft.37+ result = finalize(scope, result)38+ if (!scope.parent_) maybeFreeze(scope, result)39+ }40+ // TODO: move to plugin?41+ if (scope.patches_) {42+ scope.patches_.push({43+ op: "replace",44+ path: [],45+ value: result46+ })47+ scope.inversePatches_!.push({48+ op: "replace",49+ path: [],50+ value: (baseDraft[DRAFT_STATE] as ImmerState).base_51+ })52+ }53+ } else {54+ // Finalize the base draft.55+ result = finalize(scope, baseDraft, [])56+ }57+ scope.revoke_()58+ if (scope.patches_) {59+ scope.patchListener_!(scope.patches_, scope.inversePatches_!)60+ }61+ return result !== NOTHING ? result : undefined62+}63+64+function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {65+ // Don't recurse in tho recursive data structures66+ if (Object.isFrozen(value)) return value67+68+ const state: ImmerState = value[DRAFT_STATE]69+ // A plain object, might need freezing, might contain drafts70+ if (!state) {71+ each(value, (key, childValue) =>72+ finalizeProperty(rootScope, state, value, key, childValue, path)73+ )74+ return value75+ }76+ // Never finalize drafts owned by another scope.77+ if (state.scope_ !== rootScope) return value78+ // Unmodified draft, return the (frozen) original79+ if (!state.modified_) {80+ maybeFreeze(rootScope, state.base_, true)81+ return state.base_82+ }83+ // Not finalized yet, let's do that now84+ if (!state.finalized_) {85+ state.finalized_ = true86+ state.scope_.unfinalizedDrafts_--87+ const result =88+ // For ES5, create a good copy from the draft first, with added keys and without deleted keys.89+ state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array90+ ? (state.copy_ = shallowCopy(state.draft_, true))91+ : state.copy_92+ // finalize all children of the copy93+ each(result as any, (key, childValue) =>94+ finalizeProperty(rootScope, state, result, key, childValue, path)95+ )96+ // everything inside is frozen, we can freeze here97+ maybeFreeze(rootScope, result, false)98+ // first time finalizing, let's create those patches99+ if (path && rootScope.patches_) {100+ getPlugin("patches").generatePatches_(101+ state,102+ path,103+ rootScope.patches_,104+ rootScope.inversePatches_!105+ )106+ }107+ }108+ return state.copy_109+}110+111+function finalizeProperty(112+ rootScope: ImmerScope,113+ parentState: undefined | ImmerState,114+ targetObject: any,115+ prop: string | number,116+ childValue: any,117+ rootPath?: PatchPath118+) {119+ if (__DEV__ && childValue === targetObject) die(5)120+ if (isDraft(childValue)) {121+ const path =122+ rootPath &&123+ parentState &&124+ parentState!.type_ !== ProxyTypeSet && // Set objects are atomic since they have no keys.125+ !has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.126+ ? rootPath!.concat(prop)127+ : undefined128+ // Drafts owned by `scope` are finalized here.129+ const res = finalize(rootScope, childValue, path)130+ set(targetObject, prop, res)131+ // Drafts from another scope must prevented to be frozen132+ // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze133+ if (isDraft(res)) {134+ rootScope.canAutoFreeze_ = false135+ } else return136+ }137+ // Unchanged draft properties are ignored.138+ if (parentState && is(childValue, get(parentState!.base_, prop))) {139+ return140+ }141+ // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.142+ if (isDraftable(childValue)) {143+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {144+ // optimization: if an object is not a draft, and we don't have to145+ // deepfreeze everything, and we are sure that no drafts are left in the remaining object146+ // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.147+ // This benefits especially adding large data tree's without further processing.148+ // See add-data.js perf test149+ return150+ }151+ finalize(rootScope, childValue)152+ // immer deep freezes plain objects, so if there is no parent state, we freeze as well153+ if (!parentState || !parentState.scope_.parent_)154+ maybeFreeze(rootScope, childValue)155+ }156+}157+158+function maybeFreeze(scope: ImmerScope, value: any, deep = false) {159+ if (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {160+ freeze(value, deep)161+ }162+}added:src/core/immerClass.ts+233 added
1+import {2+ IProduceWithPatches,3+ IProduce,4+ ImmerState,5+ Drafted,6+ isDraftable,7+ ImmerScope,8+ processResult,9+ NOTHING,10+ Patch,11+ Objectish,12+ DRAFT_STATE,13+ Draft,14+ PatchListener,15+ isDraft,16+ isMap,17+ isSet,18+ markChangedProxy,19+ createProxyProxy,20+ freeze,21+ getPlugin,22+ die23+} from "../internal"24+25+/* istanbul ignore next */26+function verifyMinified() {}27+28+interface ProducersFns {29+ produce: IProduce30+ produceWithPatches: IProduceWithPatches31+}32+33+export class Immer implements ProducersFns {34+ useProxies_: boolean =35+ typeof Proxy !== "undefined" &&36+ typeof Proxy.revocable !== "undefined" &&37+ typeof Reflect !== "undefined"38+ autoFreeze_: boolean = __DEV__39+ ? false /* istanbul ignore next */40+ : verifyMinified.name === "verifyMinified"41+42+ constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {43+ if (typeof config?.useProxies === "boolean")44+ this.setUseProxies(config!.useProxies)45+ if (typeof config?.autoFreeze === "boolean")46+ this.setAutoFreeze(config!.autoFreeze)47+ this.produce = this.produce.bind(this)48+ this.produceWithPatches = this.produceWithPatches.bind(this)49+ }50+51+ /**52+ * The `produce` function takes a value and a "recipe function" (whose53+ * return value often depends on the base state). The recipe function is54+ * free to mutate its first argument however it wants. All mutations are55+ * only ever applied to a __copy__ of the base state.56+ *57+ * Pass only a function to create a "curried producer" which relieves you58+ * from passing the recipe function every time.59+ *60+ * Only plain objects and arrays are made mutable. All other objects are61+ * considered uncopyable.62+ *63+ * Note: This function is __bound__ to its `Immer` instance.64+ *65+ * @param {any} base - the initial state66+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified67+ * @param {Function} patchListener - optional function that will be called with all the patches produced here68+ * @returns {any} a new state, or the initial state if nothing was modified69+ */70+ produce(base: any, recipe?: any, patchListener?: any) {71+ // curried invocation72+ if (typeof base === "function" && typeof recipe !== "function") {73+ const defaultBase = recipe74+ recipe = base75+76+ const self = this77+ return function curriedProduce(78+ this: any,79+ base = defaultBase,80+ ...args: any[]81+ ) {82+ return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore83+ }84+ }85+86+ if (typeof recipe !== "function") die(6)87+ if (patchListener !== undefined && typeof patchListener !== "function")88+ die(7)89+90+ let result91+92+ // Only plain objects, arrays, and "immerable classes" are drafted.93+ if (isDraftable(base)) {94+ const scope = ImmerScope.enter_(this)95+ const proxy = createProxy(this, base, undefined)96+ let hasError = true97+ try {98+ result = recipe(proxy)99+ hasError = false100+ } finally {101+ // finally instead of catch + rethrow better preserves original stack102+ if (hasError) scope.revoke_()103+ else scope.leave_()104+ }105+ if (typeof Promise !== "undefined" && result instanceof Promise) {106+ return result.then(107+ result => {108+ scope.usePatches_(patchListener)109+ return processResult(result, scope)110+ },111+ error => {112+ scope.revoke_()113+ throw error114+ }115+ )116+ }117+ scope.usePatches_(patchListener)118+ return processResult(result, scope)119+ } else {120+ result = recipe(base)121+ if (result === NOTHING) return undefined122+ if (result === undefined) result = base123+ if (this.autoFreeze_) freeze(result, true)124+ return result125+ }126+ }127+128+ produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {129+ if (typeof arg1 === "function") {130+ return (state: any, ...args: any[]) =>131+ this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))132+ }133+134+ let patches: Patch[], inversePatches: Patch[]135+ const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {136+ patches = p137+ inversePatches = ip138+ })139+ return [nextState, patches!, inversePatches!]140+ }141+142+ createDraft<T extends Objectish>(base: T): Draft<T> {143+ if (!isDraftable(base)) die(8)144+ const scope = ImmerScope.enter_(this)145+ const proxy = createProxy(this, base, undefined)146+ proxy[DRAFT_STATE].isManual_ = true147+ scope.leave_()148+ return proxy as any149+ }150+151+ finishDraft<D extends Draft<any>>(152+ draft: D,153+ patchListener?: PatchListener154+ ): D extends Draft<infer T> ? T : never {155+ const state: ImmerState = draft && draft[DRAFT_STATE]156+ if (__DEV__) {157+ if (!state || !state.isManual_) die(9)158+ if (state.finalized_) die(10)159+ }160+ const {scope_: scope} = state161+ scope.usePatches_(patchListener)162+ return processResult(undefined, scope)163+ }164+165+ /**166+ * Pass true to automatically freeze all copies created by Immer.167+ *168+ * By default, auto-freezing is disabled in production.169+ */170+ setAutoFreeze(value: boolean) {171+ this.autoFreeze_ = value172+ }173+174+ /**175+ * Pass true to use the ES2015 `Proxy` class when creating drafts, which is176+ * always faster than using ES5 proxies.177+ *178+ * By default, feature detection is used, so calling this is rarely necessary.179+ */180+ setUseProxies(value: boolean) {181+ this.useProxies_ = value182+ }183+184+ applyPatches(base: Objectish, patches: Patch[]) {185+ // If a patch replaces the entire state, take that replacement as base186+ // before applying patches187+ let i: number188+ for (i = patches.length - 1; i >= 0; i--) {189+ const patch = patches[i]190+ if (patch.path.length === 0 && patch.op === "replace") {191+ base = patch.value192+ break193+ }194+ }195+196+ const applyPatchesImpl = getPlugin("patches").applyPatches_197+ if (isDraft(base)) {198+ // N.B: never hits if some patch a replacement, patches are never drafts199+ return applyPatchesImpl(base, patches)200+ }201+ // Otherwise, produce a copy of the base state.202+ return this.produce(base, (draft: Drafted) =>203+ applyPatchesImpl(draft, patches.slice(i + 1))204+ )205+ }206+}207+208+export function createProxy<T extends Objectish>(209+ immer: Immer,210+ value: T,211+ parent?: ImmerState212+): Drafted<T, ImmerState> {213+ // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft214+ const draft: Drafted = isMap(value)215+ ? getPlugin("mapset").proxyMap_(value, parent)216+ : isSet(value)217+ ? getPlugin("mapset").proxySet_(value, parent)218+ : immer.useProxies_219+ ? createProxyProxy(value, parent)220+ : getPlugin("es5").createES5Proxy_(value, parent)221+222+ const scope = parent ? parent.scope_ : ImmerScope.current_!223+ scope.drafts_.push(draft)224+ return draft225+}226+227+export function markChanged(immer: Immer, state: ImmerState) {228+ if (immer.useProxies_) {229+ markChangedProxy(state)230+ } else {231+ getPlugin("es5").markChangedES5_(state)232+ }233+}added:src/core/proxy.ts+260 added
1+"use strict"2+import {3+ each,4+ has,5+ is,6+ isDraftable,7+ shallowCopy,8+ latest,9+ ImmerBaseState,10+ ImmerState,11+ Drafted,12+ AnyObject,13+ AnyArray,14+ Objectish,15+ ImmerScope,16+ DRAFT_STATE,17+ die,18+ createProxy,19+ ProxyTypeProxyObject,20+ ProxyTypeProxyArray21+} from "../internal"22+23+interface ProxyBaseState extends ImmerBaseState {24+ assigned_: {25+ [property: string]: boolean26+ }27+ parent_?: ImmerState28+ drafts_?: {29+ [property: string]: Drafted<any, any>30+ }31+ revoke_(): void32+}33+34+export interface ProxyObjectState extends ProxyBaseState {35+ type_: typeof ProxyTypeProxyObject36+ base_: AnyObject37+ copy_: AnyObject | null38+ draft_: Drafted<AnyObject, ProxyObjectState>39+}40+41+export interface ProxyArrayState extends ProxyBaseState {42+ type_: typeof ProxyTypeProxyArray43+ base_: AnyArray44+ copy_: AnyArray | null45+ draft_: Drafted<AnyArray, ProxyArrayState>46+}47+48+type ProxyState = ProxyObjectState | ProxyArrayState49+50+/**51+ * Returns a new draft of the `base` object.52+ *53+ * The second argument is the parent draft-state (used internally).54+ */55+export function createProxyProxy<T extends Objectish>(56+ base: T,57+ parent?: ImmerState58+): Drafted<T, ProxyState> {59+ const isArray = Array.isArray(base)60+ const state: ProxyState = {61+ type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),62+ // Track which produce call this is associated with.63+ scope_: parent ? parent.scope_ : ImmerScope.current_!,64+ // True for both shallow and deep changes.65+ modified_: false,66+ // Used during finalization.67+ finalized_: false,68+ // Track which properties have been assigned (true) or deleted (false).69+ assigned_: {},70+ // The parent draft state.71+ parent_: parent,72+ // The base state.73+ base_: base,74+ // The base proxy.75+ draft_: null as any, // set below76+ // Any property proxies.77+ drafts_: {},78+ // The base copy with any updated values.79+ copy_: null,80+ // Called by the `produce` function.81+ revoke_: null as any,82+ isManual_: false83+ }84+85+ // the traps must target something, a bit like the 'real' base.86+ // but also, we need to be able to determine from the target what the relevant state is87+ // (to avoid creating traps per instance to capture the state in closure,88+ // and to avoid creating weird hidden properties as well)89+ // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)90+ // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb91+ let target: T = state as any92+ let traps: ProxyHandler<object | Array<any>> = objectTraps93+ if (isArray) {94+ target = [state] as any95+ traps = arrayTraps96+ }97+98+ // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy99+ // and administrate revoking ourselves100+ const {revoke, proxy} = Proxy.revocable(target, traps)101+ state.draft_ = proxy as any102+ state.revoke_ = revoke103+ return proxy as any104+}105+106+/**107+ * Object drafts108+ */109+const objectTraps: ProxyHandler<ProxyState> = {110+ get(state, prop) {111+ if (prop === DRAFT_STATE) return state112+ let {drafts_: drafts} = state113+114+ // Check for existing draft in unmodified state.115+ if (!state.modified_ && has(drafts, prop)) {116+ return drafts![prop as any]117+ }118+119+ const value = latest(state)[prop]120+ if (state.finalized_ || !isDraftable(value)) {121+ return value122+ }123+124+ // Check for existing draft in modified state.125+ if (state.modified_) {126+ // Assigned values are never drafted. This catches any drafts we created, too.127+ if (value !== peek(state.base_, prop)) return value128+ // Store drafts on the copy (when one exists).129+ // @ts-ignore130+ drafts = state.copy_131+ }132+133+ return (drafts![prop as any] = createProxy(134+ state.scope_.immer_,135+ value,136+ state137+ ))138+ },139+ has(state, prop) {140+ return prop in latest(state)141+ },142+ ownKeys(state) {143+ return Reflect.ownKeys(latest(state))144+ },145+ set(state, prop: string /* strictly not, but helps TS */, value) {146+ if (!state.modified_) {147+ const baseValue = peek(state.base_, prop)148+ // Optimize based on value's truthiness. Truthy values are guaranteed to149+ // never be undefined, so we can avoid the `in` operator. Lastly, truthy150+ // values may be drafts, but falsy values are never drafts.151+ const isUnchanged = value152+ ? is(baseValue, value) || value === state.drafts_![prop]153+ : is(baseValue, value) && prop in state.base_154+ if (isUnchanged) return true155+ prepareCopy(state)156+ markChangedProxy(state)157+ }158+ state.assigned_[prop] = true159+ // @ts-ignore160+ state.copy_![prop] = value161+ return true162+ },163+ deleteProperty(state, prop: string) {164+ // The `undefined` check is a fast path for pre-existing keys.165+ if (peek(state.base_, prop) !== undefined || prop in state.base_) {166+ state.assigned_[prop] = false167+ prepareCopy(state)168+ markChangedProxy(state)169+ } else if (state.assigned_[prop]) {170+ // if an originally not assigned property was deleted171+ delete state.assigned_[prop]172+ }173+ // @ts-ignore174+ if (state.copy_) delete state.copy_[prop]175+ return true176+ },177+ // Note: We never coerce `desc.value` into an Immer draft, because we can't make178+ // the same guarantee in ES5 mode.179+ getOwnPropertyDescriptor(state, prop) {180+ const owner = latest(state)181+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop)182+ if (desc) {183+ desc.writable = true184+ desc.configurable =185+ state.type_ !== ProxyTypeProxyArray || prop !== "length"186+ }187+ return desc188+ },189+ defineProperty() {190+ die(11)191+ },192+ getPrototypeOf(state) {193+ return Object.getPrototypeOf(state.base_)194+ },195+ setPrototypeOf() {196+ die(12)197+ }198+}199+200+/**201+ * Array drafts202+ */203+204+const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}205+each(objectTraps, (key, fn) => {206+ // @ts-ignore207+ arrayTraps[key] = function() {208+ arguments[0] = arguments[0][0]209+ return fn.apply(this, arguments)210+ }211+})212+arrayTraps.deleteProperty = function(state, prop) {213+ if (__DEV__ && isNaN(parseInt(prop as any))) die(13)214+ return objectTraps.deleteProperty!.call(this, state[0], prop)215+}216+arrayTraps.set = function(state, prop, value) {217+ if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)218+ return objectTraps.set!.call(this, state[0], prop, value, state[0])219+}220+221+/**222+ * Map drafts223+ */224+225+// Access a property without creating an Immer draft.226+function peek(draft: Drafted, prop: PropertyKey): any {227+ const state = draft[DRAFT_STATE]228+ const desc = Reflect.getOwnPropertyDescriptor(229+ state ? latest(state) : draft,230+ prop231+ )232+ return desc && desc.value233+}234+235+export function markChangedProxy(state: ImmerState) {236+ if (!state.modified_) {237+ state.modified_ = true238+ if (239+ state.type_ === ProxyTypeProxyObject ||240+ state.type_ === ProxyTypeProxyArray241+ ) {242+ const copy = (state.copy_ = shallowCopy(state.base_))243+ each(state.drafts_!, (key, value) => {244+ // @ts-ignore245+ copy[key] = value246+ })247+ state.drafts_ = undefined248+ }249+250+ if (state.parent_) {251+ markChangedProxy(state.parent_)252+ }253+ }254+}255+256+function prepareCopy(state: ProxyState) {257+ if (!state.copy_) {258+ state.copy_ = shallowCopy(state.base_)259+ }260+}added:src/core/scope.ts+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { Patch, PatchListener, Drafted, Immer, DRAFT_STATE, ImmerState, ProxyTypeProxyObject, ProxyTypeProxyArray} from "../internal"
/** Each scope represents a `produce` call. */// TODO: non-class?export class ImmerScope { static current_?: ImmerScope
patches_?: Patch[] inversePatches_?: Patch[] canAutoFreeze_: boolean drafts_: any[] parent_?: ImmerScope patchListener_?: PatchListener immer_: Immer unfinalizedDrafts_ = 0
constructor(parent: ImmerScope | undefined, immer: Immer) { this.drafts_ = [] this.parent_ = parent this.immer_ = immer
// Whenever the modified draft contains a draft from another scope, we // need to prevent auto-freezing so the unowned draft can be finalized. this.canAutoFreeze_ = true }
usePatches_(patchListener?: PatchListener) { if (patchListener) { this.patches_ = [] this.inversePatches_ = [] this.patchListener_ = patchListener } }
revoke_() { this.leave_() this.drafts_.forEach(revoke) // @ts-ignore this.drafts_ = null }
leave_() { if (this === ImmerScope.current_) { ImmerScope.current_ = this.parent_ } }
static enter_(immer: Immer) { const scope = new ImmerScope(ImmerScope.current_, immer) ImmerScope.current_ = scope return scope }}
function revoke(draft: Drafted) { const state: ImmerState = draft[DRAFT_STATE] if ( state.type_ === ProxyTypeProxyObject || state.type_ === ProxyTypeProxyArray ) state.revoke_() else state.revoked_ = true}added:src/crap/common.ts+192 added
1+import {2+ DRAFT_STATE,3+ DRAFTABLE,4+ hasSet,5+ Objectish,6+ Drafted,7+ AnyObject,8+ AnyArray,9+ AnyMap,10+ AnySet,11+ ImmerState,12+ hasMap,13+ ArchtypeObject,14+ ArchtypeArray,15+ ArchtypeMap,16+ ArchtypeSet,17+ die18+} from "../internal"19+20+/** Returns true if the given value is an Immer draft */21+/*#__PURE__*/22+export function isDraft(value: any): boolean {23+ return !!value && !!value[DRAFT_STATE]24+}25+26+/** Returns true if the given value can be drafted by Immer */27+/*#__PURE__*/28+export function isDraftable(value: any): boolean {29+ if (!value) return false30+ return (31+ isPlainObject(value) ||32+ Array.isArray(value) ||33+ !!value[DRAFTABLE] ||34+ !!value.constructor[DRAFTABLE] ||35+ isMap(value) ||36+ isSet(value)37+ )38+}39+40+/*#__PURE__*/41+export function isPlainObject(value: any): boolean {42+ if (!value || typeof value !== "object") return false43+ const proto = Object.getPrototypeOf(value)44+ return !proto || proto === Object.prototype45+}46+47+/** Get the underlying object that is represented by the given draft */48+/*#__PURE__*/49+export function original<T>(value: T): T | undefined50+export function original(value: Drafted<any>): any {51+ if (value && value[DRAFT_STATE]) {52+ return value[DRAFT_STATE].base_ as any53+ }54+ // otherwise return undefined55+}56+57+/*#__PURE__*/58+export const ownKeys: (target: AnyObject) => PropertyKey[] =59+ typeof Reflect !== "undefined" && Reflect.ownKeys60+ ? Reflect.ownKeys61+ : typeof Object.getOwnPropertySymbols !== "undefined"62+ ? obj =>63+ Object.getOwnPropertyNames(obj).concat(64+ Object.getOwnPropertySymbols(obj) as any65+ )66+ : /* istanbul ignore next */ Object.getOwnPropertyNames67+68+export function each<T extends Objectish>(69+ obj: T,70+ iter: (key: string | number, value: any, source: T) => void71+): void72+export function each(obj: any, iter: any) {73+ if (getArchtype(obj) === ArchtypeObject) {74+ ownKeys(obj).forEach(key => iter(key, obj[key], obj))75+ } else {76+ obj.forEach((entry: any, index: any) => iter(index, entry, obj))77+ }78+}79+80+/*#__PURE__*/81+export function getArchtype(thing: any): 0 | 1 | 2 | 3 {82+ /* istanbul ignore next */83+ const state: undefined | ImmerState = thing[DRAFT_STATE]84+ return state85+ ? state.type_ > 386+ ? state.type_ - 4 // cause Object and Array map back from 4 and 587+ : (state.type_ as any) // others are the same88+ : Array.isArray(thing)89+ ? ArchtypeArray90+ : isMap(thing)91+ ? ArchtypeMap92+ : isSet(thing)93+ ? ArchtypeSet94+ : ArchtypeObject95+}96+97+/*#__PURE__*/98+export function has(thing: any, prop: PropertyKey): boolean {99+ return getArchtype(thing) === ArchtypeMap100+ ? thing.has(prop)101+ : Object.prototype.hasOwnProperty.call(thing, prop)102+}103+104+/*#__PURE__*/105+export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {106+ // @ts-ignore107+ return getArchtype(thing) === ArchtypeMap ? thing.get(prop) : thing[prop]108+}109+110+/*#__PURE__*/111+export function set(thing: any, propOrOldValue: PropertyKey, value: any) {112+ switch (getArchtype(thing)) {113+ case ArchtypeMap:114+ thing.set(propOrOldValue, value)115+ break116+ case ArchtypeSet:117+ thing.delete(propOrOldValue)118+ thing.add(value)119+ break120+ default:121+ thing[propOrOldValue] = value122+ }123+}124+125+/*#__PURE__*/126+export function is(x: any, y: any): boolean {127+ // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js128+ if (x === y) {129+ return x !== 0 || 1 / x === 1 / y130+ } else {131+ return x !== x && y !== y132+ }133+}134+135+/*#__PURE__*/136+export function isMap(target: any): target is AnyMap {137+ return hasMap && target instanceof Map138+}139+140+/*#__PURE__*/141+export function isSet(target: any): target is AnySet {142+ return hasSet && target instanceof Set143+}144+/*#__PURE__*/145+export function latest(state: ImmerState): any {146+ return state.copy_ || state.base_147+}148+149+/*#__PURE__*/150+export function shallowCopy<T extends AnyObject | AnyArray>(151+ base: T,152+ invokeGetters?: boolean153+): T154+export function shallowCopy(base: any, invokeGetters = false) {155+ if (Array.isArray(base)) return base.slice()156+ const clone = Object.create(Object.getPrototypeOf(base))157+ // TODO: each?158+ ownKeys(base).forEach(key => {159+ if (key === DRAFT_STATE) {160+ return // Never copy over draft state.161+ }162+ const desc = Object.getOwnPropertyDescriptor(base, key)!163+ let {value} = desc164+ if (desc.get) {165+ if (!invokeGetters) die(1)166+ value = desc.get.call(base)167+ }168+ if (desc.enumerable) {169+ clone[key] = value170+ } else {171+ Object.defineProperty(clone, key, {172+ value,173+ writable: true,174+ configurable: true175+ })176+ }177+ })178+ return clone179+}180+181+export function freeze(obj: any, deep: boolean): void {182+ if (isDraft(obj) || Object.isFrozen(obj) || !isDraftable(obj)) return183+ if (getArchtype(obj) > 1 /* Map or Set */) {184+ obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any185+ }186+ Object.freeze(obj)187+ if (deep) each(obj, (_, value) => freeze(value, true))188+}189+190+function dontMutateFrozenCollections() {191+ die(2)192+}added:src/crap/env.ts+40 added
12345678910111213141516171819202122232425262728293031323334353637383940// Should be no imports here!
// SOme things that should be evaluated before all else...const hasSymbol = typeof Symbol !== "undefined"export const hasMap = typeof Map !== "undefined"export const hasSet = typeof Set !== "undefined"
/** * The sentinel value returned by producers to replace the draft with undefined. */export const NOTHING: Nothing = hasSymbol ? Symbol("immer-nothing") : ({["immer-nothing"]: true} as any)
/** * To let Immer treat your class instances as plain immutable objects * (albeit with a custom prototype), you must define either an instance property * or a static property on each of your custom classes. * * Otherwise, your class instance will never be drafted, which means it won't be * safe to mutate in a produce callback. */export const DRAFTABLE: unique symbol = hasSymbol ? Symbol("immer-draftable") : ("__$immer_draftable" as any)
export const DRAFT_STATE: unique symbol = hasSymbol ? Symbol("immer-state") : ("__$immer_state" as any)
export const iteratorSymbol: typeof Symbol.iterator = hasSymbol ? Symbol.iterator : ("@@iterator" as any)
/** Use a class type for `nothing` so its type is unique */export class Nothing { // This lets us do `Exclude<T, Nothing>` // @ts-ignore private _!: unique symbol}added:src/crap/errors.ts+52 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152const errors = { 0: "Illegal state", 1: "Immer drafts cannot have computed properties", 2: "This object has been frozen and should not be mutated", 3(data: any) { return ( "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data ) }, 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", 5: "Immer forbids circular references", 6: "The first or second argument to `produce` must be a function", 7: "The third argument to `produce` must be a function or undefined", 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object", 9: "First argument to `finishDraft` must be a draft returned by `createDraft`", 10: "The given draft is already finalized", 11: "Object.defineProperty() cannot be used on an Immer draft", 12: "Object.setPrototypeOf() cannot be used on an Immer draft", 13: "Immer only supports deleting array indices", 14: "Immer only supports setting array indices and the 'length' property", 15(path: string) { return "Cannot apply patch, path doesn't resolve: " + path }, 16: 'Sets cannot have "replace" patches.', 17(op: string) { return "Unsupported patch operation: " + op }, 18(plugin: string) { return `The plugin ${plugin} has not been loaded into Immer. Make sure to call "enable${plugin[0].toUpperCase()}${plugin.substr( 1 )}()" when initializing your application, just after requiring immer itself.` }, 19: "plugin not loaded"} as const
export function die(error: keyof typeof errors, ...args: any[]): never { if (__DEV__) { const e = errors[error] const msg = !e ? "unknown error nr: " + error : typeof e === "function" ? e.apply(null, args as any) : e throw new Error(`[Immer] ${msg}`) } throw new Error( `[Immer] minified error nr: ${error}${ args.length ? " " + args.join(",") : "" }` )}added:src/crap/plugins.ts+108 added
1+import {2+ ImmerState,3+ Patch,4+ ImmerScope,5+ Drafted,6+ AnyObject,7+ ImmerBaseState,8+ AnyArray,9+ AnyMap,10+ AnySet,11+ ProxyTypeES5Array,12+ ProxyTypeES5Object,13+ ProxyTypeMap,14+ ProxyTypeSet,15+ die16+} from "../internal"17+18+/** Plugin utilities */19+const plugins: {20+ patches?: {21+ generatePatches_(22+ state: ImmerState,23+ basePath: PatchPath,24+ patches: Patch[],25+ inversePatches: Patch[]26+ ): void27+ applyPatches_<T>(draft: T, patches: Patch[]): T28+ }29+ es5?: {30+ willFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void31+ createES5Proxy_<T>(32+ base: T,33+ parent?: ImmerState34+ ): Drafted<T, ES5ObjectState | ES5ArrayState>35+ markChangedES5_(state: ImmerState): void36+ }37+ mapset?: {38+ proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T39+ proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T40+ }41+} = {}42+43+type Plugins = typeof plugins44+45+export function getPlugin<K extends keyof Plugins>(46+ pluginKey: K47+): Exclude<Plugins[K], undefined> {48+ const plugin = plugins[pluginKey]49+ if (!plugin) {50+ die(__DEV__ ? 18 : 19, plugin)51+ }52+ // @ts-ignore53+ return plugin54+}55+56+export function loadPlugin<K extends keyof Plugins>(57+ pluginKey: K,58+ implementation: Plugins[K]59+): void {60+ plugins[pluginKey] = implementation61+}62+63+/** ES5 Plugin */64+65+interface ES5BaseState extends ImmerBaseState {66+ finalizing_: boolean67+ assigned_: {[key: string]: any}68+ parent_?: ImmerState69+ revoked_: boolean70+}71+72+export interface ES5ObjectState extends ES5BaseState {73+ type_: typeof ProxyTypeES5Object74+ draft_: Drafted<AnyObject, ES5ObjectState>75+ base_: AnyObject76+ copy_: AnyObject | null77+}78+79+export interface ES5ArrayState extends ES5BaseState {80+ type_: typeof ProxyTypeES5Array81+ draft_: Drafted<AnyObject, ES5ArrayState>82+ base_: AnyArray83+ copy_: AnyArray | null84+}85+86+/** Map / Set plugin */87+88+export interface MapState extends ImmerBaseState {89+ type_: typeof ProxyTypeMap90+ copy_: AnyMap | undefined91+ assigned_: Map<any, boolean> | undefined92+ base_: AnyMap93+ revoked_: boolean94+ draft_: Drafted<AnyMap, MapState>95+}96+97+export interface SetState extends ImmerBaseState {98+ type_: typeof ProxyTypeSet99+ copy_: AnySet | undefined100+ base_: AnySet101+ drafts_: Map<any, Drafted> // maps the original value to the draft value in the new set102+ revoked_: boolean103+ draft_: Drafted<AnySet, SetState>104+}105+106+/** Patches plugin */107+108+export type PatchPath = (string | number)[]modified:src/plugins/patches.ts+2 added-2 removed
154 unmodified lines155 ) {156 let {base_, copy_} = state157 158 let i = 0159- base_.forEach(value => {159+ base_.forEach((value: any) => {160 if (!copy_!.has(value)) {161 const path = basePath.concat([i])162 patches.push({163 op: "remove",8 unmodified lines172 }173 i++174 })175 i = 0176- copy_!.forEach(value => {176+ copy_!.forEach((value: any) => {177 if (!base_.has(value)) {178 const path = basePath.concat([i])179 patches.push({180 op: "add",90 unmodified linesadded:src/types/globals.d.ts+1 added
1declare const __DEV__: booleanadded:src/types/immer.js.flow+107 added
1+// @flow2+3+export interface Patch {4+ op: "replace" | "remove" | "add",5+ path: (string|number)[],6+ value?: any7+}8+9+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void10+11+interface IProduce {12+ /**13+ * Immer takes a state, and runs a function against it.14+ * That function can freely mutate the state, as it will create copies-on-write.15+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16+ *17+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18+ * any time it is called with the current state.19+ *20+ * @param currentState - the state to start with21+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22+ * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23+ * @returns The next state: a new state, or the current state if nothing was modified24+ */25+ <S>(26+ currentState: S,27+ recipe: (draftState: S) => S | void,28+ patchListener?: PatchListener29+ ): S;30+ // curried invocations with inital state31+ <S, A, B, C>(32+ recipe: (draftState: S, a: A, b: B, c: C) => S | void,33+ initialState: S34+ ): (currentState: S | void, a: A, b: B, c: C) => S;35+ <S, A, B>(36+ recipe: (draftState: S, a: A, b: B) => S | void,37+ initialState: S38+ ): (currentState: S | void, a: A, b: B) => S;39+ <S, A>(40+ recipe: (draftState: S, a: A) => S | void,41+ initialState: S42+ ): (currentState: S | void, a: A) => S;43+ <S>(44+ recipe: (draftState: S) => S | void,45+ initialState: S46+ ): (currentState: S | void) => S;47+ <S>(48+ recipe: (draftState: S, ...extraArgs: any[]) => S | void,49+ initialState: S50+ ): (currentState: S | void, ...extraArgs: any[]) => S;51+ // curried invocations without inital state52+ <S, A, B, C>(53+ recipe: (draftState: S, a: A, b: B, c: C) => S | void54+ ): (currentState: S, a: A, b: B, c: C) => S;55+ <S, A, B>(56+ recipe: (draftState: S, a: A, b: B) => S | void57+ ): (currentState: S, a: A, b: B) => S;58+ <S, A>(59+ recipe: (draftState: S, a: A) => S | void60+ ): (currentState: S, a: A) => S;61+ <S>(62+ recipe: (draftState: S) => S | void63+ ): (currentState: S) => S;64+ <S>(65+ recipe: (draftState: S, ...extraArgs: any[]) => S | void66+ ): (currentState: S, ...extraArgs: any[]) => S;67+}68+69+declare export var produce: IProduce70+declare export default IProduce71+72+declare export var nothing: typeof undefined73+74+declare export var immerable: Symbol75+76+/**77+ * Automatically freezes any state trees generated by immer.78+ * This protects against accidental modifications of the state tree outside of an immer function.79+ * This comes with a performance impact, so it is recommended to disable this option in production.80+ * By default it is turned on during local development, and turned off in production.81+ */82+declare export function setAutoFreeze(autoFreeze: boolean): void83+84+/**85+ * Manually override whether proxies should be used.86+ * By default done by using feature detection87+ */88+declare export function setUseProxies(useProxies: boolean): void89+90+declare export function applyPatches<S>(state: S, patches: Patch[]): S91+92+declare export function original<S>(value: S): ?S93+94+declare export function isDraft(value: any): boolean95+96+/**97+ * Creates a mutable draft from an (immutable) object / array. 98+ * The draft can be modified until `finishDraft` is called99+ */100+declare export function createDraft<T>(base: T): T101+102+/**103+ * Given a draft that was created using `createDraft`, 104+ * finalizes the draft into a new immutable object.105+ * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.106+ */107+declare export function finishDraft<T>(base: T, listener?: PatchListener): Tadded:src/types/types-external.ts+169 added
1+import {Nothing} from "../internal"2+3+type Tail<T extends any[]> = ((...t: T) => any) extends (4+ _: any,5+ ...tail: infer TT6+) => any7+ ? TT8+ : []9+10+/** Object types that should never be mapped */11+type AtomicObject =12+ | Function13+ | Promise<any>14+ | Date15+ | RegExp16+ | Boolean17+ | Number18+ | String19+20+/**21+ * These should also never be mapped but must be tested after regular Map and22+ * Set23+ */24+type WeakReferences = WeakMap<any, any> | WeakSet<any>25+26+export type Draft<T> = T extends AtomicObject27+ ? T28+ : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap29+ ? Map<Draft<K>, Draft<V>>30+ : T extends ReadonlySet<infer V> // Set extends ReadonlySet31+ ? Set<Draft<V>>32+ : T extends WeakReferences33+ ? T34+ : T extends object35+ ? {-readonly [K in keyof T]: Draft<T[K]>}36+ : T37+38+/** Convert a mutable type into a readonly type */39+export type Immutable<T> = T extends AtomicObject40+ ? T41+ : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap42+ ? ReadonlyMap<Immutable<K>, Immutable<V>>43+ : T extends ReadonlySet<infer V> // Set extends ReadonlySet44+ ? ReadonlySet<Immutable<V>>45+ : T extends WeakReferences46+ ? T47+ : T extends object48+ ? {readonly [K in keyof T]: Immutable<T[K]>}49+ : T50+51+export interface Patch {52+ op: "replace" | "remove" | "add"53+ path: (string | number)[]54+ value?: any55+}56+57+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void58+59+/** Converts `nothing` into `undefined` */60+type FromNothing<T> = T extends Nothing ? undefined : T61+62+/** The inferred return type of `produce` */63+export type Produced<Base, Return> = Return extends void64+ ? Base65+ : Return extends Promise<infer Result>66+ ? Promise<Result extends void ? Base : FromNothing<Result>>67+ : FromNothing<Return>68+69+/**70+ * The `produce` function takes a value and a "recipe function" (whose71+ * return value often depends on the base state). The recipe function is72+ * free to mutate its first argument however it wants. All mutations are73+ * only ever applied to a __copy__ of the base state.74+ *75+ * Pass only a function to create a "curried producer" which relieves you76+ * from passing the recipe function every time.77+ *78+ * Only plain objects and arrays are made mutable. All other objects are79+ * considered uncopyable.80+ *81+ * Note: This function is __bound__ to its `Immer` instance.82+ *83+ * @param {any} base - the initial state84+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified85+ * @param {Function} patchListener - optional function that will be called with all the patches produced here86+ * @returns {any} a new state, or the initial state if nothing was modified87+ */88+export interface IProduce {89+ /** Curried producer */90+ <91+ Recipe extends (...args: any[]) => any,92+ Params extends any[] = Parameters<Recipe>,93+ T = Params[0]94+ >(95+ recipe: Recipe96+ ): <Base extends Immutable<T>>(97+ base: Base,98+ ...rest: Tail<Params>99+ ) => Produced<Base, ReturnType<Recipe>>100+ // ^ by making the returned type generic, the actual type of the passed in object is preferred101+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe102+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!103+104+ /** Curried producer with initial state */105+ <106+ Recipe extends (...args: any[]) => any,107+ Params extends any[] = Parameters<Recipe>,108+ T = Params[0]109+ >(110+ recipe: Recipe,111+ initialState: Immutable<T>112+ ): <Base extends Immutable<T>>(113+ base?: Base,114+ ...rest: Tail<Params>115+ ) => Produced<Base, ReturnType<Recipe>>116+117+ /** Normal producer */118+ <Base, D = Draft<Base>, Return = void>(119+ base: Base,120+ recipe: (draft: D) => Return,121+ listener?: PatchListener122+ ): Produced<Base, Return>123+}124+125+/**126+ * Like `produce`, but instead of just returning the new state,127+ * a tuple is returned with [nextState, patches, inversePatches]128+ *129+ * Like produce, this function supports currying130+ */131+export interface IProduceWithPatches {132+ /** Curried producer */133+ <134+ Recipe extends (...args: any[]) => any,135+ Params extends any[] = Parameters<Recipe>,136+ T = Params[0]137+ >(138+ recipe: Recipe139+ ): <Base extends Immutable<T>>(140+ base: Base,141+ ...rest: Tail<Params>142+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]143+ // ^ by making the returned type generic, the actual type of the passed in object is preferred144+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe145+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!146+147+ /** Curried producer with initial state */148+ <149+ Recipe extends (...args: any[]) => any,150+ Params extends any[] = Parameters<Recipe>,151+ T = Params[0]152+ >(153+ recipe: Recipe,154+ initialState: Immutable<T>155+ ): <Base extends Immutable<T>>(156+ base?: Base,157+ ...rest: Tail<Params>158+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159+160+ /** Normal producer */161+ <Base, D = Draft<Base>, Return = void>(162+ base: Base,163+ recipe: (draft: D) => Return164+ ): [Produced<Base, Return>, Patch[], Patch[]]165+}166+167+// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..168+// hopefully it get's tree-shaken away for everyone :)169+export function never_used() {}added:src/types/types-internal.ts+51 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { SetState, ImmerScope, ProxyObjectState, ProxyArrayState, ES5ObjectState, ES5ArrayState, MapState, DRAFT_STATE} from "../internal"
export type Objectish = AnyObject | AnyArray | AnyMap | AnySetexport type ObjectishNoSet = AnyObject | AnyArray | AnyMap
export type AnyObject = {[key: string]: any}export type AnyArray = Array<any>export type AnySet = Set<any>export type AnyMap = Map<any, any>
export const ArchtypeObject = 0export const ArchtypeArray = 1export const ArchtypeMap = 2export const ArchtypeSet = 3
export const ProxyTypeProxyObject = 0export const ProxyTypeProxyArray = 1export const ProxyTypeES5Object = 4export const ProxyTypeES5Array = 5export const ProxyTypeMap = 2export const ProxyTypeSet = 3
export interface ImmerBaseState { parent_?: ImmerState scope_: ImmerScope modified_: boolean finalized_: boolean isManual_: boolean}
export type ImmerState = | ProxyObjectState | ProxyArrayState | ES5ObjectState | ES5ArrayState | MapState | SetState
// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)export type Drafted<Base = any, T extends ImmerState = ImmerState> = { [DRAFT_STATE]: T} & Basedeleted:src/common.ts-192 removed
1-import {2- DRAFT_STATE,3- DRAFTABLE,4- hasSet,5- Objectish,6- Drafted,7- AnyObject,8- AnyArray,9- AnyMap,10- AnySet,11- ImmerState,12- hasMap,13- ArchtypeObject,14- ArchtypeArray,15- ArchtypeMap,16- ArchtypeSet,17- die18-} from "./internal"19-20-/** Returns true if the given value is an Immer draft */21-/*#__PURE__*/22-export function isDraft(value: any): boolean {23- return !!value && !!value[DRAFT_STATE]24-}25-26-/** Returns true if the given value can be drafted by Immer */27-/*#__PURE__*/28-export function isDraftable(value: any): boolean {29- if (!value) return false30- return (31- isPlainObject(value) ||32- Array.isArray(value) ||33- !!value[DRAFTABLE] ||34- !!value.constructor[DRAFTABLE] ||35- isMap(value) ||36- isSet(value)37- )38-}39-40-/*#__PURE__*/41-export function isPlainObject(value: any): boolean {42- if (!value || typeof value !== "object") return false43- const proto = Object.getPrototypeOf(value)44- return !proto || proto === Object.prototype45-}46-47-/** Get the underlying object that is represented by the given draft */48-/*#__PURE__*/49-export function original<T>(value: T): T | undefined50-export function original(value: Drafted<any>): any {51- if (value && value[DRAFT_STATE]) {52- return value[DRAFT_STATE].base_ as any53- }54- // otherwise return undefined55-}56-57-/*#__PURE__*/58-export const ownKeys: (target: AnyObject) => PropertyKey[] =59- typeof Reflect !== "undefined" && Reflect.ownKeys60- ? Reflect.ownKeys61- : typeof Object.getOwnPropertySymbols !== "undefined"62- ? obj =>63- Object.getOwnPropertyNames(obj).concat(64- Object.getOwnPropertySymbols(obj) as any65- )66- : /* istanbul ignore next */ Object.getOwnPropertyNames67-68-export function each<T extends Objectish>(69- obj: T,70- iter: (key: string | number, value: any, source: T) => void71-): void72-export function each(obj: any, iter: any) {73- if (getArchtype(obj) === ArchtypeObject) {74- ownKeys(obj).forEach(key => iter(key, obj[key], obj))75- } else {76- obj.forEach((entry: any, index: any) => iter(index, entry, obj))77- }78-}79-80-/*#__PURE__*/81-export function getArchtype(thing: any): 0 | 1 | 2 | 3 {82- /* istanbul ignore next */83- const state: undefined | ImmerState = thing[DRAFT_STATE]84- return state85- ? state.type_ > 386- ? state.type_ - 4 // cause Object and Array map back from 4 and 587- : (state.type_ as any) // others are the same88- : Array.isArray(thing)89- ? ArchtypeArray90- : isMap(thing)91- ? ArchtypeMap92- : isSet(thing)93- ? ArchtypeSet94- : ArchtypeObject95-}96-97-/*#__PURE__*/98-export function has(thing: any, prop: PropertyKey): boolean {99- return getArchtype(thing) === ArchtypeMap100- ? thing.has(prop)101- : Object.prototype.hasOwnProperty.call(thing, prop)102-}103-104-/*#__PURE__*/105-export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {106- // @ts-ignore107- return getArchtype(thing) === ArchtypeMap ? thing.get(prop) : thing[prop]108-}109-110-/*#__PURE__*/111-export function set(thing: any, propOrOldValue: PropertyKey, value: any) {112- switch (getArchtype(thing)) {113- case ArchtypeMap:114- thing.set(propOrOldValue, value)115- break116- case ArchtypeSet:117- thing.delete(propOrOldValue)118- thing.add(value)119- break120- default:121- thing[propOrOldValue] = value122- }123-}124-125-/*#__PURE__*/126-export function is(x: any, y: any): boolean {127- // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js128- if (x === y) {129- return x !== 0 || 1 / x === 1 / y130- } else {131- return x !== x && y !== y132- }133-}134-135-/*#__PURE__*/136-export function isMap(target: any): target is AnyMap {137- return hasMap && target instanceof Map138-}139-140-/*#__PURE__*/141-export function isSet(target: any): target is AnySet {142- return hasSet && target instanceof Set143-}144-/*#__PURE__*/145-export function latest(state: ImmerState): any {146- return state.copy_ || state.base_147-}148-149-/*#__PURE__*/150-export function shallowCopy<T extends AnyObject | AnyArray>(151- base: T,152- invokeGetters?: boolean153-): T154-export function shallowCopy(base: any, invokeGetters = false) {155- if (Array.isArray(base)) return base.slice()156- const clone = Object.create(Object.getPrototypeOf(base))157- // TODO: each?158- ownKeys(base).forEach(key => {159- if (key === DRAFT_STATE) {160- return // Never copy over draft state.161- }162- const desc = Object.getOwnPropertyDescriptor(base, key)!163- let {value} = desc164- if (desc.get) {165- if (!invokeGetters) die(1)166- value = desc.get.call(base)167- }168- if (desc.enumerable) {169- clone[key] = value170- } else {171- Object.defineProperty(clone, key, {172- value,173- writable: true,174- configurable: true175- })176- }177- })178- return clone179-}180-181-export function freeze(obj: any, deep: boolean): void {182- if (isDraft(obj) || Object.isFrozen(obj) || !isDraftable(obj)) return183- if (getArchtype(obj) > 1 /* Map or Set */) {184- obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any185- }186- Object.freeze(obj)187- if (deep) each(obj, (_, value) => freeze(value, true))188-}189-190-function dontMutateFrozenCollections() {191- die(2)192-}deleted:src/env.ts-40 removed
12345678910111213141516171819202122232425262728293031323334353637383940// Should be no imports here!
// SOme things that should be evaluated before all else...const hasSymbol = typeof Symbol !== "undefined"export const hasMap = typeof Map !== "undefined"export const hasSet = typeof Set !== "undefined"
/** * The sentinel value returned by producers to replace the draft with undefined. */export const NOTHING: Nothing = hasSymbol ? Symbol("immer-nothing") : ({["immer-nothing"]: true} as any)
/** * To let Immer treat your class instances as plain immutable objects * (albeit with a custom prototype), you must define either an instance property * or a static property on each of your custom classes. * * Otherwise, your class instance will never be drafted, which means it won't be * safe to mutate in a produce callback. */export const DRAFTABLE: unique symbol = hasSymbol ? Symbol("immer-draftable") : ("__$immer_draftable" as any)
export const DRAFT_STATE: unique symbol = hasSymbol ? Symbol("immer-state") : ("__$immer_state" as any)
export const iteratorSymbol: typeof Symbol.iterator = hasSymbol ? Symbol.iterator : ("@@iterator" as any)
/** Use a class type for `nothing` so its type is unique */export class Nothing { // This lets us do `Exclude<T, Nothing>` // @ts-ignore private _!: unique symbol}deleted:src/errors.ts-52 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152const errors = { 0: "Illegal state", 1: "Immer drafts cannot have computed properties", 2: "This object has been frozen and should not be mutated", 3(data: any) { return ( "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data ) }, 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", 5: "Immer forbids circular references", 6: "The first or second argument to `produce` must be a function", 7: "The third argument to `produce` must be a function or undefined", 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object", 9: "First argument to `finishDraft` must be a draft returned by `createDraft`", 10: "The given draft is already finalized", 11: "Object.defineProperty() cannot be used on an Immer draft", 12: "Object.setPrototypeOf() cannot be used on an Immer draft", 13: "Immer only supports deleting array indices", 14: "Immer only supports setting array indices and the 'length' property", 15(path: string) { return "Cannot apply patch, path doesn't resolve: " + path }, 16: 'Sets cannot have "replace" patches.', 17(op: string) { return "Unsupported patch operation: " + op }, 18(plugin: string) { return `The plugin ${plugin} has not been loaded into Immer. Make sure to call "enable${plugin[0].toUpperCase()}${plugin.substr( 1 )}()" when initializing your application, just after requiring immer itself.` }, 19: "plugin not loaded"} as const
export function die(error: keyof typeof errors, ...args: any[]): never { if (__DEV__) { const e = errors[error] const msg = !e ? "unknown error nr: " + error : typeof e === "function" ? e.apply(null, args as any) : e throw new Error(`[Immer] ${msg}`) } throw new Error( `[Immer] minified error nr: ${error}${ args.length ? " " + args.join(",") : "" }` )}deleted:src/finalize.ts-162 removed
1-import {2- ImmerScope,3- DRAFT_STATE,4- isDraftable,5- NOTHING,6- PatchPath,7- each,8- has,9- freeze,10- shallowCopy,11- ImmerState,12- isDraft,13- SetState,14- set,15- is,16- get,17- ProxyTypeES5Object,18- ProxyTypeES5Array,19- ProxyTypeSet,20- getPlugin,21- die22-} from "./internal"23-24-export function processResult(result: any, scope: ImmerScope) {25- scope.unfinalizedDrafts_ = scope.drafts_.length26- const baseDraft = scope.drafts_![0]27- const isReplaced = result !== undefined && result !== baseDraft28- if (!scope.immer_.useProxies_)29- getPlugin("es5").willFinalizeES5_(scope, result, isReplaced)30- if (isReplaced) {31- if (baseDraft[DRAFT_STATE].modified_) {32- scope.revoke_()33- die(4)34- }35- if (isDraftable(result)) {36- // Finalize the result in case it contains (or is) a subset of the draft.37- result = finalize(scope, result)38- if (!scope.parent_) maybeFreeze(scope, result)39- }40- // TODO: move to plugin?41- if (scope.patches_) {42- scope.patches_.push({43- op: "replace",44- path: [],45- value: result46- })47- scope.inversePatches_!.push({48- op: "replace",49- path: [],50- value: (baseDraft[DRAFT_STATE] as ImmerState).base_51- })52- }53- } else {54- // Finalize the base draft.55- result = finalize(scope, baseDraft, [])56- }57- scope.revoke_()58- if (scope.patches_) {59- scope.patchListener_!(scope.patches_, scope.inversePatches_!)60- }61- return result !== NOTHING ? result : undefined62-}63-64-function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {65- // Don't recurse in tho recursive data structures66- if (Object.isFrozen(value)) return value67-68- const state: ImmerState = value[DRAFT_STATE]69- // A plain object, might need freezing, might contain drafts70- if (!state) {71- each(value, (key, childValue) =>72- finalizeProperty(rootScope, state, value, key, childValue, path)73- )74- return value75- }76- // Never finalize drafts owned by another scope.77- if (state.scope_ !== rootScope) return value78- // Unmodified draft, return the (frozen) original79- if (!state.modified_) {80- maybeFreeze(rootScope, state.base_, true)81- return state.base_82- }83- // Not finalized yet, let's do that now84- if (!state.finalized_) {85- state.finalized_ = true86- state.scope_.unfinalizedDrafts_--87- const result =88- // For ES5, create a good copy from the draft first, with added keys and without deleted keys.89- state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array90- ? (state.copy_ = shallowCopy(state.draft_, true))91- : state.copy_92- // finalize all children of the copy93- each(result as any, (key, childValue) =>94- finalizeProperty(rootScope, state, result, key, childValue, path)95- )96- // everything inside is frozen, we can freeze here97- maybeFreeze(rootScope, result, false)98- // first time finalizing, let's create those patches99- if (path && rootScope.patches_) {100- getPlugin("patches").generatePatches_(101- state,102- path,103- rootScope.patches_,104- rootScope.inversePatches_!105- )106- }107- }108- return state.copy_109-}110-111-function finalizeProperty(112- rootScope: ImmerScope,113- parentState: undefined | ImmerState,114- targetObject: any,115- prop: string | number,116- childValue: any,117- rootPath?: PatchPath118-) {119- if (__DEV__ && childValue === targetObject) die(5)120- if (isDraft(childValue)) {121- const path =122- rootPath &&123- parentState &&124- parentState!.type_ !== ProxyTypeSet && // Set objects are atomic since they have no keys.125- !has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.126- ? rootPath!.concat(prop)127- : undefined128- // Drafts owned by `scope` are finalized here.129- const res = finalize(rootScope, childValue, path)130- set(targetObject, prop, res)131- // Drafts from another scope must prevented to be frozen132- // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze133- if (isDraft(res)) {134- rootScope.canAutoFreeze_ = false135- } else return136- }137- // Unchanged draft properties are ignored.138- if (parentState && is(childValue, get(parentState!.base_, prop))) {139- return140- }141- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.142- if (isDraftable(childValue)) {143- if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {144- // optimization: if an object is not a draft, and we don't have to145- // deepfreeze everything, and we are sure that no drafts are left in the remaining object146- // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.147- // This benefits especially adding large data tree's without further processing.148- // See add-data.js perf test149- return150- }151- finalize(rootScope, childValue)152- // immer deep freezes plain objects, so if there is no parent state, we freeze as well153- if (!parentState || !parentState.scope_.parent_)154- maybeFreeze(rootScope, childValue)155- }156-}157-158-function maybeFreeze(scope: ImmerScope, value: any, deep = false) {159- if (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {160- freeze(value, deep)161- }162-}deleted:src/globals.d.ts-1 removed
1-declare const __DEV__: booleandeleted:src/immer.js.flow-107 removed
1-// @flow2-3-export interface Patch {4- op: "replace" | "remove" | "add",5- path: (string|number)[],6- value?: any7-}8-9-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void10-11-interface IProduce {12- /**13- * Immer takes a state, and runs a function against it.14- * That function can freely mutate the state, as it will create copies-on-write.15- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16- *17- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18- * any time it is called with the current state.19- *20- * @param currentState - the state to start with21- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22- * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23- * @returns The next state: a new state, or the current state if nothing was modified24- */25- <S>(26- currentState: S,27- recipe: (draftState: S) => S | void,28- patchListener?: PatchListener29- ): S;30- // curried invocations with inital state31- <S, A, B, C>(32- recipe: (draftState: S, a: A, b: B, c: C) => S | void,33- initialState: S34- ): (currentState: S | void, a: A, b: B, c: C) => S;35- <S, A, B>(36- recipe: (draftState: S, a: A, b: B) => S | void,37- initialState: S38- ): (currentState: S | void, a: A, b: B) => S;39- <S, A>(40- recipe: (draftState: S, a: A) => S | void,41- initialState: S42- ): (currentState: S | void, a: A) => S;43- <S>(44- recipe: (draftState: S) => S | void,45- initialState: S46- ): (currentState: S | void) => S;47- <S>(48- recipe: (draftState: S, ...extraArgs: any[]) => S | void,49- initialState: S50- ): (currentState: S | void, ...extraArgs: any[]) => S;51- // curried invocations without inital state52- <S, A, B, C>(53- recipe: (draftState: S, a: A, b: B, c: C) => S | void54- ): (currentState: S, a: A, b: B, c: C) => S;55- <S, A, B>(56- recipe: (draftState: S, a: A, b: B) => S | void57- ): (currentState: S, a: A, b: B) => S;58- <S, A>(59- recipe: (draftState: S, a: A) => S | void60- ): (currentState: S, a: A) => S;61- <S>(62- recipe: (draftState: S) => S | void63- ): (currentState: S) => S;64- <S>(65- recipe: (draftState: S, ...extraArgs: any[]) => S | void66- ): (currentState: S, ...extraArgs: any[]) => S;67-}68-69-declare export var produce: IProduce70-declare export default IProduce71-72-declare export var nothing: typeof undefined73-74-declare export var immerable: Symbol75-76-/**77- * Automatically freezes any state trees generated by immer.78- * This protects against accidental modifications of the state tree outside of an immer function.79- * This comes with a performance impact, so it is recommended to disable this option in production.80- * By default it is turned on during local development, and turned off in production.81- */82-declare export function setAutoFreeze(autoFreeze: boolean): void83-84-/**85- * Manually override whether proxies should be used.86- * By default done by using feature detection87- */88-declare export function setUseProxies(useProxies: boolean): void89-90-declare export function applyPatches<S>(state: S, patches: Patch[]): S91-92-declare export function original<S>(value: S): ?S93-94-declare export function isDraft(value: any): boolean95-96-/**97- * Creates a mutable draft from an (immutable) object / array. 98- * The draft can be modified until `finishDraft` is called99- */100-declare export function createDraft<T>(base: T): T101-102-/**103- * Given a draft that was created using `createDraft`, 104- * finalizes the draft into a new immutable object.105- * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.106- */107-declare export function finishDraft<T>(base: T, listener?: PatchListener): Tdeleted:src/immerClass.ts-233 removed
1-import {2- IProduceWithPatches,3- IProduce,4- ImmerState,5- Drafted,6- isDraftable,7- ImmerScope,8- processResult,9- NOTHING,10- Patch,11- Objectish,12- DRAFT_STATE,13- Draft,14- PatchListener,15- isDraft,16- isMap,17- isSet,18- markChangedProxy,19- createProxyProxy,20- freeze,21- getPlugin,22- die23-} from "./internal"24-25-/* istanbul ignore next */26-function verifyMinified() {}27-28-interface ProducersFns {29- produce: IProduce30- produceWithPatches: IProduceWithPatches31-}32-33-export class Immer implements ProducersFns {34- useProxies_: boolean =35- typeof Proxy !== "undefined" &&36- typeof Proxy.revocable !== "undefined" &&37- typeof Reflect !== "undefined"38- autoFreeze_: boolean = __DEV__39- ? false /* istanbul ignore next */40- : verifyMinified.name === "verifyMinified"41-42- constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {43- if (typeof config?.useProxies === "boolean")44- this.setUseProxies(config!.useProxies)45- if (typeof config?.autoFreeze === "boolean")46- this.setAutoFreeze(config!.autoFreeze)47- this.produce = this.produce.bind(this)48- this.produceWithPatches = this.produceWithPatches.bind(this)49- }50-51- /**52- * The `produce` function takes a value and a "recipe function" (whose53- * return value often depends on the base state). The recipe function is54- * free to mutate its first argument however it wants. All mutations are55- * only ever applied to a __copy__ of the base state.56- *57- * Pass only a function to create a "curried producer" which relieves you58- * from passing the recipe function every time.59- *60- * Only plain objects and arrays are made mutable. All other objects are61- * considered uncopyable.62- *63- * Note: This function is __bound__ to its `Immer` instance.64- *65- * @param {any} base - the initial state66- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified67- * @param {Function} patchListener - optional function that will be called with all the patches produced here68- * @returns {any} a new state, or the initial state if nothing was modified69- */70- produce(base: any, recipe?: any, patchListener?: any) {71- // curried invocation72- if (typeof base === "function" && typeof recipe !== "function") {73- const defaultBase = recipe74- recipe = base75-76- const self = this77- return function curriedProduce(78- this: any,79- base = defaultBase,80- ...args: any[]81- ) {82- return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore83- }84- }85-86- if (typeof recipe !== "function") die(6)87- if (patchListener !== undefined && typeof patchListener !== "function")88- die(7)89-90- let result91-92- // Only plain objects, arrays, and "immerable classes" are drafted.93- if (isDraftable(base)) {94- const scope = ImmerScope.enter_(this)95- const proxy = createProxy(this, base, undefined)96- let hasError = true97- try {98- result = recipe(proxy)99- hasError = false100- } finally {101- // finally instead of catch + rethrow better preserves original stack102- if (hasError) scope.revoke_()103- else scope.leave_()104- }105- if (typeof Promise !== "undefined" && result instanceof Promise) {106- return result.then(107- result => {108- scope.usePatches_(patchListener)109- return processResult(result, scope)110- },111- error => {112- scope.revoke_()113- throw error114- }115- )116- }117- scope.usePatches_(patchListener)118- return processResult(result, scope)119- } else {120- result = recipe(base)121- if (result === NOTHING) return undefined122- if (result === undefined) result = base123- if (this.autoFreeze_) freeze(result, true)124- return result125- }126- }127-128- produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {129- if (typeof arg1 === "function") {130- return (state: any, ...args: any[]) =>131- this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))132- }133-134- let patches: Patch[], inversePatches: Patch[]135- const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {136- patches = p137- inversePatches = ip138- })139- return [nextState, patches!, inversePatches!]140- }141-142- createDraft<T extends Objectish>(base: T): Draft<T> {143- if (!isDraftable(base)) die(8)144- const scope = ImmerScope.enter_(this)145- const proxy = createProxy(this, base, undefined)146- proxy[DRAFT_STATE].isManual_ = true147- scope.leave_()148- return proxy as any149- }150-151- finishDraft<D extends Draft<any>>(152- draft: D,153- patchListener?: PatchListener154- ): D extends Draft<infer T> ? T : never {155- const state: ImmerState = draft && draft[DRAFT_STATE]156- if (__DEV__) {157- if (!state || !state.isManual_) die(9)158- if (state.finalized_) die(10)159- }160- const {scope_: scope} = state161- scope.usePatches_(patchListener)162- return processResult(undefined, scope)163- }164-165- /**166- * Pass true to automatically freeze all copies created by Immer.167- *168- * By default, auto-freezing is disabled in production.169- */170- setAutoFreeze(value: boolean) {171- this.autoFreeze_ = value172- }173-174- /**175- * Pass true to use the ES2015 `Proxy` class when creating drafts, which is176- * always faster than using ES5 proxies.177- *178- * By default, feature detection is used, so calling this is rarely necessary.179- */180- setUseProxies(value: boolean) {181- this.useProxies_ = value182- }183-184- applyPatches(base: Objectish, patches: Patch[]) {185- // If a patch replaces the entire state, take that replacement as base186- // before applying patches187- let i: number188- for (i = patches.length - 1; i >= 0; i--) {189- const patch = patches[i]190- if (patch.path.length === 0 && patch.op === "replace") {191- base = patch.value192- break193- }194- }195-196- const applyPatchesImpl = getPlugin("patches").applyPatches_197- if (isDraft(base)) {198- // N.B: never hits if some patch a replacement, patches are never drafts199- return applyPatchesImpl(base, patches)200- }201- // Otherwise, produce a copy of the base state.202- return this.produce(base, (draft: Drafted) =>203- applyPatchesImpl(draft, patches.slice(i + 1))204- )205- }206-}207-208-export function createProxy<T extends Objectish>(209- immer: Immer,210- value: T,211- parent?: ImmerState212-): Drafted<T, ImmerState> {213- // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft214- const draft: Drafted = isMap(value)215- ? getPlugin("mapset").proxyMap_(value, parent)216- : isSet(value)217- ? getPlugin("mapset").proxySet_(value, parent)218- : immer.useProxies_219- ? createProxyProxy(value, parent)220- : getPlugin("es5").createES5Proxy_(value, parent)221-222- const scope = parent ? parent.scope_ : ImmerScope.current_!223- scope.drafts_.push(draft)224- return draft225-}226-227-export function markChanged(immer: Immer, state: ImmerState) {228- if (immer.useProxies_) {229- markChangedProxy(state)230- } else {231- getPlugin("es5").markChangedES5_(state)232- }233-}modified:src/internal.ts+10 added-10 removed
1-export * from "./env"2-export * from "./errors"3-export * from "./types-external"4-export * from "./types-internal"5-export * from "./common"6-export * from "./plugins"7-export * from "./scope"8-export * from "./finalize"9-export * from "./proxy"10-export * from "./immerClass"1+export * from "./crap/env"2+export * from "./crap/errors"3+export * from "./types/types-external"4+export * from "./types/types-internal"5+export * from "./crap/common"6+export * from "./crap/plugins"7+export * from "./core/scope"8+export * from "./core/finalize"9+export * from "./core/proxy"10+export * from "./core/immerClass"deleted:src/plugins.ts-108 removed
1-import {2- ImmerState,3- Patch,4- ImmerScope,5- Drafted,6- AnyObject,7- ImmerBaseState,8- AnyArray,9- AnyMap,10- AnySet,11- ProxyTypeES5Array,12- ProxyTypeES5Object,13- ProxyTypeMap,14- ProxyTypeSet,15- die16-} from "./internal"17-18-/** Plugin utilities */19-const plugins: {20- patches?: {21- generatePatches_(22- state: ImmerState,23- basePath: PatchPath,24- patches: Patch[],25- inversePatches: Patch[]26- ): void27- applyPatches_<T>(draft: T, patches: Patch[]): T28- }29- es5?: {30- willFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void31- createES5Proxy_<T>(32- base: T,33- parent?: ImmerState34- ): Drafted<T, ES5ObjectState | ES5ArrayState>35- markChangedES5_(state: ImmerState): void36- }37- mapset?: {38- proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T39- proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T40- }41-} = {}42-43-type Plugins = typeof plugins44-45-export function getPlugin<K extends keyof Plugins>(46- pluginKey: K47-): Exclude<Plugins[K], undefined> {48- const plugin = plugins[pluginKey]49- if (!plugin) {50- die(__DEV__ ? 18 : 19, plugin)51- }52- // @ts-ignore53- return plugin54-}55-56-export function loadPlugin<K extends keyof Plugins>(57- pluginKey: K,58- implementation: Plugins[K]59-): void {60- plugins[pluginKey] = implementation61-}62-63-/** ES5 Plugin */64-65-interface ES5BaseState extends ImmerBaseState {66- finalizing_: boolean67- assigned_: {[key: string]: any}68- parent_?: ImmerState69- revoked_: boolean70-}71-72-export interface ES5ObjectState extends ES5BaseState {73- type_: typeof ProxyTypeES5Object74- draft_: Drafted<AnyObject, ES5ObjectState>75- base_: AnyObject76- copy_: AnyObject | null77-}78-79-export interface ES5ArrayState extends ES5BaseState {80- type_: typeof ProxyTypeES5Array81- draft_: Drafted<AnyObject, ES5ArrayState>82- base_: AnyArray83- copy_: AnyArray | null84-}85-86-/** Map / Set plugin */87-88-export interface MapState extends ImmerBaseState {89- type_: typeof ProxyTypeMap90- copy_: AnyMap | undefined91- assigned_: Map<any, boolean> | undefined92- base_: AnyMap93- revoked_: boolean94- draft_: Drafted<AnyMap, MapState>95-}96-97-export interface SetState extends ImmerBaseState {98- type_: typeof ProxyTypeSet99- copy_: AnySet | undefined100- base_: AnySet101- drafts_: Map<any, Drafted> // maps the original value to the draft value in the new set102- revoked_: boolean103- draft_: Drafted<AnySet, SetState>104-}105-106-/** Patches plugin */107-108-export type PatchPath = (string | number)[]deleted:src/proxy.ts-260 removed
1-"use strict"2-import {3- each,4- has,5- is,6- isDraftable,7- shallowCopy,8- latest,9- ImmerBaseState,10- ImmerState,11- Drafted,12- AnyObject,13- AnyArray,14- Objectish,15- ImmerScope,16- DRAFT_STATE,17- createProxy,18- ProxyTypeProxyObject,19- ProxyTypeProxyArray20-} from "./internal"21-import {die} from "./errors"22-23-interface ProxyBaseState extends ImmerBaseState {24- assigned_: {25- [property: string]: boolean26- }27- parent_?: ImmerState28- drafts_?: {29- [property: string]: Drafted<any, any>30- }31- revoke_(): void32-}33-34-export interface ProxyObjectState extends ProxyBaseState {35- type_: typeof ProxyTypeProxyObject36- base_: AnyObject37- copy_: AnyObject | null38- draft_: Drafted<AnyObject, ProxyObjectState>39-}40-41-export interface ProxyArrayState extends ProxyBaseState {42- type_: typeof ProxyTypeProxyArray43- base_: AnyArray44- copy_: AnyArray | null45- draft_: Drafted<AnyArray, ProxyArrayState>46-}47-48-type ProxyState = ProxyObjectState | ProxyArrayState49-50-/**51- * Returns a new draft of the `base` object.52- *53- * The second argument is the parent draft-state (used internally).54- */55-export function createProxyProxy<T extends Objectish>(56- base: T,57- parent?: ImmerState58-): Drafted<T, ProxyState> {59- const isArray = Array.isArray(base)60- const state: ProxyState = {61- type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),62- // Track which produce call this is associated with.63- scope_: parent ? parent.scope_ : ImmerScope.current_!,64- // True for both shallow and deep changes.65- modified_: false,66- // Used during finalization.67- finalized_: false,68- // Track which properties have been assigned (true) or deleted (false).69- assigned_: {},70- // The parent draft state.71- parent_: parent,72- // The base state.73- base_: base,74- // The base proxy.75- draft_: null as any, // set below76- // Any property proxies.77- drafts_: {},78- // The base copy with any updated values.79- copy_: null,80- // Called by the `produce` function.81- revoke_: null as any,82- isManual_: false83- }84-85- // the traps must target something, a bit like the 'real' base.86- // but also, we need to be able to determine from the target what the relevant state is87- // (to avoid creating traps per instance to capture the state in closure,88- // and to avoid creating weird hidden properties as well)89- // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)90- // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb91- let target: T = state as any92- let traps: ProxyHandler<object | Array<any>> = objectTraps93- if (isArray) {94- target = [state] as any95- traps = arrayTraps96- }97-98- // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy99- // and administrate revoking ourselves100- const {revoke, proxy} = Proxy.revocable(target, traps)101- state.draft_ = proxy as any102- state.revoke_ = revoke103- return proxy as any104-}105-106-/**107- * Object drafts108- */109-const objectTraps: ProxyHandler<ProxyState> = {110- get(state, prop) {111- if (prop === DRAFT_STATE) return state112- let {drafts_: drafts} = state113-114- // Check for existing draft in unmodified state.115- if (!state.modified_ && has(drafts, prop)) {116- return drafts![prop as any]117- }118-119- const value = latest(state)[prop]120- if (state.finalized_ || !isDraftable(value)) {121- return value122- }123-124- // Check for existing draft in modified state.125- if (state.modified_) {126- // Assigned values are never drafted. This catches any drafts we created, too.127- if (value !== peek(state.base_, prop)) return value128- // Store drafts on the copy (when one exists).129- // @ts-ignore130- drafts = state.copy_131- }132-133- return (drafts![prop as any] = createProxy(134- state.scope_.immer_,135- value,136- state137- ))138- },139- has(state, prop) {140- return prop in latest(state)141- },142- ownKeys(state) {143- return Reflect.ownKeys(latest(state))144- },145- set(state, prop: string /* strictly not, but helps TS */, value) {146- if (!state.modified_) {147- const baseValue = peek(state.base_, prop)148- // Optimize based on value's truthiness. Truthy values are guaranteed to149- // never be undefined, so we can avoid the `in` operator. Lastly, truthy150- // values may be drafts, but falsy values are never drafts.151- const isUnchanged = value152- ? is(baseValue, value) || value === state.drafts_![prop]153- : is(baseValue, value) && prop in state.base_154- if (isUnchanged) return true155- prepareCopy(state)156- markChangedProxy(state)157- }158- state.assigned_[prop] = true159- // @ts-ignore160- state.copy_![prop] = value161- return true162- },163- deleteProperty(state, prop: string) {164- // The `undefined` check is a fast path for pre-existing keys.165- if (peek(state.base_, prop) !== undefined || prop in state.base_) {166- state.assigned_[prop] = false167- prepareCopy(state)168- markChangedProxy(state)169- } else if (state.assigned_[prop]) {170- // if an originally not assigned property was deleted171- delete state.assigned_[prop]172- }173- // @ts-ignore174- if (state.copy_) delete state.copy_[prop]175- return true176- },177- // Note: We never coerce `desc.value` into an Immer draft, because we can't make178- // the same guarantee in ES5 mode.179- getOwnPropertyDescriptor(state, prop) {180- const owner = latest(state)181- const desc = Reflect.getOwnPropertyDescriptor(owner, prop)182- if (desc) {183- desc.writable = true184- desc.configurable =185- state.type_ !== ProxyTypeProxyArray || prop !== "length"186- }187- return desc188- },189- defineProperty() {190- die(11)191- },192- getPrototypeOf(state) {193- return Object.getPrototypeOf(state.base_)194- },195- setPrototypeOf() {196- die(12)197- }198-}199-200-/**201- * Array drafts202- */203-204-const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}205-each(objectTraps, (key, fn) => {206- // @ts-ignore207- arrayTraps[key] = function() {208- arguments[0] = arguments[0][0]209- return fn.apply(this, arguments)210- }211-})212-arrayTraps.deleteProperty = function(state, prop) {213- if (__DEV__ && isNaN(parseInt(prop as any))) die(13)214- return objectTraps.deleteProperty!.call(this, state[0], prop)215-}216-arrayTraps.set = function(state, prop, value) {217- if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)218- return objectTraps.set!.call(this, state[0], prop, value, state[0])219-}220-221-/**222- * Map drafts223- */224-225-// Access a property without creating an Immer draft.226-function peek(draft: Drafted, prop: PropertyKey): any {227- const state = draft[DRAFT_STATE]228- const desc = Reflect.getOwnPropertyDescriptor(229- state ? latest(state) : draft,230- prop231- )232- return desc && desc.value233-}234-235-export function markChangedProxy(state: ImmerState) {236- if (!state.modified_) {237- state.modified_ = true238- if (239- state.type_ === ProxyTypeProxyObject ||240- state.type_ === ProxyTypeProxyArray241- ) {242- const copy = (state.copy_ = shallowCopy(state.base_))243- each(state.drafts_!, (key, value) => {244- // @ts-ignore245- copy[key] = value246- })247- state.drafts_ = undefined248- }249-250- if (state.parent_) {251- markChangedProxy(state.parent_)252- }253- }254-}255-256-function prepareCopy(state: ProxyState) {257- if (!state.copy_) {258- state.copy_ = shallowCopy(state.base_)259- }260-}deleted:src/scope.ts-68 removed
1-import {Patch, PatchListener, Drafted, Immer, DRAFT_STATE} from "./internal"2-import {3- ImmerState,4- ProxyTypeProxyObject,5- ProxyTypeProxyArray6-} from "./types-internal"7-8-/** Each scope represents a `produce` call. */9-// TODO: non-class?10-export class ImmerScope {11- static current_?: ImmerScope12-13- patches_?: Patch[]14- inversePatches_?: Patch[]15- canAutoFreeze_: boolean16- drafts_: any[]17- parent_?: ImmerScope18- patchListener_?: PatchListener19- immer_: Immer20- unfinalizedDrafts_ = 021-22- constructor(parent: ImmerScope | undefined, immer: Immer) {23- this.drafts_ = []24- this.parent_ = parent25- this.immer_ = immer26-27- // Whenever the modified draft contains a draft from another scope, we28- // need to prevent auto-freezing so the unowned draft can be finalized.29- this.canAutoFreeze_ = true30- }31-32- usePatches_(patchListener?: PatchListener) {33- if (patchListener) {34- this.patches_ = []35- this.inversePatches_ = []36- this.patchListener_ = patchListener37- }38- }39-40- revoke_() {41- this.leave_()42- this.drafts_.forEach(revoke)43- // @ts-ignore44- this.drafts_ = null45- }46-47- leave_() {48- if (this === ImmerScope.current_) {49- ImmerScope.current_ = this.parent_50- }51- }52-53- static enter_(immer: Immer) {54- const scope = new ImmerScope(ImmerScope.current_, immer)55- ImmerScope.current_ = scope56- return scope57- }58-}59-60-function revoke(draft: Drafted) {61- const state: ImmerState = draft[DRAFT_STATE]62- if (63- state.type_ === ProxyTypeProxyObject ||64- state.type_ === ProxyTypeProxyArray65- )66- state.revoke_()67- else state.revoked_ = true68-}deleted:src/types-external.ts-169 removed
1-import {Nothing} from "./internal"2-3-type Tail<T extends any[]> = ((...t: T) => any) extends (4- _: any,5- ...tail: infer TT6-) => any7- ? TT8- : []9-10-/** Object types that should never be mapped */11-type AtomicObject =12- | Function13- | Promise<any>14- | Date15- | RegExp16- | Boolean17- | Number18- | String19-20-/**21- * These should also never be mapped but must be tested after regular Map and22- * Set23- */24-type WeakReferences = WeakMap<any, any> | WeakSet<any>25-26-export type Draft<T> = T extends AtomicObject27- ? T28- : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap29- ? Map<Draft<K>, Draft<V>>30- : T extends ReadonlySet<infer V> // Set extends ReadonlySet31- ? Set<Draft<V>>32- : T extends WeakReferences33- ? T34- : T extends object35- ? {-readonly [K in keyof T]: Draft<T[K]>}36- : T37-38-/** Convert a mutable type into a readonly type */39-export type Immutable<T> = T extends AtomicObject40- ? T41- : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap42- ? ReadonlyMap<Immutable<K>, Immutable<V>>43- : T extends ReadonlySet<infer V> // Set extends ReadonlySet44- ? ReadonlySet<Immutable<V>>45- : T extends WeakReferences46- ? T47- : T extends object48- ? {readonly [K in keyof T]: Immutable<T[K]>}49- : T50-51-export interface Patch {52- op: "replace" | "remove" | "add"53- path: (string | number)[]54- value?: any55-}56-57-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void58-59-/** Converts `nothing` into `undefined` */60-type FromNothing<T> = T extends Nothing ? undefined : T61-62-/** The inferred return type of `produce` */63-export type Produced<Base, Return> = Return extends void64- ? Base65- : Return extends Promise<infer Result>66- ? Promise<Result extends void ? Base : FromNothing<Result>>67- : FromNothing<Return>68-69-/**70- * The `produce` function takes a value and a "recipe function" (whose71- * return value often depends on the base state). The recipe function is72- * free to mutate its first argument however it wants. All mutations are73- * only ever applied to a __copy__ of the base state.74- *75- * Pass only a function to create a "curried producer" which relieves you76- * from passing the recipe function every time.77- *78- * Only plain objects and arrays are made mutable. All other objects are79- * considered uncopyable.80- *81- * Note: This function is __bound__ to its `Immer` instance.82- *83- * @param {any} base - the initial state84- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified85- * @param {Function} patchListener - optional function that will be called with all the patches produced here86- * @returns {any} a new state, or the initial state if nothing was modified87- */88-export interface IProduce {89- /** Curried producer */90- <91- Recipe extends (...args: any[]) => any,92- Params extends any[] = Parameters<Recipe>,93- T = Params[0]94- >(95- recipe: Recipe96- ): <Base extends Immutable<T>>(97- base: Base,98- ...rest: Tail<Params>99- ) => Produced<Base, ReturnType<Recipe>>100- // ^ by making the returned type generic, the actual type of the passed in object is preferred101- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe102- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!103-104- /** Curried producer with initial state */105- <106- Recipe extends (...args: any[]) => any,107- Params extends any[] = Parameters<Recipe>,108- T = Params[0]109- >(110- recipe: Recipe,111- initialState: Immutable<T>112- ): <Base extends Immutable<T>>(113- base?: Base,114- ...rest: Tail<Params>115- ) => Produced<Base, ReturnType<Recipe>>116-117- /** Normal producer */118- <Base, D = Draft<Base>, Return = void>(119- base: Base,120- recipe: (draft: D) => Return,121- listener?: PatchListener122- ): Produced<Base, Return>123-}124-125-/**126- * Like `produce`, but instead of just returning the new state,127- * a tuple is returned with [nextState, patches, inversePatches]128- *129- * Like produce, this function supports currying130- */131-export interface IProduceWithPatches {132- /** Curried producer */133- <134- Recipe extends (...args: any[]) => any,135- Params extends any[] = Parameters<Recipe>,136- T = Params[0]137- >(138- recipe: Recipe139- ): <Base extends Immutable<T>>(140- base: Base,141- ...rest: Tail<Params>142- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]143- // ^ by making the returned type generic, the actual type of the passed in object is preferred144- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe145- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!146-147- /** Curried producer with initial state */148- <149- Recipe extends (...args: any[]) => any,150- Params extends any[] = Parameters<Recipe>,151- T = Params[0]152- >(153- recipe: Recipe,154- initialState: Immutable<T>155- ): <Base extends Immutable<T>>(156- base?: Base,157- ...rest: Tail<Params>158- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159-160- /** Normal producer */161- <Base, D = Draft<Base>, Return = void>(162- base: Base,163- recipe: (draft: D) => Return164- ): [Produced<Base, Return>, Patch[], Patch[]]165-}166-167-// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..168-// hopefully it get's tree-shaken away for everyone :)169-export function never_used() {}deleted:src/types-internal.ts-51 removed
1-import {2- SetState,3- ImmerScope,4- ProxyObjectState,5- ProxyArrayState,6- ES5ObjectState,7- ES5ArrayState,8- MapState,9- DRAFT_STATE10-} from "./internal"11-12-export type Objectish = AnyObject | AnyArray | AnyMap | AnySet13-export type ObjectishNoSet = AnyObject | AnyArray | AnyMap14-15-export type AnyObject = {[key: string]: any}16-export type AnyArray = Array<any>17-export type AnySet = Set<any>18-export type AnyMap = Map<any, any>19-20-export const ArchtypeObject = 021-export const ArchtypeArray = 122-export const ArchtypeMap = 223-export const ArchtypeSet = 324-25-export const ProxyTypeProxyObject = 026-export const ProxyTypeProxyArray = 127-export const ProxyTypeES5Object = 428-export const ProxyTypeES5Array = 529-export const ProxyTypeMap = 230-export const ProxyTypeSet = 331-32-export interface ImmerBaseState {33- parent_?: ImmerState34- scope_: ImmerScope35- modified_: boolean36- finalized_: boolean37- isManual_: boolean38-}39-40-export type ImmerState =41- | ProxyObjectState42- | ProxyArrayState43- | ES5ObjectState44- | ES5ArrayState45- | MapState46- | SetState47-48-// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)49-export type Drafted<Base = any, T extends ImmerState = ImmerState> = {50- [DRAFT_STATE]: T51-} & Basemodified:notes.txt+1 added-1 removed
112 unmodified lines113 add draft optimization114 3199115 116 invariant117-3206117+3094modified:package.json+1 added-1 removed
19 unmodified lines20 "watch": "jest --watch",21 "coverage": "jest --coverage",22 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",23 "build": "rimraf dist/ && tsdx build --name immer --format esm,cjs,umd && yarn build:flow",24- "build:flow": "cpx 'src/immer.js.flow' dist -v",24+ "build:flow": "cpx 'src/types/immer.js.flow' dist -v",25 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",26 "start": "cd website && yarn start",27 "test:size": "yarn build && yarn import-size --report . produce enableES5 enableMapSet enablePatches"28 },57 unmodified linesmodified:tsconfig.json+1 added-1 removed
13 unmodified lines14 "moduleResolution": "node",15 "module": "esnext",16 "allowJs": true17 },18- "files": ["./src/immer.ts", "./src/plugins/es5.ts", "./src/plugins/mapset.ts", "./src/plugins/patches.ts", "./src/globals.d.ts"]18+ "files": ["./src/immer.ts", "./src/plugins/es5.ts", "./src/plugins/mapset.ts", "./src/plugins/patches.ts", "src/types/globals.d.ts"]19 }