import type { Reporter } from '../Reporter'; import type { EnvContext, LinkedData } from '../types'; import { Adapter } from '../Adapter'; import { stringifyQuery } from '../utils'; declare let wx: any; export class MiniProgramAdapter, R extends Reporter> extends Adapter { storage = { supportSync: true, setItem(key: string, value: any) { if (!wx?.setStorageSync) return; if (value === undefined || value === null) return; try { wx.setStorageSync(key, value); } catch (e) { // 静默处理 } }, async getItem(key: string, defaultValue?: string) { if (!wx?.getStorageSync) return defaultValue; try { const value = wx.getStorageSync(key); if (value === undefined || value === null) return defaultValue; return value; } catch (e) { // TODO: 报错 console.error('[Merlin] getItem failed', e); return defaultValue; } }, removeItem(key: string) { if (!wx?.removeStorageSync) return; wx.removeStorageSync(key); }, }; init(reporter: R) { super.init(reporter); if (!wx) { console.error('[Merlin] MiniProgramAdapter can only be used in Weixin MiniProgram environment (with wx defined)'); return; } } settle() {} updateScopeInfo() { if (!this.reporter || !wx) return; const info = wx.getSystemInfoSync(); this.updateScopeInfoField('devicePixelRatio', info.pixelRatio); } readLinkedData(_query?: Record) { if (!this.reporter || !wx) return; } get linkedData(): LinkedData { return { contextId: this.reporter?.scopeInfo.contextId, entranceId: this.reporter?.scopeInfo.entranceId, subEntranceid: this.reporter?.scopeInfo.entranceInfo?.subEntranceid, reddotId: this.reporter?.scopeInfo.redDotInfo?.id, }; } serializeLinkedData(extra?: LinkedData): string { return stringifyQuery({ ...this.linkedData, ...extra }); } httpPost( _url: string, _data: string, _options: { contentType: string; }, ): void {} protected getEnvInfo(): EnvContext { if (!wx) return {}; const info = wx.getSystemInfoSync(); return { // device: info.platform, deviceBrand: info.brand, deviceModel: info.model, osName: info.platform, osVersion: `${info.system}`, lang: info.language, appVersion: info.version, }; } }