UNPKG

@honor-minigame/cli

Version:

honor minigame pack cli

1,206 lines (1,160 loc) 34.9 kB
global.GameGlobal = window.global = window global.wx = {} const defineReadOnlyProperty = (obj, name, value) => { try { Object.defineProperty(obj, name, { configurable: false, enumerable: true, get () { return value }, set (newValue) { if (newValue !== value) { if (!newValue || name === 'onShow' || name === 'onHide') { console.warn(`can not rewrite the property: ${name}`) return } console.warn(`rewrite the property: ${name}`) } value = newValue } }) } catch (e) { console.error(e) } } const defineReadOnlyPropertyContain = (obj, name, value) => { try { if (obj[name]) { return } Object.defineProperty(obj, name, { configurable: false, enumerable: true, get () { return value }, set (newValue) { if (newValue !== value) { console.warn(`rewrite the property: ${name}`) } value = newValue } }) } catch (e) { console.error(e) } } const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase() const isFunction = (obj) => typeOf(obj) === 'function' /** * wx回调错误 * @param {*} params */ const failCallback = (params = {}) => { if (params === null) params = {} isFunction(params.fail) && params.fail() isFunction(params.complete) && params.complete() } /** * wx回调成功 * @param {*} params */ const successCallback = (params = {}, data) => { if (params === null) params = {} isFunction(params.success) && params.success(data) isFunction(params.complete) && params.complete() } /** * 错误回调列表 */ const failList = [ 'openSystemBluetoothSetting', 'openAppAuthorizeSetting', 'updateWeChatApp', 'preDownloadSubpackage', 'setEnableDebug', 'restartMiniProgram', 'navigateToMiniProgram', 'updateShareMenu', 'startHandoff', 'showShareMenu', 'showShareImageMenu', 'getShareInfo', 'checkHandoffEnabled', 'authPrivateMessage', 'setMenuStyle', 'setStatusBarStyle', 'setWindowSize', 'setInnerAudioOption', 'getAvailableAudioSources', 'previewMedia', 'chooseMessageFile', 'saveFileToDisk' ] failList.forEach((prop) => { defineReadOnlyProperty(global.wx, prop, (params) => { console.warn(`-----wx----- 当前不支持该接口 ${prop},调用后会回调失败.`) return failCallback(params) }) }) /** * 空实现列表 */ const nullProp = () => {} const nullList = [ 'onUnhandledRejection', 'offUnhandledRejection', 'reportPerformance', // 'getRealtimeLogManager', // 'getLogManager', 'getUserCryptoManager', 'shareAppMessage', 'setMessageToFriendQuery', 'setHandoffQuery', 'onShareTimeline', 'onShareMessageToFriend', 'onShareAppMessage', 'onHandoff', 'onCopyUrl', 'onAddToFavorites', 'offShareTimeline', 'offShareAppMessage', 'offHandoff', 'offCopyUrl', 'offAddToFavorites', 'hideShareMenu', 'createUDPSocket', 'revokeBufferURL', 'createBufferURL', 'reportUserBehaviorBranchAnalytics', 'reportScene', 'reportMonitor', 'reportEvent', 'getExptInfoSync', 'setCursor', 'getRecorderManager', 'chooseMedia', 'createCamera', 'createVideoDecoder', 'updateVoIPChatMuteConfig', 'onVoIPChatStateChanged', 'onVoIPChatSpeakersChanged', 'onVoIPChatMembersChanged', 'onVoIPChatInterrupted', 'offVoIPChatStateChanged', 'offVoIPChatSpeakersChanged', 'offVoIPChatMembersChanged', 'offVoIPChatInterrupted', 'joinVoIPChat', 'exitVoIPChat', 'createUserInfoButton', 'checkSession', 'authorize', 'shareMessageToFriend', 'setUserCloudStorage', 'removeUserCloudStorage', 'onInteractiveStorageModified', 'offInteractiveStorageModified', 'modifyFriendInteractiveStorage', 'getUserInteractiveStorage', 'getUserCloudStorageKeys', 'getUserCloudStorage', 'getSharedCanvas', 'getPotentialFriendList', 'getGroupInfo', 'getGroupCloudStorage', 'getFriendCloudStorage', 'onMessage', 'getOpenDataContext', 'createFeedbackButton', 'openSetting', 'createOpenSettingButton', 'getGameClubData', 'createGameClubButton', 'openCustomerServiceConversation', 'getWeRunData', 'openCard', 'addCard', 'checkIsAddedToMyMiniProgram', 'reserveChannelsLive', 'openChannelsUserProfile', 'openChannelsLive', 'openChannelsEvent', 'openChannelsActivity', 'getChannelsLiveNoticeInfo', 'getChannelsLiveInfo', 'getGroupEnterInfo', 'requestSubscribeSystemMessage', 'requestSubscribeMessage', 'updateKeyboard', 'onKeyUp', 'onKeyDown', 'onKeyboardHeightChange', 'offKeyUp', 'offKeyDown', 'offKeyboardHeightChange', 'onMouseUp', 'onMouseMove', 'onMouseDown', 'offMouseUp', 'offMouseMove', 'offMouseDown', 'onWheel', 'offWheel', 'stopBeaconDiscovery', 'startBeaconDiscovery', 'onBeaconUpdate', 'onBeaconServiceChange', 'offBeaconUpdate', 'offBeaconServiceChange', 'getBeacons', 'onBLEPeripheralConnectionStateChanged', 'offBLEPeripheralConnectionStateChanged', 'createBLEPeripheralServer', 'writeBLECharacteristicValue', 'setBLEMTU', 'readBLECharacteristicValue', 'onBLEMTUChange', 'onBLEConnectionStateChange', 'onBLECharacteristicValueChange', 'offBLEMTUChange', 'offBLEConnectionStateChange', 'offBLECharacteristicValueChange', 'notifyBLECharacteristicValueChange', 'getBLEMTU', 'getBLEDeviceServices', 'getBLEDeviceRSSI', 'getBLEDeviceCharacteristics', 'createBLEConnection', 'closeBLEConnection', 'stopBluetoothDevicesDiscovery', 'startBluetoothDevicesDiscovery', 'openBluetoothAdapter', 'onBluetoothDeviceFound', 'onBluetoothAdapterStateChange', 'offBluetoothDeviceFound', 'offBluetoothAdapterStateChange', 'makeBluetoothPair', 'isBluetoothDevicePaired', 'getConnectedBluetoothDevices', 'getBluetoothDevices', 'getBluetoothAdapterState', 'closeBluetoothAdapter', 'getLocalIPAddress', 'onNetworkWeakChange', 'offNetworkWeakChange', 'onUserCaptureScreen', 'stopDeviceMotionListening', 'startDeviceMotionListening', 'onDeviceMotionChange', 'offDeviceMotionChange', 'setDeviceOrientation', 'onDeviceOrientationChange', 'offDeviceOrientationChange', 'onMemoryWarning', 'offMemoryWarning', 'stopGyroscope', 'startGyroscope', 'onGyroscopeChange', 'scanCode', 'getInferenceEnvInfo', 'createInferenceSession', 'stopFaceDetect', 'initFaceDetect', 'faceDetect', 'createWorker', 'operateGameRecorderVideo', 'createGameIcon', 'getGameRecorder', 'createGameRecorderShareButton', 'getGameServerManager', 'getExtConfigSync', 'getExtConfig', 'encode', 'decode', 'createImageData', 'offAccelerometerChange', 'addNativeDownloadTask', 'addToDesktop', 'addWeRunData', 'bindGroup', 'calRqt', 'captureScreen', 'checkGameLiveEnabled', 'checkIsSupportMidasFriendPayment', 'checkIsUserAdvisedToRest', 'cloud', 'createCpsAd', 'createGameComponent', 'createIncentiveVideoAd', 'createLivePlayer', 'createLivePusher', 'createOffScreenCanvas', 'createPath2D', 'createSharedArrayBuffer', // 'createSignal', 'createUserGameData', 'createVKReference', 'createVKSession', 'createWebView', 'dumpGameLivePanelUI', 'error', 'gameLoginReport', 'gameLogoutReport', 'getAd', 'getAdsSkipCardQuestInfo', 'getAdsSkipCardSharePresentQuota', 'getBox2D', 'getChannelsLiveReservation', 'getChannelsLiveState', 'getDebuggerMessager', 'getExptInfo', 'getGameLiveState', 'getGroupMsgTicket', 'getPrivacySetting', 'getRealNameVerifyMethod', 'getSavedFileInfo', 'getUserCurrentGameliveInfo', 'getUserGameLabel', 'getUserGameLiveDetails', 'getUserRecentGameLiveInfo', 'getWhatsNewSubscriptionsSetting', 'hideSplashScreen', 'isPointerLocked', 'isSDKError', 'isSystemError', 'isThirdError', 'isVKSupport', 'joinGroup', 'lanDebug', 'launchApp', 'markScene', 'navigateToUserCenter', 'notifyBLECharacteristicValueChanged', 'offGameLiveStateChange', 'offLaunch', 'offPointerLockChange', 'offPointerLockError', 'offShareInvitationToLiveRoom', 'offVerifyNotify', 'offVoIPVideoMembersChanged', 'onGameLiveStateChange', 'onLaunch', 'onNeedPrivacyAuthorization', 'onPointerLockChange', 'onPointerLockError', 'onShareInvitationToLiveRoom', 'onVerifyNotify', 'openChannelsLiveCollection', 'openCustomerServiceChat', 'openDocument', 'openPage', 'openPrivacyContract', 'openRedPacket', 'openTencentAccountCancelContract', 'openTencentBoardGameContract', 'openTencentChildrenGuideContract', 'openTencentGameContract', 'openTencentPrivacyContract', 'openUrl', 'operateWXData', 'parseXML', 'postMessage', 'previewPlayableView', 'protobuf', 'publishWeChatState', 'removeSavedFile', 'reportAnalytics', 'requestConsumeAdsSkipCard', 'requestMidasPaymentGameItem', 'requestPointerLock', 'requestSubscribeLiveActivity', 'requestSubscribeWhatsNew', 'requirePrivacyAuthorize', 'saveFile', 'sendBizRedPacket', 'sendRedPacket', 'serviceMarket', 'setTopBarText', 'shareInvitationToLiveRoom', 'showRedPackage', 'startCPUProfiling', 'startGameLive', 'stopCPUProfiling', 'subscribeVoIPVideoMembers', 'testApiCallTime', 'updateGameLivePanelMenu', 'updateUserGameData', 'uploadWeRunData', 'offLocalServiceDiscoveryStop', 'offLocalServiceFound', 'offLocalServiceLost', 'offLocalServiceResolveFail', 'onLocalServiceDiscoveryStop', 'onLocalServiceFound', 'onLocalServiceLost', 'onLocalServiceResolveFail', 'startLocalServiceDiscovery', 'stopLocalServiceDiscovery', 'createWebAudioContext', 'createMediaAudioPlayer' ] nullList.forEach((prop) => { defineReadOnlyProperty(global.wx, prop, (params) => { console.warn(`-----wx----- 当前不支持该接口 ${prop},调用后无响应.`) return nullProp(params) }) }) defineReadOnlyProperty(global.wx, 'createSignal', (params) => { console.warn(`-----wx----- 当前不支持该接口 createSignal,调用后返回null`) return null }) /** * qg实现列表 */ const qgList = [ 'getUpdateManager', 'onHide', 'offShow', 'offHide', 'onError', 'onAudioInterruptionEnd', 'onAudioInterruptionBegin', 'offError', 'offAudioInterruptionEnd', 'offAudioInterruptionBegin', 'triggerGC', 'getPerformance', 'showModal', 'showActionSheet', 'hideToast', 'hideLoading', 'getMenuButtonBoundingClientRect', 'clearStorage', 'clearStorageSync', 'getStorageInfoSync', 'getStorageInfo', 'setPreferredFramesPerSecond', 'cancelAnimationFrame', 'requestAnimationFrame', 'getTextLineHeight', 'createImage', 'createInnerAudioContext', 'saveImageToPhotosAlbum', 'previewImage', 'chooseImage', 'getLocation', 'showKeyboard', 'onKeyboardInput', 'onKeyboardConfirm', 'onKeyboardComplete', 'offKeyboardInput', 'offKeyboardConfirm', 'offKeyboardComplete', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel', 'offTouchStart', 'offTouchMove', 'offTouchEnd', 'offTouchCancel', 'stopAccelerometer', 'startAccelerometer', 'onAccelerometerChange', 'stopCompass', 'startCompass', 'onCompassChange', 'getNetworkType', 'setScreenBrightness', 'setKeepScreenOn', 'getScreenBrightness', 'vibrateShort', 'vibrateLong', 'onNetworkStatusChange', 'offNetworkStatusChange', 'createCanvas', 'env', 'getProvider', 'saveImageTemp', 'saveImageTempSync', 'getDeviceId', 'setTextBaseLine', 'exitApplication' ] qgList.forEach((prop) => { if (global.qg[prop]) { defineReadOnlyProperty(global.wx, prop, global.qg[prop]) } else { defineReadOnlyProperty(global.wx, prop, (params) => { console.warn(`-----wx----- 当前不支持该接口 ${prop},调用后无响应.`) return nullProp(params) }) } }) const info = global.qg.getSystemInfoSync() // 获取系统信息 const fs = global.qg.getFileSystemManager() /** * 使用联盟接口,将wxAPI适配成qgAPI */ const qgAllianceList = [ 'showToast', 'showLoading', 'onWindowResize', 'offWindowResize', 'request', 'downloadFile', 'uploadFile', 'setStorageSync', 'setStorage', 'removeStorageSync', 'removeStorage', 'getStorageSync', 'getStorage', 'loadFont', 'getFileSystemManager', 'getBatteryInfoSync', 'getBatteryInfo', 'setClipboardData', 'getClipboardData', 'createVideo' ] qgAllianceList.forEach((prop) => { if (global.qg[prop]) { defineReadOnlyProperty(global.wx, prop, global.qg[prop]) } else { console.error(`${prop} has not in qg`) } }) // 联盟socket兼容 defineReadOnlyPropertyContain(global.wx, 'connectSocket', (params = {}) => { const _ws = global.qg.connectSocket(params) global._ws = _ws return _ws }) defineReadOnlyPropertyContain(global.wx, 'sendSocketMessage', (params = {}) => { if (global.qg.sendSocketMessage) { global.qg.sendSocketMessage(params) } else if (global._ws) { global._ws.send(params) } }) defineReadOnlyPropertyContain(global.wx, 'onSocketOpen', (params) => { if (global.qg.onSocketOpen) { global.qg.onSocketOpen(params) } else if (global._ws) { global._ws.onOpen(params) } }) defineReadOnlyPropertyContain(global.wx, 'onSocketMessage', (params) => { if (global.qg.onSocketMessage) { global.qg.onSocketMessage(params) } else if (global._ws) { global._ws.onMessage(params) } }) defineReadOnlyPropertyContain(global.wx, 'onSocketError', (params) => { if (global.qg.onSocketError) { global.qg.onSocketError(params) } else if (global._ws) { global._ws.onError(params) } }) defineReadOnlyPropertyContain(global.wx, 'onSocketClose', (params) => { if (global.qg.onSocketClose) { global.qg.onSocketClose(params) } else if (global._ws) { global._ws.onClose(params) } }) defineReadOnlyPropertyContain(global.wx, 'closeSocket', (params = {}) => { if (global.qg.closeSocket) { global.qg.closeSocket(params) } else if (global._ws) { global._ws.close(params) } }) // code // 以下为非联盟引擎,则进行改造 defineReadOnlyPropertyContain(global.wx, 'onWindowResize', (params) => { if (global.qg.onWindowResize) { return global.qg.onWindowResize(params) } if (params === null) params = {} if (isFunction(params)) { global.qg.onWindowResize = params } }) defineReadOnlyPropertyContain(global.wx, 'offWindowResize', (params) => { if (global.qg.offWindowResize) { return global.qg.offWindowResize(params) } if (params === null) params = {} if (global.qg.onWindowResize && global.qg.onWindowResize === params) { global.qg.onWindowResize = nullProp } }) // 文件 读取路径可能不以/或internal:开头 // 缓存原始 writeFileSync 方法 const writeFileSyncInject = fs.writeFileSync defineReadOnlyPropertyContain(fs, 'writeFileSync', (filePath, data, encoding) => { if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) { encoding = 'binary' } return writeFileSyncInject.bind(fs)(filePath, data, encoding) }) // 解决encoding传入空的逻辑兼容 const readFileInject = fs.readFile defineReadOnlyPropertyContain(fs, 'readFile', (params = {}) => { const encoding = params.encoding if (!encoding) { params.encoding = 'binary' } return readFileInject.bind(fs)(params) }) // 系统 defineReadOnlyProperty(global.wx, 'getWindowInfo', (params = {}) => { const windowInfo = { pixelRatio: info.pixelRatio, screenWidth: info.screenWidth, screenHeight: info.screenHeight, windowWidth: info.screenWidth, windowHeight: info.screenHeight, statusBarHeight: info.statusBarHeight, safeArea: info.safeArea, screenTop: 0 } return windowInfo }) defineReadOnlyProperty(global.wx, 'getSystemSetting', (params = {}) => { const systemSetting = { bluetoothEnabled: false, locationEnabled: false, wifiEnabled: false, deviceOrientation: info.screenWidth > info.screenHeight ? 'landscape' : 'portrait' } return systemSetting }) defineReadOnlyProperty(global.wx, 'getSystemInfoSync', (params = {}) => { const systemInfo = global.qg.getSystemInfoSync() systemInfo.version = '8.0.29' // 微信版本号 systemInfo.platform = 'android' systemInfo.fontSizeSetting = 0 systemInfo.SDKVersion = '2.28.0' // 客户端基础库版本 systemInfo.benchmarkLevel = 30 systemInfo.albumAuthorized = false systemInfo.cameraAuthorized = true systemInfo.locationAuthorized = true systemInfo.microphoneAuthorized = true systemInfo.notificationAuthorized = false systemInfo.notificationAlertAuthorized = false systemInfo.notificationBadgeAuthorized = false systemInfo.notificationSoundAuthorized = false systemInfo.phoneCalendarAuthorized = false systemInfo.bluetoothEnabled = false systemInfo.locationEnabled = false systemInfo.wifiEnabled = false systemInfo.locationReducedAccuracy = false systemInfo.theme = 'light' systemInfo.pixelRatio = 1 systemInfo.host = { appId: systemInfo.miniGame && systemInfo.miniGame.package } systemInfo.enableDebug = false systemInfo.deviceOrientation = systemInfo.screenWidth > systemInfo.screenHeight ? 'landscape' : 'portrait' return systemInfo }) defineReadOnlyProperty(global.wx, 'getSystemInfoAsync', (params = {}) => { const suc = params.success params.success = (data) => { const systemInfo = data systemInfo.version = '8.0.29' // 微信版本号 systemInfo.platform = 'android' systemInfo.fontSizeSetting = 0 systemInfo.SDKVersion = '2.28.0' // 客户端基础库版本 systemInfo.benchmarkLevel = 30 systemInfo.albumAuthorized = false systemInfo.cameraAuthorized = true systemInfo.locationAuthorized = true systemInfo.microphoneAuthorized = true systemInfo.notificationAuthorized = false systemInfo.notificationAlertAuthorized = false systemInfo.notificationBadgeAuthorized = false systemInfo.notificationSoundAuthorized = false systemInfo.phoneCalendarAuthorized = false systemInfo.bluetoothEnabled = false systemInfo.locationEnabled = false systemInfo.wifiEnabled = false systemInfo.locationReducedAccuracy = false systemInfo.theme = 'light' systemInfo.pixelRatio = 1 systemInfo.host = { appId: systemInfo.miniGame && systemInfo.miniGame.package } systemInfo.enableDebug = false systemInfo.deviceOrientation = systemInfo.screenWidth > systemInfo.screenHeight ? 'landscape' : 'portrait' suc(systemInfo) } return global.qg.getSystemInfo(params) }) defineReadOnlyProperty(global.wx, 'getSystemInfo', (params = {}) => { const suc = params.success if (isFunction(suc)) { const systemInfo = global.wx.getSystemInfoSync() suc(systemInfo) } }) defineReadOnlyProperty(global.wx, 'getDeviceInfo', (params = {}) => { const deviceInfo = { abi: '', deviceAbi: '', benchmarkLevel: -1, brand: info.brand, model: info.model, system: info.system, platform: 'android', CPUType: '', memorySize: '' } console.warn('-----wx----- qg未有getDeviceInfo接口,返回数据为构造的数据,建议换其他方式') return deviceInfo }) defineReadOnlyProperty(global.wx, 'getAppBaseInfo', (params = {}) => { const appBaseInfo = { SDKVersion: '2.28.0', enableDebug: false, host: { appId: info.miniGame && info.miniGame.package }, language: 'zh', version: '8.0.29', theme: 'light' } console.warn('-----wx----- qg未有getAppBaseInfo接口,返回数据为构造的数据,建议换其他方式') return appBaseInfo }) defineReadOnlyProperty(global.wx, 'getAppAuthorizeSetting', (params = {}) => { const appBaseInfo = { albumAuthorized: false, bluetoothAuthorized: false, cameraAuthorized: true, locationAuthorized: true, locationReducedAccuracy: false, microphoneAuthorized: true, notificationAuthorized: false, notificationAlertAuthorized: false, notificationBadgeAuthorized: false, notificationSoundAuthorized: false, phoneCalendarAuthorized: false } console.warn('-----wx----- qg未有 getAppAuthorizeSetting 接口,返回数据为构造的数据,建议换其他方式') return appBaseInfo }) // 生命周期 defineReadOnlyProperty(global.wx, 'getLaunchOptionsSync', (params = {}) => { const launchO = global.qg.getLaunchOptionsSync() const launchOptions = { scene: 1001, query: launchO.query, shareTicket: '', referrerInfo: launchO.referrerInfo, chatType: 1, apiCategory: 'default' } const mergedObj = Object.assign({}, launchO, launchOptions) if (mergedObj.query && !mergedObj.query.channel) { mergedObj.query.channel = mergedObj.query.internal && mergedObj.query.internal.channel ? mergedObj.query.internal.channel : '' } console.warn('-----wx----- vivo小游戏getLaunchOptionsSync与微信不一致, getLaunchOptionsSync:', mergedObj) return mergedObj }) defineReadOnlyProperty(global.wx, 'getEnterOptionsSync', (params = {}) => { const launchO = global.qg.getEnterOptionsSync ? global.qg.getEnterOptionsSync() : global.qg.getLaunchOptionsSync() const launchOptions = { scene: 1001, query: launchO.query, shareTicket: '', referrerInfo: launchO.referrerInfo, chatType: 1, apiCategory: 'default' } const mergedObj = Object.assign({}, launchO, launchOptions) if (mergedObj.query && !mergedObj.query.channel) { mergedObj.query.channel = mergedObj.query.internal && mergedObj.query.internal.channel ? mergedObj.query.internal.channel : '' } console.warn('-----wx----- vivo小游戏getEnterOptionsSync与微信不一致, getEnterOptionsSync:', mergedObj) return mergedObj }) defineReadOnlyProperty(global.wx, 'onShow', (params) => { var showf = function () { if (params === null) params = {} if (isFunction(params)) { params(global.wx.getEnterOptionsSync()) } } setTimeout(showf, 0) return global.qg.onShow(showf) }) // 分包main进行特殊处理 defineReadOnlyProperty(global.wx, 'loadSubpackage', (params = {}) => { const name = params.name if (params.name === 'main' && global._main_sub_name_) { params.name = global._main_sub_name_ console.warn(`-----wx----- loadSubpackage name: ${name}, realname:${params.name}`) } try { if (!global.qg.manifest) { const manifest = fs.readFileSync('manifest.json', 'utf8') global.qg.manifest = JSON.parse(manifest) console.warn('-----wx----- manifest:', global.qg.manifest) } if (global.qg.manifest && global.qg.manifest.subpackages) { const subpackages = global.qg.manifest.subpackages for (let i = 0; i < subpackages.length; i++) { if (subpackages[i].name === params.name) { break } if (subpackages[i].root === params.name) { params.name = subpackages[i].name } if (!params.name.endsWith('/') && subpackages[i].root === (params.name + '/')) { params.name = subpackages[i].name } } } } catch (err) {} console.warn(`-----wx----- loadSubpackage name: ${name} loadName: ${params.name}`) var loadSubTask = global.qg.loadSubpackage(params) loadSubTask.await = () => {} return loadSubTask }) // 跳转 defineReadOnlyProperty(global.wx, 'exitMiniProgram', (params) => { console.warn( '-----wx----- 微信小游戏的exitMiniProgram和vivo小游戏的exitApplication稍有区别,请确认是否需要手动修改' ) return global.qg.exitApplication() }) // 以下需要特殊适配的接口 // 虚拟支付 defineReadOnlyProperty(global.wx, 'requestMidasPayment', (params = {}) => { console.error('-----wx----- 请使用vivo平台的支付接口进行适配') }) defineReadOnlyProperty( global.wx, 'requestMidasFriendPayment', global.wx.requestMidasPayment ) // 地理位置 defineReadOnlyProperty(global.wx, 'getFuzzyLocation', global.qg.getLocation) global.wx.hideKeyboard = function (e) { global.qg.hideKeyboard() e && (typeof e.success === 'function' && e.success({ errMsg: 'hideKeyboard:ok' })) e && (typeof e.complete === 'function' && e.complete({ errMsg: 'hideKeyboard:ok' })) } defineReadOnlyProperty(global.wx, 'getAccountInfoSync', (params = {}) => { const accountInfo = { miniProgram: { appId: 'wxa89a52c508f18788', envVersion: 'release', version: '' } } return accountInfo }) defineReadOnlyProperty(global.wx, 'getLogManager', (params = {}) => { const log = {} log.info = () => { } log.debug = () => { } log.log = () => { } log.warn = () => { } log.error = () => { } return log }) defineReadOnlyProperty(global.wx, 'getRealtimeLogManager', (params = {}) => { const log = console log.setFilterMsg = () => { } log.addFilterMsg = () => { } return log }) // 用户信息 defineReadOnlyProperty(global.wx, 'getUserInfo', (params = {}) => { if (!global.qg.getUserInfo()) { return } global.qg.getUserInfo().then( (res) => { if (res.data) { console.log('-----wx----- 当前用户信息: ' + JSON.stringify(res.data)) const wxUser = { userInfo: { nickName: res.data.nickName, avatarUrl: res.data.smallAvatar, gender: res.data.gender, language: 'zh_CN' }, rawData: res.data, signature: '', encryptedData: '', iv: '', cloudID: '' } successCallback(params, wxUser) } }, (err) => { console.log('-----wx----- 获取用户信息失败' + JSON.stringify(err)) } ) }) defineReadOnlyProperty(global.wx, 'login', (params = {}) => { console.error('-----wx----- 需要接入vivo平台的login接口') successCallback(params, { code: '0b18Dwml2rLD8b4XBTol26l5tu28DwmP', errMsg: 'login:ok' }) }) // 设置 defineReadOnlyProperty(global.wx, 'getSetting', (params = {}) => { successCallback(params, { authSetting: { 'scope.userInfo': true, 'scope.userLocation': true, 'scope.werun': false, 'scope.writePhotosAlbum': true, 'scope.WxFriendInteraction': false }, subscriptionsSetting: { mainSwitch: false }, miniprogramAuthSetting: { 'scope.userInfo': true, 'scope.userLocation': true, 'scope.werun': false, 'scope.writePhotosAlbum': true, 'scope.WxFriendInteraction': false } }) }) // 广告 defineReadOnlyProperty(global.wx, 'createGamePortal', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的gamePortal,调用时会自动获取,与盒子九宫格广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.gamePortal) { params.adUnitId = global.qg.manifest.ad_config.gamePortal } return global.qg.createBoxPortalAd(params) }) defineReadOnlyProperty(global.wx, 'createGameBanner', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的gridAd,调用时会自动获取,与盒子Banner广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.gridAd) { params.adUnitId = global.qg.manifest.ad_config.gridAd } return global.qg.createBoxBannerAd(params) }) defineReadOnlyProperty(global.wx, 'createGridAd', global.wx.createGameBanner) defineReadOnlyProperty(global.wx, 'createRewardedVideoAd', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的rewardedVideoAd,调用时会自动获取,与激励视频广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.rewardedVideoAd) { params.adUnitId = global.qg.manifest.ad_config.rewardedVideoAd } return global.qg.createRewardedVideoAd(params) }) defineReadOnlyProperty(global.wx, 'createInterstitialAd', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的interstitialAd,调用时会自动获取,与插屏广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.interstitialAd) { params.adUnitId = global.qg.manifest.ad_config.interstitialAd } return global.qg.createInterstitialAd(params) }) defineReadOnlyProperty(global.wx, 'createCustomAd', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的customAd,调用时会自动获取,与模板广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.customAd) { params.adUnitId = global.qg.manifest.ad_config.customAd } return global.qg.createCustomAd(params) }) defineReadOnlyProperty(global.wx, 'createBannerAd', (params = {}) => { console.warn('-----wx----- 广告位ID配置到manifest的bannerAd,调用时会自动获取,与bannerAd广告一致') if (global.qg.manifest && global.qg.manifest.ad_config && global.qg.manifest.ad_config.bannerAd) { params.adUnitId = global.qg.manifest.ad_config.bannerAd } return global.qg.createBannerAd(params) }) // 微信的WebAssembly实现,传入路径,解析文件进行编译 if (global.WebAssembly) { // 原始的 WebAssembly 对象 const originalWebAssembly = global.WebAssembly global.WXWebAssembly = new Proxy(global.WebAssembly, { construct (target, args) { if (target === originalWebAssembly.Instance) { const path = args[0] console.log('-----wx----- path:', path) if (global.qg && global.qg.setWasmTaskCompile) { global.qg.setWasmTaskCompile(true) } try { if (path.indexOf('.br') !== -1 && global.fs && global.fs.readCompressedFileSync) { const data = global.fs.readCompressedFileSync({ filePath: path, compressionAlgorithm: 'br' }) args[0] = data.data ? data.data : data console.warn(`WXWebAssembly readCompressedFileSync ${path} read data: `, args[0]) } else if (global.fs && global.fs.readFileSync) { const data = global.fs.readFileSync(path) args[0] = data console.warn(`WXWebAssembly readFileSync ${path} read data: `, args[0]) } } catch (err) { console.error(`WXWebAssembly ${path} read error. `, err) } const result = Reflect.construct(target, args) return Promise.resolve(result).then(x => { if (global.qg && global.qg.setWasmTaskCompile) { global.qg.setWasmTaskCompile(false) } console.log('wasm then...') return x }).catch(e => { if (global.qg && global.qg.setWasmTaskCompile) { global.qg.setWasmTaskCompile(false) } console.log('wasm catch...') throw e }) } // 如果不是创建 Instance,直接使用原始的构造函数 return Reflect.construct(target, args) }, get: (target, name) => { const origMethod = target[name] if (name !== 'instantiate' && name !== 'Instance') { return origMethod } return function (...args) { const path = args[0] console.log('-----wx----- path:', path) if (window.qg && window.qg.setWasmTaskCompile) { window.qg.setWasmTaskCompile(true) } try { if (path.indexOf('.br') !== -1 && fs.readCompressedFileSync) { const data = fs.readCompressedFileSync({ filePath: path, compressionAlgorithm: 'br' }) args[0] = data.data ? data.data : data console.warn(`WXWebAssembly readCompressedFileSync ${path} read data: `, args[0]) } else { const data = fs.readFileSync(path) args[0] = data console.warn(`WXWebAssembly readFileSync ${path} read data: `, args[0]) } } catch (err) { console.error(`WXWebAssembly ${path} read error. `, err) } const result = origMethod.apply(this, args) return result.then(x => { if (window.qg && window.qg.setWasmTaskCompile) { window.qg.setWasmTaskCompile(false) } console.log('wasm then...') return x }).catch(e => { if (window.qg && window.qg.setWasmTaskCompile) { window.qg.setWasmTaskCompile(false) } console.log('wasm then...') throw e }) } } }) } else if (global.qg && global.qg.setWasmTaskCompile && global.qg.getProvider() === 'OPPO') { // OPPO必须一直开着才会有wasm global.qg.setWasmTaskCompile(true) } defineReadOnlyProperty(window, 'WXWebAssembly', global.WXWebAssembly) // 微信环境变量适配 window.__wxConfig = { envVersion: 'release' } /** * 遗留的qgkey进行绑定 */ var qgKeys = Object.keys(global.qg) qgKeys.forEach((prop) => { var wxKeys = Object.keys(global.wx) if (wxKeys.indexOf(prop) === -1 && !prop.includes('requirePlugin')) { // console.warn(`qg to wx : ${prop}`) defineReadOnlyProperty(global.wx, prop, global.qg[prop]) } }) // 针对Object.assign()方法进行重写,防止有报错 global.assign = Object.assign function assign (target, ...sources) { try { return global.assign(target, ...sources) } catch (err) { } } Object.assign = assign try { window.qg.reportGameInfo && window.qg.reportGameInfo(JSON.stringify({ wxEngine: '2' })) } catch (err) { } if (!global.webpack_use_moudle) { try { // 解析本地webpack配置,在webpackEmptyContext中支持动态编译js var res = fs.accessSync('webpack_use_moudle.json') if (res) { console.log('-----wx----- webpack_use_moudle.json 文件存在,将绑定到global上用于动态加载.') const result = fs.readFileSync('webpack_use_moudle.json', 'utf8') try { global.webpack_use_moudle = JSON.parse(result) } catch (err) { } } } catch (err) { } } // 适配解决Unity转换问题 try { const stringObj = String.prototype const descriptor = Object.getOwnPropertyDescriptor(stringObj, 'replaceAll') if (descriptor && descriptor.writable && descriptor.configurable) { Object.defineProperty(stringObj, 'replaceAll', { value: function (search, replacement) { return this.split(search).join(replacement) }, writable: true, configurable: true, enumerable: false }) } if (!global.qg.manifest) { if (global.qg.getManifestInfoSync) { global.qg.manifest = global.qg.getManifestInfoSync() } else { // 异步加载manifest fs.readFile({ filePath: 'manifest.json', encoding: 'utf8', success: function (data) { try { console.log('-----wx----- manifest解析到global中') global.qg.manifest = JSON.parse(data.data) } catch (err) { } } }) } } } catch (err) { }