From 48235ef3c7017b8a6fa18d7dc01ec28ec822d5cd Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Wed, 28 Apr 2021 21:15:48 +0800 Subject: [PATCH] feat: support cjs --- packages/uni-app/build.json | 2 +- packages/uni-app/dist/uni-app.cjs.js | 84 + .../dist/{uni-app.esm.js => uni-app.es.js} | 0 packages/uni-app/package.json | 6 +- .../{uni-cloud.esm.js => uni-cloud.cjs.js} | 0 packages/uni-cloud/dist/uni-cloud.es.js | 1 + packages/uni-cloud/package.json | 4 +- packages/uni-h5-vue/build.json | 14 - .../vue.runtime.cjs.js} | 1381 +- packages/uni-h5-vue/dist/vue.runtime.esm.js | 2 +- packages/uni-h5-vue/package.json | 2 +- packages/uni-h5-vue/src/index.ts | 2 - .../uni-h5/dist/assets/index-1458ad61.css | 871 - .../uni-h5/dist/assets/index-5e20c801.css | 821 - .../uni-h5/dist/assets/index-74eeac14.css | 871 - .../uni-h5/dist/assets/index-7b54b60d.css | 827 - .../uni-h5/dist/assets/index-868b4e9a.css | 22 - .../uni-h5/dist/assets/index-bebb7f36.css | 742 - .../uni-h5/dist/assets/index-c3818808.css | 743 - .../uni-h5/dist/assets/index-ca7b8a5a.css | 821 - .../uni-h5/dist/assets/index-de6d6907.css | 743 - .../uni-h5/dist/assets/index-e2b5cfbf.css | 857 - .../uni-h5/dist/assets/index-f7451dc5.css | 1022 -- packages/uni-h5/dist/uni-h5.cjs.js | 14656 ++++++++++++++++ .../dist/{uni-h5.esm.js => uni-h5.es.js} | 7 +- packages/uni-h5/package.json | 8 +- .../uni-h5/src/framework/plugin/router.ts | 10 +- packages/uni-h5/vite.config.ts | 46 +- packages/uni-i18n/build.json | 2 +- .../dist/{uni-i18n.esm.js => uni-i18n.es.js} | 0 packages/uni-i18n/package.json | 6 +- packages/uni-shared/build.json | 2 +- .../{uni-shared.esm.js => uni-shared.es.js} | 0 packages/uni-shared/package.json | 6 +- packages/vite-plugin-uni/src/config/index.ts | 2 +- .../vite-plugin-uni/src/config/resolve.ts | 17 +- .../src/configResolved/plugins/easycom.ts | 2 +- .../src/configResolved/plugins/mainJs.ts | 12 +- .../src/configureServer/index.ts | 7 +- .../src/handleHotUpdate/index.ts | 2 +- .../vite-plugin-uni/src/resolveId/index.ts | 23 +- .../vite-plugin-uni/src/utils/constants.ts | 36 + 42 files changed, 15550 insertions(+), 9132 deletions(-) create mode 100644 packages/uni-app/dist/uni-app.cjs.js rename packages/uni-app/dist/{uni-app.esm.js => uni-app.es.js} (100%) rename packages/uni-cloud/dist/{uni-cloud.esm.js => uni-cloud.cjs.js} (100%) create mode 100644 packages/uni-cloud/dist/uni-cloud.es.js delete mode 100644 packages/uni-h5-vue/build.json rename packages/uni-h5-vue/{lib/vue.runtime.esm.js => dist/vue.runtime.cjs.js} (86%) delete mode 100644 packages/uni-h5-vue/src/index.ts delete mode 100644 packages/uni-h5/dist/assets/index-1458ad61.css delete mode 100644 packages/uni-h5/dist/assets/index-5e20c801.css delete mode 100644 packages/uni-h5/dist/assets/index-74eeac14.css delete mode 100644 packages/uni-h5/dist/assets/index-7b54b60d.css delete mode 100644 packages/uni-h5/dist/assets/index-868b4e9a.css delete mode 100644 packages/uni-h5/dist/assets/index-bebb7f36.css delete mode 100644 packages/uni-h5/dist/assets/index-c3818808.css delete mode 100644 packages/uni-h5/dist/assets/index-ca7b8a5a.css delete mode 100644 packages/uni-h5/dist/assets/index-de6d6907.css delete mode 100644 packages/uni-h5/dist/assets/index-e2b5cfbf.css delete mode 100644 packages/uni-h5/dist/assets/index-f7451dc5.css create mode 100644 packages/uni-h5/dist/uni-h5.cjs.js rename packages/uni-h5/dist/{uni-h5.esm.js => uni-h5.es.js} (99%) rename packages/uni-i18n/dist/{uni-i18n.esm.js => uni-i18n.es.js} (100%) rename packages/uni-shared/dist/{uni-shared.esm.js => uni-shared.es.js} (100%) diff --git a/packages/uni-app/build.json b/packages/uni-app/build.json index 77d1b557d..39c823bd2 100644 --- a/packages/uni-app/build.json +++ b/packages/uni-app/build.json @@ -1,6 +1,6 @@ { "input": { - "src/index.ts": ["dist/uni-app.esm.js"] + "src/index.ts": ["dist/uni-app.es.js", "dist/uni-app.cjs.js"] }, "compilerOptions": { "declaration": true diff --git a/packages/uni-app/dist/uni-app.cjs.js b/packages/uni-app/dist/uni-app.cjs.js new file mode 100644 index 000000000..1b114ca53 --- /dev/null +++ b/packages/uni-app/dist/uni-app.cjs.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var vue = require('vue'); + +// @ts-ignore +// App and Page +const ON_SHOW = 'onShow'; +const ON_HIDE = 'onHide'; +//App +const ON_LAUNCH = 'onLaunch'; +const ON_ERROR = 'onError'; +const ON_THEME_CHANGE = 'onThemeChange'; +const ON_PAGE_NOT_FOUND = 'onPageNotFound'; +const ON_UNHANDLE_REJECTION = 'onUnhandledRejection'; +const ON_READY = 'onReady'; +const ON_UNLOAD = 'onUnload'; +const ON_RESIZE = 'onResize'; +const ON_BACK_PRESS = 'onBackPress'; +const ON_PAGE_SCROLL = 'onPageScroll'; +const ON_TAB_ITEM_TAP = 'onTabItemTap'; +const ON_REACH_BOTTOM = 'onReachBottom'; +const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh'; +const ON_SHARE_TIMELINE = 'onShareTimeline'; +const ON_ADD_TO_FAVORITES = 'onAddToFavorites'; +const ON_SHARE_APP_MESSAGE = 'onShareAppMessage'; +// navigationBar +const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged'; +const createHook = (lifecycle) => (hook, target = vue.getCurrentInstance()) => +// post-create lifecycle registrations are noops during SSR +!vue.isInSSRComponentSetup && vue.injectHook(lifecycle, hook, target); +const onShow = /*#__PURE__*/ createHook(ON_SHOW); +const onHide = /*#__PURE__*/ createHook(ON_HIDE); +const onLaunch = /*#__PURE__*/ createHook(ON_LAUNCH); +const onError = /*#__PURE__*/ createHook(ON_ERROR); +const onThemeChange = /*#__PURE__*/ createHook(ON_THEME_CHANGE); +const onPageNotFound = /*#__PURE__*/ createHook(ON_PAGE_NOT_FOUND); +const onUnhandledRejection = /*#__PURE__*/ createHook(ON_UNHANDLE_REJECTION); +// export const onLoad = /*#__PURE__*/ createHook(ON_LOAD) +const onReady = /*#__PURE__*/ createHook(ON_READY); +const onUnload = /*#__PURE__*/ createHook(ON_UNLOAD); +const onResize = /*#__PURE__*/ createHook(ON_RESIZE); +const onBackPress = /*#__PURE__*/ createHook(ON_BACK_PRESS); +const onPageScroll = /*#__PURE__*/ createHook(ON_PAGE_SCROLL); +const onTabItemTap = /*#__PURE__*/ createHook(ON_TAB_ITEM_TAP); +const onReachBottom = /*#__PURE__*/ createHook(ON_REACH_BOTTOM); +const onPullDownRefresh = /*#__PURE__*/ createHook(ON_PULL_DOWN_REFRESH); +const onShareTimeline = /*#__PURE__*/ createHook(ON_SHARE_TIMELINE); +const onAddToFavorites = /*#__PURE__*/ createHook(ON_ADD_TO_FAVORITES); +const onShareAppMessage = /*#__PURE__*/ createHook(ON_SHARE_APP_MESSAGE); +const onNavigationBarButtonTap = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_BUTTON_TAP); +const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED); +const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED); +const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED); +const onNavigationBarSearchInputFocusChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED); + +exports.onAddToFavorites = onAddToFavorites; +exports.onBackPress = onBackPress; +exports.onError = onError; +exports.onHide = onHide; +exports.onLaunch = onLaunch; +exports.onNavigationBarButtonTap = onNavigationBarButtonTap; +exports.onNavigationBarSearchInputChanged = onNavigationBarSearchInputChanged; +exports.onNavigationBarSearchInputClicked = onNavigationBarSearchInputClicked; +exports.onNavigationBarSearchInputConfirmed = onNavigationBarSearchInputConfirmed; +exports.onNavigationBarSearchInputFocusChanged = onNavigationBarSearchInputFocusChanged; +exports.onPageNotFound = onPageNotFound; +exports.onPageScroll = onPageScroll; +exports.onPullDownRefresh = onPullDownRefresh; +exports.onReachBottom = onReachBottom; +exports.onReady = onReady; +exports.onResize = onResize; +exports.onShareAppMessage = onShareAppMessage; +exports.onShareTimeline = onShareTimeline; +exports.onShow = onShow; +exports.onTabItemTap = onTabItemTap; +exports.onThemeChange = onThemeChange; +exports.onUnhandledRejection = onUnhandledRejection; +exports.onUnload = onUnload; diff --git a/packages/uni-app/dist/uni-app.esm.js b/packages/uni-app/dist/uni-app.es.js similarity index 100% rename from packages/uni-app/dist/uni-app.esm.js rename to packages/uni-app/dist/uni-app.es.js diff --git a/packages/uni-app/package.json b/packages/uni-app/package.json index bf3c04dce..75f13b299 100644 --- a/packages/uni-app/package.json +++ b/packages/uni-app/package.json @@ -2,9 +2,9 @@ "name": "@dcloudio/uni-app", "version": "3.0.0", "description": "@dcloudio/uni-app", - "main": "dist/uni-app.esm.js", - "module": "dist/uni-app.esm.js", - "types": "dist/uni-app.d.ts", + "main": "./dist/uni-app.cjs.js", + "module": "./dist/uni-app.es.js", + "types": "./dist/uni-app.d.ts", "files": [ "dist" ], diff --git a/packages/uni-cloud/dist/uni-cloud.esm.js b/packages/uni-cloud/dist/uni-cloud.cjs.js similarity index 100% rename from packages/uni-cloud/dist/uni-cloud.esm.js rename to packages/uni-cloud/dist/uni-cloud.cjs.js diff --git a/packages/uni-cloud/dist/uni-cloud.es.js b/packages/uni-cloud/dist/uni-cloud.es.js new file mode 100644 index 000000000..8ac8716e3 --- /dev/null +++ b/packages/uni-cloud/dist/uni-cloud.es.js @@ -0,0 +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 s(e,t,s){return e(s={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&s.path)}},s.exports),s.exports}var n=s((function(e,t){var s;e.exports=(s=s||function(e,t){var s=Object.create||function(){function e(){}return function(t){var s;return e.prototype=t,s=new e,e.prototype=null,s}}(),n={},r=n.lib={},o=r.Base={extend:function(e){var t=s(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,s=e.words,n=this.sigBytes,r=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=i<<24-(n+o)%4*8}else for(o=0;o>>2]=s[o>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s,n=[],r=function(t){t=t;var s=987654321,n=4294967295;return function(){var r=((s=36969*(65535&s)+(s>>16)&n)<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n;return r/=4294967296,(r+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-r%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new i.init(s,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,s=e.sigBytes,n=[],r=0;r>>2]>>>24-r%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new i.init(s,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 s=this._data,n=s.words,r=s.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],v=e[t+8],w=e[t+9],S=e[t+10],T=e[t+11],k=e[t+12],A=e[t+13],P=e[t+14],I=e[t+15],E=o[0],O=o[1],U=o[2],b=o[3];E=u(E,O,U,b,i,7,a[0]),b=u(b,E,O,U,c,12,a[1]),U=u(U,b,E,O,f,17,a[2]),O=u(O,U,b,E,p,22,a[3]),E=u(E,O,U,b,g,7,a[4]),b=u(b,E,O,U,m,12,a[5]),U=u(U,b,E,O,y,17,a[6]),O=u(O,U,b,E,_,22,a[7]),E=u(E,O,U,b,v,7,a[8]),b=u(b,E,O,U,w,12,a[9]),U=u(U,b,E,O,S,17,a[10]),O=u(O,U,b,E,T,22,a[11]),E=u(E,O,U,b,k,7,a[12]),b=u(b,E,O,U,A,12,a[13]),U=u(U,b,E,O,P,17,a[14]),E=h(E,O=u(O,U,b,E,I,22,a[15]),U,b,c,5,a[16]),b=h(b,E,O,U,y,9,a[17]),U=h(U,b,E,O,T,14,a[18]),O=h(O,U,b,E,i,20,a[19]),E=h(E,O,U,b,m,5,a[20]),b=h(b,E,O,U,S,9,a[21]),U=h(U,b,E,O,I,14,a[22]),O=h(O,U,b,E,g,20,a[23]),E=h(E,O,U,b,w,5,a[24]),b=h(b,E,O,U,P,9,a[25]),U=h(U,b,E,O,p,14,a[26]),O=h(O,U,b,E,v,20,a[27]),E=h(E,O,U,b,A,5,a[28]),b=h(b,E,O,U,f,9,a[29]),U=h(U,b,E,O,_,14,a[30]),E=l(E,O=h(O,U,b,E,k,20,a[31]),U,b,m,4,a[32]),b=l(b,E,O,U,v,11,a[33]),U=l(U,b,E,O,T,16,a[34]),O=l(O,U,b,E,P,23,a[35]),E=l(E,O,U,b,c,4,a[36]),b=l(b,E,O,U,g,11,a[37]),U=l(U,b,E,O,_,16,a[38]),O=l(O,U,b,E,S,23,a[39]),E=l(E,O,U,b,A,4,a[40]),b=l(b,E,O,U,i,11,a[41]),U=l(U,b,E,O,p,16,a[42]),O=l(O,U,b,E,y,23,a[43]),E=l(E,O,U,b,w,4,a[44]),b=l(b,E,O,U,k,11,a[45]),U=l(U,b,E,O,I,16,a[46]),E=d(E,O=l(O,U,b,E,f,23,a[47]),U,b,i,6,a[48]),b=d(b,E,O,U,_,10,a[49]),U=d(U,b,E,O,P,15,a[50]),O=d(O,U,b,E,m,21,a[51]),E=d(E,O,U,b,k,6,a[52]),b=d(b,E,O,U,p,10,a[53]),U=d(U,b,E,O,S,15,a[54]),O=d(O,U,b,E,c,21,a[55]),E=d(E,O,U,b,v,6,a[56]),b=d(b,E,O,U,I,10,a[57]),U=d(U,b,E,O,y,15,a[58]),O=d(O,U,b,E,A,21,a[59]),E=d(E,O,U,b,g,6,a[60]),b=d(b,E,O,U,T,10,a[61]),U=d(U,b,E,O,f,15,a[62]),O=d(O,U,b,E,w,21,a[63]),o[0]=o[0]+E|0,o[1]=o[1]+O|0,o[2]=o[2]+U|0,o[3]=o[3]+b|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var o=e.floor(n/4294967296),i=n;s[15+(r+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),s[14+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),t.sigBytes=4*(s.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,s,n,r,o,i){var a=e+(t&s|~t&n)+r+i;return(a<>>32-o)+t}function h(e,t,s,n,r,o,i){var a=e+(t&n|s&~n)+r+i;return(a<>>32-o)+t}function l(e,t,s,n,r,o,i){var a=e+(t^s^n)+r+i;return(a<>>32-o)+t}function d(e,t,s,n,r,o,i){var a=e+(s^(t|~n))+r+i;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),s.MD5)})),s((function(e,t){var s,r,o;e.exports=(r=(s=n).lib.Base,o=s.enc.Utf8,void(s.algo.HMAC=r.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=o.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(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{t.success&&t.success(e),t.complete&&t.complete(e)},e=>{t.fail&&t.fail(e),t.complete&&t.complete(e)})}}class i 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:a,setLocale:c,getLocale:u}=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 h,l,d;try{h=require("uni-stat-config").default||require("uni-stat-config")}catch(e){h={appid:""}}function f(e=8){let t="";for(;t.length{t(Object.assign(e,{complete(e){e||(e={}),"h5"===process.env.VUE_APP_PLATFORM&&"development"===process.env.NODE_ENV&&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 n(new i({code:"SYS_ERR",message:e.errMsg||"request:fail",requestId:t}));const r=e.data;if(r.error)return n(new i({code:r.error.code,message:r.error.message,requestId:t}));r.result=r.data,r.requestId=t,delete r.data,s(r)}}))})}};const y={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 _{constructor(e){["spaceId","clientSecret"].forEach(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw new Error(a("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=y}get hasAccessToken(){return!!this.accessToken}setAccessToken(e){this.accessToken=e}requestWrapped(e){return m.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,s)=>{!t||"GATEWAY_INVALID_TOKEN"!==t.code&&"InvalidParameter.InvalidToken"!==t.code?s(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"]=m.sign(t.data,this.config.clientSecret),t}setupRequest(e,t){const s=Object.assign({},e,{spaceId:this.config.spaceId,timestamp:Date.now()}),n={"Content-Type":"application/json"};return"auth"!==t&&(s.token=this.accessToken,n["x-basement-token"]=this.accessToken),n["x-serverless-sign"]=m.sign(s,this.config.clientSecret),{url:this.config.requestUrl,method:"POST",data:s,dataType:"json",header:n}}getAccessToken(){return this.requestAuth(this.setupRequest({method:"serverless.auth.user.anonymousAuthorize",params:"{}"},"auth")).then(e=>new Promise((t,s)=>{e.result&&e.result.accessToken?(this.setAccessToken(e.result.accessToken),t(this.accessToken)):s(new i({code:"AUTH_FAILED",message:"获取accessToken失败"}))}))}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:s,filePath:n,fileType:r,onUploadProgress:o}){return new Promise((a,c)=>{const u=this.adapter.uploadFile({url:e,formData:t,name:s,filePath:n,fileType:r,header:{"X-OSS-server-side-encrpytion":"AES256"},success(e){e&&e.statusCode<400?a(e):c(new i({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){c(new i({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&u&&"function"==typeof u.onProgressUpdate&&u.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:s="image",onUploadProgress:n,config:r}){if(!t)throw new i({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});const o=r&&r.envType||this.config.envType;let a,c;return this.getOSSUploadOptionsFromPath({env:o,filename:t}).then(t=>{const r=t.result;a=r.id,c="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:a,key:r.ossPath,policy:r.policy,success_action_status:200},fileName:"file",name:"file",filePath:e,fileType:s};return this.uploadFileToOSS(Object.assign({},o,{onUploadProgress:n}))}).then(()=>this.reportOSSUpload({id:a})).then(t=>new Promise((s,n)=>{t.success?s({success:!0,filePath:e,fileID:c}):n(new i({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,s)=>{Array.isArray(e)&&0!==e.length||s(new i({code:"INVALID_PARAM",message:"fileList的元素必须是非空的字符串"})),t({fileList:e.map(e=>({fileID:e,tempFileURL:e}))})})}}const v={init(e){const t=new _(e);["deleteFile","getTempFileURL"].forEach(e=>{t[e]=o(t[e]).bind(t)});const s={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return s},t.customAuth=t.auth,t}},w="undefined"!=typeof location&&"http:"===location.protocol?"http:":"https:",S="undefined"!=typeof process&&"e2e"===process.env.NODE_ENV&&"pre"===process.env.END_POINT?"//tcb-pre.tencentcloudapi.com/web":"//tcb-api.tencentcloudapi.com/web";var T;!function(e){e.local="local",e.none="none",e.session="session"}(T||(T={}));var k=function(){};s((function(e,t){var s;e.exports=(s=n,function(e){var t=s,n=t.lib,r=n.WordArray,o=n.Hasher,i=t.algo,a=[],c=[];!function(){function t(t){for(var s=e.sqrt(t),n=2;n<=s;n++)if(!(t%n))return!1;return!0}function s(e){return 4294967296*(e-(0|e))|0}for(var n=2,r=0;r<64;)t(n)&&(r<8&&(a[r]=s(e.pow(n,.5))),c[r]=s(e.pow(n,1/3)),r++),n++}();var u=[],h=i.SHA256=o.extend({_doReset:function(){this._hash=new r.init(a.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],o=s[2],i=s[3],a=s[4],h=s[5],l=s[6],d=s[7],f=0;f<64;f++){if(f<16)u[f]=0|e[t+f];else{var p=u[f-15],g=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,m=u[f-2],y=(m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10;u[f]=g+u[f-7]+y+u[f-16]}var _=n&r^n&o^r&o,v=(n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22),w=d+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&h^~a&l)+c[f]+u[f];d=l,l=h,h=a,a=i+w|0,i=o,o=r,r=n,n=w+(v+_)|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+o|0,s[3]=s[3]+i|0,s[4]=s[4]+a|0,s[5]=s[5]+h|0,s[6]=s[6]+l|0,s[7]=s[7]+d|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(h),t.HmacSHA256=o._createHmacHelper(h)}(Math),s.SHA256)})),s((function(e,t){e.exports=n.HmacSHA256})),s((function(e,t){var s,r,o;e.exports=(r=(s=o=n).lib.WordArray,s.enc.Base64={stringify:function(e){var t=e.words,s=e.sigBytes,n=this._map;e.clamp();for(var r=[],o=0;o>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=n.charAt(64);if(c)for(;r.length%4;)r.push(c);return r.join("")},parse:function(e){var t=e.length,s=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var o=0;o>>6-i%4*2;n[o>>>2]|=(a|c)<<24-o%4*8,o++}return r.create(n,o)}(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},o.enc.Base64)})),s((function(e,t){e.exports=n.enc.Utf8}));const A=()=>{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,s)=>{e=(e,n)=>e?s(e):t(n)});return e.promise=t,e};function P(e){return void 0===e}function I(e){return"[object Null]"===Object.prototype.toString.call(e)}var E;function O(e){const t=(s=e,"[object Array]"===Object.prototype.toString.call(s)?e:[e]);var s;for(const e of t){const{isMatch:t,genAdapter:s,runtime:n}=e;if(t())return{adapter:s(),runtime:n}}}!function(e){e.WEB="web",e.WX_MP="wx_mp"}(E||(E={}));const U={adapter:null,runtime:void 0},b=["anonymousUuidKey"];class D extends k{constructor(){super(),U.adapter.root.tcbObject||(U.adapter.root.tcbObject={})}setItem(e,t){U.adapter.root.tcbObject[e]=t}getItem(e){return U.adapter.root.tcbObject[e]}removeItem(e){delete U.adapter.root.tcbObject[e]}clear(){delete U.adapter.root.tcbObject}}function C(e,t){switch(e){case"local":return t.localStorage||new D;case"none":return new D;default:return t.sessionStorage||new D}}class R{constructor(e){if(!this._storage){this._persistence=U.adapter.primaryStorage||e.persistence,this._storage=C(this._persistence,U.adapter);const t="access_token_"+e.env,s="access_token_expire_"+e.env,n="refresh_token_"+e.env,r="anonymous_uuid_"+e.env,o="login_type_"+e.env,i="user_info_"+e.env;this.keys={accessTokenKey:t,accessTokenExpireKey:s,refreshTokenKey:n,anonymousUuidKey:r,loginTypeKey:o,userInfoKey:i}}}updatePersistence(e){if(e===this._persistence)return;const t="local"===this._persistence;this._persistence=e;const s=C(e,U.adapter);for(const e in this.keys){const n=this.keys[e];if(t&&b.includes(e))continue;const r=this._storage.getItem(n);P(r)||I(r)||(s.setItem(n,r),this._storage.removeItem(n))}this._storage=s}setStore(e,t,s){if(!this._storage)return;const n={version:s||"localCachev1",content:t},r=JSON.stringify(n);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 s=this._storage.getItem(e);if(!s)return"";if(s.indexOf(t)>=0){return JSON.parse(s).content}return""}removeStore(e){this._storage.removeItem(e)}}const x={},q={};function F(e){return x[e]}class L{constructor(e,t){this.data=t||null,this.name=e}}class N extends L{constructor(e,t){super("error",{error:e,data:t}),this.error=e}}const M=new class{constructor(){this._listeners={}}on(e,t){return function(e,t,s){s[e]=s[e]||[],s[e].push(t)}(e,t,this._listeners),this}off(e,t){return function(e,t,s){if(s&&s[e]){const n=s[e].indexOf(t);-1!==n&&s[e].splice(n,1)}}(e,t,this._listeners),this}fire(e,t){if(e instanceof N)return console.error(e.error),this;const s="string"==typeof e?new L(e,t||{}):e;const n=s.name;if(this._listens(n)){s.target=this;const e=this._listeners[n]?[...this._listeners[n]]:[];for(const t of e)t.call(this,s)}return this}_listens(e){return this._listeners[e]&&this._listeners[e].length>0}};function $(e,t){M.on(e,t)}function K(e,t={}){M.fire(e,t)}function B(e,t){M.off(e,t)}const j="loginStateChanged",H="loginStateExpire",W="loginTypeChanged",V="anonymousConverted",z="refreshAccessToken";var Y;!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"}(Y||(Y={}));const J=["auth.getJwt","auth.logout","auth.signInWithTicket","auth.signInAnonymously","auth.signIn","auth.fetchAccessTokenWithRefreshToken","auth.signUpWithEmailAndPassword","auth.activateEndUserMail","auth.sendPasswordResetEmail","auth.resetPasswordWithToken","auth.isUsernameRegistered"],X={"X-SDK-Version":"1.3.5"};function G(e,t,s){const n=e[t];e[t]=function(t){const r={},o={};s.forEach(s=>{const{data:n,headers:i}=s.call(e,t);Object.assign(r,n),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},n.call(e,t)}}function Q(){const e=Math.random().toString(16).slice(2);return{data:{seqId:e},headers:{...X,"x-seqid":e}}}class Z{constructor(e={}){var t;this.config=e,this._reqClass=new U.adapter.reqClass({timeout:this.config.timeout,timeoutMsg:`请求在${this.config.timeout/1e3}s内未完成,已中断`,restrictedMethods:["post"]}),this._cache=F(this.config.env),this._localCache=(t=this.config.env,q[t]),G(this._reqClass,"post",[Q]),G(this._reqClass,"upload",[Q]),G(this._reqClass,"download",[Q])}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:s,loginTypeKey:n,anonymousUuidKey:r}=this._cache.keys;this._cache.removeStore(e),this._cache.removeStore(t);let o=this._cache.getStore(s);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(n)===Y.ANONYMOUS&&"INVALID_REFRESH_TOKEN"===e){const e=this._cache.getStore(r),t=this._cache.getStore(s),n=await this.send("auth.signInAnonymously",{anonymous_uuid:e,refresh_token:t});return this.setRefreshToken(n.refresh_token),this._refreshAccessToken()}K(H),this._cache.removeStore(s)}throw new Error("刷新access token失败:"+a.data.code)}if(a.data.access_token)return K(z),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(s),this._cache.setStore(s,a.data.refresh_token),this._refreshAccessToken())}async getAccessToken(){const{accessTokenKey:e,accessTokenExpireKey:t,refreshTokenKey:s}=this._cache.keys;if(!this._cache.getStore(s))throw new Error("refresh token不存在,登录状态异常");let n=this._cache.getStore(e),r=this._cache.getStore(t),o=!0;return this._shouldRefreshAccessTokenHook&&!await this._shouldRefreshAccessTokenHook(n,r)&&(o=!1),(!n||!r||r{e.wxOpenId&&e.wxPublicId&&(t=!0)}),{users:s,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:s,avatarUrl:n,province:r,country:o,city:i}=e,{data:a}=await this._request.send("auth.updateUserInfo",{nickName:t,gender:s,avatarUrl:n,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 re{constructor(e){if(!e)throw new Error("envId is not defined");this._cache=F(e);const{refreshTokenKey:t,accessTokenKey:s,accessTokenExpireKey:n}=this._cache.keys,r=this._cache.getStore(t),o=this._cache.getStore(s),i=this._cache.getStore(n);this.credential={refreshToken:r,accessToken:o,accessTokenExpire:i},this.user=new ne(e)}get isAnonymousAuth(){return this.loginType===Y.ANONYMOUS}get isCustomAuth(){return this.loginType===Y.CUSTOM}get isWeixinAuth(){return this.loginType===Y.WECHAT||this.loginType===Y.WECHAT_OPEN||this.loginType===Y.WECHAT_PUBLIC}get loginType(){return this._cache.getStore(this._cache.keys.loginTypeKey)}}class oe extends se{async signIn(){this._cache.updatePersistence("local");const{anonymousUuidKey:e,refreshTokenKey:t}=this._cache.keys,s=this._cache.getStore(e)||void 0,n=this._cache.getStore(t)||void 0,r=await this._request.send("auth.signInAnonymously",{anonymous_uuid:s,refresh_token:n});if(r.uuid&&r.refresh_token){this._setAnonymousUUID(r.uuid),this.setRefreshToken(r.refresh_token),await this._request.refreshAccessToken(),K(j),K(W,{env:this.config.env,loginType:Y.ANONYMOUS,persistence:"local"});const e=new re(this.config.env);return await e.user.refresh(),e}throw new Error("匿名登录失败")}async linkAndRetrieveDataWithTicket(e){const{anonymousUuidKey:t,refreshTokenKey:s}=this._cache.keys,n=this._cache.getStore(t),r=this._cache.getStore(s),o=await this._request.send("auth.linkAndRetrieveDataWithTicket",{anonymous_uuid:n,refresh_token:r,ticket:e});if(o.refresh_token)return this._clearAnonymousUUID(),this.setRefreshToken(o.refresh_token),await this._request.refreshAccessToken(),K(V,{env:this.config.env}),K(W,{loginType:Y.CUSTOM,persistence:"local"}),{credential:{refreshToken:o.refresh_token}};throw new Error("匿名转化失败")}_setAnonymousUUID(e){const{anonymousUuidKey:t,loginTypeKey:s}=this._cache.keys;this._cache.removeStore(t),this._cache.setStore(t,e),this._cache.setStore(s,Y.ANONYMOUS)}_clearAnonymousUUID(){this._cache.removeStore(this._cache.keys.anonymousUuidKey)}}class ie extends se{async signIn(e){if("string"!=typeof e)throw new Error("ticket must be a string");const{refreshTokenKey:t}=this._cache.keys,s=await this._request.send("auth.signInWithTicket",{ticket:e,refresh_token:this._cache.getStore(t)||""});if(s.refresh_token)return this.setRefreshToken(s.refresh_token),await this._request.refreshAccessToken(),K(j),K(W,{env:this.config.env,loginType:Y.CUSTOM,persistence:this.config.persistence}),await this.refreshUserInfo(),new re(this.config.env);throw new Error("自定义登录失败")}}class ae extends se{async signIn(e,t){if("string"!=typeof e)throw new Error("email must be a string");const{refreshTokenKey:s}=this._cache.keys,n=await this._request.send("auth.signIn",{loginType:"EMAIL",email:e,password:t,refresh_token:this._cache.getStore(s)||""}),{refresh_token:r,access_token:o,access_token_expire:i}=n;if(r)return this.setRefreshToken(r),o&&i?this.setAccessToken(o,i):await this._request.refreshAccessToken(),await this.refreshUserInfo(),K(j),K(W,{env:this.config.env,loginType:Y.EMAIL,persistence:this.config.persistence}),new re(this.config.env);throw n.code?new Error(`邮箱登录失败: [${n.code}] ${n.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 ce extends se{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:s}=this._cache.keys,n=await this._request.send("auth.signIn",{loginType:Y.USERNAME,username:e,password:t,refresh_token:this._cache.getStore(s)||""}),{refresh_token:r,access_token_expire:o,access_token:i}=n;if(r)return this.setRefreshToken(r),i&&o?this.setAccessToken(i,o):await this._request.refreshAccessToken(),await this.refreshUserInfo(),K(j),K(W,{env:this.config.env,loginType:Y.USERNAME,persistence:this.config.persistence}),new re(this.config.env);throw n.code?new Error(`用户名密码登录失败: [${n.code}] ${n.message}`):new Error("用户名密码登录失败")}}class ue{constructor(e){this.config=e,this._cache=F(e.env),this._request=te(e.env),this._onAnonymousConverted=this._onAnonymousConverted.bind(this),this._onLoginTypeChanged=this._onLoginTypeChanged.bind(this),$(W,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 oe(this.config)}customAuthProvider(){return new ie(this.config)}emailAuthProvider(){return new ae(this.config)}usernameAuthProvider(){return new ce(this.config)}async signInAnonymously(){return new oe(this.config).signIn()}async signInWithEmailAndPassword(e,t){return new ae(this.config).signIn(e,t)}signInWithUsernameAndPassword(e,t){return new ce(this.config).signIn(e,t)}async linkAndRetrieveDataWithTicket(e){this._anonymousAuthProvider||(this._anonymousAuthProvider=new oe(this.config)),$(V,this._onAnonymousConverted);return await this._anonymousAuthProvider.linkAndRetrieveDataWithTicket(e)}async signOut(){if(this.loginType===Y.ANONYMOUS)throw new Error("匿名用户不支持登出操作");const{refreshTokenKey:e,accessTokenKey:t,accessTokenExpireKey:s}=this._cache.keys,n=this._cache.getStore(e);if(!n)return;const r=await this._request.send("auth.logout",{refresh_token:n});return this._cache.removeStore(e),this._cache.removeStore(t),this._cache.removeStore(s),K(j),K(W,{env:this.config.env,loginType:Y.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){$(j,()=>{const t=this.hasLoginState();e.call(this,t)});const t=this.hasLoginState();e.call(this,t)}onLoginStateExpired(e){$(H,e.bind(this))}onAccessTokenRefreshed(e){$(z,e.bind(this))}onAnonymousConverted(e){$(V,e.bind(this))}onLoginTypeChanged(e){$(W,()=>{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 re(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 ie(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,s=this._cache.getStore(e);return{"x-cloudbase-credentials":this._cache.getStore(t)+"/@@/"+s}}_onAnonymousConverted(e){const{env:t}=e.data;t===this.config.env&&this._cache.updatePersistence(this.config.persistence)}_onLoginTypeChanged(e){const{loginType:t,persistence:s,env:n}=e.data;n===this.config.env&&(this._cache.updatePersistence(s),this._cache.setStore(this._cache.keys.loginTypeKey,t))}}const he=function(e,t){t=t||A();const s=te(this.config.env),{cloudPath:n,filePath:r,onUploadProgress:o,fileType:i="image"}=e;return s.send("storage.getUploadMetadata",{path:n}).then(e=>{const{data:{url:a,authorization:c,token:u,fileId:h,cosFileId:l},requestId:d}=e,f={key:n,signature:c,"x-cos-meta-fileid":l,success_action_status:"201","x-cos-security-token":u};s.upload({url:a,data:f,file:r,name:n,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},le=function(e,t){t=t||A();const s=te(this.config.env),{cloudPath:n}=e;return s.send("storage.getUploadMetadata",{path:n}).then(e=>{t(null,e)}).catch(e=>{t(e)}),t.promise},de=function({fileList:e},t){if(t=t||A(),!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 s={fileid_list:e};return te(this.config.env).send("storage.batchDeleteFile",s).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.delete_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},fe=function({fileList:e},t){t=t||A(),e&&Array.isArray(e)||t(null,{code:"INVALID_PARAM",message:"fileList必须是非空的数组"});let s=[];for(let n of e)"object"==typeof n?(n.hasOwnProperty("fileID")&&n.hasOwnProperty("maxAge")||t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是包含fileID和maxAge的对象"}),s.push({fileid:n.fileID,max_age:n.maxAge})):"string"==typeof n?s.push({fileid:n}):t(null,{code:"INVALID_PARAM",message:"fileList的元素必须是字符串"});const n={file_list:s};return te(this.config.env).send("storage.batchGetDownloadUrl",n).then(e=>{e.code?t(null,e):t(null,{fileList:e.data.download_list,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise},pe=async function({fileID:e},t){const s=(await fe.call(this,{fileList:[{fileID:e,maxAge:600}]})).fileList[0];if("SUCCESS"!==s.code)return t?t(s):new Promise(e=>{e(s)});const n=te(this.config.env);let r=s.download_url;if(r=encodeURI(r),!t)return n.download({url:r});t(await n.download({url:r}))},ge=function({name:e,data:t,query:s,parse:n,search:r},o){const i=o||A();let a;try{a=t?JSON.stringify(t):""}catch(e){return Promise.reject(e)}if(!e)return Promise.reject(new Error("函数名不能为空"));const c={inQuery:s,parse:n,search:r,function_name:e,request_data:a};return te(this.config.env).send("functions.invokeFunction",c).then(e=>{if(e.code)i(null,e);else{let t=e.data.response_data;if(n)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},me={timeout:15e3,persistence:"session"},ye={};class _e{constructor(e){this.config=e||this.config,this.authObj=void 0}init(e){switch(U.adapter||(this.requestClient=new U.adapter.reqClass({timeout:e.timeout||5e3,timeoutMsg:`请求在${(e.timeout||5e3)/1e3}s内未完成,已中断`})),this.config={...me,...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 _e(this.config)}auth({persistence:e}={}){if(this.authObj)return this.authObj;const t=e||U.adapter.primaryStorage||me.persistence;var s;return t!==this.config.persistence&&(this.config.persistence=t),function(e){const{env:t}=e;x[t]=new R(e),q[t]=new R({...e,persistence:"local"})}(this.config),s=this.config,ee[s.env]=new Z(s),this.authObj=new ue(this.config),this.authObj}on(e,t){return $.apply(this,[e,t])}off(e,t){return B.apply(this,[e,t])}callFunction(e,t){return ge.apply(this,[e,t])}deleteFile(e,t){return de.apply(this,[e,t])}getTempFileURL(e,t){return fe.apply(this,[e,t])}downloadFile(e,t){return pe.apply(this,[e,t])}uploadFile(e,t){return he.apply(this,[e,t])}getUploadMetadata(e,t){return le.apply(this,[e,t])}registerExtension(e){ye[e.name]=e}async invokeExtension(e,t){const s=ye[e];if(!s)throw Error(`扩展${e} 必须先注册`);return await s.invoke(t,this)}useAdapters(e){const{adapter:t,runtime:s}=O(e)||{};t&&(U.adapter=t),s&&(U.runtime=s)}}const ve=new _e;function we(e,t,s){void 0===s&&(s={});var n=/\?/.test(t),r="";for(var o in s)""===r?!n&&(t+="?"):r+="&",r+=o+"="+encodeURIComponent(s[o]);return/^http(s)?:\/\//.test(t+=r)?t:""+e+t}class Se{post(e){const{url:t,data:s,headers:n}=e;return new Promise((e,r)=>{y.request({url:we("https:",t),data:s,method:"POST",header:n,success(t){e(t)},fail(e){r(e)}})})}upload(e){return new Promise((t,s)=>{const{url:n,file:r,data:o,headers:i,fileType:a}=e,c=y.uploadFile({url:we("https:",n),name:"file",formData:Object.assign({},o),filePath:r,fileType:a,header:i,success(e){const s={statusCode:e.statusCode,data:e.data||{}};200===e.statusCode&&o.success_action_status&&(s.statusCode=parseInt(o.success_action_status,10)),t(s)},fail(e){"mp-alipay"===process.env.VUE_APP_PLATFORM&&"development"===process.env.NODE_ENV&&console.warn("支付宝小程序开发工具上传腾讯云时无法准确判断是否上传成功,请使用真机测试"),s(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 Te={setItem(e,t){y.setStorageSync(e,t)},getItem:e=>y.getStorageSync(e),removeItem(e){y.removeStorageSync(e)},clear(){y.clearStorageSync()}};const ke={genAdapter:function(){return{root:{},reqClass:Se,localStorage:Te,primaryStorage:"local"}},isMatch:function(){return!0},runtime:"uni_app"};ve.useAdapters(ke);const Ae=ve,Pe=Ae.init;Ae.init=function(e){e.env=e.spaceId;const t=Pe.call(this,e);t.config.provider="tencent",t.config.spaceId=e.spaceId;const s=t.auth;t.auth=function(e){const t=s.call(this,e);return["linkAndRetrieveDataWithTicket","signInAnonymously","signOut","getAccessToken","getLoginState","signInWithTicket","getUserInfo"].forEach(e=>{t[e]=o(t[e]).bind(t)}),t},t.customAuth=t.auth;return["deleteFile","getTempFileURL","downloadFile"].forEach(e=>{t[e]=o(t[e]).bind(t)}),t};class Ie extends _{getAccessToken(){return new Promise((e,t)=>{this.setAccessToken("Anonymous_Access_token"),e("Anonymous_Access_token")})}uploadFileToOSS({url:e,formData:t,name:s,filePath:n,fileType:r,onUploadProgress:o}){return new Promise((a,c)=>{const u=this.adapter.uploadFile({url:e,formData:t,name:s,filePath:n,fileType:r,success(e){e&&e.statusCode<400?a(e):c(new i({code:"UPLOAD_FAILED",message:"文件上传失败"}))},fail(e){c(new i({code:e.code||"UPLOAD_FAILED",message:e.message||e.errMsg||"文件上传失败"}))}});"function"==typeof o&&u&&"function"==typeof u.onProgressUpdate&&u.onProgressUpdate(e=>{o({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend})})})}uploadFile({filePath:e,cloudPath:t,fileType:s="image",onUploadProgress:n}){if(!t)throw new i({code:"CLOUDPATH_REQUIRED",message:"cloudPath不可为空"});let r;return this.getOSSUploadOptionsFromPath({filename: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:s};return this.uploadFileToOSS(Object.assign({},u,{onUploadProgress:n}))}).then(()=>this.reportOSSUpload({id:t})).then(t=>new Promise((s,n)=>{t.success?s({success:!0,filePath:e,fileID:r}):n(new i({code:"UPLOAD_FAILED",message:"文件上传失败"}))}))}}const Ee={init(e){const t=new Ie(e);["deleteFile","getTempFileURL"].forEach(e=>{t[e]=o(t[e]).bind(t)});const s={signInAnonymously:function(){return t.authorize()},getLoginState:function(){return Promise.resolve(!1)}};return t.auth=function(){return s},t.customAuth=t.auth,t}};let Oe,Ue;function be({name:e,data:t,spaceId:s,provider:n}){Oe||(Oe=function(){const{deviceId:e}=uni.getSystemInfoSync();return{PLATFORM:process.env.VUE_APP_PLATFORM,OS:d,APPID:h.appid,LOCALE:u(),DEVICEID:e,CLIENT_SDK_VERSION:"1.0.1"}}(),Ue={ak:h.appid,p:"android"===d?"a":"i",ut:g(),uuid:p()});const r=JSON.parse(JSON.stringify(t||{})),o=e,i=s,a={tencent:"t",aliyun:"a"}[n];{const e=Object.assign({},Ue,{fn:o,sid:i,pvd:a});Object.assign(r,{clientInfo:Oe,uniCloudClientInfo:encodeURIComponent(JSON.stringify(e))});const{deviceId:t}=uni.getSystemInfoSync();r.uniCloudDeviceId=t}if(!r.uniIdToken){const e=y.getStorageSync("uni_id_token")||y.getStorageSync("uniIdToken");e&&(r.uniIdToken=e)}return r}function De({name:e,data:t}){const{localAddress:s,localPort:n}=this,r={aliyun:"aliyun",tencent:"tcb"}[this.config.provider],o=this.config.spaceId,a=`http://${s}:${n}/system/check-function`,c=`http://${s}:${n}/cloudfunctions/${e}`;return new Promise((t,s)=>{y.request({method:"POST",url:a,data:{name:e,platform:process.env.VUE_APP_PLATFORM,provider:r,spaceId:o},timeout:3e3,success(e){t(e)},fail(){t({data:{code:"NETWORK_ERROR",message:"连接本地调试服务失败,请检查客户端是否和主机在同一局域网下,自动切换为已部署的云函数。"}})}})}).then(({data:e}={})=>{const{code:t,message:s}=e||{};return{code:0===t?0:t||"SYS_ERR",message:s||"SYS_ERR"}}).then(({code:s,message:n})=>{if(0!==s){switch(s){case"MODULE_ENCRYPTED":console.error(`此云函数(${e})依赖加密公共模块不可本地调试,自动切换为云端已部署的云函数`);break;case"FUNCTION_ENCRYPTED":console.error(`此云函数(${e})已加密不可本地调试,自动切换为云端已部署的云函数`);break;case"ACTION_ENCRYPTED":console.error(n||"需要访问加密的uni-clientDB-action,自动切换为云端环境");break;case"NETWORK_ERROR":{const e="连接本地调试服务失败,请检查客户端是否和主机在同一局域网下";throw console.error(e),new Error(e)}case"SWITCH_TO_CLOUD":break;default:{const e=`检测本地调试服务出现错误:${n},请检查网络环境或重启客户端再试`;throw console.error(e),new Error(e)}}return this.originCallFunction({name:e,data:t})}return new Promise((s,n)=>{const a=be({name:e,data:t,provider:this.config.provider,spaceId:o});y.request({method:"POST",url:c,data:{provider:r,platform:process.env.VUE_APP_PLATFORM,param:a},success:({statusCode:e,data:t}={})=>!e||e>=400?n(new i({code:t.code||"SYS_ERR",message:t.message||"request:fail"})):s({result:t}),fail(e){n(new i({code:e.code||e.errCode||"SYS_ERR",message:e.message||e.errMsg||"request:fail"}))}})})})}const Ce=[{rule:/fc_function_not_found|FUNCTION_NOT_FOUND/,content:",云函数[{functionName}]在云端不存在,请检查此云函数名称是否正确已经是否已上传到服务空间",mode:"append"}];var Re=/[\\^$.*+?()[\]{}|]/g,xe=RegExp(Re.source);function qe(e,t,s){return e.replace(new RegExp((n=t)&&xe.test(n)?n.replace(Re,"\\$&"):n,"g"),s);var n}function Fe(e){const t=e.callFunction;e.callFunction=function(e){let s;s=this.isReady?Promise.resolve():this.initUniCloud;const n=e.name;return s.then(()=>{e.data=be({name:n,data:e.data,provider:this.config.provider,spaceId:this.config.spaceId});const s={aliyun:"aliyun",tencent:"tcb"}[this.config.provider];return new Promise((r,o)=>{t.call(this,e).then(e=>{if(this.config.useDebugFunction&&e&&e.requestId){const t=JSON.stringify({spaceId:this.config.spaceId,functionName:n,requestId:e.requestId});console.log(`[${s}-request]${t}[/${s}-request]`)}r(e)}).catch(t=>{if(this.config.useDebugFunction&&t&&t.requestId){const e=JSON.stringify({spaceId:this.config.spaceId,functionName:n,requestId:t.requestId});console.log(`[${s}-request]${e}[/${s}-request]`)}t&&t.message&&(t.message=function({message:e="",extraInfo:t={},formatter:s=[]}={}){for(let n=0;n"development"===process.env.NODE_ENV&&e.debugInfo&&!e.debugInfo.forceRemote&&process.env.UNI_CLOUD_PROVIDER?De.call(this,t):s.call(this,t))})).call(this,t)}}const Le=Symbol("CLIENT_DB_INTERNAL");function Ne(e,t){return e.then="DoNotReturnProxyWithAFunctionNamedThen",e._internalType=Le,new Proxy(e,{get:(e,s,n)=>function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,s)||e[s]||"string"!=typeof s?e[s]:t.get(e,s,n)})}class Me extends Error{constructor(e,t){super(e),this.code=t}}function $e(e){switch(t=e,Object.prototype.toString.call(t).slice(8,-1).toLowerCase()){case"array":return e.map(e=>$e(e));case"object":return e._internalType===Le||Object.keys(e).forEach(t=>{e[t]=$e(e[t])}),e;case"regexp":return{$regexp:{source:e.source,flags:e.flags}};case"date":return{$date:e.toISOString()};default:return e}var t}function Ke(){const e=y.getStorageSync("uni_id_token")||"",t=e.split(".");if(!e||3!==t.length)return{uid:null,role:[],permission:[]};let s;try{s=JSON.parse((n=t[1],decodeURIComponent(atob(n).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))))}catch(e){throw new Error("获取当前用户信息出错,详细错误信息为:"+e.message)}var n;return s}var Be=t(s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const s="chooseAndUploadFile:fail";function n(e,t){return e.tempFiles.forEach((e,s)=>{e.name||(e.name=e.path.substring(e.path.lastIndexOf("/")+1)),t&&(e.fileType=t),e.cloudPath=Date.now()+"_"+s+e.name.substring(e.name.lastIndexOf("."))}),e.tempFilePaths||(e.tempFilePaths=e.tempFiles.map(e=>e.path)),e}function r(e,t,{onChooseFile:s,onUploadProgress:n}){return t.then(e=>{if(s){const t=s(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,s=5,n){(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[s];e.uploadFile({filePath:u.path,cloudPath:u.cloudPath,fileType:u.fileType,onUploadProgress(e){e.index=s,e.tempFile=u,e.tempFilePath=u.path,n&&n(e)}}).then(e=>{u.url=e.fileID,s{u.errMsg=e.errMsg||e.message,s{uni.chooseImage({count:t,sizeType:r,sourceType:o,extension:i,success(t){e(n(t,"image"))},fail(e){a({errMsg:e.errMsg.replace("chooseImage:fail",s)})}})})}(t),t):"video"===t.type?r(e,function(e){const{camera:t,compressed:r,maxDuration:o,sourceType:i,extension:a}=e;return new Promise((e,c)=>{uni.chooseVideo({camera:t,compressed:r,maxDuration:o,sourceType:i,extension:a,success(t){const{tempFilePath:s,duration:r,size:o,height:i,width:a}=t;e(n({errMsg:"chooseVideo:ok",tempFilePaths:[s],tempFiles:[{name:t.tempFile&&t.tempFile.name||"",path:s,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",s)})}})})}(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:s+" 请指定 type 类型,该平台仅支持选择 image 或 video。"});i({type:"all",count:t,extension:r,success(t){e(n(t))},fail(e){o({errMsg:e.errMsg.replace("chooseFile:fail",s)})}})})}(t),t)}}})));const je="manual";async function He(e,t){const s=`http://${e}:${t}/system/ping`;try{const e=await(n={url:s,timeout:500},new Promise((e,t)=>{y.request({...n,success(t){e(t)},fail(e){t(e)}})}));return!(!e.data||0!==e.data.code)}catch(e){return!1}var n}let We=new class{init(e){let t={};const s=!1!==e.debugFunction&&"development"===process.env.NODE_ENV&&("h5"===process.env.VUE_APP_PLATFORM&&navigator.userAgent.indexOf("HBuilderX")>0||"app-plus"===process.env.VUE_APP_PLATFORM);switch(e.provider){case"tencent":t=Ae.init(Object.assign(e,{useDebugFunction:s}));break;case"aliyun":t=v.init(Object.assign(e,{useDebugFunction:s}));break;case"private":t=Ee.init(Object.assign(e,{useDebugFunction:s}));break;default:throw new Error("未提供正确的provider参数")}const n=process.env.UNICLOUD_DEBUG;"development"===process.env.NODE_ENV&&n&&!n.code&&(t.debugInfo=n),t.isReady=!1;const r=t.auth();return t.initUniCloud=r.getLoginState().then(e=>e?Promise.resolve():r.signInAnonymously()).then(()=>{if("development"===process.env.NODE_ENV&&t.debugInfo){const{address:e,servePort:s}=t.debugInfo;return async function(e,t){let s;for(let n=0;n{if(e)t.localAddress=e,t.localPort=s;else if(t.debugInfo){const e="app-plus"===process.env.VUE_APP_PLATFORM?"error":"warn",s=console[e];"remote"===t.debugInfo.initialLaunchType?(t.debugInfo.forceRemote=!0,s("当前客户端和HBuilderX不在同一局域网下(或其他网络原因无法连接HBuilderX),uniCloud本地调试服务不对当前客户端生效。\n- 如果不使用uniCloud本地调试服务,请直接忽略此信息。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试")):s("无法连接uniCloud本地调试服务,请检查当前客户端是否与主机在同一局域网下。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试")}}).then(()=>(function(){if("h5"!==process.env.VUE_APP_PLATFORM||"development"!==process.env.NODE_ENV)return;if(uni.getStorageSync("__LAST_DCLOUD_APPID")===h.appid)return;uni.setStorageSync("__LAST_DCLOUD_APPID",h.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"===process.env.VUE_APP_PLATFORM?(d="android",uni.getStorage({key:"__DC_CLOUD_UUID",success(t){l=t.data?t.data:f(32),e()}})):setTimeout(()=>{d=uni.getSystemInfoSync().platform,l=uni.getStorageSync("__DC_CLOUD_UUID")||f(32),e()},0)}))).then(()=>{t.isReady=!0}),Fe(t),function(e){const t=e.uploadFile;e.uploadFile=function(e){let s;return s=this.isReady?Promise.resolve():this.initUniCloud,s.then(()=>t.call(this,e))};const s=e.uploadFile;e.uploadFile=function(e){return o(s).call(this,e)}}(t),function(e){e.database=function(){if(this._database)return this._database;const t={},s={};class n{constructor(e,t,s){this.content=e,this.prevStage=t,this.actionName=s}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}))}}get useAggregate(){let e=this,t=!1;for(;e.prevStage;){e=e.prevStage;const s=e.content.$method;if("aggregate"===s||"pipeline"===s){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 i({$method:"count",$param:$e(Array.from(arguments))},e,e.actionName)}}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方法")}_send(n,r){const o=this.toJSON();return o.$db.push({$method:n,$param:r}),e.callFunction({name:"DCloud-clientDB",data:{action:this.actionName,command:o}}).then(e=>{const{code:n,message:r,token:o,tokenExpired:i,systemInfo:a=[]}=e.result;if(a)for(let e=0;e{e({token:o,tokenExpired:i})}),o&&i&&s.refreshToken&&s.refreshToken.forEach(e=>{e({token:o,tokenExpired:i})}),Promise.resolve(e))}).catch(e=>{const t=new Me(e.message,e.code||"SYSTEM_ERROR");return s.error&&s.error.forEach(e=>{e(t)}),/fc_function_not_found|FUNCTION_NOT_FOUND/g.test(e.message)&&console.warn("clientDB未初始化,请在web控制台保存一次schema以开启clientDB"),Promise.reject(e)})}}const r=["db.Geo","db.command","command.aggregate"];function o(e,t){return r.indexOf(`${e}.${t}`)>-1}function i(e,t,s){return Ne(new n(e,t,s),{get(e,t){let n="db";return e&&e.content&&(n=e.content.$method),o(n,t)?i({$method:t},e,s):function(){return i({$method:t,$param:$e(Array.from(arguments))},e,s)}}})}function a({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 c={auth:{on:(e,s)=>{t[e]=t[e]||[],t[e].indexOf(s)>-1||t[e].push(s)},off:(e,s)=>{t[e]=t[e]||[];const n=t[e].indexOf(s);-1!==n&&t[e].splice(n,1)}},on:(e,t)=>{s[e]=s[e]||[],s[e].indexOf(t)>-1||s[e].push(t)},off:(e,t)=>{s[e]=s[e]||[];const n=s[e].indexOf(t);-1!==n&&s[e].splice(n,1)},env:Ne({},{get:(e,t)=>({$env:t})}),action:e=>Ne({},{get:(t,s)=>o("db",s)?i({$method:s},null,e):function(){return i({$method:s,$param:$e(Array.from(arguments))},null,e)}}),Geo:Ne({},{get:(e,t)=>a({path:["Geo"],method:t})}),getCloudEnv:function(e){if("string"!=typeof e||!e.trim())throw new Error("getCloudEnv参数错误");return{$env:e.replace("$cloudEnv_","")}},get serverDate(){return a({path:[],method:"serverDate"})},get RegExp(){return a({path:[],method:"RegExp"})}},u=Ne(c,{get:(e,t)=>o("db",t)?i({$method:t}):function(){return i({$method:t,$param:$e(Array.from(arguments))})}});return this._database=u,u}}(t),function(e){e.getCurrentUserInfo=Ke,e.chooseAndUploadFile=o(Be.initChooseAndUploadFile(e))}(t),t.init=this.init,t}};(()=>{{let e={};if(1===process.env.UNI_CLOUD_PROVIDER.length)e=process.env.UNI_CLOUD_PROVIDER[0],We=We.init(e);else{const e=["auth","callFunction","uploadFile","deleteFile","getTempFileURL","downloadFile","database","getCurrentUSerInfo"],t=process.env.UNI_CLOUD_PROVIDER.length>0?"应用有多个服务空间,请通过uniCloud.init方法指定要使用的服务空间":"应用未关联服务空间,请在cloudfunctions目录右键关联服务空间";e.forEach(e=>{We[e]=function(){return console.error(t),Promise.reject(new i({code:"SYS_ERR",message:t}))}})}Object.assign(We,{get mixinDatacom(){return e=We,{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===je)return;let s=!1;const n=[];for(let r=2;r{this.mixinDatacomLoading=!1;const{data:n,count:r}=s.result;this.getcount&&(this.mixinDatacomPage.count=r),this.mixinDatacomHasMore=n.length{this.mixinDatacomLoading=!1,this.mixinDatacomErrorMessage=e,s&&s(e)}))},mixinDatacomGet(t={}){let s=e.database();const n=t.action||this.action;n&&(s=s.action(n));const r=t.collection||this.collection;s=s.collection(r);const o=t.where||this.where;o&&Object.keys(o).length&&(s=s.where(o));const i=t.field||this.field;i&&(s=s.field(i));const a=t.foreignKey||this.foreignKey;a&&(s=s.foreignKey(a));const c=t.groupby||this.groupby;c&&(s=s.groupBy(c));const u=t.groupField||this.groupField;u&&(s=s.groupField(u)),!0===(void 0!==t.distinct?t.distinct:this.distinct)&&(s=s.distinct());const h=t.orderby||this.orderby;h&&(s=s.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),s=s.skip(d*(l-1)).limit(d).get(m),s}}};var e}})}})();var Ve=We;export default Ve; diff --git a/packages/uni-cloud/package.json b/packages/uni-cloud/package.json index 4b00f4793..0d1bd4a59 100644 --- a/packages/uni-cloud/package.json +++ b/packages/uni-cloud/package.json @@ -2,8 +2,8 @@ "name": "@dcloudio/uni-cloud", "version": "3.0.0", "description": "@dcloudio/uni-cloud", - "main": "dist/uni-cloud.esm.js", - "module": "dist/uni-cloud.esm.js", + "main": "dist/uni-cloud.cjs.js", + "module": "dist/uni-cloud.es.js", "files": [ "dist" ], diff --git a/packages/uni-h5-vue/build.json b/packages/uni-h5-vue/build.json deleted file mode 100644 index eb8d00d09..000000000 --- a/packages/uni-h5-vue/build.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "input": { - "src/index.ts": "dist/vue.runtime.esm.js" - }, - "alias": { - "entries": [ - { - "find": "vue", - "replacement": "@dcloudio/uni-h5-vue/lib/vue.runtime.esm.js" - } - ] - }, - "external": ["@dcloudio/uni-h5"] -} diff --git a/packages/uni-h5-vue/lib/vue.runtime.esm.js b/packages/uni-h5-vue/dist/vue.runtime.cjs.js similarity index 86% rename from packages/uni-h5-vue/lib/vue.runtime.esm.js rename to packages/uni-h5-vue/dist/vue.runtime.cjs.js index 77e477d90..44167d018 100644 --- a/packages/uni-h5-vue/lib/vue.runtime.esm.js +++ b/packages/uni-h5-vue/dist/vue.runtime.cjs.js @@ -1,15 +1,18 @@ -import { EMPTY_OBJ, isArray, isMap, isIntegerKey, isSymbol, extend, hasOwn, isObject, hasChanged, makeMap, capitalize, toRawType, def, isFunction, NOOP, isString, isPromise, toHandlerKey, toNumber, hyphenate, camelize, isOn, isModelListener, isReservedProp, EMPTY_ARR, remove, isSet, invokeArrayFns, NO, getGlobalThis, normalizeClass, normalizeStyle, isGloballyWhitelisted, isSpecialBooleanAttr, looseIndexOf, looseEqual, isHTMLTag, isSVGTag } from '@vue/shared'; -export { camelize, capitalize, toDisplayString, toHandlerKey } from '@vue/shared'; +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var shared = require('@vue/shared'); const targetMap = new WeakMap(); const effectStack = []; let activeEffect; -const ITERATE_KEY = Symbol((process.env.NODE_ENV !== 'production') ? 'iterate' : ''); -const MAP_KEY_ITERATE_KEY = Symbol((process.env.NODE_ENV !== 'production') ? 'Map key iterate' : ''); +const ITERATE_KEY = Symbol('iterate' ); +const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' ); function isEffect(fn) { return fn && fn._isEffect === true; } -function effect(fn, options = EMPTY_OBJ) { +function effect(fn, options = shared.EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } @@ -96,7 +99,7 @@ function track(target, type, key) { if (!dep.has(activeEffect)) { dep.add(activeEffect); activeEffect.deps.push(dep); - if ((process.env.NODE_ENV !== 'production') && activeEffect.options.onTrack) { + if (activeEffect.options.onTrack) { activeEffect.options.onTrack({ effect: activeEffect, target, @@ -127,7 +130,7 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { // trigger all effects for target depsMap.forEach(add); } - else if (key === 'length' && isArray(target)) { + else if (key === 'length' && shared.isArray(target)) { depsMap.forEach((dep, key) => { if (key === 'length' || key >= newValue) { add(dep); @@ -142,34 +145,34 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { // also run for iteration key on ADD | DELETE | Map.SET switch (type) { case "add" /* ADD */: - if (!isArray(target)) { + if (!shared.isArray(target)) { add(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { + if (shared.isMap(target)) { add(depsMap.get(MAP_KEY_ITERATE_KEY)); } } - else if (isIntegerKey(key)) { + else if (shared.isIntegerKey(key)) { // new index added to array -> length changes add(depsMap.get('length')); } break; case "delete" /* DELETE */: - if (!isArray(target)) { + if (!shared.isArray(target)) { add(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { + if (shared.isMap(target)) { add(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set" /* SET */: - if (isMap(target)) { + if (shared.isMap(target)) { add(depsMap.get(ITERATE_KEY)); } break; } } const run = (effect) => { - if ((process.env.NODE_ENV !== 'production') && effect.options.onTrigger) { + if (effect.options.onTrigger) { effect.options.onTrigger({ effect, target, @@ -190,10 +193,10 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { effects.forEach(run); } -const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`); +const isNonTrackableKeys = /*#__PURE__*/ shared.makeMap(`__proto__,__v_isRef,__isVue`); const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol) .map(key => Symbol[key]) - .filter(isSymbol)); + .filter(shared.isSymbol)); const get = /*#__PURE__*/ createGetter(); const shallowGet = /*#__PURE__*/ createGetter(false, true); const readonlyGet = /*#__PURE__*/ createGetter(true); @@ -245,12 +248,12 @@ function createGetter(isReadonly = false, shallow = false) { : reactiveMap).get(target)) { return target; } - const targetIsArray = isArray(target); - if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) { + const targetIsArray = shared.isArray(target); + if (!isReadonly && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); - if (isSymbol(key) + if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; @@ -263,10 +266,10 @@ function createGetter(isReadonly = false, shallow = false) { } if (isRef(res)) { // ref unwrapping - does not apply for Array + integer key. - const shouldUnwrap = !targetIsArray || !isIntegerKey(key); + const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key); return shouldUnwrap ? res.value : res; } - if (isObject(res)) { + if (shared.isObject(res)) { // Convert returned value into a proxy as well. we do the isObject check // here to avoid invalid value warning. Also need to lazy access readonly // and reactive here to avoid circular dependency. @@ -282,21 +285,21 @@ function createSetter(shallow = false) { const oldValue = target[key]; if (!shallow) { value = toRaw(value); - if (!isArray(target) && isRef(oldValue) && !isRef(value)) { + if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } - const hadKey = isArray(target) && isIntegerKey(key) + const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length - : hasOwn(target, key); + : shared.hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); // don't trigger if target is something up in the prototype chain of original if (target === toRaw(receiver)) { if (!hadKey) { trigger(target, "add" /* ADD */, key, value); } - else if (hasChanged(value, oldValue)) { + else if (shared.hasChanged(value, oldValue)) { trigger(target, "set" /* SET */, key, value, oldValue); } } @@ -304,7 +307,7 @@ function createSetter(shallow = false) { }; } function deleteProperty(target, key) { - const hadKey = hasOwn(target, key); + const hadKey = shared.hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { @@ -314,13 +317,13 @@ function deleteProperty(target, key) { } function has(target, key) { const result = Reflect.has(target, key); - if (!isSymbol(key) || !builtInSymbols.has(key)) { + if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has" /* HAS */, key); } return result; } function ownKeys(target) { - track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY); + track(target, "iterate" /* ITERATE */, shared.isArray(target) ? 'length' : ITERATE_KEY); return Reflect.ownKeys(target); } const mutableHandlers = { @@ -333,31 +336,31 @@ const mutableHandlers = { const readonlyHandlers = { get: readonlyGet, set(target, key) { - if ((process.env.NODE_ENV !== 'production')) { + { console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { - if ((process.env.NODE_ENV !== 'production')) { + { console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; -const shallowReactiveHandlers = extend({}, mutableHandlers, { +const shallowReactiveHandlers = shared.extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); // Props handlers are special in the sense that it should not unwrap top-level // refs (in order to allow refs to be explicitly passed down), but should // retain the reactivity of the normal readonly object. -const shallowReadonlyHandlers = extend({}, readonlyHandlers, { +const shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, { get: shallowReadonlyGet }); -const toReactive = (value) => isObject(value) ? reactive(value) : value; -const toReadonly = (value) => isObject(value) ? readonly(value) : value; +const toReactive = (value) => shared.isObject(value) ? reactive(value) : value; +const toReadonly = (value) => shared.isObject(value) ? readonly(value) : value; const toShallow = (value) => value; const getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly = false, isShallow = false) { @@ -416,7 +419,7 @@ function set$1(key, value) { key = toRaw(key); hadKey = has.call(target, key); } - else if ((process.env.NODE_ENV !== 'production')) { + else { checkIdentityKeys(target, has, key); } const oldValue = get.call(target, key); @@ -424,7 +427,7 @@ function set$1(key, value) { if (!hadKey) { trigger(target, "add" /* ADD */, key, value); } - else if (hasChanged(value, oldValue)) { + else if (shared.hasChanged(value, oldValue)) { trigger(target, "set" /* SET */, key, value, oldValue); } return this; @@ -437,7 +440,7 @@ function deleteEntry(key) { key = toRaw(key); hadKey = has.call(target, key); } - else if ((process.env.NODE_ENV !== 'production')) { + else { checkIdentityKeys(target, has, key); } const oldValue = get ? get.call(target, key) : undefined; @@ -451,11 +454,10 @@ function deleteEntry(key) { function clear() { const target = toRaw(this); const hadItems = target.size !== 0; - const oldTarget = (process.env.NODE_ENV !== 'production') - ? isMap(target) + const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target) - : undefined; + ; // forward the operation before queueing reactions const result = target.clear(); if (hadItems) { @@ -482,7 +484,7 @@ function createIterableMethod(method, isReadonly, isShallow) { return function (...args) { const target = this["__v_raw" /* RAW */]; const rawTarget = toRaw(target); - const targetIsMap = isMap(rawTarget); + const targetIsMap = shared.isMap(rawTarget); const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap); const isKeyOnly = method === 'keys' && targetIsMap; const innerIterator = target[method](...args); @@ -511,9 +513,9 @@ function createIterableMethod(method, isReadonly, isShallow) { } function createReadonlyMethod(type) { return function (...args) { - if ((process.env.NODE_ENV !== 'production')) { + { const key = args[0] ? `on key "${args[0]}" ` : ``; - console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this)); + console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this)); } return type === "delete" /* DELETE */ ? false : this; }; @@ -603,7 +605,7 @@ function createInstrumentationGetter(isReadonly, shallow) { else if (key === "__v_raw" /* RAW */) { return target; } - return Reflect.get(hasOwn(instrumentations, key) && key in target + return Reflect.get(shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; @@ -623,7 +625,7 @@ const shallowReadonlyCollectionHandlers = { function checkIdentityKeys(target, has, key) { const rawKey = toRaw(key); if (rawKey !== key && has.call(target, rawKey)) { - const type = toRawType(target); + const type = shared.toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive ` + `versions of the same object${type === `Map` ? ` as keys` : ``}, ` + `which can lead to inconsistencies. ` + @@ -653,7 +655,7 @@ function targetTypeMap(rawType) { function getTargetType(value) { return value["__v_skip" /* SKIP */] || !Object.isExtensible(value) ? 0 /* INVALID */ - : targetTypeMap(toRawType(value)); + : targetTypeMap(shared.toRawType(value)); } function reactive(target) { // if trying to observe a readonly proxy, return the readonly version. @@ -687,8 +689,8 @@ function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) { - if (!isObject(target)) { - if ((process.env.NODE_ENV !== 'production')) { + if (!shared.isObject(target)) { + { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; @@ -729,11 +731,11 @@ function toRaw(observed) { return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed); } function markRaw(value) { - def(value, "__v_skip" /* SKIP */, true); + shared.def(value, "__v_skip" /* SKIP */, true); return value; } -const convert = (val) => isObject(val) ? reactive(val) : val; +const convert = (val) => shared.isObject(val) ? reactive(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); } @@ -755,7 +757,7 @@ class RefImpl { return this._value; } set value(newVal) { - if (hasChanged(toRaw(newVal), this._rawValue)) { + if (shared.hasChanged(toRaw(newVal), this._rawValue)) { this._rawValue = newVal; this._value = this._shallow ? newVal : convert(newVal); trigger(toRaw(this), "set" /* SET */, 'value', newVal); @@ -769,7 +771,7 @@ function createRef(rawValue, shallow = false) { return new RefImpl(rawValue, shallow); } function triggerRef(ref) { - trigger(toRaw(ref), "set" /* SET */, 'value', (process.env.NODE_ENV !== 'production') ? ref.value : void 0); + trigger(toRaw(ref), "set" /* SET */, 'value', ref.value ); } function unref(ref) { return isRef(ref) ? ref.value : ref; @@ -810,10 +812,10 @@ function customRef(factory) { return new CustomRefImpl(factory); } function toRefs(object) { - if ((process.env.NODE_ENV !== 'production') && !isProxy(object)) { + if (!isProxy(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`); } - const ret = isArray(object) ? new Array(object.length) : {}; + const ret = shared.isArray(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = toRef(object, key); } @@ -871,19 +873,18 @@ class ComputedRefImpl { function computed(getterOrOptions) { let getter; let setter; - if (isFunction(getterOrOptions)) { + if (shared.isFunction(getterOrOptions)) { getter = getterOrOptions; - setter = (process.env.NODE_ENV !== 'production') - ? () => { + setter = () => { console.warn('Write operation failed: computed value is readonly'); } - : NOOP; + ; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } - return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set); + return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set); } const stack = []; @@ -978,7 +979,7 @@ function formatProps(props) { } /* istanbul ignore next */ function formatProp(key, value, raw) { - if (isString(value)) { + if (shared.isString(value)) { value = JSON.stringify(value); return raw ? value : [`${key}=${value}`]; } @@ -991,7 +992,7 @@ function formatProp(key, value, raw) { value = formatProp(key, toRaw(value.value), true); return raw ? value : [`${key}=Ref<`, value, `>`]; } - else if (isFunction(value)) { + else if (shared.isFunction(value)) { return [`${key}=fn${value.name ? `<${value.name}>` : ``}`]; } else { @@ -1042,9 +1043,9 @@ function callWithErrorHandling(fn, instance, type, args) { return res; } function callWithAsyncErrorHandling(fn, instance, type, args) { - if (isFunction(fn)) { + if (shared.isFunction(fn)) { const res = callWithErrorHandling(fn, instance, type, args); - if (res && isPromise(res)) { + if (res && shared.isPromise(res)) { res.catch(err => { handleError(err, instance, type); }); @@ -1064,7 +1065,7 @@ function handleError(err, instance, type, throwInDev = true) { // the exposed instance is the render proxy to keep it consistent with 2.x const exposedInstance = instance.proxy; // in production the hook receives only the error code - const errorInfo = (process.env.NODE_ENV !== 'production') ? ErrorTypeStrings[type] : type; + const errorInfo = ErrorTypeStrings[type] ; while (cur) { const errorCapturedHooks = cur.ec; if (errorCapturedHooks) { @@ -1086,7 +1087,7 @@ function handleError(err, instance, type, throwInDev = true) { logError(err, type, contextVNode, throwInDev); } function logError(err, type, contextVNode, throwInDev = true) { - if ((process.env.NODE_ENV !== 'production')) { + { const info = ErrorTypeStrings[type]; if (contextVNode) { pushWarningContext(contextVNode); @@ -1103,10 +1104,6 @@ function logError(err, type, contextVNode, throwInDev = true) { console.error(err); } } - else { - // recover in prod to reduce the impact on end-user - console.error(err); - } } let isFlushing = false; @@ -1176,7 +1173,7 @@ function invalidateJob(job) { } } function queueCb(cb, activeQueue, pendingQueue, index) { - if (!isArray(cb)) { + if (!shared.isArray(cb)) { if (!activeQueue || !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) { pendingQueue.push(cb); @@ -1201,11 +1198,11 @@ function flushPreFlushCbs(seen, parentJob = null) { currentPreFlushParentJob = parentJob; activePreFlushCbs = [...new Set(pendingPreFlushCbs)]; pendingPreFlushCbs.length = 0; - if ((process.env.NODE_ENV !== 'production')) { + { seen = seen || new Map(); } for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) { - if ((process.env.NODE_ENV !== 'production')) { + { checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]); } activePreFlushCbs[preFlushIndex](); @@ -1227,12 +1224,12 @@ function flushPostFlushCbs(seen) { return; } activePostFlushCbs = deduped; - if ((process.env.NODE_ENV !== 'production')) { + { seen = seen || new Map(); } activePostFlushCbs.sort((a, b) => getId(a) - getId(b)); for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - if ((process.env.NODE_ENV !== 'production')) { + { checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]); } activePostFlushCbs[postFlushIndex](); @@ -1245,7 +1242,7 @@ const getId = (job) => job.id == null ? Infinity : job.id; function flushJobs(seen) { isFlushPending = false; isFlushing = true; - if ((process.env.NODE_ENV !== 'production')) { + { seen = seen || new Map(); } flushPreFlushCbs(seen); @@ -1261,7 +1258,7 @@ function flushJobs(seen) { for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { const job = queue[flushIndex]; if (job) { - if ((process.env.NODE_ENV !== 'production')) { + if (true) { checkRecursiveUpdates(seen, job); } callWithErrorHandling(job, null, 14 /* SCHEDULER */); @@ -1308,7 +1305,7 @@ const hmrDirtyComponents = new Set(); // it easier to be used in toolings like vue-loader // Note: for a component to be eligible for HMR it also needs the __hmrId option // to be set so that its instances can be registered / removed. -if ((process.env.NODE_ENV !== 'production')) { +{ const globalObject = typeof global !== 'undefined' ? global : typeof self !== 'undefined' @@ -1380,7 +1377,7 @@ function reload(id, newComp) { if (!hmrDirtyComponents.has(component)) { // 1. Update existing comp definition to match new one newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp; - extend(component, newComp); + shared.extend(component, newComp); for (const key in component) { if (!(key in newComp)) { delete component[key]; @@ -1427,15 +1424,14 @@ function tryWrap(fn) { }; } -let devtools; function setDevtoolsHook(hook) { - devtools = hook; + exports.devtools = hook; } function devtoolsInitApp(app, version) { // TODO queue if devtools is undefined - if (!devtools) + if (!exports.devtools) return; - devtools.emit("app:init" /* APP_INIT */, app, version, { + exports.devtools.emit("app:init" /* APP_INIT */, app, version, { Fragment, Text, Comment, @@ -1443,40 +1439,40 @@ function devtoolsInitApp(app, version) { }); } function devtoolsUnmountApp(app) { - if (!devtools) + if (!exports.devtools) return; - devtools.emit("app:unmount" /* APP_UNMOUNT */, app); + exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app); } const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */); const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */); const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */); function createDevtoolsComponentHook(hook) { return (component) => { - if (!devtools) + if (!exports.devtools) return; - devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component); + exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component); }; } function devtoolsComponentEmit(component, event, params) { - if (!devtools) + if (!exports.devtools) return; - devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params); + exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params); } function emit(instance, event, ...rawArgs) { - const props = instance.vnode.props || EMPTY_OBJ; - if ((process.env.NODE_ENV !== 'production')) { + const props = instance.vnode.props || shared.EMPTY_OBJ; + { const { emitsOptions, propsOptions: [propsOptions] } = instance; if (emitsOptions) { if (!(event in emitsOptions)) { - if (!propsOptions || !(toHandlerKey(event) in propsOptions)) { + if (!propsOptions || !(shared.toHandlerKey(event) in propsOptions)) { warn(`Component emitted event "${event}" but it is neither declared in ` + - `the emits option nor as an "${toHandlerKey(event)}" prop.`); + `the emits option nor as an "${shared.toHandlerKey(event)}" prop.`); } } else { const validator = emitsOptions[event]; - if (isFunction(validator)) { + if (shared.isFunction(validator)) { const isValid = validator(...rawArgs); if (!isValid) { warn(`Invalid event arguments: event validation failed for event "${event}".`); @@ -1491,34 +1487,34 @@ function emit(instance, event, ...rawArgs) { const modelArg = isModelListener && event.slice(7); if (modelArg && modelArg in props) { const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`; - const { number, trim } = props[modifiersKey] || EMPTY_OBJ; + const { number, trim } = props[modifiersKey] || shared.EMPTY_OBJ; if (trim) { args = rawArgs.map(a => a.trim()); } else if (number) { - args = rawArgs.map(toNumber); + args = rawArgs.map(shared.toNumber); } } - if ((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) { + { devtoolsComponentEmit(instance, event, args); } - if ((process.env.NODE_ENV !== 'production')) { + { const lowerCaseEvent = event.toLowerCase(); - if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) { + if (lowerCaseEvent !== event && props[shared.toHandlerKey(lowerCaseEvent)]) { warn(`Event "${lowerCaseEvent}" is emitted in component ` + `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` + `Note that HTML attributes are case-insensitive and you cannot use ` + `v-on to listen to camelCase events when using in-DOM templates. ` + - `You should probably use "${hyphenate(event)}" instead of "${event}".`); + `You should probably use "${shared.hyphenate(event)}" instead of "${event}".`); } } // convert handler name to camelCase. See issue #2249 - let handlerName = toHandlerKey(camelize(event)); + let handlerName = shared.toHandlerKey(shared.camelize(event)); let handler = props[handlerName]; // for v-model update:xxx events, also trigger kebab-case equivalent // for props passed via kebab-case if (!handler && isModelListener) { - handlerName = toHandlerKey(hyphenate(event)); + handlerName = shared.toHandlerKey(shared.hyphenate(event)); handler = props[handlerName]; } if (handler) { @@ -1543,12 +1539,12 @@ function normalizeEmitsOptions(comp, appContext, asMixin = false) { let normalized = {}; // apply mixin/extends props let hasExtends = false; - if (__VUE_OPTIONS_API__ && !isFunction(comp)) { + if (!shared.isFunction(comp)) { const extendEmits = (raw) => { const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true); if (normalizedFromExtend) { hasExtends = true; - extend(normalized, normalizedFromExtend); + shared.extend(normalized, normalizedFromExtend); } }; if (!asMixin && appContext.mixins.length) { @@ -1564,11 +1560,11 @@ function normalizeEmitsOptions(comp, appContext, asMixin = false) { if (!raw && !hasExtends) { return (comp.__emits = null); } - if (isArray(raw)) { + if (shared.isArray(raw)) { raw.forEach(key => (normalized[key] = null)); } else { - extend(normalized, raw); + shared.extend(normalized, raw); } return (comp.__emits = normalized); } @@ -1576,13 +1572,13 @@ function normalizeEmitsOptions(comp, appContext, asMixin = false) { // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are // both considered matched listeners. function isEmitListener(options, key) { - if (!options || !isOn(key)) { + if (!options || !shared.isOn(key)) { return false; } key = key.slice(2).replace(/Once$/, ''); - return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) || - hasOwn(options, hyphenate(key)) || - hasOwn(options, key)); + return (shared.hasOwn(options, key[0].toLowerCase() + key.slice(1)) || + shared.hasOwn(options, shared.hyphenate(key)) || + shared.hasOwn(options, key)); } let isRenderingCompiledSlot = 0; @@ -1596,7 +1592,7 @@ function renderSlot(slots, name, props = {}, // the compiler and guaranteed to be a function returning an array fallback, noSlotted) { let slot = slots[name]; - if ((process.env.NODE_ENV !== 'production') && slot && slot.length > 1) { + if (slot && slot.length > 1) { warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` + `function. You need to mark this component with $dynamic-slots in the ` + `parent template.`); @@ -1717,7 +1713,7 @@ function renderComponentRoot(instance) { const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance; let result; const prev = setCurrentRenderingInstance(instance); - if ((process.env.NODE_ENV !== 'production')) { + { accessedAttrs = false; } try { @@ -1733,11 +1729,11 @@ function renderComponentRoot(instance) { // functional const render = Component; // in dev, mark attrs accessed if optional props (attrs === props) - if ((process.env.NODE_ENV !== 'production') && attrs === props) { + if (true && attrs === props) { markAttrsAccessed(); } result = normalizeVNode(render.length > 1 - ? render(props, (process.env.NODE_ENV !== 'production') + ? render(props, true ? { get attrs() { markAttrsAccessed(); @@ -1757,7 +1753,7 @@ function renderComponentRoot(instance) { // to have comments along side the root element which makes it a fragment let root = result; let setRoot = undefined; - if ((process.env.NODE_ENV !== 'production') && + if (true && result.patchFlag > 0 && result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) { ; @@ -1769,7 +1765,7 @@ function renderComponentRoot(instance) { if (keys.length) { if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 6 /* COMPONENT */) { - if (propsOptions && keys.some(isModelListener)) { + if (propsOptions && keys.some(shared.isModelListener)) { // If a v-model listener (onUpdate:xxx) has a corresponding declared // prop, it indicates this component expects to handle v-model and // it should not fallthrough. @@ -1778,15 +1774,15 @@ function renderComponentRoot(instance) { } root = cloneVNode(root, fallthroughAttrs); } - else if ((process.env.NODE_ENV !== 'production') && !accessedAttrs && root.type !== Comment) { + else if (true && !accessedAttrs && root.type !== Comment) { const allAttrs = Object.keys(attrs); const eventAttrs = []; const extraAttrs = []; for (let i = 0, l = allAttrs.length; i < l; i++) { const key = allAttrs[i]; - if (isOn(key)) { + if (shared.isOn(key)) { // ignore v-model handlers when they fail to fallthrough - if (!isModelListener(key)) { + if (!shared.isModelListener(key)) { // remove `on`, lowercase first letter to reflect event casing // accurately eventAttrs.push(key[2].toLowerCase() + key.slice(3)); @@ -1815,7 +1811,7 @@ function renderComponentRoot(instance) { } // inherit directives if (vnode.dirs) { - if ((process.env.NODE_ENV !== 'production') && !isElementRoot(root)) { + if (true && !isElementRoot(root)) { warn(`Runtime directive used on component with non-element root node. ` + `The directives will not function as intended.`); } @@ -1823,13 +1819,13 @@ function renderComponentRoot(instance) { } // inherit transition data if (vnode.transition) { - if ((process.env.NODE_ENV !== 'production') && !isElementRoot(root)) { + if (true && !isElementRoot(root)) { warn(`Component inside renders non-element root node ` + `that cannot be animated.`); } root.transition = vnode.transition; } - if ((process.env.NODE_ENV !== 'production') && setRoot) { + if (true && setRoot) { setRoot(root); } else { @@ -1897,7 +1893,7 @@ function filterSingleRoot(children) { const getFunctionalFallthrough = (attrs) => { let res; for (const key in attrs) { - if (key === 'class' || key === 'style' || isOn(key)) { + if (key === 'class' || key === 'style' || shared.isOn(key)) { (res || (res = {}))[key] = attrs[key]; } } @@ -1906,7 +1902,7 @@ const getFunctionalFallthrough = (attrs) => { const filterModelListeners = (attrs, props) => { const res = {}; for (const key in attrs) { - if (!isModelListener(key) || !(key.slice(9) in props)) { + if (!shared.isModelListener(key) || !(key.slice(9) in props)) { res[key] = attrs[key]; } } @@ -1925,7 +1921,7 @@ function shouldUpdateComponent(prevVNode, nextVNode, optimized) { // Parent component's render function was hot-updated. Since this may have // caused the child component's slots content to have changed, we need to // force the child to update as well. - if ((process.env.NODE_ENV !== 'production') && (prevChildren || nextChildren) && isHmrUpdating) { + if ((prevChildren || nextChildren) && isHmrUpdating) { return true; } // force child update for runtime directive or transition on component vnode. @@ -2123,7 +2119,7 @@ function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotSc // root node toggled // invoke @pending event const onPending = n2.props && n2.props.onPending; - if (isFunction(onPending)) { + if (shared.isFunction(onPending)) { onPending(); } // mount pending branch in off-dom container @@ -2153,13 +2149,13 @@ function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotSc let hasWarned = false; function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) { /* istanbul ignore if */ - if ((process.env.NODE_ENV !== 'production') && !false && !hasWarned) { + if (!hasWarned) { hasWarned = true; // @ts-ignore `console.info` cannot be null error console[console.info ? 'info' : 'log'](` is an experimental feature and its API will likely change.`); } const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals; - const timeout = toNumber(vnode.props && vnode.props.timeout); + const timeout = shared.toNumber(vnode.props && vnode.props.timeout); const suspense = { vnode, parent, @@ -2178,7 +2174,7 @@ function createSuspenseBoundary(vnode, parent, parentComponent, container, hidde isUnmounted: false, effects: [], resolve(resume = false) { - if ((process.env.NODE_ENV !== 'production')) { + { if (!resume && !suspense.pendingBranch) { throw new Error(`suspense.resolve() is called without a pending branch.`); } @@ -2239,7 +2235,7 @@ function createSuspenseBoundary(vnode, parent, parentComponent, container, hidde suspense.effects = []; // invoke @resolve event const onResolve = vnode.props && vnode.props.onResolve; - if (isFunction(onResolve)) { + if (shared.isFunction(onResolve)) { onResolve(); } }, @@ -2250,7 +2246,7 @@ function createSuspenseBoundary(vnode, parent, parentComponent, container, hidde const { vnode, activeBranch, parentComponent, container, isSVG } = suspense; // invoke @fallback event const onFallback = vnode.props && vnode.props.onFallback; - if (isFunction(onFallback)) { + if (shared.isFunction(onFallback)) { onFallback(); } const anchor = next(activeBranch); @@ -2305,7 +2301,7 @@ function createSuspenseBoundary(vnode, parent, parentComponent, container, hidde // retry from this component instance.asyncResolved = true; const { vnode } = instance; - if ((process.env.NODE_ENV !== 'production')) { + { pushWarningContext(vnode); } handleSetupResult(instance, asyncSetupResult, false); @@ -2327,7 +2323,7 @@ function createSuspenseBoundary(vnode, parent, parentComponent, container, hidde remove(placeholder); } updateHOCHostEl(instance, vnode.el); - if ((process.env.NODE_ENV !== 'production')) { + { popWarningContext(); } // only decrease deps count if suspense is not already resolved @@ -2382,12 +2378,12 @@ function normalizeSuspenseChildren(vnode) { }; } function normalizeSuspenseSlot(s) { - if (isFunction(s)) { + if (shared.isFunction(s)) { s = s(); } - if (isArray(s)) { + if (shared.isArray(s)) { const singleChild = filterSingleRoot(s); - if ((process.env.NODE_ENV !== 'production') && !singleChild) { + if (!singleChild) { warn(` slots expect a single root node.`); } s = singleChild; @@ -2396,7 +2392,7 @@ function normalizeSuspenseSlot(s) { } function queueEffectWithSuspense(fn, suspense) { if (suspense && suspense.pendingBranch) { - if (isArray(fn)) { + if (shared.isArray(fn)) { suspense.effects.push(...fn); } else { @@ -2423,11 +2419,11 @@ function initProps(instance, rawProps, isStateful, // result of bitwise flag com isSSR = false) { const props = {}; const attrs = {}; - def(attrs, InternalObjectKey, 1); + shared.def(attrs, InternalObjectKey, 1); instance.propsDefaults = Object.create(null); setFullProps(instance, rawProps, props, attrs); // validation - if ((process.env.NODE_ENV !== 'production')) { + { validateProps(rawProps || {}, props, instance); } if (isStateful) { @@ -2454,8 +2450,7 @@ function updateProps(instance, rawProps, rawPrevProps, optimized) { // always force full diff in dev // - #1942 if hmr is enabled with sfc component // - vite#872 non-sfc component used by sfc component - !((process.env.NODE_ENV !== 'production') && - (instance.type.__hmrId || + !((instance.type.__hmrId || (instance.parent && instance.parent.type.__hmrId))) && (optimized || patchFlag > 0) && !(patchFlag & 16 /* FULL_PROPS */)) { @@ -2470,11 +2465,11 @@ function updateProps(instance, rawProps, rawPrevProps, optimized) { if (options) { // attr / props separation was done on init and will be consistent // in this code path, so just check if attrs have it. - if (hasOwn(attrs, key)) { + if (shared.hasOwn(attrs, key)) { attrs[key] = value; } else { - const camelizedKey = camelize(key); + const camelizedKey = shared.camelize(key); props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance); } } @@ -2493,17 +2488,17 @@ function updateProps(instance, rawProps, rawPrevProps, optimized) { for (const key in rawCurrentProps) { if (!rawProps || // for camelCase - (!hasOwn(rawProps, key) && + (!shared.hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case // and converted to camelCase (#955) - ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) { + ((kebabKey = shared.hyphenate(key)) === key || !shared.hasOwn(rawProps, kebabKey)))) { if (options) { if (rawPrevProps && // for camelCase (rawPrevProps[key] !== undefined || // for kebab-case rawPrevProps[kebabKey] !== undefined)) { - props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance); + props[key] = resolvePropValue(options, rawProps || shared.EMPTY_OBJ, key, undefined, instance); } } else { @@ -2515,7 +2510,7 @@ function updateProps(instance, rawProps, rawPrevProps, optimized) { // attrs point to the same object so it should already have been updated. if (attrs !== rawCurrentProps) { for (const key in attrs) { - if (!rawProps || !hasOwn(rawProps, key)) { + if (!rawProps || !shared.hasOwn(rawProps, key)) { delete attrs[key]; } } @@ -2523,7 +2518,7 @@ function updateProps(instance, rawProps, rawPrevProps, optimized) { } // trigger updates for $attrs in case it's used in component slots trigger(instance, "set" /* SET */, '$attrs'); - if ((process.env.NODE_ENV !== 'production')) { + { validateProps(rawProps || {}, props, instance); } } @@ -2533,13 +2528,13 @@ function setFullProps(instance, rawProps, props, attrs) { for (const key in rawProps) { const value = rawProps[key]; // key, ref are reserved and never passed down - if (isReservedProp(key)) { + if (shared.isReservedProp(key)) { continue; } // prop option names are camelized during normalization, so to support // kebab -> camel conversion here we need to camelize the key. let camelKey; - if (options && hasOwn(options, (camelKey = camelize(key)))) { + if (options && shared.hasOwn(options, (camelKey = shared.camelize(key)))) { props[camelKey] = value; } else if (!isEmitListener(instance.emitsOptions, key)) { @@ -2561,11 +2556,11 @@ function setFullProps(instance, rawProps, props, attrs) { function resolvePropValue(options, props, key, value, instance) { const opt = options[key]; if (opt != null) { - const hasDefault = hasOwn(opt, 'default'); + const hasDefault = shared.hasOwn(opt, 'default'); // default values if (hasDefault && value === undefined) { const defaultValue = opt.default; - if (opt.type !== Function && isFunction(defaultValue)) { + if (opt.type !== Function && shared.isFunction(defaultValue)) { const { propsDefaults } = instance; if (key in propsDefaults) { value = propsDefaults[key]; @@ -2582,11 +2577,11 @@ function resolvePropValue(options, props, key, value, instance) { } // boolean casting if (opt[0 /* shouldCast */]) { - if (!hasOwn(props, key) && !hasDefault) { + if (!shared.hasOwn(props, key) && !hasDefault) { value = false; } else if (opt[1 /* shouldCastTrue */] && - (value === '' || value === hyphenate(key))) { + (value === '' || value === shared.hyphenate(key))) { value = true; } } @@ -2602,11 +2597,11 @@ function normalizePropsOptions(comp, appContext, asMixin = false) { const needCastKeys = []; // apply mixin/extends props let hasExtends = false; - if (__VUE_OPTIONS_API__ && !isFunction(comp)) { + if (!shared.isFunction(comp)) { const extendProps = (raw) => { hasExtends = true; const [props, keys] = normalizePropsOptions(raw, appContext, true); - extend(normalized, props); + shared.extend(normalized, props); if (keys) needCastKeys.push(...keys); }; @@ -2621,29 +2616,29 @@ function normalizePropsOptions(comp, appContext, asMixin = false) { } } if (!raw && !hasExtends) { - return (comp.__props = EMPTY_ARR); + return (comp.__props = shared.EMPTY_ARR); } - if (isArray(raw)) { + if (shared.isArray(raw)) { for (let i = 0; i < raw.length; i++) { - if ((process.env.NODE_ENV !== 'production') && !isString(raw[i])) { + if (!shared.isString(raw[i])) { warn(`props must be strings when using array syntax.`, raw[i]); } - const normalizedKey = camelize(raw[i]); + const normalizedKey = shared.camelize(raw[i]); if (validatePropName(normalizedKey)) { - normalized[normalizedKey] = EMPTY_OBJ; + normalized[normalizedKey] = shared.EMPTY_OBJ; } } } else if (raw) { - if ((process.env.NODE_ENV !== 'production') && !isObject(raw)) { + if (!shared.isObject(raw)) { warn(`invalid props options`, raw); } for (const key in raw) { - const normalizedKey = camelize(key); + const normalizedKey = shared.camelize(key); if (validatePropName(normalizedKey)) { const opt = raw[key]; const prop = (normalized[normalizedKey] = - isArray(opt) || isFunction(opt) ? { type: opt } : opt); + shared.isArray(opt) || shared.isFunction(opt) ? { type: opt } : opt); if (prop) { const booleanIndex = getTypeIndex(Boolean, prop.type); const stringIndex = getTypeIndex(String, prop.type); @@ -2651,7 +2646,7 @@ function normalizePropsOptions(comp, appContext, asMixin = false) { prop[1 /* shouldCastTrue */] = stringIndex < 0 || booleanIndex < stringIndex; // if the prop needs boolean casting or default value - if (booleanIndex > -1 || hasOwn(prop, 'default')) { + if (booleanIndex > -1 || shared.hasOwn(prop, 'default')) { needCastKeys.push(normalizedKey); } } @@ -2664,7 +2659,7 @@ function validatePropName(key) { if (key[0] !== '$') { return true; } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn(`Invalid prop name: "${key}" is a reserved property.`); } return false; @@ -2679,14 +2674,14 @@ function isSameType(a, b) { return getType(a) === getType(b); } function getTypeIndex(type, expectedTypes) { - if (isArray(expectedTypes)) { + if (shared.isArray(expectedTypes)) { for (let i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i; } } } - else if (isFunction(expectedTypes)) { + else if (shared.isFunction(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1; } return -1; @@ -2701,7 +2696,7 @@ function validateProps(rawProps, props, instance) { let opt = options[key]; if (opt == null) continue; - validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))); + validateProp(key, resolvedValues[key], opt, !shared.hasOwn(rawProps, key) && !shared.hasOwn(rawProps, shared.hyphenate(key))); } } /** @@ -2721,7 +2716,7 @@ function validateProp(name, value, prop, isAbsent) { // type check if (type != null && type !== true) { let isValid = false; - const types = isArray(type) ? type : [type]; + const types = shared.isArray(type) ? type : [type]; const expectedTypes = []; // value is valid as long as one of the specified types match for (let i = 0; i < types.length && !isValid; i++) { @@ -2739,7 +2734,7 @@ function validateProp(name, value, prop, isAbsent) { warn('Invalid prop: custom validator check failed for prop "' + name + '".'); } } -const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt'); +const isSimpleType = /*#__PURE__*/ shared.makeMap('String,Number,Boolean,Function,Symbol,BigInt'); /** * dev only */ @@ -2755,10 +2750,10 @@ function assertType(value, type) { } } else if (expectedType === 'Object') { - valid = isObject(value); + valid = shared.isObject(value); } else if (expectedType === 'Array') { - valid = isArray(value); + valid = shared.isArray(value); } else { valid = value instanceof type; @@ -2773,9 +2768,9 @@ function assertType(value, type) { */ function getInvalidTypeMessage(name, value, expectedTypes) { let message = `Invalid prop: type check failed for prop "${name}".` + - ` Expected ${expectedTypes.map(capitalize).join(', ')}`; + ` Expected ${expectedTypes.map(shared.capitalize).join(', ')}`; const expectedType = expectedTypes[0]; - const receivedType = toRawType(value); + const receivedType = shared.toRawType(value); const expectedValue = styleValue(value, expectedType); const receivedValue = styleValue(value, receivedType); // check if we need to specify expected value @@ -2850,8 +2845,8 @@ function injectHook(type, hook, target = currentInstance, prepend = false) { } return wrappedHook; } - else if ((process.env.NODE_ENV !== 'production')) { - const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, '')); + else { + const apiName = shared.toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, '')); warn(`${apiName} is called when there is no active component instance to be ` + `associated with. ` + `Lifecycle injection APIs can only be used during execution of setup().` + @@ -2862,7 +2857,7 @@ function injectHook(type, hook, target = currentInstance, prepend = false) { } const createHook = (lifecycle) => (hook, target = currentInstance) => // post-create lifecycle registrations are noops during SSR -!isInSSRComponentSetup && injectHook(lifecycle, hook, target); +!exports.isInSSRComponentSetup && injectHook(lifecycle, hook, target); const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */); const onMounted = createHook("m" /* MOUNTED */); const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */); @@ -2883,15 +2878,15 @@ function watchEffect(effect, options) { const INITIAL_WATCHER_VALUE = {}; // implementation function watch(source, cb, options) { - if ((process.env.NODE_ENV !== 'production') && !isFunction(cb)) { + if (!shared.isFunction(cb)) { warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` + `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` + `supports \`watch(source, cb, options?) signature.`); } return doWatch(source, cb, options); } -function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) { - if ((process.env.NODE_ENV !== 'production') && !cb) { +function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = shared.EMPTY_OBJ, instance = currentInstance) { + if (!cb) { if (immediate !== undefined) { warn(`watch() "immediate" option is only respected when using the ` + `watch(source, callback, options?) signature.`); @@ -2915,7 +2910,7 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM getter = () => source; deep = true; } - else if (isArray(source)) { + else if (shared.isArray(source)) { getter = () => source.map(s => { if (isRef(s)) { return s.value; @@ -2923,17 +2918,17 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM else if (isReactive(s)) { return traverse(s); } - else if (isFunction(s)) { + else if (shared.isFunction(s)) { return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */, [ instance && instance.proxy ]); } else { - (process.env.NODE_ENV !== 'production') && warnInvalidSource(s); + warnInvalidSource(s); } }); } - else if (isFunction(source)) { + else if (shared.isFunction(source)) { if (cb) { // getter with cb getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */, [ @@ -2954,8 +2949,8 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM } } else { - getter = NOOP; - (process.env.NODE_ENV !== 'production') && warnInvalidSource(source); + getter = shared.NOOP; + warnInvalidSource(source); } if (cb && deep) { const baseGetter = getter; @@ -2967,7 +2962,7 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */); }; }; - let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE; + let oldValue = shared.isArray(source) ? [] : INITIAL_WATCHER_VALUE; const job = () => { if (!runner.active) { return; @@ -2975,7 +2970,7 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM if (cb) { // watch(source, cb) const newValue = runner(); - if (deep || forceTrigger || hasChanged(newValue, oldValue)) { + if (deep || forceTrigger || shared.hasChanged(newValue, oldValue)) { // cleanup before running cb again if (cleanup) { cleanup(); @@ -3042,32 +3037,32 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM return () => { stop(runner); if (instance) { - remove(instance.effects, runner); + shared.remove(instance.effects, runner); } }; } // this.$watch function instanceWatch(source, cb, options) { const publicThis = this.proxy; - const getter = isString(source) + const getter = shared.isString(source) ? () => publicThis[source] : source.bind(publicThis); return doWatch(getter, cb.bind(publicThis), options, this); } function traverse(value, seen = new Set()) { - if (!isObject(value) || seen.has(value)) { + if (!shared.isObject(value) || seen.has(value)) { return value; } seen.add(value); if (isRef(value)) { traverse(value.value, seen); } - else if (isArray(value)) { + else if (shared.isArray(value)) { for (let i = 0; i < value.length; i++) { traverse(value[i], seen); } } - else if (isSet(value) || isMap(value)) { + else if (shared.isSet(value) || shared.isMap(value)) { value.forEach((v) => { traverse(v, seen); }); @@ -3128,7 +3123,7 @@ const BaseTransitionImpl = { return; } // warn multiple elements - if ((process.env.NODE_ENV !== 'production') && children.length > 1) { + if (children.length > 1) { warn(' can only be used on a single element or component. Use ' + ' for lists.'); } @@ -3137,7 +3132,7 @@ const BaseTransitionImpl = { const rawProps = toRaw(props); const { mode } = rawProps; // check mode - if ((process.env.NODE_ENV !== 'production') && mode && !['in-out', 'out-in', 'default'].includes(mode)) { + if (mode && !['in-out', 'out-in', 'default'].includes(mode)) { warn(`invalid mode: ${mode}`); } // at this point children has a guaranteed length of 1. @@ -3459,7 +3454,7 @@ const KeepAliveImpl = { if (!sharedContext.renderer) { return slots.default; } - if ((process.env.NODE_ENV !== 'production') && props.cache && hasOwn(props, 'max')) { + if (props.cache && shared.hasOwn(props, 'max')) { warn('The `max` prop will be ignored if you provide a custom caching strategy'); } const cache = props.cache || new Cache(props.max); @@ -3485,7 +3480,7 @@ const KeepAliveImpl = { if (instance.ba) { const currentState = instance.isDeactivated; instance.isDeactivated = false; - invokeArrayFns(instance.ba); + shared.invokeArrayFns(instance.ba); instance.isDeactivated = currentState; } move(vnode, container, anchor, 0 /* ENTER */, parentSuspense); @@ -3494,7 +3489,7 @@ const KeepAliveImpl = { queuePostRenderEffect(() => { instance.isDeactivated = false; if (instance.a) { - invokeArrayFns(instance.a); + shared.invokeArrayFns(instance.a); } const vnodeHook = vnode.props && vnode.props.onVnodeMounted; if (vnodeHook) { @@ -3513,7 +3508,7 @@ const KeepAliveImpl = { resetHookState(instance.bda); } if (instance.da) { - invokeArrayFns(instance.da); + shared.invokeArrayFns(instance.da); } const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted; if (vnodeHook) { @@ -3563,7 +3558,7 @@ const KeepAliveImpl = { (props.matchBy !== 'key' || cached.key === vnode.key)) { // invoke its beforeDeactivate hook here if (vnode.component.bda) { - invokeArrayFns(vnode.component.bda); + shared.invokeArrayFns(vnode.component.bda); } // current instance will be unmounted as part of keep-alive's unmount resetShapeFlag(vnode); @@ -3582,7 +3577,7 @@ const KeepAliveImpl = { const children = slots.default(); const rawVNode = children[0]; if (children.length > 1) { - if ((process.env.NODE_ENV !== 'production')) { + { warn(`KeepAlive should contain exactly one component child.`); } current = null; @@ -3640,10 +3635,10 @@ const KeepAliveImpl = { // also to avoid inline import() in generated d.ts files const KeepAlive = KeepAliveImpl; function matches(pattern, name) { - if (isArray(pattern)) { + if (shared.isArray(pattern)) { return pattern.some((p) => matches(p, name)); } - else if (isString(pattern)) { + else if (shared.isString(pattern)) { return pattern.split(',').indexOf(name) > -1; } else if (pattern.test) { @@ -3702,7 +3697,7 @@ function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { // the wrapped version. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */); onUnmounted(() => { - remove(keepAliveRoot[type], injected); + shared.remove(keepAliveRoot[type], injected); }, target); } function resetShapeFlag(vnode) { @@ -3738,11 +3733,11 @@ function resetHookState(hooks) { } const isInternalKey = (key) => key[0] === '_' || key === '$stable'; -const normalizeSlotValue = (value) => isArray(value) +const normalizeSlotValue = (value) => shared.isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => { - if ((process.env.NODE_ENV !== 'production') && currentInstance) { + if (currentInstance) { warn(`Slot "${key}" invoked outside of the render function: ` + `this will not track dependencies used in the slot. ` + `Invoke the slot function inside the render function instead.`); @@ -3755,11 +3750,11 @@ const normalizeObjectSlots = (rawSlots, slots) => { if (isInternalKey(key)) continue; const value = rawSlots[key]; - if (isFunction(value)) { + if (shared.isFunction(value)) { slots[key] = normalizeSlot(key, value, ctx); } else if (value != null) { - if ((process.env.NODE_ENV !== 'production')) { + { warn(`Non-function value encountered for slot "${key}". ` + `Prefer function slots for better performance.`); } @@ -3769,7 +3764,7 @@ const normalizeObjectSlots = (rawSlots, slots) => { } }; const normalizeVNodeSlots = (instance, children) => { - if ((process.env.NODE_ENV !== 'production') && !isKeepAlive(instance.vnode)) { + if (!isKeepAlive(instance.vnode)) { warn(`Non-function value encountered for default slot. ` + `Prefer function slots for better performance.`); } @@ -3782,7 +3777,7 @@ const initSlots = (instance, children) => { if (type) { instance.slots = children; // make compiler marker non-enumerable - def(children, '_', type); + shared.def(children, '_', type); } else { normalizeObjectSlots(children, (instance.slots = {})); @@ -3794,20 +3789,20 @@ const initSlots = (instance, children) => { normalizeVNodeSlots(instance, children); } } - def(instance.slots, InternalObjectKey, 1); + shared.def(instance.slots, InternalObjectKey, 1); }; const updateSlots = (instance, children) => { const { vnode, slots } = instance; let needDeletionCheck = true; - let deletionComparisonTarget = EMPTY_OBJ; + let deletionComparisonTarget = shared.EMPTY_OBJ; if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) { const type = children._; if (type) { // compiled slots. - if ((process.env.NODE_ENV !== 'production') && isHmrUpdating) { + if (isHmrUpdating) { // Parent was HMR updated so slot content may have changed. // force update slots and mark instance for hmr as well - extend(slots, children); + shared.extend(slots, children); } else if (type === 1 /* STABLE */) { // compiled AND stable. @@ -3817,7 +3812,7 @@ const updateSlots = (instance, children) => { else { // compiled but dynamic (v-if/v-for on slots) - update slots, but skip // normalization. - extend(slots, children); + shared.extend(slots, children); } } else { @@ -3853,7 +3848,7 @@ return withDirectives(h(comp), [ [bar, this.y] ]) */ -const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text'); +const isBuiltInDirective = /*#__PURE__*/ shared.makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text'); function validateDirectiveName(name) { if (isBuiltInDirective(name)) { warn('Do not use built-in directive ids as custom directive id: ' + name); @@ -3865,14 +3860,14 @@ function validateDirectiveName(name) { function withDirectives(vnode, directives) { const internalInstance = currentRenderingInstance; if (internalInstance === null) { - (process.env.NODE_ENV !== 'production') && warn(`withDirectives can only be used inside render functions.`); + warn(`withDirectives can only be used inside render functions.`); return vnode; } const instance = internalInstance.proxy; const bindings = vnode.dirs || (vnode.dirs = []); for (let i = 0; i < directives.length; i++) { - let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; - if (isFunction(dir)) { + let [dir, value, arg, modifiers = shared.EMPTY_OBJ] = directives[i]; + if (shared.isFunction(dir)) { dir = { mounted: dir, updated: dir @@ -3913,11 +3908,11 @@ function createAppContext() { return { app: null, config: { - isNativeTag: NO, + isNativeTag: shared.NO, performance: false, globalProperties: {}, optionMergeStrategies: {}, - isCustomElement: NO, + isCustomElement: shared.NO, errorHandler: undefined, warnHandler: undefined }, @@ -3930,8 +3925,8 @@ function createAppContext() { let uid$1 = 0; function createAppAPI(render, hydrate) { 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.`); + if (rootProps != null && !shared.isObject(rootProps)) { + warn(`root props passed to app.mount() must be an object.`); rootProps = null; } const context = createAppContext(); @@ -3948,30 +3943,30 @@ function createAppAPI(render, hydrate) { return context.config; }, set config(v) { - if ((process.env.NODE_ENV !== 'production')) { + { warn(`app.config cannot be replaced. Modify individual options instead.`); } }, use(plugin, ...options) { if (installedPlugins.has(plugin)) { - (process.env.NODE_ENV !== 'production') && warn(`Plugin has already been applied to target app.`); + warn(`Plugin has already been applied to target app.`); } - else if (plugin && isFunction(plugin.install)) { + else if (plugin && shared.isFunction(plugin.install)) { installedPlugins.add(plugin); plugin.install(app, ...options); } - else if (isFunction(plugin)) { + else if (shared.isFunction(plugin)) { installedPlugins.add(plugin); plugin(app, ...options); } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn(`A plugin must either be a function or an object with an "install" ` + `function.`); } return app; }, mixin(mixin) { - if (__VUE_OPTIONS_API__) { + { if (!context.mixins.includes(mixin)) { context.mixins.push(mixin); // global mixin with props/emits de-optimizes props/emits @@ -3980,37 +3975,34 @@ function createAppAPI(render, hydrate) { context.deopt = true; } } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn('Mixin has already been applied to target app' + (mixin.name ? `: ${mixin.name}` : '')); } } - else if ((process.env.NODE_ENV !== 'production')) { - warn('Mixins are only available in builds supporting Options API'); - } return app; }, component(name, component) { - if ((process.env.NODE_ENV !== 'production')) { + { validateComponentName(name, context.config); } if (!component) { return context.components[name]; } - if ((process.env.NODE_ENV !== 'production') && context.components[name]) { + if (context.components[name]) { warn(`Component "${name}" has already been registered in target app.`); } context.components[name] = component; return app; }, directive(name, directive) { - if ((process.env.NODE_ENV !== 'production')) { + { validateDirectiveName(name); } if (!directive) { return context.directives[name]; } - if ((process.env.NODE_ENV !== 'production') && context.directives[name]) { + if (context.directives[name]) { warn(`Directive "${name}" has already been registered in target app.`); } context.directives[name] = directive; @@ -4023,7 +4015,7 @@ function createAppAPI(render, hydrate) { // this will be set on the root instance on initial mount. vnode.appContext = context; // HMR root reload - if ((process.env.NODE_ENV !== 'production')) { + { context.reload = () => { render(cloneVNode(vnode), rootContainer, isSVG); }; @@ -4037,12 +4029,12 @@ function createAppAPI(render, hydrate) { isMounted = true; app._container = rootContainer; rootContainer.__vue_app__ = app; - if ((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) { + { devtoolsInitApp(app, version); } return vnode.component.proxy; } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn(`App has already been mounted.\n` + `If you want to remount the same app, move your app creation logic ` + `into a factory function and create fresh app instances for each ` + @@ -4052,17 +4044,17 @@ function createAppAPI(render, hydrate) { unmount() { if (isMounted) { render(null, app._container); - if ((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) { + { devtoolsUnmountApp(app); } delete app._container.__vue_app__; } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn(`Cannot unmount an app that is not mounted.`); } }, provide(key, value) { - if ((process.env.NODE_ENV !== 'production') && key in context.provides) { + if (key in context.provides) { warn(`App already provides property with key "${String(key)}". ` + `It will be overwritten with the new value.`); } @@ -4087,7 +4079,7 @@ const isComment = (node) => node.nodeType === 8 /* COMMENT */; function createHydrationFunctions(rendererInternals) { const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals; const hydrate = (vnode, container) => { - if ((process.env.NODE_ENV !== 'production') && !container.hasChildNodes()) { + if (!container.hasChildNodes()) { warn(`Attempting to hydrate existing markup but container is empty. ` + `Performing full mount instead.`); patch(null, vnode, container); @@ -4116,8 +4108,7 @@ function createHydrationFunctions(rendererInternals) { else { if (node.data !== vnode.children) { hasMismatch = true; - (process.env.NODE_ENV !== 'production') && - warn(`Hydration text mismatch:` + + warn(`Hydration text mismatch:` + `\n- Client: ${JSON.stringify(node.data)}` + `\n- Server: ${JSON.stringify(vnode.children)}`); node.data = vnode.children; @@ -4208,7 +4199,7 @@ function createHydrationFunctions(rendererInternals) { else if (shapeFlag & 128 /* SUSPENSE */) { nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode); } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn('Invalid HostVNode type:', type, `(${typeof type})`); } } @@ -4231,7 +4222,7 @@ function createHydrationFunctions(rendererInternals) { (patchFlag & 16 /* FULL_PROPS */ || patchFlag & 32 /* HYDRATE_EVENTS */)) { for (const key in props) { - if (!isReservedProp(key) && isOn(key)) { + if (!shared.isReservedProp(key) && shared.isOn(key)) { patchProp(el, key, null, props[key]); } } @@ -4264,7 +4255,7 @@ function createHydrationFunctions(rendererInternals) { let hasWarned = false; while (next) { hasMismatch = true; - if ((process.env.NODE_ENV !== 'production') && !hasWarned) { + if (!hasWarned) { warn(`Hydration children mismatch in <${vnode.type}>: ` + `server rendered element contains more child nodes than client vdom.`); hasWarned = true; @@ -4278,8 +4269,7 @@ function createHydrationFunctions(rendererInternals) { else if (shapeFlag & 8 /* TEXT_CHILDREN */) { if (el.textContent !== vnode.children) { hasMismatch = true; - (process.env.NODE_ENV !== 'production') && - warn(`Hydration text content mismatch in <${vnode.type}>:\n` + + warn(`Hydration text content mismatch in <${vnode.type}>:\n` + `- Client: ${el.textContent}\n` + `- Server: ${vnode.children}`); el.textContent = vnode.children; @@ -4305,7 +4295,7 @@ function createHydrationFunctions(rendererInternals) { } else { hasMismatch = true; - if ((process.env.NODE_ENV !== 'production') && !hasWarned) { + if (!hasWarned) { warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` + `server rendered element contains fewer child nodes than client vdom.`); hasWarned = true; @@ -4339,8 +4329,7 @@ function createHydrationFunctions(rendererInternals) { }; const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => { hasMismatch = true; - (process.env.NODE_ENV !== 'production') && - warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */ + warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */ ? `(text)` : isComment(node) && node.data === '[' ? `(start of fragment)` @@ -4420,39 +4409,14 @@ function isSupported() { return supported; } -/** - * This is only called in esm-bundler builds. - * It is called when a renderer is created, in `baseCreateRenderer` so that - * importing runtime-core is side-effects free. - * - * istanbul-ignore-next - */ -function initFeatureFlags() { - let needWarn = false; - if (typeof __VUE_OPTIONS_API__ !== 'boolean') { - needWarn = true; - getGlobalThis().__VUE_OPTIONS_API__ = true; - } - if (typeof __VUE_PROD_DEVTOOLS__ !== 'boolean') { - needWarn = true; - getGlobalThis().__VUE_PROD_DEVTOOLS__ = false; - } - if ((process.env.NODE_ENV !== 'production') && needWarn) { - console.warn(`You are running the esm-bundler build of Vue. It is recommended to ` + - `configure your bundler to explicitly replace feature flag globals ` + - `with boolean literals to get proper tree-shaking in the final bundle. ` + - `See http://link.vuejs.org/feature-flags for more details.`); - } -} - // implementation, close to no-op function defineComponent(options) { - return isFunction(options) ? { setup: options, name: options.name } : options; + return shared.isFunction(options) ? { setup: options, name: options.name } : options; } const isAsyncWrapper = (i) => !!i.type.__asyncLoader; function defineAsyncComponent(source) { - if (isFunction(source)) { + if (shared.isFunction(source)) { source = { loader: source }; } const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out @@ -4486,7 +4450,7 @@ function defineAsyncComponent(source) { if (thisRequest !== pendingRequest && pendingRequest) { return pendingRequest; } - if ((process.env.NODE_ENV !== 'production') && !comp) { + if (!comp) { warn(`Async component loader resolved to undefined. ` + `If you are using retry(), make sure to return its return value.`); } @@ -4495,7 +4459,7 @@ function defineAsyncComponent(source) { (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) { comp = comp.default; } - if ((process.env.NODE_ENV !== 'production') && comp && !isObject(comp) && !isFunction(comp)) { + if (comp && !shared.isObject(comp) && !shared.isFunction(comp)) { throw new Error(`Invalid async component load result: ${comp}`); } resolvedComp = comp; @@ -4579,24 +4543,19 @@ function createInnerComp(comp, { vnode: { ref, props, children } }) { return vnode; } -const prodEffectOptions = { - scheduler: queueJob, - // #1801, #2043 component render effects should allow recursive updates - allowRecurse: true -}; function createDevEffectOptions(instance) { return { scheduler: queueJob, allowRecurse: true, - onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0, - onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0 + onTrack: instance.rtc ? e => shared.invokeArrayFns(instance.rtc, e) : void 0, + onTrigger: instance.rtg ? e => shared.invokeArrayFns(instance.rtg, e) : void 0 }; } const queuePostRenderEffect = queueEffectWithSuspense ; const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => { - if (isArray(rawRef)) { - rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode)); + if (shared.isArray(rawRef)) { + rawRef.forEach((r, i) => setRef(r, oldRawRef && (shared.isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode)); return; } let value; @@ -4616,19 +4575,19 @@ const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => { value = vnode.el; } const { i: owner, r: ref } = rawRef; - if ((process.env.NODE_ENV !== 'production') && !owner) { + if (!owner) { warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` + `A vnode with ref must be created inside the render function.`); return; } const oldRef = oldRawRef && oldRawRef.r; - const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs; + const refs = owner.refs === shared.EMPTY_OBJ ? (owner.refs = {}) : owner.refs; const setupState = owner.setupState; // unset old ref if (oldRef != null && oldRef !== ref) { - if (isString(oldRef)) { + if (shared.isString(oldRef)) { refs[oldRef] = null; - if (hasOwn(setupState, oldRef)) { + if (shared.hasOwn(setupState, oldRef)) { setupState[oldRef] = null; } } @@ -4636,10 +4595,10 @@ const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => { oldRef.value = null; } } - if (isString(ref)) { + if (shared.isString(ref)) { const doSet = () => { refs[ref] = value; - if (hasOwn(setupState, ref)) { + if (shared.hasOwn(setupState, ref)) { setupState[ref] = value; } }; @@ -4666,10 +4625,10 @@ const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => { doSet(); } } - else if (isFunction(ref)) { + else if (shared.isFunction(ref)) { callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]); } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn('Invalid template ref type:', value, `(${typeof value})`); } }; @@ -4699,16 +4658,12 @@ function createHydrationRenderer(options) { } // implementation function baseCreateRenderer(options, createHydrationFns) { - // compile-time feature flags check { - initFeatureFlags(); - } - if ((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) { - const target = getGlobalThis(); + const target = shared.getGlobalThis(); target.__VUE__ = true; setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__); } - const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options; + const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = shared.NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options; // Note: functions inside this closure should use `const xxx = () => {}` // style in order to prevent being inlined by minifiers. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = false) => { @@ -4734,7 +4689,7 @@ function baseCreateRenderer(options, createHydrationFns) { if (n1 == null) { mountStaticNode(n2, container, anchor, isSVG); } - else if ((process.env.NODE_ENV !== 'production')) { + else { patchStaticNode(n1, n2, container, isSVG); } break; @@ -4754,7 +4709,7 @@ function baseCreateRenderer(options, createHydrationFns) { else if (shapeFlag & 128 /* SUSPENSE */) { type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals); } - else if ((process.env.NODE_ENV !== 'production')) { + else { warn('Invalid VNode type:', type, `(${typeof type})`); } } @@ -4833,17 +4788,7 @@ function baseCreateRenderer(options, createHydrationFns) { let el; let vnodeHook; const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode; - if (!(process.env.NODE_ENV !== 'production') && - vnode.el && - hostCloneNode !== undefined && - patchFlag === -1 /* HOISTED */) { - // If a vnode has non-null el, it means it's being reused. - // Only static vnodes can be reused, so its mounted DOM nodes should be - // exactly the same, and we can simply do a clone here. - // only do this in production since cloned trees cannot be HMR updated. - el = vnode.el = hostCloneNode(vnode.el); - } - else { + { el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props); // mount children first, since some props may rely on child content // being already rendered, e.g. `