import { extend, isArray, isMap, isIntegerKey, hasOwn, isSymbol, isObject, hasChanged, makeMap, capitalize, toRawType, def, isFunction, NOOP, isString, isPromise, isOn, hyphenate, EMPTY_OBJ, toHandlerKey, toNumber, camelize, remove, isSet, isPlainObject, isBuiltInDirective, isReservedProp, EMPTY_ARR, NO, normalizeClass, normalizeStyle, toTypeString, invokeArrayFns, isModelListener } from '@vue/shared'; export { EMPTY_OBJ, camelize, normalizeClass, normalizeProps, normalizeStyle, toDisplayString, toHandlerKey } from '@vue/shared'; import { isRootHook, getValueByDataPath } from '@dcloudio/uni-shared'; function warn(msg, ...args) { console.warn(`[Vue warn] ${msg}`, ...args); } let activeEffectScope; class EffectScope { constructor(detached = false) { /** * @internal */ this.active = true; /** * @internal */ this.effects = []; /** * @internal */ this.cleanups = []; if (!detached && activeEffectScope) { this.parent = activeEffectScope; this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1; } } run(fn) { if (this.active) { const currentEffectScope = activeEffectScope; try { activeEffectScope = this; return fn(); } finally { activeEffectScope = currentEffectScope; } } else if ((process.env.NODE_ENV !== 'production')) { warn(`cannot run an inactive effect scope.`); } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this; } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent; } stop(fromParent) { if (this.active) { let i, l; for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop(); } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i](); } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true); } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes.pop(); if (last && last !== this) { this.parent.scopes[this.index] = last; last.index = this.index; } } this.active = false; } } } function effectScope(detached) { return new EffectScope(detached); } function recordEffectScope(effect, scope = activeEffectScope) { if (scope && scope.active) { scope.effects.push(effect); } } function getCurrentScope() { return activeEffectScope; } function onScopeDispose(fn) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn); } else if ((process.env.NODE_ENV !== 'production')) { warn(`onScopeDispose() is called when there is no active effect scope` + ` to be associated with.`); } } const createDep = (effects) => { const dep = new Set(effects); dep.w = 0; dep.n = 0; return dep; }; const wasTracked = (dep) => (dep.w & trackOpBit) > 0; const newTracked = (dep) => (dep.n & trackOpBit) > 0; const initDepMarkers = ({ deps }) => { if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].w |= trackOpBit; // set was tracked } } }; const finalizeDepMarkers = (effect) => { const { deps } = effect; if (deps.length) { let ptr = 0; for (let i = 0; i < deps.length; i++) { const dep = deps[i]; if (wasTracked(dep) && !newTracked(dep)) { dep.delete(effect); } else { deps[ptr++] = dep; } // clear bits dep.w &= ~trackOpBit; dep.n &= ~trackOpBit; } deps.length = ptr; } }; const targetMap = new WeakMap(); // The number of effects currently being tracked recursively. let effectTrackDepth = 0; let trackOpBit = 1; /** * The bitwise track markers support at most 30 levels of recursion. * This value is chosen to enable modern JS engines to use a SMI on all platforms. * When recursion depth is greater, fall back to using a full cleanup. */ const maxMarkerBits = 30; let activeEffect; const ITERATE_KEY = Symbol((process.env.NODE_ENV !== 'production') ? 'iterate' : ''); const MAP_KEY_ITERATE_KEY = Symbol((process.env.NODE_ENV !== 'production') ? 'Map key iterate' : ''); class ReactiveEffect { constructor(fn, scheduler = null, scope) { this.fn = fn; this.scheduler = scheduler; this.active = true; this.deps = []; this.parent = undefined; recordEffectScope(this, scope); } run() { if (!this.active) { return this.fn(); } let parent = activeEffect; let lastShouldTrack = shouldTrack; while (parent) { if (parent === this) { return; } parent = parent.parent; } try { this.parent = activeEffect; activeEffect = this; shouldTrack = true; trackOpBit = 1 << ++effectTrackDepth; if (effectTrackDepth <= maxMarkerBits) { initDepMarkers(this); } else { cleanupEffect(this); } return this.fn(); } finally { if (effectTrackDepth <= maxMarkerBits) { finalizeDepMarkers(this); } trackOpBit = 1 << --effectTrackDepth; activeEffect = this.parent; shouldTrack = lastShouldTrack; this.parent = undefined; if (this.deferStop) { this.stop(); } } } stop() { // stopped while running itself - defer the cleanup if (activeEffect === this) { this.deferStop = true; } else if (this.active) { cleanupEffect(this); if (this.onStop) { this.onStop(); } this.active = false; } } } function cleanupEffect(effect) { const { deps } = effect; if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].delete(effect); } deps.length = 0; } } function effect(fn, options) { if (fn.effect) { fn = fn.effect.fn; } const _effect = new ReactiveEffect(fn); if (options) { extend(_effect, options); if (options.scope) recordEffectScope(_effect, options.scope); } if (!options || !options.lazy) { _effect.run(); } const runner = _effect.run.bind(_effect); runner.effect = _effect; return runner; } function stop(runner) { runner.effect.stop(); } let shouldTrack = true; const trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === undefined ? true : last; } function track(target, type, key) { if (shouldTrack && activeEffect) { let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, (depsMap = new Map())); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, (dep = createDep())); } const eventInfo = (process.env.NODE_ENV !== 'production') ? { effect: activeEffect, target, type, key } : undefined; trackEffects(dep, eventInfo); } } function trackEffects(dep, debuggerEventExtraInfo) { let shouldTrack = false; if (effectTrackDepth <= maxMarkerBits) { if (!newTracked(dep)) { dep.n |= trackOpBit; // set newly tracked shouldTrack = !wasTracked(dep); } } else { // Full cleanup mode. shouldTrack = !dep.has(activeEffect); } if (shouldTrack) { dep.add(activeEffect); activeEffect.deps.push(dep); if ((process.env.NODE_ENV !== 'production') && activeEffect.onTrack) { activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo)); } } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { // never been tracked return; } let deps = []; if (type === "clear" /* CLEAR */) { // collection being cleared // trigger all effects for target deps = [...depsMap.values()]; } else if (key === 'length' && isArray(target)) { depsMap.forEach((dep, key) => { if (key === 'length' || key >= newValue) { deps.push(dep); } }); } else { // schedule runs for SET | ADD | DELETE if (key !== void 0) { deps.push(depsMap.get(key)); } // also run for iteration key on ADD | DELETE | Map.SET switch (type) { case "add" /* ADD */: if (!isArray(target)) { deps.push(depsMap.get(ITERATE_KEY)); if (isMap(target)) { deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (isIntegerKey(key)) { // new index added to array -> length changes deps.push(depsMap.get('length')); } break; case "delete" /* DELETE */: if (!isArray(target)) { deps.push(depsMap.get(ITERATE_KEY)); if (isMap(target)) { deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set" /* SET */: if (isMap(target)) { deps.push(depsMap.get(ITERATE_KEY)); } break; } } const eventInfo = (process.env.NODE_ENV !== 'production') ? { target, type, key, newValue, oldValue, oldTarget } : undefined; if (deps.length === 1) { if (deps[0]) { if ((process.env.NODE_ENV !== 'production')) { triggerEffects(deps[0], eventInfo); } else { triggerEffects(deps[0]); } } } else { const effects = []; for (const dep of deps) { if (dep) { effects.push(...dep); } } if ((process.env.NODE_ENV !== 'production')) { triggerEffects(createDep(effects), eventInfo); } else { triggerEffects(createDep(effects)); } } } function triggerEffects(dep, debuggerEventExtraInfo) { // spread into array for stabilization const effects = isArray(dep) ? dep : [...dep]; for (const effect of effects) { if (effect.computed) { triggerEffect(effect, debuggerEventExtraInfo); } } for (const effect of effects) { if (!effect.computed) { triggerEffect(effect, debuggerEventExtraInfo); } } } function triggerEffect(effect, debuggerEventExtraInfo) { if (effect !== activeEffect || effect.allowRecurse) { if ((process.env.NODE_ENV !== 'production') && effect.onTrigger) { effect.onTrigger(extend({ effect }, debuggerEventExtraInfo)); } if (effect.scheduler) { effect.scheduler(); } else { effect.run(); } } } const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`); const builtInSymbols = new Set( /*#__PURE__*/ Object.getOwnPropertyNames(Symbol) // ios10.x Object.getOwnPropertyNames(Symbol) can enumerate 'arguments' and 'caller' // but accessing them on Symbol leads to TypeError because Symbol is a strict mode // function .filter(key => key !== 'arguments' && key !== 'caller') .map(key => Symbol[key]) .filter(isSymbol)); const get = /*#__PURE__*/ createGetter(); const shallowGet = /*#__PURE__*/ createGetter(false, true); const readonlyGet = /*#__PURE__*/ createGetter(true); const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true); const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations(); function createArrayInstrumentations() { const instrumentations = {}; ['includes', 'indexOf', 'lastIndexOf'].forEach(key => { instrumentations[key] = function (...args) { const arr = toRaw(this); for (let i = 0, l = this.length; i < l; i++) { track(arr, "get" /* GET */, i + ''); } // we run the method using the original args first (which may be reactive) const res = arr[key](...args); if (res === -1 || res === false) { // if that didn't work, run it again using raw values. return arr[key](...args.map(toRaw)); } else { return res; } }; }); ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => { instrumentations[key] = function (...args) { pauseTracking(); const res = toRaw(this)[key].apply(this, args); resetTracking(); return res; }; }); return instrumentations; } function createGetter(isReadonly = false, shallow = false) { return function get(target, key, receiver) { if (key === "__v_isReactive" /* IS_REACTIVE */) { return !isReadonly; } else if (key === "__v_isReadonly" /* IS_READONLY */) { return isReadonly; } else if (key === "__v_isShallow" /* IS_SHALLOW */) { return shallow; } else if (key === "__v_raw" /* RAW */ && receiver === (isReadonly ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { return target; } const targetIsArray = isArray(target); if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly) { track(target, "get" /* GET */, key); } if (shallow) { return res; } if (isRef(res)) { // ref unwrapping - skip unwrap for Array + integer key. return targetIsArray && isIntegerKey(key) ? res : res.value; } if (isObject(res)) { // Convert returned value into a proxy as well. we do the isObject check // here to avoid invalid value warning. Also need to lazy access readonly // and reactive here to avoid circular dependency. return isReadonly ? readonly(res) : reactive(res); } return res; }; } const set = /*#__PURE__*/ createSetter(); const shallowSet = /*#__PURE__*/ createSetter(true); function createSetter(shallow = false) { return function set(target, key, value, receiver) { let oldValue = target[key]; if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) { return false; } if (!shallow && !isReadonly(value)) { if (!isShallow(value)) { value = toRaw(value); oldValue = toRaw(oldValue); } if (!isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); // don't trigger if target is something up in the prototype chain of original if (target === toRaw(receiver)) { if (!hadKey) { trigger(target, "add" /* ADD */, key, value); } else if (hasChanged(value, oldValue)) { trigger(target, "set" /* SET */, key, value, oldValue); } } return result; }; } function deleteProperty(target, key) { const hadKey = hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete" /* DELETE */, key, undefined, oldValue); } return result; } function has(target, key) { const result = Reflect.has(target, key); if (!isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has" /* HAS */, key); } return result; } function ownKeys(target) { track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY); return Reflect.ownKeys(target); } const mutableHandlers = { get, set, deleteProperty, has, ownKeys }; const readonlyHandlers = { get: readonlyGet, set(target, key) { if ((process.env.NODE_ENV !== 'production')) { warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { if ((process.env.NODE_ENV !== 'production')) { warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); // Props handlers are special in the sense that it should not unwrap top-level // refs (in order to allow refs to be explicitly passed down), but should // retain the reactivity of the normal readonly object. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, { get: shallowReadonlyGet }); const toShallow = (value) => value; const getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly = false, isShallow = false) { // #1772: readonly(reactive(Map)) should return readonly + reactive version // of the value target = target["__v_raw" /* RAW */]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!isReadonly) { if (key !== rawKey) { track(rawTarget, "get" /* GET */, key); } track(rawTarget, "get" /* GET */, rawKey); } const { has } = getProto(rawTarget); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; if (has.call(rawTarget, key)) { return wrap(target.get(key)); } else if (has.call(rawTarget, rawKey)) { return wrap(target.get(rawKey)); } else if (target !== rawTarget) { // #3602 readonly(reactive(Map)) // ensure that the nested reactive `Map` can do tracking for itself target.get(key); } } function has$1(key, isReadonly = false) { const target = this["__v_raw" /* RAW */]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!isReadonly) { if (key !== rawKey) { track(rawTarget, "has" /* HAS */, key); } track(rawTarget, "has" /* HAS */, rawKey); } return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } function size(target, isReadonly = false) { target = target["__v_raw" /* RAW */]; !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY); return Reflect.get(target, 'size', target); } function add(value) { value = toRaw(value); const target = toRaw(this); const proto = getProto(target); const hadKey = proto.has.call(target, value); if (!hadKey) { target.add(value); trigger(target, "add" /* ADD */, value, value); } return this; } function set$1(key, value) { value = toRaw(value); const target = toRaw(this); const { has, get } = getProto(target); let hadKey = has.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has.call(target, key); } else if ((process.env.NODE_ENV !== 'production')) { checkIdentityKeys(target, has, key); } const oldValue = get.call(target, key); target.set(key, value); if (!hadKey) { trigger(target, "add" /* ADD */, key, value); } else if (hasChanged(value, oldValue)) { trigger(target, "set" /* SET */, key, value, oldValue); } return this; } function deleteEntry(key) { const target = toRaw(this); const { has, get } = getProto(target); let hadKey = has.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has.call(target, key); } else if ((process.env.NODE_ENV !== 'production')) { checkIdentityKeys(target, has, key); } const oldValue = get ? get.call(target, key) : undefined; // forward the operation before queueing reactions const result = target.delete(key); if (hadKey) { trigger(target, "delete" /* DELETE */, key, undefined, oldValue); } return result; } function clear() { const target = toRaw(this); const hadItems = target.size !== 0; const oldTarget = (process.env.NODE_ENV !== 'production') ? isMap(target) ? new Map(target) : new Set(target) : undefined; // forward the operation before queueing reactions const result = target.clear(); if (hadItems) { trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget); } return result; } function createForEach(isReadonly, isShallow) { return function forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw" /* RAW */]; const rawTarget = toRaw(target); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY); return target.forEach((value, key) => { // important: make sure the callback is // 1. invoked with the reactive map as `this` and 3rd arg // 2. the value received should be a corresponding reactive/readonly. return callback.call(thisArg, wrap(value), wrap(key), observed); }); }; } function createIterableMethod(method, isReadonly, isShallow) { return function (...args) { const target = this["__v_raw" /* RAW */]; const rawTarget = toRaw(target); const targetIsMap = isMap(rawTarget); const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap); const isKeyOnly = method === 'keys' && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; !isReadonly && track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); // return a wrapped iterator which returns observed versions of the // values emitted from the real iterator return { // iterator protocol next() { const { value, done } = innerIterator.next(); return done ? { value, done } : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; }, // iterable protocol [Symbol.iterator]() { return this; } }; }; } function createReadonlyMethod(type) { return function (...args) { if ((process.env.NODE_ENV !== 'production')) { const key = args[0] ? `on key "${args[0]}" ` : ``; console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this)); } return type === "delete" /* DELETE */ ? false : this; }; } function createInstrumentations() { const mutableInstrumentations = { get(key) { return get$1(this, key); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, false) }; const shallowInstrumentations = { get(key) { return get$1(this, key, false, true); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, true) }; const readonlyInstrumentations = { get(key) { return get$1(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add" /* ADD */), set: createReadonlyMethod("set" /* SET */), delete: createReadonlyMethod("delete" /* DELETE */), clear: createReadonlyMethod("clear" /* CLEAR */), forEach: createForEach(true, false) }; const shallowReadonlyInstrumentations = { get(key) { return get$1(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add" /* ADD */), set: createReadonlyMethod("set" /* SET */), delete: createReadonlyMethod("delete" /* DELETE */), clear: createReadonlyMethod("clear" /* CLEAR */), forEach: createForEach(true, true) }; const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]; iteratorMethods.forEach(method => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true); }); return [ mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations ]; } const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations(); function createInstrumentationGetter(isReadonly, shallow) { const instrumentations = shallow ? isReadonly ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive" /* IS_REACTIVE */) { return !isReadonly; } else if (key === "__v_isReadonly" /* IS_READONLY */) { return isReadonly; } else if (key === "__v_raw" /* RAW */) { return target; } return Reflect.get(hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } const mutableCollectionHandlers = { get: /*#__PURE__*/ createInstrumentationGetter(false, false) }; const shallowCollectionHandlers = { get: /*#__PURE__*/ createInstrumentationGetter(false, true) }; const readonlyCollectionHandlers = { get: /*#__PURE__*/ createInstrumentationGetter(true, false) }; const shallowReadonlyCollectionHandlers = { get: /*#__PURE__*/ createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has, key) { const rawKey = toRaw(key); if (rawKey !== key && has.call(target, rawKey)) { const type = toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive ` + `versions of the same object${type === `Map` ? ` as keys` : ``}, ` + `which can lead to inconsistencies. ` + `Avoid differentiating between the raw and reactive versions ` + `of an object and only use the reactive version if possible.`); } } const reactiveMap = new WeakMap(); const shallowReactiveMap = new WeakMap(); const readonlyMap = new WeakMap(); const shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case 'Object': case 'Array': return 1 /* COMMON */; case 'Map': case 'Set': case 'WeakMap': case 'WeakSet': return 2 /* COLLECTION */; default: return 0 /* INVALID */; } } function getTargetType(value) { return value["__v_skip" /* SKIP */] || !Object.isExtensible(value) ? 0 /* INVALID */ : targetTypeMap(toRawType(value)); } function reactive(target) { // if trying to observe a readonly proxy, return the readonly version. if (isReadonly(target)) { return target; } return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } /** * Return a shallowly-reactive copy of the original object, where only the root * level properties are reactive. It also does not auto-unwrap refs (even at the * root level). */ function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); } /** * Creates a readonly copy of the original object. Note the returned copy is not * made reactive, but `readonly` can be called on an already reactive object. */ function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } /** * Returns a reactive-copy of the original object, where only the root level * properties are readonly, and does NOT unwrap refs nor recursively convert * returned properties. * This is used for creating the props proxy object for stateful components. */ function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) { if (!isObject(target)) { if ((process.env.NODE_ENV !== 'production')) { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; } // target is already a Proxy, return it. // exception: calling readonly() on a reactive object if (target["__v_raw" /* RAW */] && !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) { return target; } // target already has corresponding Proxy const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } // only specific value types can be observed. const targetType = getTargetType(target); if (targetType === 0 /* INVALID */) { return target; } const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } function isReactive(value) { if (isReadonly(value)) { return isReactive(value["__v_raw" /* RAW */]); } return !!(value && value["__v_isReactive" /* IS_REACTIVE */]); } function isReadonly(value) { return !!(value && value["__v_isReadonly" /* IS_READONLY */]); } function isShallow(value) { return !!(value && value["__v_isShallow" /* IS_SHALLOW */]); } function isProxy(value) { return isReactive(value) || isReadonly(value); } function toRaw(observed) { const raw = observed && observed["__v_raw" /* RAW */]; return raw ? toRaw(raw) : observed; } function markRaw(value) { def(value, "__v_skip" /* SKIP */, true); return value; } const toReactive = (value) => isObject(value) ? reactive(value) : value; const toReadonly = (value) => isObject(value) ? readonly(value) : value; function trackRefValue(ref) { if (shouldTrack && activeEffect) { ref = toRaw(ref); if ((process.env.NODE_ENV !== 'production')) { trackEffects(ref.dep || (ref.dep = createDep()), { target: ref, type: "get" /* GET */, key: 'value' }); } else { trackEffects(ref.dep || (ref.dep = createDep())); } } } function triggerRefValue(ref, newVal) { ref = toRaw(ref); if (ref.dep) { if ((process.env.NODE_ENV !== 'production')) { triggerEffects(ref.dep, { target: ref, type: "set" /* SET */, key: 'value', newValue: newVal }); } else { triggerEffects(ref.dep); } } } function isRef(r) { return !!(r && r.__v_isRef === true); } function ref(value) { return createRef(value, false); } function shallowRef(value) { return createRef(value, true); } function createRef(rawValue, shallow) { if (isRef(rawValue)) { return rawValue; } return new RefImpl(rawValue, shallow); } class RefImpl { constructor(value, __v_isShallow) { this.__v_isShallow = __v_isShallow; this.dep = undefined; this.__v_isRef = true; this._rawValue = __v_isShallow ? value : toRaw(value); this._value = __v_isShallow ? value : toReactive(value); } get value() { trackRefValue(this); return this._value; } set value(newVal) { newVal = this.__v_isShallow ? newVal : toRaw(newVal); if (hasChanged(newVal, this._rawValue)) { this._rawValue = newVal; this._value = this.__v_isShallow ? newVal : toReactive(newVal); triggerRefValue(this, newVal); } } } function triggerRef(ref) { triggerRefValue(ref, (process.env.NODE_ENV !== 'production') ? ref.value : void 0); } function unref(ref) { return isRef(ref) ? ref.value : ref; } const shallowUnwrapHandlers = { get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } else { return Reflect.set(target, key, value, receiver); } } }; function proxyRefs(objectWithRefs) { return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } class CustomRefImpl { constructor(factory) { this.dep = undefined; this.__v_isRef = true; const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this)); this._get = get; this._set = set; } get value() { return this._get(); } set value(newVal) { this._set(newVal); } } function customRef(factory) { return new CustomRefImpl(factory); } function toRefs(object) { if ((process.env.NODE_ENV !== 'production') && !isProxy(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`); } const ret = isArray(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = toRef(object, key); } return ret; } class ObjectRefImpl { constructor(_object, _key, _defaultValue) { this._object = _object; this._key = _key; this._defaultValue = _defaultValue; this.__v_isRef = true; } get value() { const val = this._object[this._key]; return val === undefined ? this._defaultValue : val; } set value(newVal) { this._object[this._key] = newVal; } } function toRef(object, key, defaultValue) { const val = object[key]; return isRef(val) ? val : new ObjectRefImpl(object, key, defaultValue); } class ComputedRefImpl { constructor(getter, _setter, isReadonly, isSSR) { this._setter = _setter; this.dep = undefined; this.__v_isRef = true; this._dirty = true; this.effect = new ReactiveEffect(getter, () => { if (!this._dirty) { this._dirty = true; triggerRefValue(this); } }); this.effect.computed = this; this.effect.active = this._cacheable = !isSSR; this["__v_isReadonly" /* IS_READONLY */] = isReadonly; } get value() { // the computed ref may get wrapped by other proxies e.g. readonly() #3376 const self = toRaw(this); trackRefValue(self); if (self._dirty || !self._cacheable) { self._dirty = false; self._value = self.effect.run(); } return self._value; } set value(newValue) { this._setter(newValue); } } function computed(getterOrOptions, debugOptions, isSSR = false) { let getter; let setter; const onlyGetter = isFunction(getterOrOptions); if (onlyGetter) { getter = getterOrOptions; setter = (process.env.NODE_ENV !== 'production') ? () => { console.warn('Write operation failed: computed value is readonly'); } : NOOP; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); if ((process.env.NODE_ENV !== 'production') && debugOptions && !isSSR) { cRef.effect.onTrack = debugOptions.onTrack; cRef.effect.onTrigger = debugOptions.onTrigger; } return cRef; } const stack = []; function pushWarningContext(vnode) { stack.push(vnode); } function popWarningContext() { stack.pop(); } function warn$1(msg, ...args) { // avoid props formatting or warn handler tracking deps that might be mutated // during patch, leading to infinite recursion. pauseTracking(); const instance = stack.length ? stack[stack.length - 1].component : null; const appWarnHandler = instance && instance.appContext.config.warnHandler; const trace = getComponentTrace(); if (appWarnHandler) { callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [ msg + args.join(''), instance && instance.proxy, trace .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`) .join('\n'), trace ]); } else { const warnArgs = [`[Vue warn]: ${msg}`, ...args]; /* istanbul ignore if */ if (trace.length && // avoid spamming console during tests !false) { warnArgs.push(`\n`, ...formatTrace(trace)); } console.warn(...warnArgs); } resetTracking(); } function getComponentTrace() { let currentVNode = stack[stack.length - 1]; if (!currentVNode) { return []; } // we can't just use the stack because it will be incomplete during updates // that did not start from the root. Re-construct the parent chain using // instance parent pointers. const normalizedStack = []; while (currentVNode) { const last = normalizedStack[0]; if (last && last.vnode === currentVNode) { last.recurseCount++; } else { normalizedStack.push({ vnode: currentVNode, recurseCount: 0 }); } const parentInstance = currentVNode.component && currentVNode.component.parent; currentVNode = parentInstance && parentInstance.vnode; } return normalizedStack; } /* istanbul ignore next */ function formatTrace(trace) { const logs = []; trace.forEach((entry, i) => { logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry)); }); return logs; } function formatTraceEntry({ vnode, recurseCount }) { const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; const isRoot = vnode.component ? vnode.component.parent == null : false; const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`; const close = `>` + postfix; return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; } /* istanbul ignore next */ function formatProps(props) { const res = []; const keys = Object.keys(props); keys.slice(0, 3).forEach(key => { res.push(...formatProp(key, props[key])); }); if (keys.length > 3) { res.push(` ...`); } return res; } /* istanbul ignore next */ function formatProp(key, value, raw) { if (isString(value)) { value = JSON.stringify(value); return raw ? value : [`${key}=${value}`]; } else if (typeof value === 'number' || typeof value === 'boolean' || value == null) { return raw ? value : [`${key}=${value}`]; } else if (isRef(value)) { value = formatProp(key, toRaw(value.value), true); return raw ? value : [`${key}=Ref<`, value, `>`]; } else if (isFunction(value)) { return [`${key}=fn${value.name ? `<${value.name}>` : ``}`]; } else { value = toRaw(value); return raw ? value : [`${key}=`, value]; } } const ErrorTypeStrings = { ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook', ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook', ["c" /* CREATED */]: 'created hook', ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook', ["m" /* MOUNTED */]: 'mounted hook', ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook', ["u" /* UPDATED */]: 'updated', ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook', ["um" /* UNMOUNTED */]: 'unmounted hook', ["a" /* ACTIVATED */]: 'activated hook', ["da" /* DEACTIVATED */]: 'deactivated hook', ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook', ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook', ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook', [0 /* SETUP_FUNCTION */]: 'setup function', [1 /* RENDER_FUNCTION */]: 'render function', [2 /* WATCH_GETTER */]: 'watcher getter', [3 /* WATCH_CALLBACK */]: 'watcher callback', [4 /* WATCH_CLEANUP */]: 'watcher cleanup function', [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler', [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler', [7 /* VNODE_HOOK */]: 'vnode hook', [8 /* DIRECTIVE_HOOK */]: 'directive hook', [9 /* TRANSITION_HOOK */]: 'transition hook', [10 /* APP_ERROR_HANDLER */]: 'app errorHandler', [11 /* APP_WARN_HANDLER */]: 'app warnHandler', [12 /* FUNCTION_REF */]: 'ref function', [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader', [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' + 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core' }; function callWithErrorHandling(fn, instance, type, args) { let res; try { res = args ? fn(...args) : fn(); } catch (err) { handleError(err, instance, type); } return res; } function callWithAsyncErrorHandling(fn, instance, type, args) { if (isFunction(fn)) { const res = callWithErrorHandling(fn, instance, type, args); if (res && isPromise(res)) { res.catch(err => { handleError(err, instance, type); }); } return res; } const values = []; for (let i = 0; i < fn.length; i++) { values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); } return values; } function handleError(err, instance, type, throwInDev = true) { const contextVNode = instance ? instance.vnode : null; if (instance) { let cur = instance.parent; // the exposed instance is the render proxy to keep it consistent with 2.x const exposedInstance = instance.proxy; // in production the hook receives only the error code const errorInfo = (process.env.NODE_ENV !== 'production') ? ErrorTypeStrings[type] || type : type; // fixed by xxxxxxx while (cur) { const errorCapturedHooks = cur.ec; if (errorCapturedHooks) { for (let i = 0; i < errorCapturedHooks.length; i++) { if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { return; } } } cur = cur.parent; } // app-level handling const appErrorHandler = instance.appContext.config.errorHandler; if (appErrorHandler) { callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]); return; } } logError(err, type, contextVNode, throwInDev); } // fixed by xxxxxx function logError(err, type, contextVNode, throwInDev = true) { if ((process.env.NODE_ENV !== 'production')) { const info = ErrorTypeStrings[type] || type; // fixed by xxxxxx if (contextVNode) { pushWarningContext(contextVNode); } warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); if (contextVNode) { popWarningContext(); } // crash in dev by default so it's more noticeable if (throwInDev) { // throw err fixed by xxxxxx 避免 error 导致 小程序 端不可用(比如跳转时报错) console.error(err); } else { console.error(err); } } else { // recover in prod to reduce the impact on end-user console.error(err); } } let isFlushing = false; let isFlushPending = false; // fixed by xxxxxx const queue = []; let flushIndex = 0; const pendingPreFlushCbs = []; let activePreFlushCbs = null; let preFlushIndex = 0; const pendingPostFlushCbs = []; let activePostFlushCbs = null; let postFlushIndex = 0; const resolvedPromise = /*#__PURE__*/ Promise.resolve(); let currentFlushPromise = null; let currentPreFlushParentJob = null; const RECURSION_LIMIT = 100; function nextTick(fn) { const p = currentFlushPromise || resolvedPromise; return fn ? p.then(this ? fn.bind(this) : fn) : p; } // #2768 // Use binary-search to find a suitable position in the queue, // so that the queue maintains the increasing order of job's id, // which can prevent the job from being skipped and also can avoid repeated patching. function findInsertionIndex(id) { // the start index should be `flushIndex + 1` let start = flushIndex + 1; let end = queue.length; while (start < end) { const middle = (start + end) >>> 1; const middleJobId = getId(queue[middle]); middleJobId < id ? (start = middle + 1) : (end = middle); } return start; } function queueJob(job) { // the dedupe search uses the startIndex argument of Array.includes() // by default the search index includes the current job that is being run // so it cannot recursively trigger itself again. // if the job is a watch() callback, the search will start with a +1 index to // allow it recursively trigger itself - it is the user's responsibility to // ensure it doesn't end up in an infinite loop. if ((!queue.length || !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) && job !== currentPreFlushParentJob) { if (job.id == null) { queue.push(job); } else { queue.splice(findInsertionIndex(job.id), 0, job); } queueFlush(); } } function queueFlush() { if (!isFlushing && !isFlushPending) { isFlushPending = true; currentFlushPromise = resolvedPromise.then(flushJobs); } } function invalidateJob(job) { const i = queue.indexOf(job); if (i > flushIndex) { queue.splice(i, 1); } // fixed by xxxxxx return i; } function queueCb(cb, activeQueue, pendingQueue, index) { if (!isArray(cb)) { if (!activeQueue || !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) { pendingQueue.push(cb); } } else { // if cb is an array, it is a component lifecycle hook which can only be // triggered by a job, which is already deduped in the main queue, so // we can skip duplicate check here to improve perf pendingQueue.push(...cb); } queueFlush(); } function queuePreFlushCb(cb) { queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex); } function queuePostFlushCb(cb) { queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex); } function flushPreFlushCbs(seen, parentJob = null) { if (pendingPreFlushCbs.length) { currentPreFlushParentJob = parentJob; activePreFlushCbs = [...new Set(pendingPreFlushCbs)]; pendingPreFlushCbs.length = 0; if ((process.env.NODE_ENV !== 'production')) { seen = seen || new Map(); } for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) { if ((process.env.NODE_ENV !== 'production') && checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) { continue; } activePreFlushCbs[preFlushIndex](); } activePreFlushCbs = null; preFlushIndex = 0; currentPreFlushParentJob = null; // recursively flush until it drains flushPreFlushCbs(seen, parentJob); } } function flushPostFlushCbs(seen) { // flush any pre cbs queued during the flush (e.g. pre watchers) flushPreFlushCbs(); if (pendingPostFlushCbs.length) { const deduped = [...new Set(pendingPostFlushCbs)]; pendingPostFlushCbs.length = 0; // #1947 already has active queue, nested flushPostFlushCbs call if (activePostFlushCbs) { activePostFlushCbs.push(...deduped); return; } activePostFlushCbs = deduped; if ((process.env.NODE_ENV !== 'production')) { seen = seen || new Map(); } activePostFlushCbs.sort((a, b) => getId(a) - getId(b)); for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { if ((process.env.NODE_ENV !== 'production') && checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) { continue; } activePostFlushCbs[postFlushIndex](); } activePostFlushCbs = null; postFlushIndex = 0; } } const getId = (job) => job.id == null ? Infinity : job.id; function flushJobs(seen) { isFlushPending = false; isFlushing = true; if ((process.env.NODE_ENV !== 'production')) { seen = seen || new Map(); } flushPreFlushCbs(seen); // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child so its render effect will have smaller // priority number) // 2. If a component is unmounted during a parent component's update, // its update can be skipped. queue.sort((a, b) => getId(a) - getId(b)); // conditional usage of checkRecursiveUpdate must be determined out of // try ... catch block since Rollup by default de-optimizes treeshaking // inside try-catch. This can leave all warning code unshaked. Although // they would get eventually shaken by a minifier like terser, some minifiers // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610) const check = (process.env.NODE_ENV !== 'production') ? (job) => checkRecursiveUpdates(seen, job) : NOOP; try { for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { const job = queue[flushIndex]; if (job && job.active !== false) { if ((process.env.NODE_ENV !== 'production') && check(job)) { continue; } // console.log(`running:`, job.id) callWithErrorHandling(job, null, 14 /* SCHEDULER */); } } } finally { flushIndex = 0; queue.length = 0; flushPostFlushCbs(seen); isFlushing = false; currentFlushPromise = null; // some postFlushCb queued jobs! // keep flushing until it drains. if (queue.length || pendingPreFlushCbs.length || pendingPostFlushCbs.length) { flushJobs(seen); } } } function checkRecursiveUpdates(seen, fn) { if (!seen.has(fn)) { seen.set(fn, 1); } else { const count = seen.get(fn); if (count > RECURSION_LIMIT) { const instance = fn.ownerInstance; const componentName = instance && getComponentName(instance.type); warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` + `This means you have a reactive effect that is mutating its own ` + `dependencies and thus recursively triggering itself. Possible sources ` + `include component template, render function, updated hook or ` + `watcher source function.`); return true; } else { seen.set(fn, count + 1); } } } function emit(event, ...args) { } const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */); function createDevtoolsComponentHook(hook) { return (component) => { emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component); }; } function devtoolsComponentEmit(component, event, params) { emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params); } function emit$1(instance, event, ...rawArgs) { if (instance.isUnmounted) return; const props = instance.vnode.props || EMPTY_OBJ; if ((process.env.NODE_ENV !== 'production')) { const { emitsOptions, propsOptions: [propsOptions] } = instance; if (emitsOptions) { if (!(event in emitsOptions) && !(false )) { if (!propsOptions || !(toHandlerKey(event) in propsOptions)) { warn$1(`Component emitted event "${event}" but it is neither declared in ` + `the emits option nor as an "${toHandlerKey(event)}" prop.`); } } else { const validator = emitsOptions[event]; if (isFunction(validator)) { const isValid = validator(...rawArgs); if (!isValid) { warn$1(`Invalid event arguments: event validation failed for event "${event}".`); } } } } } let args = rawArgs; const isModelListener = event.startsWith('update:'); // for v-model update:xxx events, apply modifiers on args const modelArg = isModelListener && event.slice(7); if (modelArg && modelArg in props) { const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`; const { number, trim } = props[modifiersKey] || EMPTY_OBJ; if (trim) { args = rawArgs.map(a => a.trim()); } if (number) { args = rawArgs.map(toNumber); } } if ((process.env.NODE_ENV !== 'production') || false) { devtoolsComponentEmit(instance, event, args); } if ((process.env.NODE_ENV !== 'production')) { const lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) { warn$1(`Event "${lowerCaseEvent}" is emitted in component ` + `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` + `Note that HTML attributes are case-insensitive and you cannot use ` + `v-on to listen to camelCase events when using in-DOM templates. ` + `You should probably use "${hyphenate(event)}" instead of "${event}".`); } } let handlerName; let handler = props[(handlerName = toHandlerKey(event))] || // also try camelCase event handler (#2249) props[(handlerName = toHandlerKey(camelize(event)))]; // for v-model update:xxx events, also trigger kebab-case equivalent // for props passed via kebab-case if (!handler && isModelListener) { handler = props[(handlerName = toHandlerKey(hyphenate(event)))]; } if (handler) { callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args); } const onceHandler = props[handlerName + `Once`]; if (onceHandler) { if (!instance.emitted) { instance.emitted = {}; } else if (instance.emitted[handlerName]) { return; } instance.emitted[handlerName] = true; callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args); } } function normalizeEmitsOptions(comp, appContext, asMixin = false) { const cache = appContext.emitsCache; const cached = cache.get(comp); if (cached !== undefined) { return cached; } const raw = comp.emits; let normalized = {}; // apply mixin/extends props let hasExtends = false; if (__VUE_OPTIONS_API__ && !isFunction(comp)) { const extendEmits = (raw) => { const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true); if (normalizedFromExtend) { hasExtends = true; extend(normalized, normalizedFromExtend); } }; if (!asMixin && appContext.mixins.length) { appContext.mixins.forEach(extendEmits); } if (comp.extends) { extendEmits(comp.extends); } if (comp.mixins) { comp.mixins.forEach(extendEmits); } } if (!raw && !hasExtends) { cache.set(comp, null); return null; } if (isArray(raw)) { raw.forEach(key => (normalized[key] = null)); } else { extend(normalized, raw); } cache.set(comp, normalized); return normalized; } // Check if an incoming prop key is a declared emit event listener. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are // both considered matched listeners. function isEmitListener(options, key) { if (!options || !isOn(key)) { return false; } key = key.slice(2).replace(/Once$/, ''); return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key)); } /** * mark the current rendering instance for asset resolution (e.g. * resolveComponent, resolveDirective) during render */ let currentRenderingInstance = null; let currentScopeId = null; /** * Note: rendering calls maybe nested. The function returns the parent rendering * instance if present, which should be restored after the render is done: * * ```js * const prev = setCurrentRenderingInstance(i) * // ...render * setCurrentRenderingInstance(prev) * ``` */ function setCurrentRenderingInstance(instance) { const prev = currentRenderingInstance; currentRenderingInstance = instance; currentScopeId = (instance && instance.type.__scopeId) || null; return prev; } /** * Only for backwards compat * @private */ const withScopeId = (_id) => withCtx; /** * Wrap a slot function to memoize current rendering instance * @private compiler helper */ function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only ) { if (!ctx) return fn; // already normalized if (fn._n) { return fn; } const renderFnWithContext = (...args) => { // If a user calls a compiled slot inside a template expression (#1745), it // can mess up block tracking, so by default we disable block tracking and // force bail out when invoking a compiled slot (indicated by the ._d flag). // This isn't necessary if rendering a compiled ``, so we flip the // ._d flag off when invoking the wrapped fn inside `renderSlot`. if (renderFnWithContext._d) { setBlockTracking(-1); } const prevInstance = setCurrentRenderingInstance(ctx); const res = fn(...args); setCurrentRenderingInstance(prevInstance); if (renderFnWithContext._d) { setBlockTracking(1); } if ((process.env.NODE_ENV !== 'production') || false) { devtoolsComponentUpdated(ctx); } return res; }; // mark normalized to avoid duplicated wrapping renderFnWithContext._n = true; // mark this as compiled by default // this is used in vnode.ts -> normalizeChildren() to set the slot // rendering flag. renderFnWithContext._c = true; // disable block tracking by default renderFnWithContext._d = true; return renderFnWithContext; } function markAttrsAccessed() { } function provide(key, value) { if (!currentInstance) { if ((process.env.NODE_ENV !== 'production')) { warn$1(`provide() can only be used inside setup().`); } } else { let provides = currentInstance.provides; // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides; if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides); } // TS doesn't allow symbol as index type provides[key] = value; // 当实例为 App 时,同步到全局 provide if (currentInstance.type.mpType === 'app') { currentInstance.appContext.app.provide(key, value); } } } function inject(key, defaultValue, treatDefaultAsFactory = false) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance; if (instance) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the instance is at root const provides = instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides; if (provides && key in provides) { // TS doesn't allow symbol as index type return provides[key]; } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance.proxy) : defaultValue; } else if ((process.env.NODE_ENV !== 'production')) { warn$1(`injection "${String(key)}" not found.`); } } else if ((process.env.NODE_ENV !== 'production')) { warn$1(`inject() can only be used inside setup() or functional components.`); } } // Simple effect. function watchEffect(effect, options) { return doWatch(effect, null, options); } function watchPostEffect(effect, options) { return doWatch(effect, null, ((process.env.NODE_ENV !== 'production') ? Object.assign(Object.assign({}, options), { flush: 'post' }) : { flush: 'post' })); } function watchSyncEffect(effect, options) { return doWatch(effect, null, ((process.env.NODE_ENV !== 'production') ? Object.assign(Object.assign({}, options), { flush: 'sync' }) : { flush: 'sync' })); } // initial value for watchers to trigger on undefined initial values const INITIAL_WATCHER_VALUE = {}; // implementation function watch(source, cb, options) { if ((process.env.NODE_ENV !== 'production') && !isFunction(cb)) { warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` + `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` + `supports \`watch(source, cb, options?) signature.`); } return doWatch(source, cb, options); } function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) { if ((process.env.NODE_ENV !== 'production') && !cb) { if (immediate !== undefined) { warn$1(`watch() "immediate" option is only respected when using the ` + `watch(source, callback, options?) signature.`); } if (deep !== undefined) { warn$1(`watch() "deep" option is only respected when using the ` + `watch(source, callback, options?) signature.`); } } const warnInvalidSource = (s) => { warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` + `a reactive object, or an array of these types.`); }; const instance = currentInstance; let getter; let forceTrigger = false; let isMultiSource = false; if (isRef(source)) { getter = () => source.value; forceTrigger = isShallow(source); } else if (isReactive(source)) { getter = () => source; deep = true; } else if (isArray(source)) { isMultiSource = true; forceTrigger = source.some(s => isReactive(s) || isShallow(s)); getter = () => source.map(s => { if (isRef(s)) { return s.value; } else if (isReactive(s)) { return traverse(s); } else if (isFunction(s)) { return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */); } else { (process.env.NODE_ENV !== 'production') && warnInvalidSource(s); } }); } else if (isFunction(source)) { if (cb) { // getter with cb getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */); } else { // no cb -> simple effect getter = () => { if (instance && instance.isUnmounted) { return; } if (cleanup) { cleanup(); } return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]); }; } } else { getter = NOOP; (process.env.NODE_ENV !== 'production') && warnInvalidSource(source); } if (cb && deep) { const baseGetter = getter; getter = () => traverse(baseGetter()); } let cleanup; let onCleanup = (fn) => { cleanup = effect.onStop = () => { callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */); }; }; let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE; const job = () => { if (!effect.active) { return; } if (cb) { // watch(source, cb) const newValue = effect.run(); if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue)) || (false )) { // cleanup before running cb again if (cleanup) { cleanup(); } callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [ newValue, // pass undefined as the old value when it's changed for the first time oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue, onCleanup ]); oldValue = newValue; } } else { // watchEffect effect.run(); } }; // important: mark the job as a watcher callback so that scheduler knows // it is allowed to self-trigger (#1727) job.allowRecurse = !!cb; let scheduler; if (flush === 'sync') { scheduler = job; // the scheduler function gets called directly } else if (flush === 'post') { scheduler = () => queuePostRenderEffect(job, instance && instance.suspense); } else { // default: 'pre' scheduler = () => queuePreFlushCb(job); } const effect = new ReactiveEffect(getter, scheduler); if ((process.env.NODE_ENV !== 'production')) { effect.onTrack = onTrack; effect.onTrigger = onTrigger; } // initial run if (cb) { if (immediate) { job(); } else { oldValue = effect.run(); } } else if (flush === 'post') { queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense); } else { effect.run(); } return () => { effect.stop(); if (instance && instance.scope) { remove(instance.scope.effects, effect); } }; } // this.$watch function instanceWatch(source, value, options) { const publicThis = this.proxy; const getter = isString(source) ? source.includes('.') ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); let cb; if (isFunction(value)) { cb = value; } else { cb = value.handler; options = value; } const cur = currentInstance; setCurrentInstance(this); const res = doWatch(getter, cb.bind(publicThis), options); if (cur) { setCurrentInstance(cur); } else { unsetCurrentInstance(); } return res; } function createPathGetter(ctx, path) { const segments = path.split('.'); return () => { let cur = ctx; for (let i = 0; i < segments.length && cur; i++) { cur = cur[segments[i]]; } return cur; }; } function traverse(value, seen) { if (!isObject(value) || value["__v_skip" /* SKIP */]) { return value; } seen = seen || new Set(); if (seen.has(value)) { return value; } seen.add(value); if (isRef(value)) { traverse(value.value, seen); } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { traverse(value[i], seen); } } else if (isSet(value) || isMap(value)) { value.forEach((v) => { traverse(v, seen); }); } else if (isPlainObject(value)) { for (const key in value) { traverse(value[key], seen); } } return value; } // implementation, close to no-op function defineComponent(options) { return isFunction(options) ? { setup: options, name: options.name } : options; } const isKeepAlive = (vnode) => vnode.type.__isKeepAlive; function onActivated(hook, target) { registerKeepAliveHook(hook, "a" /* ACTIVATED */, target); } function onDeactivated(hook, target) { registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target); } function registerKeepAliveHook(hook, type, target = currentInstance) { // cache the deactivate branch check wrapper for injected hooks so the same // hook can be properly deduped by the scheduler. "__wdc" stands for "with // deactivation check". const wrappedHook = hook.__wdc || (hook.__wdc = () => { // only fire the hook if the target instance is NOT in a deactivated branch. let current = target; while (current) { if (current.isDeactivated) { return; } current = current.parent; } return hook(); }); injectHook(type, wrappedHook, target); // In addition to registering it on the target instance, we walk up the parent // chain and register it on all ancestor instances that are keep-alive roots. // This avoids the need to walk the entire component tree when invoking these // hooks, and more importantly, avoids the need to track child components in // arrays. if (target) { let current = target.parent; while (current && current.parent) { if (isKeepAlive(current.parent.vnode)) { injectToKeepAliveRoot(wrappedHook, type, target, current); } current = current.parent; } } } function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { // injectHook wraps the original for error handling, so make sure to remove // the wrapped version. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */); onUnmounted(() => { remove(keepAliveRoot[type], injected); }, target); } function injectHook(type, hook, target = currentInstance, prepend = false) { if (target) { // fixed by xxxxxx if (isRootHook(type)) { target = target.root; } const hooks = target[type] || (target[type] = []); // cache the error handling wrapper for injected hooks so the same hook // can be properly deduped by the scheduler. "__weh" stands for "with error // handling". const wrappedHook = hook.__weh || (hook.__weh = (...args) => { if (target.isUnmounted) { return; } // disable tracking inside all lifecycle hooks // since they can potentially be called inside effects. pauseTracking(); // Set currentInstance during hook invocation. // This assumes the hook does not synchronously trigger other hooks, which // can only be false when the user does something really funky. setCurrentInstance(target); // fixed by xxxxxx const res = callWithAsyncErrorHandling(hook, target, type, args); unsetCurrentInstance(); resetTracking(); return res; }); if (prepend) { hooks.unshift(wrappedHook); } else { hooks.push(wrappedHook); } return wrappedHook; } else if ((process.env.NODE_ENV !== 'production')) { // fixed by xxxxxx const apiName = toHandlerKey((ErrorTypeStrings[type] || type.replace(/^on/, '')).replace(/ hook$/, '')); warn$1(`${apiName} is called when there is no active component instance to be ` + `associated with. ` + `Lifecycle injection APIs can only be used during execution of setup().` + (``)); } } const createHook = (lifecycle) => (hook, target = currentInstance) => // post-create lifecycle registrations are noops during SSR (except for serverPrefetch) (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) && injectHook(lifecycle, hook, target); const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */); const onMounted = createHook("m" /* MOUNTED */); const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */); const onUpdated = createHook("u" /* UPDATED */); const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */); const onUnmounted = createHook("um" /* UNMOUNTED */); const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */); const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */); const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */); function onErrorCaptured(hook, target = currentInstance) { injectHook("ec" /* ERROR_CAPTURED */, hook, target); } /** Runtime helper for applying directives to a vnode. Example usage: const comp = resolveComponent('comp') const foo = resolveDirective('foo') const bar = resolveDirective('bar') return withDirectives(h(comp), [ [foo, this.x], [bar, this.y] ]) */ function validateDirectiveName(name) { if (isBuiltInDirective(name)) { warn$1('Do not use built-in directive ids as custom directive id: ' + name); } } /** * Adds directives to a VNode. */ function withDirectives(vnode, directives) { const internalInstance = currentRenderingInstance; if (internalInstance === null) { (process.env.NODE_ENV !== 'production') && warn$1(`withDirectives can only be used inside render functions.`); return vnode; } const instance = getExposeProxy(internalInstance) || internalInstance.proxy; const bindings = vnode.dirs || (vnode.dirs = []); for (let i = 0; i < directives.length; i++) { let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; if (isFunction(dir)) { dir = { mounted: dir, updated: dir }; } if (dir.deep) { traverse(value); } bindings.push({ dir, instance, value, oldValue: void 0, arg, modifiers }); } return vnode; } const COMPONENTS = 'components'; const DIRECTIVES = 'directives'; /** * @private */ function resolveComponent(name, maybeSelfReference) { return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; } const NULL_DYNAMIC_COMPONENT = Symbol(); /** * @private */ function resolveDirective(name) { return resolveAsset(DIRECTIVES, name); } // implementation function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { const instance = currentRenderingInstance || currentInstance; if (instance) { const Component = instance.type; // explicit self name has highest priority if (type === COMPONENTS) { const selfName = getComponentName(Component, false /* do not include inferred name to avoid breaking existing code */); if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) { return Component; } } const res = // local registration // check instance[type] first which is resolved for options API resolve(instance[type] || Component[type], name) || // global registration resolve(instance.appContext[type], name); if (!res && maybeSelfReference) { // fallback to implicit self-reference return Component; } if ((process.env.NODE_ENV !== 'production') && warnMissing && !res) { const extra = type === COMPONENTS ? `\nIf this is a native custom element, make sure to exclude it from ` + `component resolution via compilerOptions.isCustomElement.` : ``; warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); } return res; } else if ((process.env.NODE_ENV !== 'production')) { warn$1(`resolve${capitalize(type.slice(0, -1))} ` + `can only be used in render() or setup().`); } } function resolve(registry, name) { return (registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))])); } /** * For prefixing keys in v-on="obj" with "on" * @private */ function toHandlers(obj) { const ret = {}; if ((process.env.NODE_ENV !== 'production') && !isObject(obj)) { warn$1(`v-on with no argument expects an object value.`); return ret; } for (const key in obj) { ret[toHandlerKey(key)] = obj[key]; } return ret; } /** * #2437 In Vue 3, functional components do not have a public instance proxy but * they exist in the internal parent chain. For code that relies on traversing * public $parent chains, skip functional ones and go to the parent instead. */ const getPublicInstance = (i) => { if (!i) return null; if (isStatefulComponent(i)) return getExposeProxy(i) || i.proxy; return getPublicInstance(i.parent); }; const publicPropertiesMap = // Move PURE marker to new line to workaround compiler discarding it // due to type annotation /*#__PURE__*/ extend(Object.create(null), { $: i => i, // fixed by xxxxxx vue-i18n 在 dev 模式,访问了 $el,故模拟一个假的 // $el: i => i.vnode.el, $el: i => i.__$el || (i.__$el = {}), $data: i => i.data, $props: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.props) : i.props), $attrs: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.attrs) : i.attrs), $slots: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.slots) : i.slots), $refs: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.refs) : i.refs), $parent: i => getPublicInstance(i.parent), $root: i => getPublicInstance(i.root), $emit: i => i.emit, $options: i => (__VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type), $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)), // $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy!)),// fixed by xxxxxx $watch: i => (__VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP) }); const isReservedPrefix = (key) => key === '_' || key === '$'; const PublicInstanceProxyHandlers = { get({ _: instance }, key) { const { ctx, setupState, data, props, accessCache, type, appContext } = instance; // for internal formatters to know that this is a Vue instance if ((process.env.NODE_ENV !== 'production') && key === '__isVue') { return true; } // prioritize