diff --git a/packages/uni-cli-shared/lib/preprocess.js b/packages/uni-cli-shared/lib/preprocess.js index 749697fed526ac5756376bcb3032116421419cd8..b495e812b19c4ef6754eaaec32b080cae113125a 100644 --- a/packages/uni-cli-shared/lib/preprocess.js +++ b/packages/uni-cli-shared/lib/preprocess.js @@ -27,7 +27,14 @@ module.exports = function initPreprocess (name, platforms, userDefines = {}) { defaultContext[normalize(name)] = false }) - defaultContext.VUE2 = true + if (process.env.UNI_USING_VUE3) { + defaultContext.VUE3 = true + } else { + defaultContext.VUE2 = true + } + // nvue 只支持vue2 + nvueContext.VUE2 = true + nvueContext.VUE3 = false vueContext[normalize(name)] = true diff --git a/packages/uni-mp-vue/dist/vue.runtime.esm.js b/packages/uni-mp-vue/dist/vue.runtime.esm.js index 805c964f8f68609e885361ca9c064154b8669a44..1b66551238998424e3641e0c19e47486548c106c 100644 --- a/packages/uni-mp-vue/dist/vue.runtime.esm.js +++ b/packages/uni-mp-vue/dist/vue.runtime.esm.js @@ -1,6 +1,15 @@ -import { isSymbol, extend, isMap, isObject, toRawType, def, isArray, isString, isFunction, isPromise, toHandlerKey, remove, EMPTY_OBJ, camelize, capitalize, normalizeClass, normalizeStyle, isOn, NOOP, isGloballyWhitelisted, isIntegerKey, hasOwn, hasChanged, NO, invokeArrayFns, makeMap, isSet, toNumber, hyphenate, isReservedProp, EMPTY_ARR, toTypeString } from '@vue/shared'; +import { isSymbol, extend, isMap, isObject, toRawType, def, isArray, isString, isFunction, isPromise, toHandlerKey, remove, EMPTY_OBJ, camelize, capitalize, normalizeClass, normalizeStyle, isOn, NOOP, isGloballyWhitelisted, isIntegerKey, hasOwn, hasChanged, invokeArrayFns as invokeArrayFns$1, makeMap, isSet, NO, toNumber, hyphenate, isReservedProp, EMPTY_ARR, toTypeString } from '@vue/shared'; export { camelize } from '@vue/shared'; +const invokeArrayFns = (fns, arg) => { + let ret; + for (let i = 0; i < fns.length; i++) { + ret = fns[i](arg); + } + return ret; +}; +const ON_ERROR = 'onError'; + const targetMap = new WeakMap(); const effectStack = []; let activeEffect; @@ -235,7 +244,14 @@ function createGetter(isReadonly = false, shallow = false) { return isReadonly; } else if (key === "__v_raw" /* RAW */ && - receiver === (isReadonly ? readonlyMap : reactiveMap).get(target)) { + receiver === + (isReadonly + ? shallow + ? shallowReadonlyMap + : readonlyMap + : shallow + ? shallowReactiveMap + : reactiveMap).get(target)) { return target; } const targetIsArray = isArray(target); @@ -268,7 +284,7 @@ function createGetter(isReadonly = false, shallow = false) { return res; }; } -const set = /*#__PURE__*/ createSetter(); +const set$1 = /*#__PURE__*/ createSetter(); const shallowSet = /*#__PURE__*/ createSetter(true); function createSetter(shallow = false) { return function set(target, key, value, receiver) { @@ -318,7 +334,7 @@ function ownKeys(target) { } const mutableHandlers = { get, - set, + set: set$1, deleteProperty, has, ownKeys @@ -364,7 +380,7 @@ function get$1(target, key, isReadonly = false, isShallow = false) { } !isReadonly && track(rawTarget, "get" /* GET */, rawKey); const { has } = getProto(rawTarget); - const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive; + const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; if (has.call(rawTarget, key)) { return wrap(target.get(key)); } @@ -400,7 +416,7 @@ function add(value) { } return this; } -function set$1(key, value) { +function set$1$1(key, value) { value = toRaw(value); const target = toRaw(this); const { has, get } = getProto(target); @@ -461,7 +477,7 @@ function createForEach(isReadonly, isShallow) { const observed = this; const target = observed["__v_raw" /* RAW */]; const rawTarget = toRaw(target); - const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive; + 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 @@ -479,7 +495,7 @@ function createIterableMethod(method, isReadonly, isShallow) { const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap); const isKeyOnly = method === 'keys' && targetIsMap; const innerIterator = target[method](...args); - const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive; + 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 @@ -520,7 +536,7 @@ const mutableInstrumentations = { }, has: has$1, add, - set: set$1, + set: set$1$1, delete: deleteEntry, clear, forEach: createForEach(false, false) @@ -534,7 +550,7 @@ const shallowInstrumentations = { }, has: has$1, add, - set: set$1, + set: set$1$1, delete: deleteEntry, clear, forEach: createForEach(false, true) @@ -555,15 +571,34 @@ const readonlyInstrumentations = { 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); }); function createInstrumentationGetter(isReadonly, shallow) { const instrumentations = shallow - ? shallowInstrumentations + ? isReadonly + ? shallowReadonlyInstrumentations + : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations; @@ -591,6 +626,9 @@ const shallowCollectionHandlers = { const readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) }; +const shallowReadonlyCollectionHandlers = { + get: createInstrumentationGetter(true, true) +}; function checkIdentityKeys(target, has, key) { const rawKey = toRaw(key); if (rawKey !== key && has.call(target, rawKey)) { @@ -604,7 +642,9 @@ function checkIdentityKeys(target, has, key) { } const reactiveMap = new WeakMap(); +const shallowReactiveMap = new WeakMap(); const readonlyMap = new WeakMap(); +const shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case 'Object': @@ -629,7 +669,7 @@ function reactive(target) { if (target && target["__v_isReadonly" /* IS_READONLY */]) { return target; } - return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers); + return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } /** * Return a shallowly-reactive copy of the original object, where only the root @@ -637,14 +677,14 @@ function reactive(target) { * root level). */ function shallowReactive(target) { - return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers); + 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); + return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } /** * Returns a reactive-copy of the original object, where only the root level @@ -653,9 +693,9 @@ function readonly(target) { * This is used for creating the props proxy object for stateful components. */ function shallowReadonly(target) { - return createReactiveObject(target, true, shallowReadonlyHandlers, readonlyCollectionHandlers); + return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } -function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers) { +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)}`); @@ -669,7 +709,6 @@ function createReactiveObject(target, isReadonly, baseHandlers, collectionHandle return target; } // target already has corresponding Proxy - const proxyMap = isReadonly ? readonlyMap : reactiveMap; const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; @@ -825,12 +864,14 @@ class ComputedRefImpl { this["__v_isReadonly" /* IS_READONLY */] = isReadonly; } get value() { - if (this._dirty) { - this._value = this.effect(); - this._dirty = false; + // the computed ref may get wrapped by other proxies e.g. readonly() #3376 + const self = toRaw(this); + if (self._dirty) { + self._value = this.effect(); + self._dirty = false; } - track(toRaw(this), "get" /* GET */, 'value'); - return this._value; + track(self, "get" /* GET */, 'value'); + return self._value; } set value(newValue) { this._setter(newValue); @@ -1344,8 +1385,11 @@ function normalizeEmitsOptions(comp, appContext, asMixin = false) { let hasExtends = false; if (__VUE_OPTIONS_API__ && !isFunction(comp)) { const extendEmits = (raw) => { - hasExtends = true; - extend(normalized, normalizeEmitsOptions(raw, appContext, true)); + const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true); + if (normalizedFromExtend) { + hasExtends = true; + extend(normalized, normalizedFromExtend); + } }; if (!asMixin && appContext.mixins.length) { appContext.mixins.forEach(extendEmits); @@ -1400,10 +1444,11 @@ isSSR = false) { const attrs = {}; // def(attrs, InternalObjectKey, 1) // fixed by xxxxxx def(attrs, '__vInternal', 1); + instance.propsDefaults = Object.create(null); setFullProps(instance, rawProps, props, attrs); // validation if ((process.env.NODE_ENV !== 'production')) { - validateProps(props, instance); + validateProps(rawProps || {}, props, instance); } if (isStateful) { // stateful @@ -1460,9 +1505,15 @@ function resolvePropValue(options, props, key, value, instance) { if (hasDefault && value === undefined) { const defaultValue = opt.default; if (opt.type !== Function && isFunction(defaultValue)) { - setCurrentInstance(instance); - value = defaultValue(props); - setCurrentInstance(null); + const { propsDefaults } = instance; + if (key in propsDefaults) { + value = propsDefaults[key]; + } + else { + setCurrentInstance(instance); + value = propsDefaults[key] = defaultValue(props); + setCurrentInstance(null); + } } else { value = defaultValue; @@ -1582,14 +1633,14 @@ function getTypeIndex(type, expectedTypes) { /** * dev only */ -function validateProps(props, instance) { - const rawValues = toRaw(props); +function validateProps(rawProps, props, instance) { + const resolvedValues = toRaw(props); const options = instance.propsOptions[0]; for (const key in options) { let opt = options[key]; if (opt == null) continue; - validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key)); + validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))); } } /** @@ -1835,7 +1886,7 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM if (cleanup) { cleanup(); } - return callWithErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]); + return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]); }; } } @@ -1848,7 +1899,7 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM getter = () => traverse(baseGetter()); } let cleanup; - const onInvalidate = (fn) => { + let onInvalidate = (fn) => { cleanup = runner.options.onStop = () => { callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */); }; @@ -2062,10 +2113,7 @@ function createAppContext() { } let uid$1 = 0; // fixed by xxxxxx -function createAppAPI( -// render: RootRenderFunction, -// hydrate?: RootHydrateFunction -) { +function createAppAPI() { return function createApp(rootComponent, rootProps = null) { if (rootProps != null && !isObject(rootProps)) { (process.env.NODE_ENV !== 'production') && warn(`root props passed to app.mount() must be an object.`); @@ -2112,7 +2160,7 @@ function createAppAPI( if (__VUE_OPTIONS_API__) { if (!context.mixins.includes(mixin)) { context.mixins.push(mixin); - // global mixin with props/emits de-optimizes props/emits + // window mixin with props/emits de-optimizes props/emits // normalization caching. if (mixin.props || mixin.emits) { context.deopt = true; @@ -2192,17 +2240,12 @@ function resolveDirective(name) { return resolveAsset(DIRECTIVES, name); } // implementation -function resolveAsset(type, name, warnMissing = true) { +function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { const instance = currentInstance; if (instance) { const Component = instance.type; - // self name has highest priority + // explicit self name has highest priority if (type === COMPONENTS) { - // special self referencing call generated by compiler - // inferred from SFC filename - if (name === `_self`) { - return Component; - } const selfName = getComponentName(Component); if (selfName && (selfName === name || @@ -2215,8 +2258,12 @@ function resolveAsset(type, name, warnMissing = true) { // local registration // check instance[type] first for components with mixin or extends. resolve(instance[type] || Component[type], name) || - // global registration + // window registration resolve(instance.appContext[type], name); + if (!res && maybeSelfReference) { + // fallback to implicit self-reference + return Component; + } if ((process.env.NODE_ENV !== 'production') && warnMissing && !res) { warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`); } @@ -2584,8 +2631,8 @@ function createDuplicateChecker() { } }; } -let isInBeforeCreate = false; -function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) { +let shouldCacheAccess = true; +function applyOptions$1(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) { const { // composition mixins, extends: extendsOptions, @@ -2605,15 +2652,15 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], } // applyOptions is called non-as-mixin once per instance if (!asMixin) { - isInBeforeCreate = true; + shouldCacheAccess = false; callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins); - isInBeforeCreate = false; - // global mixins are applied first + shouldCacheAccess = true; + // window mixins are applied first applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide); } // extending a base component... if (extendsOptions) { - applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true); + applyOptions$1(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true); } // local mixins if (mixins) { @@ -2858,43 +2905,29 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], } } function callSyncHook(name, type, options, instance, globalMixins) { - callHookFromMixins(name, type, globalMixins, instance); + for (let i = 0; i < globalMixins.length; i++) { + callHookWithMixinAndExtends(name, type, globalMixins[i], instance); + } + callHookWithMixinAndExtends(name, type, options, instance); +} +function callHookWithMixinAndExtends(name, type, options, instance) { const { extends: base, mixins } = options; + const selfHook = options[name]; if (base) { - callHookFromExtends(name, type, base, instance); + callHookWithMixinAndExtends(name, type, base, instance); } if (mixins) { - callHookFromMixins(name, type, mixins, instance); + for (let i = 0; i < mixins.length; i++) { + callHookWithMixinAndExtends(name, type, mixins[i], instance); + } } - const selfHook = options[name]; if (selfHook) { callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type); } } -function callHookFromExtends(name, type, base, instance) { - if (base.extends) { - callHookFromExtends(name, type, base.extends, instance); - } - const baseHook = base[name]; - if (baseHook) { - callWithAsyncErrorHandling(baseHook.bind(instance.proxy), instance, type); - } -} -function callHookFromMixins(name, type, mixins, instance) { - for (let i = 0; i < mixins.length; i++) { - const chainedMixins = mixins[i].mixins; - if (chainedMixins) { - callHookFromMixins(name, type, chainedMixins, instance); - } - const fn = mixins[i][name]; - if (fn) { - callWithAsyncErrorHandling(fn.bind(instance.proxy), instance, type); - } - } -} function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) { for (let i = 0; i < mixins.length; i++) { - applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true); + applyOptions$1(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true); } } function resolveData(instance, dataFn, publicThis) { @@ -2902,7 +2935,9 @@ function resolveData(instance, dataFn, publicThis) { warn(`The data option must be a function. ` + `Plain object usage is no longer supported.`); } + shouldCacheAccess = false; const data = dataFn.call(publicThis, publicThis); + shouldCacheAccess = true; if ((process.env.NODE_ENV !== 'production') && isPromise(data)) { warn(`data() returned a Promise - note data() cannot be async; If you ` + `intend to perform data fetching before component renders, use ` + @@ -3075,7 +3110,7 @@ const PublicInstanceProxyHandlers = { accessCache[key] = 3 /* CONTEXT */; return ctx[key]; } - else if (!__VUE_OPTIONS_API__ || !isInBeforeCreate) { + else if (!__VUE_OPTIONS_API__ || shouldCacheAccess) { accessCache[key] = 4 /* OTHER */; } } @@ -3101,7 +3136,7 @@ const PublicInstanceProxyHandlers = { return ctx[key]; } else if ( - // global properties + // window properties ((globalProperties = appContext.config.globalProperties), hasOwn(globalProperties, key))) { return globalProperties[key]; @@ -3213,7 +3248,7 @@ function createRenderContext(instance) { set: NOOP }); }); - // expose global properties + // expose window properties const { globalProperties } = instance.appContext.config; Object.keys(globalProperties).forEach(key => { Object.defineProperty(target, key, { @@ -3290,6 +3325,8 @@ function createComponentInstance(vnode, parent, suspense) { // emit emit: null, emitted: null, + // props default value + propsDefaults: EMPTY_OBJ, // state ctx: EMPTY_OBJ, data: EMPTY_OBJ, @@ -3401,8 +3438,12 @@ function setupStatefulComponent(instance, isSSR) { if (isPromise(setupResult)) { if (isSSR) { // return the promise so server-renderer can wait on it - return setupResult.then((resolvedResult) => { - handleSetupResult(instance, resolvedResult); + return setupResult + .then((resolvedResult) => { + handleSetupResult(instance, resolvedResult, isSSR); + }) + .catch(e => { + handleError(e, instance, 0 /* SETUP_FUNCTION */); }); } else if ((process.env.NODE_ENV !== 'production')) { @@ -3411,11 +3452,11 @@ function setupStatefulComponent(instance, isSSR) { } } else { - handleSetupResult(instance, setupResult); + handleSetupResult(instance, setupResult, isSSR); } } else { - finishComponentSetup(instance); + finishComponentSetup(instance, isSSR); } } function handleSetupResult(instance, setupResult, isSSR) { @@ -3443,7 +3484,7 @@ function handleSetupResult(instance, setupResult, isSSR) { else if ((process.env.NODE_ENV !== 'production') && setupResult !== undefined) { warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`); } - finishComponentSetup(instance); + finishComponentSetup(instance, isSSR); } function finishComponentSetup(instance, isSSR) { const Component = instance.type; @@ -3461,12 +3502,13 @@ function finishComponentSetup(instance, isSSR) { if (__VUE_OPTIONS_API__) { currentInstance = instance; pauseTracking(); - applyOptions(instance, Component); + applyOptions$1(instance, Component); resetTracking(); currentInstance = null; } // warn missing template/render - if ((process.env.NODE_ENV !== 'production') && !Component.render && instance.render === NOOP) { + // the runtime compilation of template in SSR is done by server-render + if ((process.env.NODE_ENV !== 'production') && !Component.render && instance.render === NOOP && !isSSR) { /* istanbul ignore if */ if (Component.template) { warn(`Component provided template option but ` + @@ -3504,9 +3546,6 @@ function createSetupContext(instance) { // We use getters in dev in case libs like test-utils overwrite instance // properties (overwrites should not be done in prod) return Object.freeze({ - get props() { - return instance.props; - }, get attrs() { return new Proxy(instance.attrs, attrHandlers); }, @@ -3596,7 +3635,7 @@ function defineEmit() { } // Core API ------------------------------------------------------------------ -const version = "3.0.7"; +const version = "3.0.9"; // import deepCopy from './deepCopy' /** @@ -3921,8 +3960,8 @@ const prodEffectOptions = { function createDevEffectOptions(instance) { return { scheduler: queueJob, - onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0, - onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0 + onTrack: instance.rtc ? e => invokeArrayFns$1(instance.rtc, e) : void 0, + onTrigger: instance.rtg ? e => invokeArrayFns$1(instance.rtg, e) : void 0 }; } function setupRenderEffect(instance) { @@ -3938,7 +3977,7 @@ function setupRenderEffect(instance) { const { bu, u } = instance; // beforeUpdate hook if (bu) { - invokeArrayFns(bu); + invokeArrayFns$1(bu); } patch(instance); // updated hook @@ -3952,7 +3991,7 @@ function unmountComponent(instance) { const { bum, effects, update, um } = instance; // beforeUnmount hook if (bum) { - invokeArrayFns(bum); + invokeArrayFns$1(bum); } if (effects) { for (let i = 0; i < effects.length; i++) { @@ -4009,7 +4048,15 @@ function createVueApp(rootComponent, rootProps = null) { return app; } -function applyOptions$1(options, instance, publicThis) { +function withModifiers() { } +function createVNode$1() { } + +function applyOptions(options, instance, publicThis) { + const mpType = options.mpType || publicThis.$mpType; + if (!mpType) { + // 仅 App,Page 类型支持 on 生命周期 + return; + } Object.keys(options).forEach((name) => { if (name.indexOf('on') === 0) { const hook = options[name]; @@ -4020,7 +4067,7 @@ function applyOptions$1(options, instance, publicThis) { }); } -function set$2(target, key, val) { +function set(target, key, val) { return (target[key] = val); } function hasHook(name) { @@ -4032,24 +4079,66 @@ function hasHook(name) { } function callHook(name, args) { const hooks = this.$[name]; - let ret; - if (hooks) { - for (let i = 0; i < hooks.length; i++) { - ret = hooks[i](args); - } - } - return ret; + return hooks && invokeArrayFns(hooks, args); } function errorHandler(err, instance, info) { if (!instance) { throw err; } - const appInstance = instance.$.appContext.$appInstance; - if (!appInstance) { + const app = getApp(); + if (!app || !app.$vm) { throw err; } - appInstance.$callHook('onError', err, info); + { + app.$vm.$callHook(ON_ERROR, err, info); + } +} + +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str) + .split('') + .map(function (c) { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); + }) + .join('')); +} +function getCurrentUserInfo() { + const token = uni.getStorageSync('uni_id_token') || ''; + const tokenArr = token.split('.'); + if (!token || tokenArr.length !== 3) { + return { + uid: null, + role: [], + permission: [], + tokenExpired: 0, + }; + } + let userInfo; + try { + userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); + } + catch (error) { + throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message); + } + userInfo.tokenExpired = userInfo.exp * 1000; + delete userInfo.exp; + delete userInfo.iat; + return userInfo; +} +function uniIdMixin(globalProperties) { + globalProperties.uniIDHasRole = function (roleId) { + const { role } = getCurrentUserInfo(); + return role.indexOf(roleId) > -1; + }; + globalProperties.uniIDHasPermission = function (permissionId) { + const { permission } = getCurrentUserInfo(); + return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1; + }; + globalProperties.uniIDTokenValid = function () { + const { tokenExpired } = getCurrentUserInfo(); + return tokenExpired > Date.now(); + }; } function initApp(app) { @@ -4058,11 +4147,15 @@ function initApp(app) { appConfig.errorHandler = errorHandler; } const globalProperties = appConfig.globalProperties; - globalProperties.$hasHook = hasHook; - globalProperties.$callHook = callHook; + uniIdMixin(globalProperties); + { + // 小程序,待重构,不再挂靠全局 + globalProperties.$hasHook = hasHook; + globalProperties.$callHook = callHook; + } if (__VUE_OPTIONS_API__) { - globalProperties.$set = set$2; - globalProperties.$applyOptions = applyOptions$1; + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; } } @@ -4089,38 +4182,10 @@ var plugin = { }, }; -// @ts-ignore -const createHook$1 = (lifecycle) => (hook, target) => -// post-create lifecycle registrations are noops during SSR -!isInSSRComponentSetup && injectHook(lifecycle, hook, target); -const onShow = /*#__PURE__*/ createHook$1("onShow" /* ON_SHOW */); -const onHide = /*#__PURE__*/ createHook$1("onHide" /* ON_HIDE */); -const onLaunch = /*#__PURE__*/ createHook$1("onLaunch" /* ON_LAUCH */); -const onError = /*#__PURE__*/ createHook$1("onError" /* ON_ERROR */); -const onThemeChange = /*#__PURE__*/ createHook$1("onThemeChange" /* ON_THEME_CHANGE */); -const onPageNotFound = /*#__PURE__*/ createHook$1("onPageNotFound" /* ON_PAGE_NOT_FOUND */); -const onUnhandledRejection = /*#__PURE__*/ createHook$1("onUnhandledRejection" /* ON_UNHANDLE_REJECTION */); -const onLoad = /*#__PURE__*/ createHook$1("onLoad" /* ON_LOAD */); -const onReady = /*#__PURE__*/ createHook$1("onReady" /* ON_READY */); -const onUnload = /*#__PURE__*/ createHook$1("onUnload" /* ON_UNLOAD */); -const onResize = /*#__PURE__*/ createHook$1("onResize" /* ON_RESIZE */); -const onBackPress = /*#__PURE__*/ createHook$1("onBackPress" /* ON_BACK_PRESS */); -const onPageScroll = /*#__PURE__*/ createHook$1("onPageScroll" /* ON_PAGE_SCROLL */); -const onTabItemTap = /*#__PURE__*/ createHook$1("onTabItemTap" /* ON_TAB_ITEM_TAP */); -const onReachBottom = /*#__PURE__*/ createHook$1("onReachBottom" /* ON_REACH_BOTTOM */); -const onPullDownRefresh = /*#__PURE__*/ createHook$1("onPullDownRefresh" /* ON_PULL_DOWN_REFRESH */); -const onShareTimeline = /*#__PURE__*/ createHook$1("onShareTimeline" /* ON_SHARE_TIMELINE */); -const onAddToFavorites = /*#__PURE__*/ createHook$1("onAddToFavorites" /* ON_ADD_TO_FAVORITES */); -const onShareAppMessage = /*#__PURE__*/ createHook$1("onShareAppMessage" /* ON_SHARE_APP_MESSAGE */); -const onNavigationBarButtonTap = /*#__PURE__*/ createHook$1("onNavigationBarButtonTap" /* ON_NAVIGATION_BAR_BUTTON_TAP */); -const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook$1("onNavigationBarSearchInputChanged" /* ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED */); -const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook$1("onNavigationBarSearchInputClicked" /* ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED */); -const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook$1("onNavigationBarSearchInputConfirmed" /* ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED */); -const onNavigationBarSearchInputFocusChanged = /*#__PURE__*/ createHook$1("onNavigationBarSearchInputFocusChanged" /* ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED */); - function createApp(rootComponent, rootProps = null) { rootComponent && (rootComponent.mpType = 'app'); return createVueApp(rootComponent, rootProps).use(plugin); -} +} +const createSSRApp = createApp; -export { callWithAsyncErrorHandling, callWithErrorHandling, computed$1 as computed, createApp, createHook$1 as createHook, createVueApp, customRef, defineComponent, defineEmit, defineProps, getCurrentInstance, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, nextTick, onActivated, onAddToFavorites, onBackPress, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onError, onErrorCaptured, onHide, onLaunch, onLoad, onMounted, onNavigationBarButtonTap, onNavigationBarSearchInputChanged, onNavigationBarSearchInputClicked, onNavigationBarSearchInputConfirmed, onNavigationBarSearchInputFocusChanged, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onRenderTracked, onRenderTriggered, onResize, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, onUnmounted, onUpdated, provide, reactive, readonly, ref, resolveDirective, shallowReactive, shallowReadonly, shallowRef, toRaw, toRef, toRefs, triggerRef, unref, version, warn, watch, watchEffect, withDirectives }; +export { callWithAsyncErrorHandling, callWithErrorHandling, computed$1 as computed, createApp, createSSRApp, createVNode$1 as createVNode, createVueApp, customRef, defineComponent, defineEmit, defineProps, getCurrentInstance, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, nextTick, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onUnmounted, onUpdated, provide, reactive, readonly, ref, resolveDirective, shallowReactive, shallowReadonly, shallowRef, toRaw, toRef, toRefs, triggerRef, unref, version, warn, watch, watchEffect, withDirectives, withModifiers }; diff --git a/packages/vue-cli-plugin-uni/index.js b/packages/vue-cli-plugin-uni/index.js index fdf2417101b7a5a57b1a77f31ff3333fd1c22f10..2c854df487eed729d78176804c19c7530ecefc84 100644 --- a/packages/vue-cli-plugin-uni/index.js +++ b/packages/vue-cli-plugin-uni/index.js @@ -87,5 +87,5 @@ const args = require('minimist')(process.argv.slice(2)) module.exports.defaultModes = { 'uni-serve': args.mode || 'development', - 'uni-build': args.mode || process.env.NODE_ENV + 'uni-build': args.mode || process.env.NODE_ENV } diff --git a/packages/vue-cli-plugin-uni/lib/env.js b/packages/vue-cli-plugin-uni/lib/env.js index f27a62d71b81562fb68a3f663d2a0e33332ca4dc..e0fd803f52ea3f94af4ee1b009bc01b317c289d0 100644 --- a/packages/vue-cli-plugin-uni/lib/env.js +++ b/packages/vue-cli-plugin-uni/lib/env.js @@ -16,11 +16,20 @@ if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0) process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR) } process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), defaultInputDir) + +const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson() + +// 小程序 vue3 标记 +if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) { + if (manifestJsonObj.vueVersion === '3' || manifestJsonObj.vueVersion === 3) { + process.env.UNI_USING_VUE3 = true + process.env.UNI_USING_VUE3_OPTIONS_API = true + } +} // 初始化全局插件对象 -global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init() +global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init() -const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson() const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {} // 插件校验环境 global.uniPlugin.validate.forEach(validate => { @@ -263,7 +272,8 @@ if (platformOptions.usingComponents === true) { // 兼容历史配置 betterScopedSlots const modes = ['legacy', 'auto', 'augmented'] -const scopedSlotsCompiler = !platformOptions.scopedSlotsCompiler && platformOptions.betterScopedSlots ? modes[2] : platformOptions.scopedSlotsCompiler +const scopedSlotsCompiler = !platformOptions.scopedSlotsCompiler && platformOptions.betterScopedSlots ? modes[2] + : platformOptions.scopedSlotsCompiler process.env.SCOPED_SLOTS_COMPILER = modes.includes(scopedSlotsCompiler) ? scopedSlotsCompiler : modes[1] // 快手小程序抽象组件编译报错,如未指定 legacy 固定为 augmented 模式 if (process.env.UNI_PLATFORM === 'mp-kuaishou' && process.env.SCOPED_SLOTS_COMPILER !== modes[0]) { @@ -465,4 +475,4 @@ runByHBuilderX && console.log('正在编译中...') module.exports = { manifestPlatformOptions: platformOptions -} +} diff --git a/packages/vue-cli-plugin-uni/lib/mp/index.js b/packages/vue-cli-plugin-uni/lib/mp/index.js index 12e15b962b508b2427fcb755924880f3bb809da8..1388223eae94a73367d5e0aa22af434740e496a4 100644 --- a/packages/vue-cli-plugin-uni/lib/mp/index.js +++ b/packages/vue-cli-plugin-uni/lib/mp/index.js @@ -128,7 +128,8 @@ class PreprocessAssetsPlugin { function initSubpackageConfig (webpackConfig, vueOptions) { if (process.env.UNI_OUTPUT_DEFAULT_DIR === process.env.UNI_OUTPUT_DIR) { // 未自定义output - process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN)) + process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, (process.env.UNI_SUBPACKGE || process.env + .UNI_MP_PLUGIN)) } vueOptions.outputDir = process.env.UNI_OUTPUT_DIR webpackConfig.output.path(process.env.UNI_OUTPUT_DIR) @@ -175,7 +176,8 @@ module.exports = { const UNI_MP_PLUGIN_MAIN = process.env.UNI_MP_PLUGIN_MAIN if (UNI_MP_PLUGIN_MAIN) { - process.UNI_ENTRY[UNI_MP_PLUGIN_MAIN.split('.')[0]] = path.resolve(process.env.UNI_INPUT_DIR, UNI_MP_PLUGIN_MAIN) + process.UNI_ENTRY[UNI_MP_PLUGIN_MAIN.split('.')[0]] = path.resolve(process.env.UNI_INPUT_DIR, + UNI_MP_PLUGIN_MAIN) } } @@ -295,4 +297,4 @@ module.exports = { webpackConfig.plugins.delete('preload') webpackConfig.plugins.delete('prefetch') } -} +} diff --git a/packages/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js b/packages/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js index f32776a370ac3a4522309bd498cf7d66779b2c1e..7f22d9818ab9cfb83f7fbaf5137fb68267646e39 100644 --- a/packages/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js +++ b/packages/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js @@ -1 +1 @@ -import{initVueI18n as e}from"@dcloudio/uni-i18n";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t,n){return e(n={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&n.path)}},n.exports),n.exports}var s=n((function(e,t){var n;e.exports=(n=n||function(e,t){var n=Object.create||function(){function e(){}return function(t){var n;return e.prototype=t,n=new e,e.prototype=null,n}}(),s={},r=s.lib={},o=r.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},i=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes,r=e.sigBytes;if(this.clamp(),s%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[s+o>>>2]|=i<<24-(s+o)%4*8}else for(o=0;o>>2]=n[o>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,s=[],r=function(t){t=t;var n=987654321,s=4294967295;return function(){var r=((n=36969*(65535&n)+(n>>16)&s)<<16)+(t=18e3*(65535&t)+(t>>16)&s)&s;return r/=4294967296,(r+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-r%4*8&255;s.push((o>>>4).toString(16)),s.push((15&o).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,s=[],r=0;r>>2]>>>24-r%4*8&255;s.push(String.fromCharCode(o))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},l=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,o=this.blockSize,a=r/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,u=e.min(4*c,r);if(c){for(var h=0;h>>24)|4278255360&(r<<24|r>>>8)}var o=this._hash.words,i=e[t+0],c=e[t+1],f=e[t+2],p=e[t+3],g=e[t+4],m=e[t+5],y=e[t+6],_=e[t+7],w=e[t+8],v=e[t+9],S=e[t+10],k=e[t+11],T=e[t+12],P=e[t+13],I=e[t+14],A=e[t+15],E=o[0],b=o[1],O=o[2],U=o[3];E=u(E,b,O,U,i,7,a[0]),U=u(U,E,b,O,c,12,a[1]),O=u(O,U,E,b,f,17,a[2]),b=u(b,O,U,E,p,22,a[3]),E=u(E,b,O,U,g,7,a[4]),U=u(U,E,b,O,m,12,a[5]),O=u(O,U,E,b,y,17,a[6]),b=u(b,O,U,E,_,22,a[7]),E=u(E,b,O,U,w,7,a[8]),U=u(U,E,b,O,v,12,a[9]),O=u(O,U,E,b,S,17,a[10]),b=u(b,O,U,E,k,22,a[11]),E=u(E,b,O,U,T,7,a[12]),U=u(U,E,b,O,P,12,a[13]),O=u(O,U,E,b,I,17,a[14]),E=h(E,b=u(b,O,U,E,A,22,a[15]),O,U,c,5,a[16]),U=h(U,E,b,O,y,9,a[17]),O=h(O,U,E,b,k,14,a[18]),b=h(b,O,U,E,i,20,a[19]),E=h(E,b,O,U,m,5,a[20]),U=h(U,E,b,O,S,9,a[21]),O=h(O,U,E,b,A,14,a[22]),b=h(b,O,U,E,g,20,a[23]),E=h(E,b,O,U,v,5,a[24]),U=h(U,E,b,O,I,9,a[25]),O=h(O,U,E,b,p,14,a[26]),b=h(b,O,U,E,w,20,a[27]),E=h(E,b,O,U,P,5,a[28]),U=h(U,E,b,O,f,9,a[29]),O=h(O,U,E,b,_,14,a[30]),E=l(E,b=h(b,O,U,E,T,20,a[31]),O,U,m,4,a[32]),U=l(U,E,b,O,w,11,a[33]),O=l(O,U,E,b,k,16,a[34]),b=l(b,O,U,E,I,23,a[35]),E=l(E,b,O,U,c,4,a[36]),U=l(U,E,b,O,g,11,a[37]),O=l(O,U,E,b,_,16,a[38]),b=l(b,O,U,E,S,23,a[39]),E=l(E,b,O,U,P,4,a[40]),U=l(U,E,b,O,i,11,a[41]),O=l(O,U,E,b,p,16,a[42]),b=l(b,O,U,E,y,23,a[43]),E=l(E,b,O,U,v,4,a[44]),U=l(U,E,b,O,T,11,a[45]),O=l(O,U,E,b,A,16,a[46]),E=d(E,b=l(b,O,U,E,f,23,a[47]),O,U,i,6,a[48]),U=d(U,E,b,O,_,10,a[49]),O=d(O,U,E,b,I,15,a[50]),b=d(b,O,U,E,m,21,a[51]),E=d(E,b,O,U,T,6,a[52]),U=d(U,E,b,O,p,10,a[53]),O=d(O,U,E,b,S,15,a[54]),b=d(b,O,U,E,c,21,a[55]),E=d(E,b,O,U,w,6,a[56]),U=d(U,E,b,O,A,10,a[57]),O=d(O,U,E,b,y,15,a[58]),b=d(b,O,U,E,P,21,a[59]),E=d(E,b,O,U,g,6,a[60]),U=d(U,E,b,O,k,10,a[61]),O=d(O,U,E,b,f,15,a[62]),b=d(b,O,U,E,v,21,a[63]),o[0]=o[0]+E|0,o[1]=o[1]+b|0,o[2]=o[2]+O|0,o[3]=o[3]+U|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var o=e.floor(s/4294967296),i=s;n[15+(r+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),t.sigBytes=4*(n.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var h=c[u];c[u]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,n,s,r,o,i){var a=e+(t&n|~t&s)+r+i;return(a<>>32-o)+t}function h(e,t,n,s,r,o,i){var a=e+(t&s|n&~s)+r+i;return(a<>>32-o)+t}function l(e,t,n,s,r,o,i){var a=e+(t^n^s)+r+i;return(a<>>32-o)+t}function d(e,t,n,s,r,o,i){var a=e+(n^(t|~s))+r+i;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),n.MD5)})),n((function(e,t){var n,r,o;e.exports=(r=(n=s).lib.Base,o=n.enc.Utf8,void(n.algo.HMAC=r.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=o.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,c=i.words,u=0;u{m.indexOf(n)>-1&&function(e,t,n){let s=y[e][t];s||(s=y[e][t]=[]),-1===s.indexOf(n)&&"function"==typeof n&&s.push(n)}(e,n,t[n])})}function w(e,t){y[e]||(y[e]={}),i(t)?Object.keys(t).forEach(n=>{m.indexOf(n)>-1&&function(e,t,n){const s=y[e][t];if(!s)return;const r=s.indexOf(n);r>-1&&s.splice(r,1)}(e,n,t[n])}):delete y[e]}function v(e,t){return e&&0!==e.length?e.reduce((e,n)=>e.then(()=>n(t)),Promise.resolve()):Promise.resolve()}function S(e,t){return y[e]&&y[e][t]||[]}function k(e,t){return t?function(n){const s="callFunction"===t&&"DCloud-clientDB"===(n&&n.name);let r;r=this.isReady?Promise.resolve():this.initUniCloud,n=n||{};const o=r.then(()=>s?Promise.resolve():v(S(t,"invoke"),n)).then(()=>e.call(this,n)).then(e=>s?Promise.resolve(e):v(S(t,"success"),e).then(()=>v(S(t,"complete"),e)).then(()=>Promise.resolve(e)),e=>s?Promise.reject(e):v(S(t,"fail"),e).then(()=>v(S(t,"complete"),e)).then(()=>Promise.reject(e)));if(!(n.success||n.fail||n.complete))return o;o.then(e=>{n.success&&n.success(e),n.complete&&n.complete(e)}).catch(e=>{n.fail&&n.fail(e),n.complete&&n.complete(e)})}:function(t){if(!((t=t||{}).success||t.fail||t.complete))return e.call(this,t);e.call(this,t).then(e=>{t.success&&t.success(e),t.complete&&t.complete(e)},e=>{t.fail&&t.fail(e),t.complete&&t.complete(e)})}}class T extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{code:{get:()=>e.code},requestId:{get:()=>e.requestId},message:{get(){return this.errMsg},set(e){this.errMsg=e}}})}}const{t:P,setLocale:I,getLocale:A}=e({"zh-Hans":{"uniCloud.init.paramRequired":"缺少参数:{param}","uniCloud.uploadFile.fileError":"filePath应为File对象"},"zh-Hant":{"uniCloud.init.paramRequired":"缺少参数:{param}","uniCloud.uploadFile.fileError":"filePath应为File对象"},en:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"},fr:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"},es:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"}},"zh-Hans");let E,b,O;try{E=require("uni-stat-config").default||require("uni-stat-config")}catch(e){E={appid:""}}function U(e=8){let t="";for(;t.length{t(Object.assign(e,{complete(e){e||(e={}),u&&"h5"===h&&e.errMsg&&0===e.errMsg.indexOf("request:fail")&&console.warn("发布H5,需要在uniCloud后台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:https://uniapp.dcloud.io/uniCloud/quickstart?id=useinh5");const t=e.data&&e.data.header&&e.data.header["x-serverless-request-id"]||e.header&&e.header["request-id"];if(!e.statusCode||e.statusCode>=400)return s(new T({code:"SYS_ERR",message:e.errMsg||"request:fail",requestId:t}));const r=e.data;if(r.error)return s(new T({code:r.error.code,message:r.error.message,requestId:t}));r.result=r.data,r.requestId=t,delete r.data,n(r)}}))})}};const q={request:e=>uni.request(e),uploadFile:e=>uni.uploadFile(e),setStorageSync:(e,t)=>uni.setStorageSync(e,t),getStorageSync:e=>uni.getStorageSync(e),removeStorageSync:e=>uni.removeStorageSync(e),clearStorageSync:()=>uni.clearStorageSync()};class F{constructor(e){["spaceId","clientSecret"].forEach(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw new Error(P("uniCloud.init.paramRequired",{param:t}))}),this.config=Object.assign({},{endpoint:"https://api.bspapp.com"},e),this.config.provider="aliyun",this.config.requestUrl=this.config.endpoint+"/client",this.config.envType=this.config.envType||"public",this.config.accessTokenKey="access_token_"+this.config.spaceId,this.adapter=q,this._getAccessTokenPromise=null,this._getAccessTokenPromiseStatus=null}get hasAccessToken(){return!!this.accessToken}setAccessToken(e){this.accessToken=e}requestWrapped(e){return R.wrappedRequest(e,this.adapter.request)}requestAuth(e){return this.requestWrapped(e)}request(e,t){return Promise.resolve().then(()=>this.hasAccessToken?t?this.requestWrapped(e):this.requestWrapped(e).catch(t=>new Promise((e,n)=>{!t||"GATEWAY_INVALID_TOKEN"!==t.code&&"InvalidParameter.InvalidToken"!==t.code?n(t):e()}).then(()=>this.getAccessToken()).then(()=>{const t=this.rebuildRequest(e);return this.request(t,!0)})):this.getAccessToken().then(()=>{const t=this.rebuildRequest(e);return this.request(t,!0)}))}rebuildRequest(e){const t=Object.assign({},e);return t.data.token=this.accessToken,t.header["x-basement-token"]=this.accessToken,t.header["x-serverless-sign"]=R.sign(t.data,this.config.clientSecret),t}setupRequest(e,t){const n=Object.assign({},e,{spaceId:this.config.spaceId,timestamp:Date.now()}),s={"Content-Type":"application/json"};return"auth"!==t&&(n.token=this.accessToken,s["x-basement-token"]=this.accessToken),s["x-serverless-sign"]=R.sign(n,this.config.clientSecret),{url:this.config.requestUrl,method:"POST",data:n,dataType:"json",header:s}}getAccessToken(){if("pending"===this._getAccessTokenPromiseStatus)return this._getAccessTokenPromise;this._getAccessTokenPromiseStatus="pending";return this._getAccessTokenPromise=this.requestAuth(this.setupRequest({method:"serverless.auth.user.anonymousAuthorize",params:"{}"},"auth")).then(e=>new Promise((t,n)=>{e.result&&e.result.accessToken?(this.setAccessToken(e.result.accessToken),this._getAccessTokenPromiseStatus="fulfilled",t(this.accessToken)):(this._getAccessTokenPromiseStatus="rejected",n(new T({code:"AUTH_FAILED",message:"获取accessToken失败"})))}),e=>(this._getAccessTokenPromiseStatus="rejected",Promise.reject(e))),this._getAccessTokenPromise}authorize(){this.getAccessToken()}callFunction(e){const t={method:"serverless.function.runtime.invoke",params:JSON.stringify({functionTarget:e.name,functionArgs:e.data||{}})};return this.request(this.setupRequest(t))}getOSSUploadOptionsFromPath(e){const t={method:"serverless.file.resource.generateProximalSign",params:JSON.stringify(e)};return this.request(this.setupRequest(t))}uploadFileToOSS({url:e,formData:t,name:n,filePath:s,fileType:r,onUploadProgress:o}){return new Promise((i,a)=>{const c=this.adapter.uploadFile({url:e,formData:t,name:n,filePath:s,fileType:r,header:{"X-OSS-server-side-encrpytion":"AES256"},success(e){e&&e.statusCode<400?i(e):a(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){a(new T({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(e=>{o({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend})})})}reportOSSUpload(e){const t={method:"serverless.file.resource.report",params:JSON.stringify(e)};return this.request(this.setupRequest(t))}uploadFile({filePath:e,cloudPath:t,fileType:n="image",onUploadProgress:s,config:r}){if(!t)throw new T({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});const o=r&&r.envType||this.config.envType;let i,a;return this.getOSSUploadOptionsFromPath({env:o,filename:t}).then(t=>{const r=t.result;i=r.id,a="https://"+r.cdnDomain+"/"+r.ossPath;const o={url:"https://"+r.host,formData:{"Cache-Control":"max-age=2592000","Content-Disposition":"attachment",OSSAccessKeyId:r.accessKeyId,Signature:r.signature,host:r.host,id:i,key:r.ossPath,policy:r.policy,success_action_status:200},fileName:"file",name:"file",filePath:e,fileType:n};return this.uploadFileToOSS(Object.assign({},o,{onUploadProgress:s}))}).then(()=>this.reportOSSUpload({id:i})).then(t=>new Promise((n,s)=>{t.success?n({success:!0,filePath:e,fileID:a}):s(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))}))}deleteFile({fileList:e}){const t={method:"serverless.file.resource.delete",params:JSON.stringify({id:e[0]})};return this.request(this.setupRequest(t))}getTempFileURL({fileList:e}={}){return new Promise((t,n)=>{Array.isArray(e)&&0!==e.length||n(new T({code:"INVALID_PARAM",message:"fileList的元素必须是非空的字符串"})),t({fileList:e.map(e=>({fileID:e,tempFileURL:e}))})})}}const L={init(e){const t=new F(e),n={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return n},t.customAuth=t.auth,t}},N="undefined"!=typeof location&&"http:"===location.protocol?"http:":"https:",M="undefined"!=typeof process&&"e2e"===process.env.NODE_ENV&&"pre"===process.env.END_POINT?"//tcb-pre.tencentcloudapi.com/web":"//tcb-api.tencentcloudapi.com/web";var j;!function(e){e.local="local",e.none="none",e.session="session"}(j||(j={}));var $=function(){};const K=()=>{let e;if(!Promise){e=()=>{},e.promise={};const t=()=>{throw new Error('Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.')};return Object.defineProperty(e.promise,"then",{get:t}),Object.defineProperty(e.promise,"catch",{get:t}),e}const t=new Promise((t,n)=>{e=(e,s)=>e?n(e):t(s)});return e.promise=t,e};function B(e){return void 0===e}function H(e){return"[object Null]"===Object.prototype.toString.call(e)}var W;function z(e){const t=(n=e,"[object Array]"===Object.prototype.toString.call(n)?e:[e]);var n;for(const e of t){const{isMatch:t,genAdapter:n,runtime:s}=e;if(t())return{adapter:n(),runtime:s}}}!function(e){e.WEB="web",e.WX_MP="wx_mp"}(W||(W={}));const V={adapter:null,runtime:void 0},J=["anonymousUuidKey"];class Y extends ${constructor(){super(),V.adapter.root.tcbObject||(V.adapter.root.tcbObject={})}setItem(e,t){V.adapter.root.tcbObject[e]=t}getItem(e){return V.adapter.root.tcbObject[e]}removeItem(e){delete V.adapter.root.tcbObject[e]}clear(){delete V.adapter.root.tcbObject}}function X(e,t){switch(e){case"local":return t.localStorage||new Y;case"none":return new Y;default:return t.sessionStorage||new Y}}class G{constructor(e){if(!this._storage){this._persistence=V.adapter.primaryStorage||e.persistence,this._storage=X(this._persistence,V.adapter);const t="access_token_"+e.env,n="access_token_expire_"+e.env,s="refresh_token_"+e.env,r="anonymous_uuid_"+e.env,o="login_type_"+e.env,i="user_info_"+e.env;this.keys={accessTokenKey:t,accessTokenExpireKey:n,refreshTokenKey:s,anonymousUuidKey:r,loginTypeKey:o,userInfoKey:i}}}updatePersistence(e){if(e===this._persistence)return;const t="local"===this._persistence;this._persistence=e;const n=X(e,V.adapter);for(const e in this.keys){const s=this.keys[e];if(t&&J.includes(e))continue;const r=this._storage.getItem(s);B(r)||H(r)||(n.setItem(s,r),this._storage.removeItem(s))}this._storage=n}setStore(e,t,n){if(!this._storage)return;const s={version:n||"localCachev1",content:t},r=JSON.stringify(s);try{this._storage.setItem(e,r)}catch(e){throw e}}getStore(e,t){try{if(!this._storage)return}catch(e){return""}t=t||"localCachev1";const n=this._storage.getItem(e);if(!n)return"";if(n.indexOf(t)>=0){return JSON.parse(n).content}return""}removeStore(e){this._storage.removeItem(e)}}const Q={},Z={};function ee(e){return Q[e]}class te{constructor(e,t){this.data=t||null,this.name=e}}class ne extends te{constructor(e,t){super("error",{error:e,data:t}),this.error=e}}const se=new class{constructor(){this._listeners={}}on(e,t){return function(e,t,n){n[e]=n[e]||[],n[e].push(t)}(e,t,this._listeners),this}off(e,t){return function(e,t,n){if(n&&n[e]){const s=n[e].indexOf(t);-1!==s&&n[e].splice(s,1)}}(e,t,this._listeners),this}fire(e,t){if(e instanceof ne)return console.error(e.error),this;const n="string"==typeof e?new te(e,t||{}):e;const s=n.name;if(this._listens(s)){n.target=this;const e=this._listeners[s]?[...this._listeners[s]]:[];for(const t of e)t.call(this,n)}return this}_listens(e){return this._listeners[e]&&this._listeners[e].length>0}};function re(e,t){se.on(e,t)}function oe(e,t={}){se.fire(e,t)}function ie(e,t){se.off(e,t)}const ae="loginStateChanged",ce="loginStateExpire",ue="loginTypeChanged",he="anonymousConverted",le="refreshAccessToken";var de;!function(e){e.ANONYMOUS="ANONYMOUS",e.WECHAT="WECHAT",e.WECHAT_PUBLIC="WECHAT-PUBLIC",e.WECHAT_OPEN="WECHAT-OPEN",e.CUSTOM="CUSTOM",e.EMAIL="EMAIL",e.USERNAME="USERNAME",e.NULL="NULL"}(de||(de={}));const fe=["auth.getJwt","auth.logout","auth.signInWithTicket","auth.signInAnonymously","auth.signIn","auth.fetchAccessTokenWithRefreshToken","auth.signUpWithEmailAndPassword","auth.activateEndUserMail","auth.sendPasswordResetEmail","auth.resetPasswordWithToken","auth.isUsernameRegistered"],pe={"X-SDK-Version":"1.3.5"};function ge(e,t,n){const s=e[t];e[t]=function(t){const r={},o={};n.forEach(n=>{const{data:s,headers:i}=n.call(e,t);Object.assign(r,s),Object.assign(o,i)});const i=t.data;return i&&(()=>{var e;if(e=i,"[object FormData]"!==Object.prototype.toString.call(e))t.data={...i,...r};else for(const e in r)i.append(e,r[e])})(),t.headers={...t.headers||{},...o},s.call(e,t)}}function me(){const e=Math.random().toString(16).slice(2);return{data:{seqId:e},headers:{...pe,"x-seqid":e}}}class ye{constructor(e={}){var t;this.config=e,this._reqClass=new V.adapter.reqClass({timeout:this.config.timeout,timeoutMsg:`请求在${this.config.timeout/1e3}s内未完成,已中断`,restrictedMethods:["post"]}),this._cache=ee(this.config.env),this._localCache=(t=this.config.env,Z[t]),ge(this._reqClass,"post",[me]),ge(this._reqClass,"upload",[me]),ge(this._reqClass,"download",[me])}async post(e){return await this._reqClass.post(e)}async upload(e){return await this._reqClass.upload(e)}async download(e){return await this._reqClass.download(e)}async refreshAccessToken(){let e,t;this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=this._refreshAccessToken());try{e=await this._refreshAccessTokenPromise}catch(e){t=e}if(this._refreshAccessTokenPromise=null,this._shouldRefreshAccessTokenHook=null,t)throw t;return e}async _refreshAccessToken(){const{accessTokenKey:e,accessTokenExpireKey:t,refreshTokenKey:n,loginTypeKey:s,anonymousUuidKey:r}=this._cache.keys;this._cache.removeStore(e),this._cache.removeStore(t);let o=this._cache.getStore(n);if(!o)throw new Error("未登录CloudBase");const i={refresh_token:o},a=await this.request("auth.fetchAccessTokenWithRefreshToken",i);if(a.data.code){const{code:e}=a.data;if("SIGN_PARAM_INVALID"===e||"REFRESH_TOKEN_EXPIRED"===e||"INVALID_REFRESH_TOKEN"===e){if(this._cache.getStore(s)===de.ANONYMOUS&&"INVALID_REFRESH_TOKEN"===e){const e=this._cache.getStore(r),t=this._cache.getStore(n),s=await this.send("auth.signInAnonymously",{anonymous_uuid:e,refresh_token:t});return this.setRefreshToken(s.refresh_token),this._refreshAccessToken()}oe(ce),this._cache.removeStore(n)}throw new Error("刷新access token失败:"+a.data.code)}if(a.data.access_token)return oe(le),this._cache.setStore(e,a.data.access_token),this._cache.setStore(t,a.data.access_token_expire+Date.now()),{accessToken:a.data.access_token,accessTokenExpire:a.data.access_token_expire};a.data.refresh_token&&(this._cache.removeStore(n),this._cache.setStore(n,a.data.refresh_token),this._refreshAccessToken())}async getAccessToken(){const{accessTokenKey:e,accessTokenExpireKey:t,refreshTokenKey:n}=this._cache.keys;if(!this._cache.getStore(n))throw new Error("refresh token不存在,登录状态异常");let s=this._cache.getStore(e),r=this._cache.getStore(t),o=!0;return this._shouldRefreshAccessTokenHook&&!await this._shouldRefreshAccessTokenHook(s,r)&&(o=!1),(!s||!r||r{e.wxOpenId&&e.wxPublicId&&(t=!0)}),{users:n,hasPrimaryUid:t}}setPrimaryUid(e){return this._request.send("auth.setPrimaryUid",{uid:e})}unlink(e){return this._request.send("auth.unlink",{platform:e})}async update(e){const{nickName:t,gender:n,avatarUrl:s,province:r,country:o,city:i}=e,{data:a}=await this._request.send("auth.updateUserInfo",{nickName:t,gender:n,avatarUrl:s,province:r,country:o,city:i});this.setLocalUserInfo(a)}async refresh(){const{data:e}=await this._request.send("auth.getUserInfo",{});return this.setLocalUserInfo(e),e}setUserInfo(){const{userInfoKey:e}=this._cache.keys,t=this._cache.getStore(e);["uid","loginType","openid","wxOpenId","wxPublicId","unionId","qqMiniOpenId","email","hasPassword","customUserId","nickName","gender","avatarUrl"].forEach(e=>{this[e]=t[e]}),this.location={country:t.country,province:t.province,city:t.city}}setLocalUserInfo(e){const{userInfoKey:t}=this._cache.keys;this._cache.setStore(t,e),this.setUserInfo()}}class ke{constructor(e){if(!e)throw new Error("envId is not defined");this._cache=ee(e);const{refreshTokenKey:t,accessTokenKey:n,accessTokenExpireKey:s}=this._cache.keys,r=this._cache.getStore(t),o=this._cache.getStore(n),i=this._cache.getStore(s);this.credential={refreshToken:r,accessToken:o,accessTokenExpire:i},this.user=new Se(e)}get isAnonymousAuth(){return this.loginType===de.ANONYMOUS}get isCustomAuth(){return this.loginType===de.CUSTOM}get isWeixinAuth(){return this.loginType===de.WECHAT||this.loginType===de.WECHAT_OPEN||this.loginType===de.WECHAT_PUBLIC}get loginType(){return this._cache.getStore(this._cache.keys.loginTypeKey)}}class Te extends ve{async signIn(){this._cache.updatePersistence("local");const{anonymousUuidKey:e,refreshTokenKey:t}=this._cache.keys,n=this._cache.getStore(e)||void 0,s=this._cache.getStore(t)||void 0,r=await this._request.send("auth.signInAnonymously",{anonymous_uuid:n,refresh_token:s});if(r.uuid&&r.refresh_token){this._setAnonymousUUID(r.uuid),this.setRefreshToken(r.refresh_token),await this._request.refreshAccessToken(),oe(ae),oe(ue,{env:this.config.env,loginType:de.ANONYMOUS,persistence:"local"});const e=new ke(this.config.env);return await e.user.refresh(),e}throw new Error("匿名登录失败")}async linkAndRetrieveDataWithTicket(e){const{anonymousUuidKey:t,refreshTokenKey:n}=this._cache.keys,s=this._cache.getStore(t),r=this._cache.getStore(n),o=await this._request.send("auth.linkAndRetrieveDataWithTicket",{anonymous_uuid:s,refresh_token:r,ticket:e});if(o.refresh_token)return this._clearAnonymousUUID(),this.setRefreshToken(o.refresh_token),await this._request.refreshAccessToken(),oe(he,{env:this.config.env}),oe(ue,{loginType:de.CUSTOM,persistence:"local"}),{credential:{refreshToken:o.refresh_token}};throw new Error("匿名转化失败")}_setAnonymousUUID(e){const{anonymousUuidKey:t,loginTypeKey:n}=this._cache.keys;this._cache.removeStore(t),this._cache.setStore(t,e),this._cache.setStore(n,de.ANONYMOUS)}_clearAnonymousUUID(){this._cache.removeStore(this._cache.keys.anonymousUuidKey)}}class Pe extends ve{async signIn(e){if("string"!=typeof e)throw new Error("ticket must be a string");const{refreshTokenKey:t}=this._cache.keys,n=await this._request.send("auth.signInWithTicket",{ticket:e,refresh_token:this._cache.getStore(t)||""});if(n.refresh_token)return this.setRefreshToken(n.refresh_token),await this._request.refreshAccessToken(),oe(ae),oe(ue,{env:this.config.env,loginType:de.CUSTOM,persistence:this.config.persistence}),await this.refreshUserInfo(),new ke(this.config.env);throw new Error("自定义登录失败")}}class Ie extends ve{async signIn(e,t){if("string"!=typeof e)throw new Error("email must be a string");const{refreshTokenKey:n}=this._cache.keys,s=await this._request.send("auth.signIn",{loginType:"EMAIL",email:e,password:t,refresh_token:this._cache.getStore(n)||""}),{refresh_token:r,access_token:o,access_token_expire:i}=s;if(r)return this.setRefreshToken(r),o&&i?this.setAccessToken(o,i):await this._request.refreshAccessToken(),await this.refreshUserInfo(),oe(ae),oe(ue,{env:this.config.env,loginType:de.EMAIL,persistence:this.config.persistence}),new ke(this.config.env);throw s.code?new Error(`邮箱登录失败: [${s.code}] ${s.message}`):new Error("邮箱登录失败")}async activate(e){return this._request.send("auth.activateEndUserMail",{token:e})}async resetPasswordWithToken(e,t){return this._request.send("auth.resetPasswordWithToken",{token:e,newPassword:t})}}class Ae extends ve{async signIn(e,t){if("string"!=typeof e)throw new Error("username must be a string");"string"!=typeof t&&(t="",console.warn("password is empty"));const{refreshTokenKey:n}=this._cache.keys,s=await this._request.send("auth.signIn",{loginType:de.USERNAME,username:e,password:t,refresh_token:this._cache.getStore(n)||""}),{refresh_token:r,access_token_expire:o,access_token:i}=s;if(r)return this.setRefreshToken(r),i&&o?this.setAccessToken(i,o):await this._request.refreshAccessToken(),await this.refreshUserInfo(),oe(ae),oe(ue,{env:this.config.env,loginType:de.USERNAME,persistence:this.config.persistence}),new ke(this.config.env);throw s.code?new Error(`用户名密码登录失败: [${s.code}] ${s.message}`):new Error("用户名密码登录失败")}}class Ee{constructor(e){this.config=e,this._cache=ee(e.env),this._request=we(e.env),this._onAnonymousConverted=this._onAnonymousConverted.bind(this),this._onLoginTypeChanged=this._onLoginTypeChanged.bind(this),re(ue,this._onLoginTypeChanged)}get currentUser(){const e=this.hasLoginState();return e&&e.user||null}get loginType(){return this._cache.getStore(this._cache.keys.loginTypeKey)}anonymousAuthProvider(){return new Te(this.config)}customAuthProvider(){return new Pe(this.config)}emailAuthProvider(){return new Ie(this.config)}usernameAuthProvider(){return new Ae(this.config)}async signInAnonymously(){return new Te(this.config).signIn()}async signInWithEmailAndPassword(e,t){return new Ie(this.config).signIn(e,t)}signInWithUsernameAndPassword(e,t){return new Ae(this.config).signIn(e,t)}async linkAndRetrieveDataWithTicket(e){this._anonymousAuthProvider||(this._anonymousAuthProvider=new Te(this.config)),re(he,this._onAnonymousConverted);return await this._anonymousAuthProvider.linkAndRetrieveDataWithTicket(e)}async signOut(){if(this.loginType===de.ANONYMOUS)throw new Error("匿名用户不支持登出操作");const{refreshTokenKey:e,accessTokenKey:t,accessTokenExpireKey:n}=this._cache.keys,s=this._cache.getStore(e);if(!s)return;const r=await this._request.send("auth.logout",{refresh_token:s});return this._cache.removeStore(e),this._cache.removeStore(t),this._cache.removeStore(n),oe(ae),oe(ue,{env:this.config.env,loginType:de.NULL,persistence:this.config.persistence}),r}async signUpWithEmailAndPassword(e,t){return this._request.send("auth.signUpWithEmailAndPassword",{email:e,password:t})}async sendPasswordResetEmail(e){return this._request.send("auth.sendPasswordResetEmail",{email:e})}onLoginStateChanged(e){re(ae,()=>{const t=this.hasLoginState();e.call(this,t)});const t=this.hasLoginState();e.call(this,t)}onLoginStateExpired(e){re(ce,e.bind(this))}onAccessTokenRefreshed(e){re(le,e.bind(this))}onAnonymousConverted(e){re(he,e.bind(this))}onLoginTypeChanged(e){re(ue,()=>{const t=this.hasLoginState();e.call(this,t)})}async getAccessToken(){return{accessToken:(await this._request.getAccessToken()).accessToken,env:this.config.env}}hasLoginState(){const{refreshTokenKey:e}=this._cache.keys;return this._cache.getStore(e)?new ke(this.config.env):null}async isUsernameRegistered(e){if("string"!=typeof e)throw new Error("username must be a string");const{data:t}=await this._request.send("auth.isUsernameRegistered",{username:e});return t&&t.isRegistered}getLoginState(){return Promise.resolve(this.hasLoginState())}async signInWithTicket(e){return new Pe(this.config).signIn(e)}shouldRefreshAccessToken(e){this._request._shouldRefreshAccessTokenHook=e.bind(this)}getUserInfo(){return this._request.send("auth.getUserInfo",{}).then(e=>e.code?e:{...e.data,requestId:e.seqId})}getAuthHeader(){const{refreshTokenKey:e,accessTokenKey:t}=this._cache.keys,n=this._cache.getStore(e);return{"x-cloudbase-credentials":this._cache.getStore(t)+"/@@/"+n}}_onAnonymousConverted(e){const{env:t}=e.data;t===this.config.env&&this._cache.updatePersistence(this.config.persistence)}_onLoginTypeChanged(e){const{loginType:t,persistence:n,env:s}=e.data;s===this.config.env&&(this._cache.updatePersistence(n),this._cache.setStore(this._cache.keys.loginTypeKey,t))}}const be=function(e,t){t=t||K();const n=we(this.config.env),{cloudPath:s,filePath:r,onUploadProgress:o,fileType:i="image"}=e;return n.send("storage.getUploadMetadata",{path:s}).then(e=>{const{data:{url:a,authorization:c,token:u,fileId:h,cosFileId:l},requestId:d}=e,f={key:s,signature:c,"x-cos-meta-fileid":l,success_action_status:"201","x-cos-security-token":u};n.upload({url:a,data:f,file:r,name:s,fileType:i,onUploadProgress:o}).then(e=>{201===e.statusCode?t(null,{fileID:h,requestId:d}):t(new Error("STORAGE_REQUEST_FAIL: "+e.data))}).catch(e=>{t(e)})}).catch(e=>{t(e)}),t.promise},Oe=function(e,t){t=t||K();const n=we(this.config.env),{cloudPath:s}=e;return n.send("storage.getUploadMetadata",{path:s}).then(e=>{t(null,e)}).catch(e=>{t(e)}),t.promise},Ue=function({fileList:e},t){if(t=t||K(),!e||!Array.isArray(e))return{code:"INVALID_PARAM",message:"fileList必须是非空的数组"};for(let t of e)if(!t||"string"!=typeof t)return{code:"INVALID_PARAM",message:"fileList的元素必须是非空的字符串"};const n={fileid_list:e};return we(this.config.env).send("storage.batchDeleteFile",n).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.delete_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},Ce=function({fileList:e},t){t=t||K(),e&&Array.isArray(e)||t(null,{code:"INVALID_PARAM",message:"fileList必须是非空的数组"});let n=[];for(let s of e)"object"==typeof s?(s.hasOwnProperty("fileID")&&s.hasOwnProperty("maxAge")||t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是包含fileID和maxAge的对象"}),n.push({fileid:s.fileID,max_age:s.maxAge})):"string"==typeof s?n.push({fileid:s}):t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是字符串"});const s={file_list:n};return we(this.config.env).send("storage.batchGetDownloadUrl",s).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.download_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},De=async function({fileID:e},t){const n=(await Ce.call(this,{fileList:[{fileID:e,maxAge:600}]})).fileList[0];if("SUCCESS"!==n.code)return t?t(n):new Promise(e=>{e(n)});const s=we(this.config.env);let r=n.download_url;if(r=encodeURI(r),!t)return s.download({url:r});t(await s.download({url:r}))},xe=function({name:e,data:t,query:n,parse:s,search:r},o){const i=o||K();let a;try{a=t?JSON.stringify(t):""}catch(e){return Promise.reject(e)}if(!e)return Promise.reject(new Error("函数名不能为空"));const c={inQuery:n,parse:s,search:r,function_name:e,request_data:a};return we(this.config.env).send("functions.invokeFunction",c).then(e=>{if(e.code)i(null,e);else{let t=e.data.response_data;if(s)i(null,{result:t,requestId:e.requestId});else try{t=JSON.parse(e.data.response_data),i(null,{result:t,requestId:e.requestId})}catch(e){i(new Error("response data must be json"))}}return i.promise}).catch(e=>{i(e)}),i.promise},Re={timeout:15e3,persistence:"session"},qe={};class Fe{constructor(e){this.config=e||this.config,this.authObj=void 0}init(e){switch(V.adapter||(this.requestClient=new V.adapter.reqClass({timeout:e.timeout||5e3,timeoutMsg:`请求在${(e.timeout||5e3)/1e3}s内未完成,已中断`})),this.config={...Re,...e},!0){case this.config.timeout>6e5:console.warn("timeout大于可配置上限[10分钟],已重置为上限数值"),this.config.timeout=6e5;break;case this.config.timeout<100:console.warn("timeout小于可配置下限[100ms],已重置为下限数值"),this.config.timeout=100}return new Fe(this.config)}auth({persistence:e}={}){if(this.authObj)return this.authObj;const t=e||V.adapter.primaryStorage||Re.persistence;var n;return t!==this.config.persistence&&(this.config.persistence=t),function(e){const{env:t}=e;Q[t]=new G(e),Z[t]=new G({...e,persistence:"local"})}(this.config),n=this.config,_e[n.env]=new ye(n),this.authObj=new Ee(this.config),this.authObj}on(e,t){return re.apply(this,[e,t])}off(e,t){return ie.apply(this,[e,t])}callFunction(e,t){return xe.apply(this,[e,t])}deleteFile(e,t){return Ue.apply(this,[e,t])}getTempFileURL(e,t){return Ce.apply(this,[e,t])}downloadFile(e,t){return De.apply(this,[e,t])}uploadFile(e,t){return be.apply(this,[e,t])}getUploadMetadata(e,t){return Oe.apply(this,[e,t])}registerExtension(e){qe[e.name]=e}async invokeExtension(e,t){const n=qe[e];if(!n)throw Error(`扩展${e} 必须先注册`);return await n.invoke(t,this)}useAdapters(e){const{adapter:t,runtime:n}=z(e)||{};t&&(V.adapter=t),n&&(V.runtime=n)}}const Le=new Fe;function Ne(e,t,n){void 0===n&&(n={});var s=/\?/.test(t),r="";for(var o in n)""===r?!s&&(t+="?"):r+="&",r+=o+"="+encodeURIComponent(n[o]);return/^http(s)?:\/\//.test(t+=r)?t:""+e+t}class Me{post(e){const{url:t,data:n,headers:s}=e;return new Promise((e,r)=>{q.request({url:Ne("https:",t),data:n,method:"POST",header:s,success(t){e(t)},fail(e){r(e)}})})}upload(e){return new Promise((t,n)=>{const{url:s,file:r,data:o,headers:i,fileType:a}=e,c=q.uploadFile({url:Ne("https:",s),name:"file",formData:Object.assign({},o),filePath:r,fileType:a,header:i,success(e){const n={statusCode:e.statusCode,data:e.data||{}};200===e.statusCode&&o.success_action_status&&(n.statusCode=parseInt(o.success_action_status,10)),t(n)},fail(e){u&&"mp-alipay"===h&&console.warn("支付宝小程序开发工具上传腾讯云时无法准确判断是否上传成功,请使用真机测试"),n(new Error(e.errMsg||"uploadFile:fail"))}});"function"==typeof e.onUploadProgress&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(t=>{e.onUploadProgress({loaded:t.totalBytesSent,total:t.totalBytesExpectedToSend})})})}}const je={setItem(e,t){q.setStorageSync(e,t)},getItem:e=>q.getStorageSync(e),removeItem(e){q.removeStorageSync(e)},clear(){q.clearStorageSync()}};const $e={genAdapter:function(){return{root:{},reqClass:Me,localStorage:je,primaryStorage:"local"}},isMatch:function(){return!0},runtime:"uni_app"};Le.useAdapters($e);const Ke=Le,Be=Ke.init;Ke.init=function(e){e.env=e.spaceId;const t=Be.call(this,e);t.config.provider="tencent",t.config.spaceId=e.spaceId;const n=t.auth;return t.auth=function(e){const t=n.call(this,e);return["linkAndRetrieveDataWithTicket","signInAnonymously","signOut","getAccessToken","getLoginState","signInWithTicket","getUserInfo"].forEach(e=>{t[e]=k(t[e]).bind(t)}),t},t.customAuth=t.auth,t};class He extends F{getAccessToken(){return new Promise((e,t)=>{this.setAccessToken("Anonymous_Access_token"),e("Anonymous_Access_token")})}setupRequest(e,t){const n=Object.assign({},e,{spaceId:this.config.spaceId,timestamp:Date.now()}),s={"Content-Type":"application/json"};"auth"!==t&&(n.token=this.accessToken,s["x-basement-token"]=this.accessToken),s["x-serverless-sign"]=R.sign(n,this.config.clientSecret);const r=C(),{APPID:o,PLATFORM:i,DEVICEID:a,CLIENT_SDK_VERSION:c}=r;return s["x-client-platform"]=i,s["x-client-appid"]=o,s["x-client-device-id"]=a,s["x-client-version"]=c,s["x-client-token"]=q.getStorageSync("uni_id_token"),{url:this.config.requestUrl,method:"POST",data:n,dataType:"json",header:JSON.parse(JSON.stringify(s))}}uploadFileToOSS({url:e,formData:t,name:n,filePath:s,fileType:r,onUploadProgress:o}){return new Promise((i,a)=>{const c=this.adapter.uploadFile({url:e,formData:t,name:n,filePath:s,fileType:r,success(e){e&&e.statusCode<400?i(e):a(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){a(new T({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(e=>{o({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend})})})}uploadFile({filePath:e,cloudPath:t,fileType:n="image",onUploadProgress:s}){if(!t)throw new T({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});let r;return this.getOSSUploadOptionsFromPath({cloudPath:t}).then(t=>{const{url:o,formData:i,name:a,fileUrl:c}=t.result;r=c;const u={url:o,formData:i,name:a,filePath:e,fileType:n};return this.uploadFileToOSS(Object.assign({},u,{onUploadProgress:s}))}).then(()=>this.reportOSSUpload({cloudPath:t})).then(t=>new Promise((n,s)=>{t.success?n({success:!0,filePath:e,fileID:r}):s(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))}))}}const We={init(e){const t=new He(e),n={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return n},t.customAuth=t.auth,t}};let ze,Ve;function Je({name:e,data:t,spaceId:n,provider:s}){ze||(ze=C(),Ve={ak:E.appid,p:"android"===O?"a":"i",ut:x(),uuid:D()});const r=JSON.parse(JSON.stringify(t||{})),o=e,i=n,a={tencent:"t",aliyun:"a"}[s];{const e=Object.assign({},Ve,{fn:o,sid:i,pvd:a});Object.assign(r,{clientInfo:ze,uniCloudClientInfo:encodeURIComponent(JSON.stringify(e))});const{deviceId:t}=uni.getSystemInfoSync();r.uniCloudDeviceId=t}if(!r.uniIdToken){const e=q.getStorageSync("uni_id_token")||q.getStorageSync("uniIdToken");e&&(r.uniIdToken=e)}return r}function Ye({name:e,data:t}){const{localAddress:n,localPort:s}=this,r={aliyun:"aliyun",tencent:"tcb"}[this.config.provider],o=this.config.spaceId,i=`http://${n}:${s}/system/check-function`,a=`http://${n}:${s}/cloudfunctions/${e}`;return new Promise((t,n)=>{q.request({method:"POST",url:i,data:{name:e,platform:h,provider:r,spaceId:o},timeout:3e3,success(e){t(e)},fail(){t({data:{code:"NETWORK_ERROR",message:"连接本地调试服务失败,请检查客户端是否和主机在同一局域网下,自动切换为已部署的云函数。"}})}})}).then(({data:e}={})=>{const{code:t,message:n}=e||{};return{code:0===t?0:t||"SYS_ERR",message:n||"SYS_ERR"}}).then(({code:n,message:s})=>{if(0!==n){switch(n){case"MODULE_ENCRYPTED":console.error(`此云函数(${e})依赖加密公共模块不可本地调试,自动切换为云端已部署的云函数`);break;case"FUNCTION_ENCRYPTED":console.error(`此云函数(${e})已加密不可本地调试,自动切换为云端已部署的云函数`);break;case"ACTION_ENCRYPTED":console.error(s||"需要访问加密的uni-clientDB-action,自动切换为云端环境");break;case"NETWORK_ERROR":{const e="连接本地调试服务失败,请检查客户端是否和主机在同一局域网下";throw console.error(e),new Error(e)}case"SWITCH_TO_CLOUD":break;default:{const e=`检测本地调试服务出现错误:${s},请检查网络环境或重启客户端再试`;throw console.error(e),new Error(e)}}return this._originCallFunction({name:e,data:t})}return new Promise((n,s)=>{const i=Je({name:e,data:t,provider:this.config.provider,spaceId:o});q.request({method:"POST",url:a,data:{provider:r,platform:h,param:i},success:({statusCode:e,data:t}={})=>!e||e>=400?s(new T({code:t.code||"SYS_ERR",message:t.message||"request:fail"})):n({result:t}),fail(e){s(new T({code:e.code||e.errCode||"SYS_ERR",message:e.message||e.errMsg||"request:fail"}))}})})})}const Xe=[{rule:/fc_function_not_found|FUNCTION_NOT_FOUND/,content:",云函数[{functionName}]在云端不存在,请检查此云函数名称是否正确以及该云函数是否已上传到服务空间",mode:"append"}];var Ge=/[\\^$.*+?()[\]{}|]/g,Qe=RegExp(Ge.source);function Ze(e,t,n){return e.replace(new RegExp((s=t)&&Qe.test(s)?s.replace(Ge,"\\$&"):s,"g"),n);var s}function et({functionName:e,result:t,logPvd:n}){if(this.config.useDebugFunction&&t&&t.requestId){const s=JSON.stringify({spaceId:this.config.spaceId,functionName:e,requestId:t.requestId});console.log(`[${n}-request]${s}[/${n}-request]`)}}function tt(e){const t=e.callFunction,n=function(e){const n=e.name;e.data=Je({name:n,data:e.data,provider:this.config.provider,spaceId:this.config.spaceId});const s={aliyun:"aliyun",tencent:"tcb"}[this.config.provider];return t.call(this,e).then(e=>(et.call(this,{functionName:n,result:e,logPvd:s}),Promise.resolve(e)),t=>(et.call(this,{functionName:n,result:t,logPvd:s}),t&&t.message&&(t.message=function({message:e="",extraInfo:t={},formatter:n=[]}={}){for(let s=0;s(console.warn("当前返回结果为Promise类型,不可直接访问其result属性,详情请参考:https://uniapp.dcloud.net.cn/uniCloud/faq?id=promise"),{})}),s}}const nt=Symbol("CLIENT_DB_INTERNAL");function st(e,t){return e.then="DoNotReturnProxyWithAFunctionNamedThen",e._internalType=nt,new Proxy(e,{get:(e,n,s)=>n in e||"string"!=typeof n?e[n]:t.get(e,n,s)})}function rt(e){switch(o(e)){case"array":return e.map(e=>rt(e));case"object":return e._internalType===nt||Object.keys(e).forEach(t=>{e[t]=rt(e[t])}),e;case"regexp":return{$regexp:{source:e.source,flags:e.flags}};case"date":return{$date:e.toISOString()};default:return e}}function ot(){const e=q.getStorageSync("uni_id_token")||"",t=e.split(".");if(!e||3!==t.length)return{uid:null,role:[],permission:[],tokenExpired:0};let n;try{n=JSON.parse((s=t[1],decodeURIComponent(atob(s).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))))}catch(e){throw new Error("获取当前用户信息出错,详细错误信息为:"+e.message)}var s;return n.tokenExpired=1e3*n.exp,delete n.exp,delete n.iat,n}var it=t(n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n="chooseAndUploadFile:fail";function s(e,t){return e.tempFiles.forEach((e,n)=>{e.name||(e.name=e.path.substring(e.path.lastIndexOf("/")+1)),t&&(e.fileType=t),e.cloudPath=Date.now()+"_"+n+e.name.substring(e.name.lastIndexOf("."))}),e.tempFilePaths||(e.tempFilePaths=e.tempFiles.map(e=>e.path)),e}function r(e,t,{onChooseFile:n,onUploadProgress:s}){return t.then(e=>{if(n){const t=n(e);if(void 0!==t)return Promise.resolve(t).then(t=>void 0===t?e:t)}return e}).then(t=>!1===t?{errMsg:"chooseAndUploadFile:ok",tempFilePaths:[],tempFiles:[]}:function(e,t,n=5,s){(t=Object.assign({},t)).errMsg="chooseAndUploadFile:ok";const r=t.tempFiles,o=r.length;let i=0;return new Promise(a=>{for(;i=o)return void(!r.find(e=>!e.url&&!e.errMsg)&&a(t));const u=r[n];e.uploadFile({filePath:u.path,cloudPath:u.cloudPath,fileType:u.fileType,onUploadProgress(e){e.index=n,e.tempFile=u,e.tempFilePath=u.path,s&&s(e)}}).then(e=>{u.url=e.fileID,n{u.errMsg=e.errMsg||e.message,n{uni.chooseImage({count:t,sizeType:r,sourceType:o,extension:i,success(t){e(s(t,"image"))},fail(e){a({errMsg:e.errMsg.replace("chooseImage:fail",n)})}})})}(t),t):"video"===t.type?r(e,function(e){const{camera:t,compressed:r,maxDuration:o,sourceType:i=["album","camera"],extension:a}=e;return new Promise((e,c)=>{uni.chooseVideo({camera:t,compressed:r,maxDuration:o,sourceType:i,extension:a,success(t){const{tempFilePath:n,duration:r,size:o,height:i,width:a}=t;e(s({errMsg:"chooseVideo:ok",tempFilePaths:[n],tempFiles:[{name:t.tempFile&&t.tempFile.name||"",path:n,size:o,type:t.tempFile&&t.tempFile.type||"",width:a,height:i,duration:r,fileType:"video",cloudPath:""}]},"video"))},fail(e){c({errMsg:e.errMsg.replace("chooseVideo:fail",n)})}})})}(t),t):r(e,function(e){const{count:t,extension:r}=e;return new Promise((e,o)=>{let i=uni.chooseFile;if("undefined"!=typeof wx&&"function"==typeof wx.chooseMessageFile&&(i=wx.chooseMessageFile),"function"!=typeof i)return o({errMsg:n+" 请指定 type 类型,该平台仅支持选择 image 或 video。"});i({type:"all",count:t,extension:r,success(t){e(s(t))},fail(e){o({errMsg:e.errMsg.replace("chooseFile:fail",n)})}})})}(t),t)}}})));const at="manual";function ct(e){return{props:{localdata:{type:Array,default:()=>[]},options:{type:[Object,Array],default:()=>({})},collection:{type:String,default:""},action:{type:String,default:""},field:{type:String,default:""},orderby:{type:String,default:""},where:{type:[String,Object],default:""},pageData:{type:String,default:"add"},pageCurrent:{type:Number,default:1},pageSize:{type:Number,default:20},getcount:{type:[Boolean,String],default:!1},gettree:{type:[Boolean,String],default:!1},gettreepath:{type:[Boolean,String],default:!1},startwith:{type:String,default:""},limitlevel:{type:Number,default:10},groupby:{type:String,default:""},groupField:{type:String,default:""},distinct:{type:[Boolean,String],default:!1},foreignKey:{type:String,default:""},loadtime:{type:String,default:"auto"},manual:{type:Boolean,default:!1}},data:()=>({mixinDatacomLoading:!1,mixinDatacomHasMore:!1,mixinDatacomResData:[],mixinDatacomErrorMessage:"",mixinDatacomPage:{}}),created(){this.mixinDatacomPage={current:this.pageCurrent,size:this.pageSize,count:0},this.$watch(()=>{var e=[];return["pageCurrent","pageSize","localdata","collection","action","field","orderby","where","getont","getcount","gettree","groupby","groupField","distinct"].forEach(t=>{e.push(this[t])}),e},(e,t)=>{if(this.loadtime===at)return;let n=!1;const s=[];for(let r=2;r{this.mixinDatacomLoading=!1;const{data:s,count:r}=n.result;this.getcount&&(this.mixinDatacomPage.count=r),this.mixinDatacomHasMore=s.length{this.mixinDatacomLoading=!1,this.mixinDatacomErrorMessage=e,n&&n(e)}))},mixinDatacomGet(t={}){let n=e.database();const s=t.action||this.action;s&&(n=n.action(s));const r=t.collection||this.collection;n=n.collection(r);const o=t.where||this.where;o&&Object.keys(o).length&&(n=n.where(o));const i=t.field||this.field;i&&(n=n.field(i));const a=t.foreignKey||this.foreignKey;a&&(n=n.foreignKey(a));const c=t.groupby||this.groupby;c&&(n=n.groupBy(c));const u=t.groupField||this.groupField;u&&(n=n.groupField(u));!0===(void 0!==t.distinct?t.distinct:this.distinct)&&(n=n.distinct());const h=t.orderby||this.orderby;h&&(n=n.orderBy(h));const l=void 0!==t.pageCurrent?t.pageCurrent:this.mixinDatacomPage.current,d=void 0!==t.pageSize?t.pageSize:this.mixinDatacomPage.size,f=void 0!==t.getcount?t.getcount:this.getcount,p=void 0!==t.gettree?t.gettree:this.gettree,g=void 0!==t.gettreepath?t.gettreepath:this.gettreepath,m={getCount:f},y={limitLevel:void 0!==t.limitlevel?t.limitlevel:this.limitlevel,startWith:void 0!==t.startwith?t.startwith:this.startwith};return p&&(m.getTree=y),g&&(m.getTreePath=y),n=n.skip(d*(l-1)).limit(d).get(m),n}}}}async function ut(e,t){const n=`http://${e}:${t}/system/ping`;try{const e=await(s={url:n,timeout:500},new Promise((e,t)=>{q.request({...s,success(t){e(t)},fail(e){t(e)}})}));return!(!e.data||0!==e.data.code)}catch(e){return!1}var s}let ht=new class{init(e){let t={};const n=!1!==e.debugFunction&&u&&("h5"===h&&navigator.userAgent.indexOf("HBuilderX")>0||"app-plus"===h);switch(e.provider){case"tencent":t=Ke.init(Object.assign(e,{useDebugFunction:n}));break;case"aliyun":t=L.init(Object.assign(e,{useDebugFunction:n}));break;case"private":t=We.init(Object.assign(e,{useDebugFunction:n}));break;default:throw new Error("未提供正确的provider参数")}const s=l;u&&s&&!s.code&&(t.debugInfo=s);let r=Promise.resolve();var o;o=1,r=new Promise((e,t)=>{setTimeout(()=>{e()},o)}),t.isReady=!1,t.isDefault=!1;const i=t.auth();t.initUniCloud=r.then(()=>i.getLoginState()).then(e=>e?Promise.resolve():i.signInAnonymously()).then(()=>{if(u&&t.debugInfo){const{address:e,servePort:n}=t.debugInfo;return async function(e,t){let n;for(let s=0;s{if(!u)return Promise.resolve();if(e)t.localAddress=e,t.localPort=n;else if(t.debugInfo){const e=console["app-plus"===h?"error":"warn"];"remote"===t.debugInfo.initialLaunchType?(t.debugInfo.forceRemote=!0,e("当前客户端和HBuilderX不在同一局域网下(或其他网络原因无法连接HBuilderX),uniCloud本地调试服务不对当前客户端生效。\n- 如果不使用uniCloud本地调试服务,请直接忽略此信息。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试\n- 检查系统防火墙是否拦截了HBuilderX自带的nodejs")):e("无法连接uniCloud本地调试服务,请检查当前客户端是否与主机在同一局域网下。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试\n- 检查系统防火墙是否拦截了HBuilderX自带的nodejs")}}).then(()=>(function(){if(!u||"h5"!==h)return;if(uni.getStorageSync("__LAST_DCLOUD_APPID")===E.appid)return;uni.setStorageSync("__LAST_DCLOUD_APPID",E.appid),uni.removeStorageSync("uni_id_token")&&(console.warn("检测到当前项目与上次运行到此端口的项目不一致,自动清理uni-id保存的token信息(仅开发调试时生效)"),uni.removeStorageSync("uni_id_token"),uni.removeStorageSync("uni_id_token_expired"))}(),new Promise(e=>{"quickapp-native"===h?(O="android",uni.getStorage({key:"__DC_CLOUD_UUID",success(t){b=t.data?t.data:U(32),e()}})):setTimeout(()=>{O=uni.getSystemInfoSync().platform,b=uni.getStorageSync("__DC_CLOUD_UUID")||U(32),e()},0)}))).then(()=>{t.isReady=!0}),tt(t),function(e){const t=e.uploadFile;e.uploadFile=function(e){let n;return n=this.isReady?Promise.resolve():this.initUniCloud,n.then(()=>t.call(this,e))}}(t),function(e){e.database=function(){if(this._database)return this._database;const t={};let n={};function s({action:s,command:r,multiCommand:o}){return v(S("database","invoke")).then(()=>e.callFunction({name:"DCloud-clientDB",data:{action:s,command:r,multiCommand:o}})).then(e=>{const{code:s,message:r,token:o,tokenExpired:i,systemInfo:c=[]}=e.result;if(c)for(let e=0;e{t(e)}),Promise.reject(e)}o&&i&&(t.refreshToken&&t.refreshToken.forEach(e=>{e({token:o,tokenExpired:i})}),n.refreshToken&&n.refreshToken.forEach(e=>{e({token:o,tokenExpired:i})}));const u=e.result.affectedDocs;return"number"==typeof u&&Object.defineProperty(e.result,"affectedDocs",{get:()=>(console.warn("affectedDocs不再推荐使用,请使用inserted/deleted/updated/data.length替代"),u)}),v(S("database","success"),e).then(()=>v(S("database","complete"),e)).then(()=>Promise.resolve(e))},e=>{const t=new a(e.message,e.code||"SYSTEM_ERROR");return n.error&&n.error.forEach(e=>{e(t)}),/fc_function_not_found|FUNCTION_NOT_FOUND/g.test(e.message)&&console.warn("clientDB未初始化,请在web控制台保存一次schema以开启clientDB"),v(S("database","fail"),e).then(()=>v(S("database","complete"),e)).then(()=>Promise.reject(e))})}this.isDefault&&(n=g("_globalUniCloudDatabaseCallback"));class r{constructor(e,t){this.content=e,this.prevStage=t,this.udb=null}toJSON(){let e=this;const t=[e.content];for(;e.prevStage;)e=e.prevStage,t.push(e.content);return{$db:t.reverse().map(e=>({$method:e.$method,$param:e.$param}))}}getAction(){const e=this.toJSON().$db.find(e=>"action"===e.$method);return e&&e.$param&&e.$param[0]}getCommand(){return{$db:this.toJSON().$db.filter(e=>"action"!==e.$method)}}get useAggregate(){let e=this,t=!1;for(;e.prevStage;){e=e.prevStage;const n=e.content.$method;if("aggregate"===n||"pipeline"===n){t=!0;break}}return t}get count(){if(!this.useAggregate)return function(){return this._send("count",Array.from(arguments))};const e=this;return function(){return c({$method:"count",$param:rt(Array.from(arguments))},e)}}get(){return this._send("get",Array.from(arguments))}add(){return this._send("add",Array.from(arguments))}remove(){return this._send("remove",Array.from(arguments))}update(){return this._send("update",Array.from(arguments))}end(){return this._send("end",Array.from(arguments))}set(){throw new Error("clientDB禁止使用set方法")}get multiSend(){}_send(e,t){const n=this.getAction(),r=this.getCommand();return r.$db.push({$method:e,$param:rt(t)}),s({action:n,command:r})}}const o=["db.Geo","db.command","command.aggregate"];function i(e,t){return o.indexOf(`${e}.${t}`)>-1}function c(e,t){return st(new r(e,t),{get(e,t){let n="db";return e&&e.content&&(n=e.content.$method),i(n,t)?c({$method:t},e):function(){return c({$method:t,$param:rt(Array.from(arguments))},e)}},set(e,t,n){e[t]=n}})}function u({path:e,method:t}){return class{constructor(){this.param=Array.from(arguments)}toJSON(){return{$newDb:[...e.map(e=>({$method:e})),{$method:t,$param:this.param}]}}}}const l={auth:{on:(e,n)=>{t[e]=t[e]||[],t[e].indexOf(n)>-1||t[e].push(n)},off:(e,n)=>{t[e]=t[e]||[];const s=t[e].indexOf(n);-1!==s&&t[e].splice(s,1)}},on:(e,t)=>{n[e]=n[e]||[],n[e].indexOf(t)>-1||n[e].push(t)},off:(e,t)=>{n[e]=n[e]||[];const s=n[e].indexOf(t);-1!==s&&n[e].splice(s,1)},env:st({},{get:(e,t)=>({$env:t})}),Geo:st({},{get:(e,t)=>u({path:["Geo"],method:t})}),getCloudEnv:function(e){if("string"!=typeof e||!e.trim())throw new Error("getCloudEnv参数错误");return{$env:e.replace("$cloudEnv_","")}},multiSend(){const e=Array.from(arguments);return s({multiCommand:e.map(e=>{const t=e.getAction(),n=e.getCommand();if("getTemp"!==n.$db[n.$db.length-1].$method)throw new Error("multiSend只支持子命令内使用getTemp");return{action:t,command:n}})}).then(t=>{for(let n=0;n{for(let n=0;ni("db",t)?c({$method:t}):function(){return c({$method:t,$param:rt(Array.from(arguments))})}});return this._database=d,d}}(t),function(e){e.getCurrentUserInfo=ot,e.chooseAndUploadFile=it.initChooseAndUploadFile(e),Object.assign(e,{get mixinDatacom(){return ct(e)}})}(t);return["callFunction","uploadFile","deleteFile","getTempFileURL","downloadFile","chooseAndUploadFile"].forEach(e=>{t[e]&&(t[e]=k(t[e],e))}),t.init=this.init,t}};(()=>{{const e=d;let t={};if(1===e.length)t=e[0],ht=ht.init(t),ht.isDefault=!0;else{const t=["auth","callFunction","uploadFile","deleteFile","getTempFileURL","downloadFile","database","getCurrentUSerInfo"];let n;n=e&&e.length>0?"应用有多个服务空间,请通过uniCloud.init方法指定要使用的服务空间":f?"应用未关联服务空间,请在uniCloud目录右键关联服务空间":"uni-app cli项目内使用uniCloud需要使用HBuilderX的运行菜单运行项目,且需要在uniCloud目录关联服务空间",t.forEach(e=>{ht[e]=function(){return console.error(n),Promise.reject(new T({code:"SYS_ERR",message:n}))}})}Object.assign(ht,{get mixinDatacom(){return ct(ht)}}),ht.addInterceptor=_,ht.removeInterceptor=w,u&&"h5"===h&&(window.uniCloud=ht)}})();var lt=ht;export default lt; +import{initVueI18n as e}from"@dcloudio/uni-i18n";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t,n){return e(n={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&n.path)}},n.exports),n.exports}var s=n((function(e,t){var n;e.exports=(n=n||function(e,t){var n=Object.create||function(){function e(){}return function(t){var n;return e.prototype=t,n=new e,e.prototype=null,n}}(),s={},r=s.lib={},o=r.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},i=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes,r=e.sigBytes;if(this.clamp(),s%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[s+o>>>2]|=i<<24-(s+o)%4*8}else for(o=0;o>>2]=n[o>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,s=[],r=function(t){t=t;var n=987654321,s=4294967295;return function(){var r=((n=36969*(65535&n)+(n>>16)&s)<<16)+(t=18e3*(65535&t)+(t>>16)&s)&s;return r/=4294967296,(r+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-r%4*8&255;s.push((o>>>4).toString(16)),s.push((15&o).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,s=[],r=0;r>>2]>>>24-r%4*8&255;s.push(String.fromCharCode(o))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},l=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,o=this.blockSize,a=r/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,u=e.min(4*c,r);if(c){for(var h=0;h>>24)|4278255360&(r<<24|r>>>8)}var o=this._hash.words,i=e[t+0],c=e[t+1],f=e[t+2],p=e[t+3],g=e[t+4],m=e[t+5],y=e[t+6],_=e[t+7],w=e[t+8],v=e[t+9],S=e[t+10],k=e[t+11],T=e[t+12],P=e[t+13],I=e[t+14],A=e[t+15],E=o[0],b=o[1],O=o[2],U=o[3];E=u(E,b,O,U,i,7,a[0]),U=u(U,E,b,O,c,12,a[1]),O=u(O,U,E,b,f,17,a[2]),b=u(b,O,U,E,p,22,a[3]),E=u(E,b,O,U,g,7,a[4]),U=u(U,E,b,O,m,12,a[5]),O=u(O,U,E,b,y,17,a[6]),b=u(b,O,U,E,_,22,a[7]),E=u(E,b,O,U,w,7,a[8]),U=u(U,E,b,O,v,12,a[9]),O=u(O,U,E,b,S,17,a[10]),b=u(b,O,U,E,k,22,a[11]),E=u(E,b,O,U,T,7,a[12]),U=u(U,E,b,O,P,12,a[13]),O=u(O,U,E,b,I,17,a[14]),E=h(E,b=u(b,O,U,E,A,22,a[15]),O,U,c,5,a[16]),U=h(U,E,b,O,y,9,a[17]),O=h(O,U,E,b,k,14,a[18]),b=h(b,O,U,E,i,20,a[19]),E=h(E,b,O,U,m,5,a[20]),U=h(U,E,b,O,S,9,a[21]),O=h(O,U,E,b,A,14,a[22]),b=h(b,O,U,E,g,20,a[23]),E=h(E,b,O,U,v,5,a[24]),U=h(U,E,b,O,I,9,a[25]),O=h(O,U,E,b,p,14,a[26]),b=h(b,O,U,E,w,20,a[27]),E=h(E,b,O,U,P,5,a[28]),U=h(U,E,b,O,f,9,a[29]),O=h(O,U,E,b,_,14,a[30]),E=l(E,b=h(b,O,U,E,T,20,a[31]),O,U,m,4,a[32]),U=l(U,E,b,O,w,11,a[33]),O=l(O,U,E,b,k,16,a[34]),b=l(b,O,U,E,I,23,a[35]),E=l(E,b,O,U,c,4,a[36]),U=l(U,E,b,O,g,11,a[37]),O=l(O,U,E,b,_,16,a[38]),b=l(b,O,U,E,S,23,a[39]),E=l(E,b,O,U,P,4,a[40]),U=l(U,E,b,O,i,11,a[41]),O=l(O,U,E,b,p,16,a[42]),b=l(b,O,U,E,y,23,a[43]),E=l(E,b,O,U,v,4,a[44]),U=l(U,E,b,O,T,11,a[45]),O=l(O,U,E,b,A,16,a[46]),E=d(E,b=l(b,O,U,E,f,23,a[47]),O,U,i,6,a[48]),U=d(U,E,b,O,_,10,a[49]),O=d(O,U,E,b,I,15,a[50]),b=d(b,O,U,E,m,21,a[51]),E=d(E,b,O,U,T,6,a[52]),U=d(U,E,b,O,p,10,a[53]),O=d(O,U,E,b,S,15,a[54]),b=d(b,O,U,E,c,21,a[55]),E=d(E,b,O,U,w,6,a[56]),U=d(U,E,b,O,A,10,a[57]),O=d(O,U,E,b,y,15,a[58]),b=d(b,O,U,E,P,21,a[59]),E=d(E,b,O,U,g,6,a[60]),U=d(U,E,b,O,k,10,a[61]),O=d(O,U,E,b,f,15,a[62]),b=d(b,O,U,E,v,21,a[63]),o[0]=o[0]+E|0,o[1]=o[1]+b|0,o[2]=o[2]+O|0,o[3]=o[3]+U|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var o=e.floor(s/4294967296),i=s;n[15+(r+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),t.sigBytes=4*(n.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var h=c[u];c[u]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,n,s,r,o,i){var a=e+(t&n|~t&s)+r+i;return(a<>>32-o)+t}function h(e,t,n,s,r,o,i){var a=e+(t&s|n&~s)+r+i;return(a<>>32-o)+t}function l(e,t,n,s,r,o,i){var a=e+(t^n^s)+r+i;return(a<>>32-o)+t}function d(e,t,n,s,r,o,i){var a=e+(n^(t|~s))+r+i;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),n.MD5)})),n((function(e,t){var n,r,o;e.exports=(r=(n=s).lib.Base,o=n.enc.Utf8,void(n.algo.HMAC=r.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=o.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,c=i.words,u=0;u{m.indexOf(n)>-1&&function(e,t,n){let s=y[e][t];s||(s=y[e][t]=[]),-1===s.indexOf(n)&&"function"==typeof n&&s.push(n)}(e,n,t[n])})}function w(e,t){y[e]||(y[e]={}),i(t)?Object.keys(t).forEach(n=>{m.indexOf(n)>-1&&function(e,t,n){const s=y[e][t];if(!s)return;const r=s.indexOf(n);r>-1&&s.splice(r,1)}(e,n,t[n])}):delete y[e]}function v(e,t){return e&&0!==e.length?e.reduce((e,n)=>e.then(()=>n(t)),Promise.resolve()):Promise.resolve()}function S(e,t){return y[e]&&y[e][t]||[]}function k(e,t){return t?function(n){const s="callFunction"===t&&"DCloud-clientDB"===(n&&n.name);let r;r=this.isReady?Promise.resolve():this.initUniCloud,n=n||{};const o=r.then(()=>s?Promise.resolve():v(S(t,"invoke"),n)).then(()=>e.call(this,n)).then(e=>s?Promise.resolve(e):v(S(t,"success"),e).then(()=>v(S(t,"complete"),e)).then(()=>Promise.resolve(e)),e=>s?Promise.reject(e):v(S(t,"fail"),e).then(()=>v(S(t,"complete"),e)).then(()=>Promise.reject(e)));if(!(n.success||n.fail||n.complete))return o;o.then(e=>{n.success&&n.success(e),n.complete&&n.complete(e)}).catch(e=>{n.fail&&n.fail(e),n.complete&&n.complete(e)})}:function(t){if(!((t=t||{}).success||t.fail||t.complete))return e.call(this,t);e.call(this,t).then(e=>{t.success&&t.success(e),t.complete&&t.complete(e)},e=>{t.fail&&t.fail(e),t.complete&&t.complete(e)})}}class T extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{code:{get:()=>e.code},requestId:{get:()=>e.requestId},message:{get(){return this.errMsg},set(e){this.errMsg=e}}})}}const{t:P,setLocale:I,getLocale:A}=e({"zh-Hans":{"uniCloud.init.paramRequired":"缺少参数:{param}","uniCloud.uploadFile.fileError":"filePath应为File对象"},"zh-Hant":{"uniCloud.init.paramRequired":"缺少参数:{param}","uniCloud.uploadFile.fileError":"filePath应为File对象"},en:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"},fr:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"},es:{"uniCloud.init.paramRequired":"{param} required","uniCloud.uploadFile.fileError":"filePath should be instance of File"}},"zh-Hans");let E,b,O;try{E=require("uni-stat-config").default||require("uni-stat-config")}catch(e){E={appid:""}}function U(e=8){let t="";for(;t.length{t(Object.assign(e,{complete(e){e||(e={}),u&&"h5"===h&&e.errMsg&&0===e.errMsg.indexOf("request:fail")&&console.warn("发布H5,需要在uniCloud后台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:https://uniapp.dcloud.io/uniCloud/quickstart?id=useinh5");const t=e.data&&e.data.header&&e.data.header["x-serverless-request-id"]||e.header&&e.header["request-id"];if(!e.statusCode||e.statusCode>=400)return s(new T({code:"SYS_ERR",message:e.errMsg||"request:fail",requestId:t}));const r=e.data;if(r.error)return s(new T({code:r.error.code,message:r.error.message,requestId:t}));r.result=r.data,r.requestId=t,delete r.data,n(r)}}))})}};const q={request:e=>uni.request(e),uploadFile:e=>uni.uploadFile(e),setStorageSync:(e,t)=>uni.setStorageSync(e,t),getStorageSync:e=>uni.getStorageSync(e),removeStorageSync:e=>uni.removeStorageSync(e),clearStorageSync:()=>uni.clearStorageSync()};class F{constructor(e){["spaceId","clientSecret"].forEach(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw new Error(P("uniCloud.init.paramRequired",{param:t}))}),this.config=Object.assign({},{endpoint:"https://api.bspapp.com"},e),this.config.provider="aliyun",this.config.requestUrl=this.config.endpoint+"/client",this.config.envType=this.config.envType||"public",this.config.accessTokenKey="access_token_"+this.config.spaceId,this.adapter=q,this._getAccessTokenPromise=null,this._getAccessTokenPromiseStatus=null}get hasAccessToken(){return!!this.accessToken}setAccessToken(e){this.accessToken=e}requestWrapped(e){return R.wrappedRequest(e,this.adapter.request)}requestAuth(e){return this.requestWrapped(e)}request(e,t){return Promise.resolve().then(()=>this.hasAccessToken?t?this.requestWrapped(e):this.requestWrapped(e).catch(t=>new Promise((e,n)=>{!t||"GATEWAY_INVALID_TOKEN"!==t.code&&"InvalidParameter.InvalidToken"!==t.code?n(t):e()}).then(()=>this.getAccessToken()).then(()=>{const t=this.rebuildRequest(e);return this.request(t,!0)})):this.getAccessToken().then(()=>{const t=this.rebuildRequest(e);return this.request(t,!0)}))}rebuildRequest(e){const t=Object.assign({},e);return t.data.token=this.accessToken,t.header["x-basement-token"]=this.accessToken,t.header["x-serverless-sign"]=R.sign(t.data,this.config.clientSecret),t}setupRequest(e,t){const n=Object.assign({},e,{spaceId:this.config.spaceId,timestamp:Date.now()}),s={"Content-Type":"application/json"};return"auth"!==t&&(n.token=this.accessToken,s["x-basement-token"]=this.accessToken),s["x-serverless-sign"]=R.sign(n,this.config.clientSecret),{url:this.config.requestUrl,method:"POST",data:n,dataType:"json",header:s}}getAccessToken(){if("pending"===this._getAccessTokenPromiseStatus)return this._getAccessTokenPromise;this._getAccessTokenPromiseStatus="pending";return this._getAccessTokenPromise=this.requestAuth(this.setupRequest({method:"serverless.auth.user.anonymousAuthorize",params:"{}"},"auth")).then(e=>new Promise((t,n)=>{e.result&&e.result.accessToken?(this.setAccessToken(e.result.accessToken),this._getAccessTokenPromiseStatus="fulfilled",t(this.accessToken)):(this._getAccessTokenPromiseStatus="rejected",n(new T({code:"AUTH_FAILED",message:"获取accessToken失败"})))}),e=>(this._getAccessTokenPromiseStatus="rejected",Promise.reject(e))),this._getAccessTokenPromise}authorize(){this.getAccessToken()}callFunction(e){const t={method:"serverless.function.runtime.invoke",params:JSON.stringify({functionTarget:e.name,functionArgs:e.data||{}})};return this.request(this.setupRequest(t))}getOSSUploadOptionsFromPath(e){const t={method:"serverless.file.resource.generateProximalSign",params:JSON.stringify(e)};return this.request(this.setupRequest(t))}uploadFileToOSS({url:e,formData:t,name:n,filePath:s,fileType:r,onUploadProgress:o}){return new Promise((i,a)=>{const c=this.adapter.uploadFile({url:e,formData:t,name:n,filePath:s,fileType:r,header:{"X-OSS-server-side-encrpytion":"AES256"},success(e){e&&e.statusCode<400?i(e):a(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){a(new T({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(e=>{o({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend})})})}reportOSSUpload(e){const t={method:"serverless.file.resource.report",params:JSON.stringify(e)};return this.request(this.setupRequest(t))}uploadFile({filePath:e,cloudPath:t,fileType:n="image",onUploadProgress:s,config:r}){if(!t)throw new T({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});const o=r&&r.envType||this.config.envType;let i,a;return this.getOSSUploadOptionsFromPath({env:o,filename:t}).then(t=>{const r=t.result;i=r.id,a="https://"+r.cdnDomain+"/"+r.ossPath;const o={url:"https://"+r.host,formData:{"Cache-Control":"max-age=2592000","Content-Disposition":"attachment",OSSAccessKeyId:r.accessKeyId,Signature:r.signature,host:r.host,id:i,key:r.ossPath,policy:r.policy,success_action_status:200},fileName:"file",name:"file",filePath:e,fileType:n};return this.uploadFileToOSS(Object.assign({},o,{onUploadProgress:s}))}).then(()=>this.reportOSSUpload({id:i})).then(t=>new Promise((n,s)=>{t.success?n({success:!0,filePath:e,fileID:a}):s(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))}))}deleteFile({fileList:e}){const t={method:"serverless.file.resource.delete",params:JSON.stringify({id:e[0]})};return this.request(this.setupRequest(t))}getTempFileURL({fileList:e}={}){return new Promise((t,n)=>{Array.isArray(e)&&0!==e.length||n(new T({code:"INVALID_PARAM",message:"fileList的元素必须是非空的字符串"})),t({fileList:e.map(e=>({fileID:e,tempFileURL:e}))})})}}const L={init(e){const t=new F(e),n={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return n},t.customAuth=t.auth,t}},N="undefined"!=typeof location&&"http:"===location.protocol?"http:":"https:",M="undefined"!=typeof process&&"e2e"===process.env.NODE_ENV&&"pre"===process.env.END_POINT?"//tcb-pre.tencentcloudapi.com/web":"//tcb-api.tencentcloudapi.com/web";var j;!function(e){e.local="local",e.none="none",e.session="session"}(j||(j={}));var $=function(){};const K=()=>{let e;if(!Promise){e=()=>{},e.promise={};const t=()=>{throw new Error('Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.')};return Object.defineProperty(e.promise,"then",{get:t}),Object.defineProperty(e.promise,"catch",{get:t}),e}const t=new Promise((t,n)=>{e=(e,s)=>e?n(e):t(s)});return e.promise=t,e};function B(e){return void 0===e}function H(e){return"[object Null]"===Object.prototype.toString.call(e)}var W;function z(e){const t=(n=e,"[object Array]"===Object.prototype.toString.call(n)?e:[e]);var n;for(const e of t){const{isMatch:t,genAdapter:n,runtime:s}=e;if(t())return{adapter:n(),runtime:s}}}!function(e){e.WEB="web",e.WX_MP="wx_mp"}(W||(W={}));const V={adapter:null,runtime:void 0},J=["anonymousUuidKey"];class Y extends ${constructor(){super(),V.adapter.root.tcbObject||(V.adapter.root.tcbObject={})}setItem(e,t){V.adapter.root.tcbObject[e]=t}getItem(e){return V.adapter.root.tcbObject[e]}removeItem(e){delete V.adapter.root.tcbObject[e]}clear(){delete V.adapter.root.tcbObject}}function X(e,t){switch(e){case"local":return t.localStorage||new Y;case"none":return new Y;default:return t.sessionStorage||new Y}}class G{constructor(e){if(!this._storage){this._persistence=V.adapter.primaryStorage||e.persistence,this._storage=X(this._persistence,V.adapter);const t="access_token_"+e.env,n="access_token_expire_"+e.env,s="refresh_token_"+e.env,r="anonymous_uuid_"+e.env,o="login_type_"+e.env,i="user_info_"+e.env;this.keys={accessTokenKey:t,accessTokenExpireKey:n,refreshTokenKey:s,anonymousUuidKey:r,loginTypeKey:o,userInfoKey:i}}}updatePersistence(e){if(e===this._persistence)return;const t="local"===this._persistence;this._persistence=e;const n=X(e,V.adapter);for(const e in this.keys){const s=this.keys[e];if(t&&J.includes(e))continue;const r=this._storage.getItem(s);B(r)||H(r)||(n.setItem(s,r),this._storage.removeItem(s))}this._storage=n}setStore(e,t,n){if(!this._storage)return;const s={version:n||"localCachev1",content:t},r=JSON.stringify(s);try{this._storage.setItem(e,r)}catch(e){throw e}}getStore(e,t){try{if(!this._storage)return}catch(e){return""}t=t||"localCachev1";const n=this._storage.getItem(e);if(!n)return"";if(n.indexOf(t)>=0){return JSON.parse(n).content}return""}removeStore(e){this._storage.removeItem(e)}}const Q={},Z={};function ee(e){return Q[e]}class te{constructor(e,t){this.data=t||null,this.name=e}}class ne extends te{constructor(e,t){super("error",{error:e,data:t}),this.error=e}}const se=new class{constructor(){this._listeners={}}on(e,t){return function(e,t,n){n[e]=n[e]||[],n[e].push(t)}(e,t,this._listeners),this}off(e,t){return function(e,t,n){if(n&&n[e]){const s=n[e].indexOf(t);-1!==s&&n[e].splice(s,1)}}(e,t,this._listeners),this}fire(e,t){if(e instanceof ne)return console.error(e.error),this;const n="string"==typeof e?new te(e,t||{}):e;const s=n.name;if(this._listens(s)){n.target=this;const e=this._listeners[s]?[...this._listeners[s]]:[];for(const t of e)t.call(this,n)}return this}_listens(e){return this._listeners[e]&&this._listeners[e].length>0}};function re(e,t){se.on(e,t)}function oe(e,t={}){se.fire(e,t)}function ie(e,t){se.off(e,t)}const ae="loginStateChanged",ce="loginStateExpire",ue="loginTypeChanged",he="anonymousConverted",le="refreshAccessToken";var de;!function(e){e.ANONYMOUS="ANONYMOUS",e.WECHAT="WECHAT",e.WECHAT_PUBLIC="WECHAT-PUBLIC",e.WECHAT_OPEN="WECHAT-OPEN",e.CUSTOM="CUSTOM",e.EMAIL="EMAIL",e.USERNAME="USERNAME",e.NULL="NULL"}(de||(de={}));const fe=["auth.getJwt","auth.logout","auth.signInWithTicket","auth.signInAnonymously","auth.signIn","auth.fetchAccessTokenWithRefreshToken","auth.signUpWithEmailAndPassword","auth.activateEndUserMail","auth.sendPasswordResetEmail","auth.resetPasswordWithToken","auth.isUsernameRegistered"],pe={"X-SDK-Version":"1.3.5"};function ge(e,t,n){const s=e[t];e[t]=function(t){const r={},o={};n.forEach(n=>{const{data:s,headers:i}=n.call(e,t);Object.assign(r,s),Object.assign(o,i)});const i=t.data;return i&&(()=>{var e;if(e=i,"[object FormData]"!==Object.prototype.toString.call(e))t.data={...i,...r};else for(const e in r)i.append(e,r[e])})(),t.headers={...t.headers||{},...o},s.call(e,t)}}function me(){const e=Math.random().toString(16).slice(2);return{data:{seqId:e},headers:{...pe,"x-seqid":e}}}class ye{constructor(e={}){var t;this.config=e,this._reqClass=new V.adapter.reqClass({timeout:this.config.timeout,timeoutMsg:`请求在${this.config.timeout/1e3}s内未完成,已中断`,restrictedMethods:["post"]}),this._cache=ee(this.config.env),this._localCache=(t=this.config.env,Z[t]),ge(this._reqClass,"post",[me]),ge(this._reqClass,"upload",[me]),ge(this._reqClass,"download",[me])}async post(e){return await this._reqClass.post(e)}async upload(e){return await this._reqClass.upload(e)}async download(e){return await this._reqClass.download(e)}async refreshAccessToken(){let e,t;this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=this._refreshAccessToken());try{e=await this._refreshAccessTokenPromise}catch(e){t=e}if(this._refreshAccessTokenPromise=null,this._shouldRefreshAccessTokenHook=null,t)throw t;return e}async _refreshAccessToken(){const{accessTokenKey:e,accessTokenExpireKey:t,refreshTokenKey:n,loginTypeKey:s,anonymousUuidKey:r}=this._cache.keys;this._cache.removeStore(e),this._cache.removeStore(t);let o=this._cache.getStore(n);if(!o)throw new Error("未登录CloudBase");const i={refresh_token:o},a=await this.request("auth.fetchAccessTokenWithRefreshToken",i);if(a.data.code){const{code:e}=a.data;if("SIGN_PARAM_INVALID"===e||"REFRESH_TOKEN_EXPIRED"===e||"INVALID_REFRESH_TOKEN"===e){if(this._cache.getStore(s)===de.ANONYMOUS&&"INVALID_REFRESH_TOKEN"===e){const e=this._cache.getStore(r),t=this._cache.getStore(n),s=await this.send("auth.signInAnonymously",{anonymous_uuid:e,refresh_token:t});return this.setRefreshToken(s.refresh_token),this._refreshAccessToken()}oe(ce),this._cache.removeStore(n)}throw new Error("刷新access token失败:"+a.data.code)}if(a.data.access_token)return oe(le),this._cache.setStore(e,a.data.access_token),this._cache.setStore(t,a.data.access_token_expire+Date.now()),{accessToken:a.data.access_token,accessTokenExpire:a.data.access_token_expire};a.data.refresh_token&&(this._cache.removeStore(n),this._cache.setStore(n,a.data.refresh_token),this._refreshAccessToken())}async getAccessToken(){const{accessTokenKey:e,accessTokenExpireKey:t,refreshTokenKey:n}=this._cache.keys;if(!this._cache.getStore(n))throw new Error("refresh token不存在,登录状态异常");let s=this._cache.getStore(e),r=this._cache.getStore(t),o=!0;return this._shouldRefreshAccessTokenHook&&!await this._shouldRefreshAccessTokenHook(s,r)&&(o=!1),(!s||!r||r{e.wxOpenId&&e.wxPublicId&&(t=!0)}),{users:n,hasPrimaryUid:t}}setPrimaryUid(e){return this._request.send("auth.setPrimaryUid",{uid:e})}unlink(e){return this._request.send("auth.unlink",{platform:e})}async update(e){const{nickName:t,gender:n,avatarUrl:s,province:r,country:o,city:i}=e,{data:a}=await this._request.send("auth.updateUserInfo",{nickName:t,gender:n,avatarUrl:s,province:r,country:o,city:i});this.setLocalUserInfo(a)}async refresh(){const{data:e}=await this._request.send("auth.getUserInfo",{});return this.setLocalUserInfo(e),e}setUserInfo(){const{userInfoKey:e}=this._cache.keys,t=this._cache.getStore(e);["uid","loginType","openid","wxOpenId","wxPublicId","unionId","qqMiniOpenId","email","hasPassword","customUserId","nickName","gender","avatarUrl"].forEach(e=>{this[e]=t[e]}),this.location={country:t.country,province:t.province,city:t.city}}setLocalUserInfo(e){const{userInfoKey:t}=this._cache.keys;this._cache.setStore(t,e),this.setUserInfo()}}class ke{constructor(e){if(!e)throw new Error("envId is not defined");this._cache=ee(e);const{refreshTokenKey:t,accessTokenKey:n,accessTokenExpireKey:s}=this._cache.keys,r=this._cache.getStore(t),o=this._cache.getStore(n),i=this._cache.getStore(s);this.credential={refreshToken:r,accessToken:o,accessTokenExpire:i},this.user=new Se(e)}get isAnonymousAuth(){return this.loginType===de.ANONYMOUS}get isCustomAuth(){return this.loginType===de.CUSTOM}get isWeixinAuth(){return this.loginType===de.WECHAT||this.loginType===de.WECHAT_OPEN||this.loginType===de.WECHAT_PUBLIC}get loginType(){return this._cache.getStore(this._cache.keys.loginTypeKey)}}class Te extends ve{async signIn(){this._cache.updatePersistence("local");const{anonymousUuidKey:e,refreshTokenKey:t}=this._cache.keys,n=this._cache.getStore(e)||void 0,s=this._cache.getStore(t)||void 0,r=await this._request.send("auth.signInAnonymously",{anonymous_uuid:n,refresh_token:s});if(r.uuid&&r.refresh_token){this._setAnonymousUUID(r.uuid),this.setRefreshToken(r.refresh_token),await this._request.refreshAccessToken(),oe(ae),oe(ue,{env:this.config.env,loginType:de.ANONYMOUS,persistence:"local"});const e=new ke(this.config.env);return await e.user.refresh(),e}throw new Error("匿名登录失败")}async linkAndRetrieveDataWithTicket(e){const{anonymousUuidKey:t,refreshTokenKey:n}=this._cache.keys,s=this._cache.getStore(t),r=this._cache.getStore(n),o=await this._request.send("auth.linkAndRetrieveDataWithTicket",{anonymous_uuid:s,refresh_token:r,ticket:e});if(o.refresh_token)return this._clearAnonymousUUID(),this.setRefreshToken(o.refresh_token),await this._request.refreshAccessToken(),oe(he,{env:this.config.env}),oe(ue,{loginType:de.CUSTOM,persistence:"local"}),{credential:{refreshToken:o.refresh_token}};throw new Error("匿名转化失败")}_setAnonymousUUID(e){const{anonymousUuidKey:t,loginTypeKey:n}=this._cache.keys;this._cache.removeStore(t),this._cache.setStore(t,e),this._cache.setStore(n,de.ANONYMOUS)}_clearAnonymousUUID(){this._cache.removeStore(this._cache.keys.anonymousUuidKey)}}class Pe extends ve{async signIn(e){if("string"!=typeof e)throw new Error("ticket must be a string");const{refreshTokenKey:t}=this._cache.keys,n=await this._request.send("auth.signInWithTicket",{ticket:e,refresh_token:this._cache.getStore(t)||""});if(n.refresh_token)return this.setRefreshToken(n.refresh_token),await this._request.refreshAccessToken(),oe(ae),oe(ue,{env:this.config.env,loginType:de.CUSTOM,persistence:this.config.persistence}),await this.refreshUserInfo(),new ke(this.config.env);throw new Error("自定义登录失败")}}class Ie extends ve{async signIn(e,t){if("string"!=typeof e)throw new Error("email must be a string");const{refreshTokenKey:n}=this._cache.keys,s=await this._request.send("auth.signIn",{loginType:"EMAIL",email:e,password:t,refresh_token:this._cache.getStore(n)||""}),{refresh_token:r,access_token:o,access_token_expire:i}=s;if(r)return this.setRefreshToken(r),o&&i?this.setAccessToken(o,i):await this._request.refreshAccessToken(),await this.refreshUserInfo(),oe(ae),oe(ue,{env:this.config.env,loginType:de.EMAIL,persistence:this.config.persistence}),new ke(this.config.env);throw s.code?new Error(`邮箱登录失败: [${s.code}] ${s.message}`):new Error("邮箱登录失败")}async activate(e){return this._request.send("auth.activateEndUserMail",{token:e})}async resetPasswordWithToken(e,t){return this._request.send("auth.resetPasswordWithToken",{token:e,newPassword:t})}}class Ae extends ve{async signIn(e,t){if("string"!=typeof e)throw new Error("username must be a string");"string"!=typeof t&&(t="",console.warn("password is empty"));const{refreshTokenKey:n}=this._cache.keys,s=await this._request.send("auth.signIn",{loginType:de.USERNAME,username:e,password:t,refresh_token:this._cache.getStore(n)||""}),{refresh_token:r,access_token_expire:o,access_token:i}=s;if(r)return this.setRefreshToken(r),i&&o?this.setAccessToken(i,o):await this._request.refreshAccessToken(),await this.refreshUserInfo(),oe(ae),oe(ue,{env:this.config.env,loginType:de.USERNAME,persistence:this.config.persistence}),new ke(this.config.env);throw s.code?new Error(`用户名密码登录失败: [${s.code}] ${s.message}`):new Error("用户名密码登录失败")}}class Ee{constructor(e){this.config=e,this._cache=ee(e.env),this._request=we(e.env),this._onAnonymousConverted=this._onAnonymousConverted.bind(this),this._onLoginTypeChanged=this._onLoginTypeChanged.bind(this),re(ue,this._onLoginTypeChanged)}get currentUser(){const e=this.hasLoginState();return e&&e.user||null}get loginType(){return this._cache.getStore(this._cache.keys.loginTypeKey)}anonymousAuthProvider(){return new Te(this.config)}customAuthProvider(){return new Pe(this.config)}emailAuthProvider(){return new Ie(this.config)}usernameAuthProvider(){return new Ae(this.config)}async signInAnonymously(){return new Te(this.config).signIn()}async signInWithEmailAndPassword(e,t){return new Ie(this.config).signIn(e,t)}signInWithUsernameAndPassword(e,t){return new Ae(this.config).signIn(e,t)}async linkAndRetrieveDataWithTicket(e){this._anonymousAuthProvider||(this._anonymousAuthProvider=new Te(this.config)),re(he,this._onAnonymousConverted);return await this._anonymousAuthProvider.linkAndRetrieveDataWithTicket(e)}async signOut(){if(this.loginType===de.ANONYMOUS)throw new Error("匿名用户不支持登出操作");const{refreshTokenKey:e,accessTokenKey:t,accessTokenExpireKey:n}=this._cache.keys,s=this._cache.getStore(e);if(!s)return;const r=await this._request.send("auth.logout",{refresh_token:s});return this._cache.removeStore(e),this._cache.removeStore(t),this._cache.removeStore(n),oe(ae),oe(ue,{env:this.config.env,loginType:de.NULL,persistence:this.config.persistence}),r}async signUpWithEmailAndPassword(e,t){return this._request.send("auth.signUpWithEmailAndPassword",{email:e,password:t})}async sendPasswordResetEmail(e){return this._request.send("auth.sendPasswordResetEmail",{email:e})}onLoginStateChanged(e){re(ae,()=>{const t=this.hasLoginState();e.call(this,t)});const t=this.hasLoginState();e.call(this,t)}onLoginStateExpired(e){re(ce,e.bind(this))}onAccessTokenRefreshed(e){re(le,e.bind(this))}onAnonymousConverted(e){re(he,e.bind(this))}onLoginTypeChanged(e){re(ue,()=>{const t=this.hasLoginState();e.call(this,t)})}async getAccessToken(){return{accessToken:(await this._request.getAccessToken()).accessToken,env:this.config.env}}hasLoginState(){const{refreshTokenKey:e}=this._cache.keys;return this._cache.getStore(e)?new ke(this.config.env):null}async isUsernameRegistered(e){if("string"!=typeof e)throw new Error("username must be a string");const{data:t}=await this._request.send("auth.isUsernameRegistered",{username:e});return t&&t.isRegistered}getLoginState(){return Promise.resolve(this.hasLoginState())}async signInWithTicket(e){return new Pe(this.config).signIn(e)}shouldRefreshAccessToken(e){this._request._shouldRefreshAccessTokenHook=e.bind(this)}getUserInfo(){return this._request.send("auth.getUserInfo",{}).then(e=>e.code?e:{...e.data,requestId:e.seqId})}getAuthHeader(){const{refreshTokenKey:e,accessTokenKey:t}=this._cache.keys,n=this._cache.getStore(e);return{"x-cloudbase-credentials":this._cache.getStore(t)+"/@@/"+n}}_onAnonymousConverted(e){const{env:t}=e.data;t===this.config.env&&this._cache.updatePersistence(this.config.persistence)}_onLoginTypeChanged(e){const{loginType:t,persistence:n,env:s}=e.data;s===this.config.env&&(this._cache.updatePersistence(n),this._cache.setStore(this._cache.keys.loginTypeKey,t))}}const be=function(e,t){t=t||K();const n=we(this.config.env),{cloudPath:s,filePath:r,onUploadProgress:o,fileType:i="image"}=e;return n.send("storage.getUploadMetadata",{path:s}).then(e=>{const{data:{url:a,authorization:c,token:u,fileId:h,cosFileId:l},requestId:d}=e,f={key:s,signature:c,"x-cos-meta-fileid":l,success_action_status:"201","x-cos-security-token":u};n.upload({url:a,data:f,file:r,name:s,fileType:i,onUploadProgress:o}).then(e=>{201===e.statusCode?t(null,{fileID:h,requestId:d}):t(new Error("STORAGE_REQUEST_FAIL: "+e.data))}).catch(e=>{t(e)})}).catch(e=>{t(e)}),t.promise},Oe=function(e,t){t=t||K();const n=we(this.config.env),{cloudPath:s}=e;return n.send("storage.getUploadMetadata",{path:s}).then(e=>{t(null,e)}).catch(e=>{t(e)}),t.promise},Ue=function({fileList:e},t){if(t=t||K(),!e||!Array.isArray(e))return{code:"INVALID_PARAM",message:"fileList必须是非空的数组"};for(let t of e)if(!t||"string"!=typeof t)return{code:"INVALID_PARAM",message:"fileList的元素必须是非空的字符串"};const n={fileid_list:e};return we(this.config.env).send("storage.batchDeleteFile",n).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.delete_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},Ce=function({fileList:e},t){t=t||K(),e&&Array.isArray(e)||t(null,{code:"INVALID_PARAM",message:"fileList必须是非空的数组"});let n=[];for(let s of e)"object"==typeof s?(s.hasOwnProperty("fileID")&&s.hasOwnProperty("maxAge")||t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是包含fileID和maxAge的对象"}),n.push({fileid:s.fileID,max_age:s.maxAge})):"string"==typeof s?n.push({fileid:s}):t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是字符串"});const s={file_list:n};return we(this.config.env).send("storage.batchGetDownloadUrl",s).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.download_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},De=async function({fileID:e},t){const n=(await Ce.call(this,{fileList:[{fileID:e,maxAge:600}]})).fileList[0];if("SUCCESS"!==n.code)return t?t(n):new Promise(e=>{e(n)});const s=we(this.config.env);let r=n.download_url;if(r=encodeURI(r),!t)return s.download({url:r});t(await s.download({url:r}))},xe=function({name:e,data:t,query:n,parse:s,search:r},o){const i=o||K();let a;try{a=t?JSON.stringify(t):""}catch(e){return Promise.reject(e)}if(!e)return Promise.reject(new Error("函数名不能为空"));const c={inQuery:n,parse:s,search:r,function_name:e,request_data:a};return we(this.config.env).send("functions.invokeFunction",c).then(e=>{if(e.code)i(null,e);else{let t=e.data.response_data;if(s)i(null,{result:t,requestId:e.requestId});else try{t=JSON.parse(e.data.response_data),i(null,{result:t,requestId:e.requestId})}catch(e){i(new Error("response data must be json"))}}return i.promise}).catch(e=>{i(e)}),i.promise},Re={timeout:15e3,persistence:"session"},qe={};class Fe{constructor(e){this.config=e||this.config,this.authObj=void 0}init(e){switch(V.adapter||(this.requestClient=new V.adapter.reqClass({timeout:e.timeout||5e3,timeoutMsg:`请求在${(e.timeout||5e3)/1e3}s内未完成,已中断`})),this.config={...Re,...e},!0){case this.config.timeout>6e5:console.warn("timeout大于可配置上限[10分钟],已重置为上限数值"),this.config.timeout=6e5;break;case this.config.timeout<100:console.warn("timeout小于可配置下限[100ms],已重置为下限数值"),this.config.timeout=100}return new Fe(this.config)}auth({persistence:e}={}){if(this.authObj)return this.authObj;const t=e||V.adapter.primaryStorage||Re.persistence;var n;return t!==this.config.persistence&&(this.config.persistence=t),function(e){const{env:t}=e;Q[t]=new G(e),Z[t]=new G({...e,persistence:"local"})}(this.config),n=this.config,_e[n.env]=new ye(n),this.authObj=new Ee(this.config),this.authObj}on(e,t){return re.apply(this,[e,t])}off(e,t){return ie.apply(this,[e,t])}callFunction(e,t){return xe.apply(this,[e,t])}deleteFile(e,t){return Ue.apply(this,[e,t])}getTempFileURL(e,t){return Ce.apply(this,[e,t])}downloadFile(e,t){return De.apply(this,[e,t])}uploadFile(e,t){return be.apply(this,[e,t])}getUploadMetadata(e,t){return Oe.apply(this,[e,t])}registerExtension(e){qe[e.name]=e}async invokeExtension(e,t){const n=qe[e];if(!n)throw Error(`扩展${e} 必须先注册`);return await n.invoke(t,this)}useAdapters(e){const{adapter:t,runtime:n}=z(e)||{};t&&(V.adapter=t),n&&(V.runtime=n)}}const Le=new Fe;function Ne(e,t,n){void 0===n&&(n={});var s=/\?/.test(t),r="";for(var o in n)""===r?!s&&(t+="?"):r+="&",r+=o+"="+encodeURIComponent(n[o]);return/^http(s)?:\/\//.test(t+=r)?t:""+e+t}class Me{post(e){const{url:t,data:n,headers:s}=e;return new Promise((e,r)=>{q.request({url:Ne("https:",t),data:n,method:"POST",header:s,success(t){e(t)},fail(e){r(e)}})})}upload(e){return new Promise((t,n)=>{const{url:s,file:r,data:o,headers:i,fileType:a}=e,c=q.uploadFile({url:Ne("https:",s),name:"file",formData:Object.assign({},o),filePath:r,fileType:a,header:i,success(e){const n={statusCode:e.statusCode,data:e.data||{}};200===e.statusCode&&o.success_action_status&&(n.statusCode=parseInt(o.success_action_status,10)),t(n)},fail(e){u&&"mp-alipay"===h&&console.warn("支付宝小程序开发工具上传腾讯云时无法准确判断是否上传成功,请使用真机测试"),n(new Error(e.errMsg||"uploadFile:fail"))}});"function"==typeof e.onUploadProgress&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(t=>{e.onUploadProgress({loaded:t.totalBytesSent,total:t.totalBytesExpectedToSend})})})}}const je={setItem(e,t){q.setStorageSync(e,t)},getItem:e=>q.getStorageSync(e),removeItem(e){q.removeStorageSync(e)},clear(){q.clearStorageSync()}};const $e={genAdapter:function(){return{root:{},reqClass:Me,localStorage:je,primaryStorage:"local"}},isMatch:function(){return!0},runtime:"uni_app"};Le.useAdapters($e);const Ke=Le,Be=Ke.init;Ke.init=function(e){e.env=e.spaceId;const t=Be.call(this,e);t.config.provider="tencent",t.config.spaceId=e.spaceId;const n=t.auth;return t.auth=function(e){const t=n.call(this,e);return["linkAndRetrieveDataWithTicket","signInAnonymously","signOut","getAccessToken","getLoginState","signInWithTicket","getUserInfo"].forEach(e=>{t[e]=k(t[e]).bind(t)}),t},t.customAuth=t.auth,t};class He extends F{getAccessToken(){return new Promise((e,t)=>{this.setAccessToken("Anonymous_Access_token"),e("Anonymous_Access_token")})}setupRequest(e,t){const n=Object.assign({},e,{spaceId:this.config.spaceId,timestamp:Date.now()}),s={"Content-Type":"application/json"};"auth"!==t&&(n.token=this.accessToken,s["x-basement-token"]=this.accessToken),s["x-serverless-sign"]=R.sign(n,this.config.clientSecret);const r=C(),{APPID:o,PLATFORM:i,DEVICEID:a,CLIENT_SDK_VERSION:c}=r;return s["x-client-platform"]=i,s["x-client-appid"]=o,s["x-client-device-id"]=a,s["x-client-version"]=c,s["x-client-token"]=q.getStorageSync("uni_id_token"),{url:this.config.requestUrl,method:"POST",data:n,dataType:"json",header:JSON.parse(JSON.stringify(s))}}uploadFileToOSS({url:e,formData:t,name:n,filePath:s,fileType:r,onUploadProgress:o}){return new Promise((i,a)=>{const c=this.adapter.uploadFile({url:e,formData:t,name:n,filePath:s,fileType:r,success(e){e&&e.statusCode<400?i(e):a(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){a(new T({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(e=>{o({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend})})})}uploadFile({filePath:e,cloudPath:t,fileType:n="image",onUploadProgress:s}){if(!t)throw new T({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});let r;return this.getOSSUploadOptionsFromPath({cloudPath:t}).then(t=>{const{url:o,formData:i,name:a,fileUrl:c}=t.result;r=c;const u={url:o,formData:i,name:a,filePath:e,fileType:n};return this.uploadFileToOSS(Object.assign({},u,{onUploadProgress:s}))}).then(()=>this.reportOSSUpload({cloudPath:t})).then(t=>new Promise((n,s)=>{t.success?n({success:!0,filePath:e,fileID:r}):s(new T({code:"UPLOAD_FAILED",message:"文件上传失败"}))}))}}const We={init(e){const t=new He(e),n={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return n},t.customAuth=t.auth,t}};let ze,Ve;function Je({name:e,data:t,spaceId:n,provider:s}){ze||(ze=C(),Ve={ak:E.appid,p:"android"===O?"a":"i",ut:x(),uuid:D()});const r=JSON.parse(JSON.stringify(t||{})),o=e,i=n,a={tencent:"t",aliyun:"a"}[s];{const e=Object.assign({},Ve,{fn:o,sid:i,pvd:a});Object.assign(r,{clientInfo:ze,uniCloudClientInfo:encodeURIComponent(JSON.stringify(e))});const{deviceId:t}=uni.getSystemInfoSync();r.uniCloudDeviceId=t}if(!r.uniIdToken){const e=q.getStorageSync("uni_id_token")||q.getStorageSync("uniIdToken");e&&(r.uniIdToken=e)}return r}function Ye({name:e,data:t}){const{localAddress:n,localPort:s}=this,r={aliyun:"aliyun",tencent:"tcb"}[this.config.provider],o=this.config.spaceId,i=`http://${n}:${s}/system/check-function`,a=`http://${n}:${s}/cloudfunctions/${e}`;return new Promise((t,n)=>{q.request({method:"POST",url:i,data:{name:e,platform:h,provider:r,spaceId:o},timeout:3e3,success(e){t(e)},fail(){t({data:{code:"NETWORK_ERROR",message:"连接本地调试服务失败,请检查客户端是否和主机在同一局域网下,自动切换为已部署的云函数。"}})}})}).then(({data:e}={})=>{const{code:t,message:n}=e||{};return{code:0===t?0:t||"SYS_ERR",message:n||"SYS_ERR"}}).then(({code:n,message:s})=>{if(0!==n){switch(n){case"MODULE_ENCRYPTED":console.error(`此云函数(${e})依赖加密公共模块不可本地调试,自动切换为云端已部署的云函数`);break;case"FUNCTION_ENCRYPTED":console.error(`此云函数(${e})已加密不可本地调试,自动切换为云端已部署的云函数`);break;case"ACTION_ENCRYPTED":console.error(s||"需要访问加密的uni-clientDB-action,自动切换为云端环境");break;case"NETWORK_ERROR":{const e="连接本地调试服务失败,请检查客户端是否和主机在同一局域网下";throw console.error(e),new Error(e)}case"SWITCH_TO_CLOUD":break;default:{const e=`检测本地调试服务出现错误:${s},请检查网络环境或重启客户端再试`;throw console.error(e),new Error(e)}}return this._originCallFunction({name:e,data:t})}return new Promise((n,s)=>{const i=Je({name:e,data:t,provider:this.config.provider,spaceId:o});q.request({method:"POST",url:a,data:{provider:r,platform:h,param:i},success:({statusCode:e,data:t}={})=>!e||e>=400?s(new T({code:t.code||"SYS_ERR",message:t.message||"request:fail"})):n({result:t}),fail(e){s(new T({code:e.code||e.errCode||"SYS_ERR",message:e.message||e.errMsg||"request:fail"}))}})})})}const Xe=[{rule:/fc_function_not_found|FUNCTION_NOT_FOUND/,content:",云函数[{functionName}]在云端不存在,请检查此云函数名称是否正确以及该云函数是否已上传到服务空间",mode:"append"}];var Ge=/[\\^$.*+?()[\]{}|]/g,Qe=RegExp(Ge.source);function Ze(e,t,n){return e.replace(new RegExp((s=t)&&Qe.test(s)?s.replace(Ge,"\\$&"):s,"g"),n);var s}function et({functionName:e,result:t,logPvd:n}){if(this.config.useDebugFunction&&t&&t.requestId){const s=JSON.stringify({spaceId:this.config.spaceId,functionName:e,requestId:t.requestId});console.log(`[${n}-request]${s}[/${n}-request]`)}}function tt(e){const t=e.callFunction,n=function(e){const n=e.name;e.data=Je({name:n,data:e.data,provider:this.config.provider,spaceId:this.config.spaceId});const s={aliyun:"aliyun",tencent:"tcb"}[this.config.provider];return t.call(this,e).then(e=>(et.call(this,{functionName:n,result:e,logPvd:s}),Promise.resolve(e)),t=>(et.call(this,{functionName:n,result:t,logPvd:s}),t&&t.message&&(t.message=function({message:e="",extraInfo:t={},formatter:n=[]}={}){for(let s=0;s(console.warn("当前返回结果为Promise类型,不可直接访问其result属性,详情请参考:https://uniapp.dcloud.net.cn/uniCloud/faq?id=promise"),{})}),s}}const nt=Symbol("CLIENT_DB_INTERNAL");function st(e,t){return e.then="DoNotReturnProxyWithAFunctionNamedThen",e._internalType=nt,e.__v_raw=void 0,new Proxy(e,{get:(e,n,s)=>n in e||"string"!=typeof n?e[n]:t.get(e,n,s)})}function rt(e){switch(o(e=function e(t){return t&&e(t.__v_raw)||t}(e))){case"array":return e.map(e=>rt(e));case"object":return e._internalType===nt||Object.keys(e).forEach(t=>{e[t]=rt(e[t])}),e;case"regexp":return{$regexp:{source:e.source,flags:e.flags}};case"date":return{$date:e.toISOString()};default:return e}}function ot(){const e=q.getStorageSync("uni_id_token")||"",t=e.split(".");if(!e||3!==t.length)return{uid:null,role:[],permission:[],tokenExpired:0};let n;try{n=JSON.parse((s=t[1],decodeURIComponent(atob(s).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))))}catch(e){throw new Error("获取当前用户信息出错,详细错误信息为:"+e.message)}var s;return n.tokenExpired=1e3*n.exp,delete n.exp,delete n.iat,n}var it=t(n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n="chooseAndUploadFile:fail";function s(e,t){return e.tempFiles.forEach((e,n)=>{e.name||(e.name=e.path.substring(e.path.lastIndexOf("/")+1)),t&&(e.fileType=t),e.cloudPath=Date.now()+"_"+n+e.name.substring(e.name.lastIndexOf("."))}),e.tempFilePaths||(e.tempFilePaths=e.tempFiles.map(e=>e.path)),e}function r(e,t,{onChooseFile:n,onUploadProgress:s}){return t.then(e=>{if(n){const t=n(e);if(void 0!==t)return Promise.resolve(t).then(t=>void 0===t?e:t)}return e}).then(t=>!1===t?{errMsg:"chooseAndUploadFile:ok",tempFilePaths:[],tempFiles:[]}:function(e,t,n=5,s){(t=Object.assign({},t)).errMsg="chooseAndUploadFile:ok";const r=t.tempFiles,o=r.length;let i=0;return new Promise(a=>{for(;i=o)return void(!r.find(e=>!e.url&&!e.errMsg)&&a(t));const u=r[n];e.uploadFile({filePath:u.path,cloudPath:u.cloudPath,fileType:u.fileType,onUploadProgress(e){e.index=n,e.tempFile=u,e.tempFilePath=u.path,s&&s(e)}}).then(e=>{u.url=e.fileID,n{u.errMsg=e.errMsg||e.message,n{uni.chooseImage({count:t,sizeType:r,sourceType:o,extension:i,success(t){e(s(t,"image"))},fail(e){a({errMsg:e.errMsg.replace("chooseImage:fail",n)})}})})}(t),t):"video"===t.type?r(e,function(e){const{camera:t,compressed:r,maxDuration:o,sourceType:i=["album","camera"],extension:a}=e;return new Promise((e,c)=>{uni.chooseVideo({camera:t,compressed:r,maxDuration:o,sourceType:i,extension:a,success(t){const{tempFilePath:n,duration:r,size:o,height:i,width:a}=t;e(s({errMsg:"chooseVideo:ok",tempFilePaths:[n],tempFiles:[{name:t.tempFile&&t.tempFile.name||"",path:n,size:o,type:t.tempFile&&t.tempFile.type||"",width:a,height:i,duration:r,fileType:"video",cloudPath:""}]},"video"))},fail(e){c({errMsg:e.errMsg.replace("chooseVideo:fail",n)})}})})}(t),t):r(e,function(e){const{count:t,extension:r}=e;return new Promise((e,o)=>{let i=uni.chooseFile;if("undefined"!=typeof wx&&"function"==typeof wx.chooseMessageFile&&(i=wx.chooseMessageFile),"function"!=typeof i)return o({errMsg:n+" 请指定 type 类型,该平台仅支持选择 image 或 video。"});i({type:"all",count:t,extension:r,success(t){e(s(t))},fail(e){o({errMsg:e.errMsg.replace("chooseFile:fail",n)})}})})}(t),t)}}})));const at="manual";function ct(e){return{props:{localdata:{type:Array,default:()=>[]},options:{type:[Object,Array],default:()=>({})},collection:{type:String,default:""},action:{type:String,default:""},field:{type:String,default:""},orderby:{type:String,default:""},where:{type:[String,Object],default:""},pageData:{type:String,default:"add"},pageCurrent:{type:Number,default:1},pageSize:{type:Number,default:20},getcount:{type:[Boolean,String],default:!1},gettree:{type:[Boolean,String],default:!1},gettreepath:{type:[Boolean,String],default:!1},startwith:{type:String,default:""},limitlevel:{type:Number,default:10},groupby:{type:String,default:""},groupField:{type:String,default:""},distinct:{type:[Boolean,String],default:!1},foreignKey:{type:String,default:""},loadtime:{type:String,default:"auto"},manual:{type:Boolean,default:!1}},data:()=>({mixinDatacomLoading:!1,mixinDatacomHasMore:!1,mixinDatacomResData:[],mixinDatacomErrorMessage:"",mixinDatacomPage:{}}),created(){this.mixinDatacomPage={current:this.pageCurrent,size:this.pageSize,count:0},this.$watch(()=>{var e=[];return["pageCurrent","pageSize","localdata","collection","action","field","orderby","where","getont","getcount","gettree","groupby","groupField","distinct"].forEach(t=>{e.push(this[t])}),e},(e,t)=>{if(this.loadtime===at)return;let n=!1;const s=[];for(let r=2;r{this.mixinDatacomLoading=!1;const{data:s,count:r}=n.result;this.getcount&&(this.mixinDatacomPage.count=r),this.mixinDatacomHasMore=s.length{this.mixinDatacomLoading=!1,this.mixinDatacomErrorMessage=e,n&&n(e)}))},mixinDatacomGet(t={}){let n=e.database();const s=t.action||this.action;s&&(n=n.action(s));const r=t.collection||this.collection;n=n.collection(r);const o=t.where||this.where;o&&Object.keys(o).length&&(n=n.where(o));const i=t.field||this.field;i&&(n=n.field(i));const a=t.foreignKey||this.foreignKey;a&&(n=n.foreignKey(a));const c=t.groupby||this.groupby;c&&(n=n.groupBy(c));const u=t.groupField||this.groupField;u&&(n=n.groupField(u));!0===(void 0!==t.distinct?t.distinct:this.distinct)&&(n=n.distinct());const h=t.orderby||this.orderby;h&&(n=n.orderBy(h));const l=void 0!==t.pageCurrent?t.pageCurrent:this.mixinDatacomPage.current,d=void 0!==t.pageSize?t.pageSize:this.mixinDatacomPage.size,f=void 0!==t.getcount?t.getcount:this.getcount,p=void 0!==t.gettree?t.gettree:this.gettree,g=void 0!==t.gettreepath?t.gettreepath:this.gettreepath,m={getCount:f},y={limitLevel:void 0!==t.limitlevel?t.limitlevel:this.limitlevel,startWith:void 0!==t.startwith?t.startwith:this.startwith};return p&&(m.getTree=y),g&&(m.getTreePath=y),n=n.skip(d*(l-1)).limit(d).get(m),n}}}}async function ut(e,t){const n=`http://${e}:${t}/system/ping`;try{const e=await(s={url:n,timeout:500},new Promise((e,t)=>{q.request({...s,success(t){e(t)},fail(e){t(e)}})}));return!(!e.data||0!==e.data.code)}catch(e){return!1}var s}let ht=new class{init(e){let t={};const n=!1!==e.debugFunction&&u&&("h5"===h&&navigator.userAgent.indexOf("HBuilderX")>0||"app-plus"===h);switch(e.provider){case"tencent":t=Ke.init(Object.assign(e,{useDebugFunction:n}));break;case"aliyun":t=L.init(Object.assign(e,{useDebugFunction:n}));break;case"private":t=We.init(Object.assign(e,{useDebugFunction:n}));break;default:throw new Error("未提供正确的provider参数")}const s=l;u&&s&&!s.code&&(t.debugInfo=s);let r=Promise.resolve();var o;o=1,r=new Promise((e,t)=>{setTimeout(()=>{e()},o)}),t.isReady=!1,t.isDefault=!1;const i=t.auth();t.initUniCloud=r.then(()=>i.getLoginState()).then(e=>e?Promise.resolve():i.signInAnonymously()).then(()=>{if(u&&t.debugInfo){const{address:e,servePort:n}=t.debugInfo;return async function(e,t){let n;for(let s=0;s{if(!u)return Promise.resolve();if(e)t.localAddress=e,t.localPort=n;else if(t.debugInfo){const e=console["app-plus"===h?"error":"warn"];"remote"===t.debugInfo.initialLaunchType?(t.debugInfo.forceRemote=!0,e("当前客户端和HBuilderX不在同一局域网下(或其他网络原因无法连接HBuilderX),uniCloud本地调试服务不对当前客户端生效。\n- 如果不使用uniCloud本地调试服务,请直接忽略此信息。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试\n- 检查系统防火墙是否拦截了HBuilderX自带的nodejs")):e("无法连接uniCloud本地调试服务,请检查当前客户端是否与主机在同一局域网下。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试\n- 检查系统防火墙是否拦截了HBuilderX自带的nodejs")}}).then(()=>(function(){if(!u||"h5"!==h)return;if(uni.getStorageSync("__LAST_DCLOUD_APPID")===E.appid)return;uni.setStorageSync("__LAST_DCLOUD_APPID",E.appid),uni.removeStorageSync("uni_id_token")&&(console.warn("检测到当前项目与上次运行到此端口的项目不一致,自动清理uni-id保存的token信息(仅开发调试时生效)"),uni.removeStorageSync("uni_id_token"),uni.removeStorageSync("uni_id_token_expired"))}(),new Promise(e=>{"quickapp-native"===h?(O="android",uni.getStorage({key:"__DC_CLOUD_UUID",success(t){b=t.data?t.data:U(32),e()}})):setTimeout(()=>{O=uni.getSystemInfoSync().platform,b=uni.getStorageSync("__DC_CLOUD_UUID")||U(32),e()},0)}))).then(()=>{t.isReady=!0}),tt(t),function(e){const t=e.uploadFile;e.uploadFile=function(e){let n;return n=this.isReady?Promise.resolve():this.initUniCloud,n.then(()=>t.call(this,e))}}(t),function(e){e.database=function(){if(this._database)return this._database;const t={};let n={};function s({action:s,command:r,multiCommand:o}){return v(S("database","invoke")).then(()=>e.callFunction({name:"DCloud-clientDB",data:{action:s,command:r,multiCommand:o}})).then(e=>{const{code:s,message:r,token:o,tokenExpired:i,systemInfo:c=[]}=e.result;if(c)for(let e=0;e{t(e)}),Promise.reject(e)}o&&i&&(t.refreshToken&&t.refreshToken.forEach(e=>{e({token:o,tokenExpired:i})}),n.refreshToken&&n.refreshToken.forEach(e=>{e({token:o,tokenExpired:i})}));const u=e.result.affectedDocs;return"number"==typeof u&&Object.defineProperty(e.result,"affectedDocs",{get:()=>(console.warn("affectedDocs不再推荐使用,请使用inserted/deleted/updated/data.length替代"),u)}),v(S("database","success"),e).then(()=>v(S("database","complete"),e)).then(()=>Promise.resolve(e))},e=>{const t=new a(e.message,e.code||"SYSTEM_ERROR");return n.error&&n.error.forEach(e=>{e(t)}),/fc_function_not_found|FUNCTION_NOT_FOUND/g.test(e.message)&&console.warn("clientDB未初始化,请在web控制台保存一次schema以开启clientDB"),v(S("database","fail"),e).then(()=>v(S("database","complete"),e)).then(()=>Promise.reject(e))})}this.isDefault&&(n=g("_globalUniCloudDatabaseCallback"));class r{constructor(e,t){this.content=e,this.prevStage=t,this.udb=null}toJSON(){let e=this;const t=[e.content];for(;e.prevStage;)e=e.prevStage,t.push(e.content);return{$db:t.reverse().map(e=>({$method:e.$method,$param:rt(e.$param)}))}}getAction(){const e=this.toJSON().$db.find(e=>"action"===e.$method);return e&&e.$param&&e.$param[0]}getCommand(){return{$db:this.toJSON().$db.filter(e=>"action"!==e.$method)}}get useAggregate(){let e=this,t=!1;for(;e.prevStage;){e=e.prevStage;const n=e.content.$method;if("aggregate"===n||"pipeline"===n){t=!0;break}}return t}get count(){if(!this.useAggregate)return function(){return this._send("count",Array.from(arguments))};const e=this;return function(){return c({$method:"count",$param:rt(Array.from(arguments))},e)}}get(){return this._send("get",Array.from(arguments))}add(){return this._send("add",Array.from(arguments))}remove(){return this._send("remove",Array.from(arguments))}update(){return this._send("update",Array.from(arguments))}end(){return this._send("end",Array.from(arguments))}set(){throw new Error("clientDB禁止使用set方法")}get multiSend(){}_send(e,t){const n=this.getAction(),r=this.getCommand();return r.$db.push({$method:e,$param:rt(t)}),s({action:n,command:r})}}const o=["db.Geo","db.command","command.aggregate"];function i(e,t){return o.indexOf(`${e}.${t}`)>-1}function c(e,t){return st(new r(e,t),{get(e,t){let n="db";return e&&e.content&&(n=e.content.$method),i(n,t)?c({$method:t},e):function(){return c({$method:t,$param:rt(Array.from(arguments))},e)}},set(e,t,n){e[t]=n}})}function u({path:e,method:t}){return class{constructor(){this.param=Array.from(arguments)}toJSON(){return{$newDb:[...e.map(e=>({$method:e})),{$method:t,$param:this.param}]}}}}const l={auth:{on:(e,n)=>{t[e]=t[e]||[],t[e].indexOf(n)>-1||t[e].push(n)},off:(e,n)=>{t[e]=t[e]||[];const s=t[e].indexOf(n);-1!==s&&t[e].splice(s,1)}},on:(e,t)=>{n[e]=n[e]||[],n[e].indexOf(t)>-1||n[e].push(t)},off:(e,t)=>{n[e]=n[e]||[];const s=n[e].indexOf(t);-1!==s&&n[e].splice(s,1)},env:st({},{get:(e,t)=>({$env:t})}),Geo:st({},{get:(e,t)=>u({path:["Geo"],method:t})}),getCloudEnv:function(e){if("string"!=typeof e||!e.trim())throw new Error("getCloudEnv参数错误");return{$env:e.replace("$cloudEnv_","")}},multiSend(){const e=Array.from(arguments);return s({multiCommand:e.map(e=>{const t=e.getAction(),n=e.getCommand();if("getTemp"!==n.$db[n.$db.length-1].$method)throw new Error("multiSend只支持子命令内使用getTemp");return{action:t,command:n}})}).then(t=>{for(let n=0;n{for(let n=0;ni("db",t)?c({$method:t}):function(){return c({$method:t,$param:rt(Array.from(arguments))})}});return this._database=d,d}}(t),function(e){e.getCurrentUserInfo=ot,e.chooseAndUploadFile=it.initChooseAndUploadFile(e),Object.assign(e,{get mixinDatacom(){return ct(e)}})}(t);return["callFunction","uploadFile","deleteFile","getTempFileURL","downloadFile","chooseAndUploadFile"].forEach(e=>{t[e]&&(t[e]=k(t[e],e))}),t.init=this.init,t}};(()=>{{const e=d;let t={};if(1===e.length)t=e[0],ht=ht.init(t),ht.isDefault=!0;else{const t=["auth","callFunction","uploadFile","deleteFile","getTempFileURL","downloadFile","database","getCurrentUSerInfo"];let n;n=e&&e.length>0?"应用有多个服务空间,请通过uniCloud.init方法指定要使用的服务空间":f?"应用未关联服务空间,请在uniCloud目录右键关联服务空间":"uni-app cli项目内使用uniCloud需要使用HBuilderX的运行菜单运行项目,且需要在uniCloud目录关联服务空间",t.forEach(e=>{ht[e]=function(){return console.error(n),Promise.reject(new T({code:"SYS_ERR",message:n}))}})}Object.assign(ht,{get mixinDatacom(){return ct(ht)}}),ht.addInterceptor=_,ht.removeInterceptor=w,u&&"h5"===h&&(window.uniCloud=ht)}})();var lt=ht;export default lt; diff --git a/packages/webpack-uni-mp-loader/lib/main-new.js b/packages/webpack-uni-mp-loader/lib/main-new.js index a6b9851a9c8fbe40c57788731105c09282ee251c..1dae7212a6f79b8a95ba7b8ae50b9abf911103bd 100644 --- a/packages/webpack-uni-mp-loader/lib/main-new.js +++ b/packages/webpack-uni-mp-loader/lib/main-new.js @@ -77,6 +77,10 @@ createPage(Page) type: jsPreprocessOptions.type }) + if (process.env.UNI_USING_VUE3) { + content = content + ';createApp().app.mount(\'#app\');' + } + const resourcePath = 'app' const { diff --git a/src/platforms/app-plus/service/publish-handler.js b/src/platforms/app-plus/service/publish-handler.js index 6104cdd387da88dc7a3147cab2ecd20189017735..77e9d98d0294f2840ac796ba8ccff0e53b2eff71 100644 --- a/src/platforms/app-plus/service/publish-handler.js +++ b/src/platforms/app-plus/service/publish-handler.js @@ -8,6 +8,9 @@ export function publishHandler (eventType, args, pageIds) { } const evalJSCode = `typeof UniViewJSBridge !== 'undefined' && UniViewJSBridge.subscribeHandler("${eventType}",${args},__PAGE_ID__)` + if (process.env.NODE_ENV !== 'production') { + console.log(`UNIAPP[publishHandler]:[${+new Date()}]`, 'length', evalJSCode.length) + } pageIds.forEach(id => { const webview = plus.webview.getWebviewById(String(id)) webview && webview.evalJS(evalJSCode.replace('__PAGE_ID__', id))