ensureUniConfig.js
8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
* iOS 高版本切回/热重载时,运行时可能未重新注入 __uniConfig,导致白屏。
*/
const STORAGE_KEY = 'ZY_UNI_CONFIG_BACKUP'
const BG_AT_KEY = 'ZY_BG_AT'
const WAS_BG_KEY = 'ZY_WAS_BACKGROUND'
const PROCESS_START_KEY = 'ZY_PROCESS_START'
const LOGIN_URL = '/pages/common/login'
const BG_REINIT_WINDOW_MS = 120000
let _runtimeBroken = false
let _recoverRequired = false
let _isNewProcess = false
let _recoverPending = false
let _recoverTimer = null
let _lastRecoverAt = 0
let _consoleHookInstalled = false
function persistConfig(cfg) {
try {
const json = JSON.stringify(cfg)
uni.setStorageSync(STORAGE_KEY, json)
if (typeof plus !== 'undefined' && plus.storage) {
plus.storage.setItem(STORAGE_KEY, json)
}
} catch (e) {
console.warn('[ensureUniConfig] persist failed', e)
}
}
function loadConfig() {
try {
let json = uni.getStorageSync(STORAGE_KEY)
if (!json && typeof plus !== 'undefined' && plus.storage) {
json = plus.storage.getItem(STORAGE_KEY)
}
return json ? JSON.parse(json) : null
} catch (e) {
return null
}
}
function restoreGlobal(cfg) {
globalThis.__uniConfig = cfg
if (typeof global !== 'undefined') {
global.__uniConfig = cfg
}
try {
;(0, eval)('var __uniConfig = globalThis.__uniConfig')
} catch (e) {
try {
Function('c', 'globalThis.__uniConfig = c')(cfg)
} catch (e2) {}
}
}
function clearBackgroundMarks() {
try {
uni.removeStorageSync(BG_AT_KEY)
uni.removeStorageSync(WAS_BG_KEY)
} catch (e) {}
}
function clearRecoverState() {
_runtimeBroken = false
_recoverRequired = false
}
function getProcessStartTime() {
try {
if (typeof plus !== 'undefined' && plus.runtime) {
const t = plus.runtime.launchLoadedTime
if (typeof t === 'number' && t > 0) return t
}
} catch (e) {}
return 0
}
function syncProcessStartupFlags() {
try {
const start = getProcessStartTime()
if (!start) return
const prev = Number(uni.getStorageSync(PROCESS_START_KEY))
if (prev && prev !== start) {
uni.setStorageSync(PROCESS_START_KEY, String(start))
clearBackgroundMarks()
clearRecoverState()
_isNewProcess = true
console.warn('[ensureUniConfig] new process, cleared BG marks')
return
}
if (!prev) {
uni.setStorageSync(PROCESS_START_KEY, String(start))
_isNewProcess = true
clearBackgroundMarks()
clearRecoverState()
}
} catch (e) {}
}
function isRecentBackground() {
try {
const bgAt = Number(uni.getStorageSync(BG_AT_KEY))
return bgAt > 0 && Date.now() - bgAt < BG_REINIT_WINDOW_MS
} catch (e) {
return false
}
}
export function markUniRuntimeBroken(reason) {
_runtimeBroken = true
_recoverRequired = true
if (reason) {
console.warn('[ensureUniConfig] runtime broken:', reason)
}
}
export function resetRuntimeHealthyIfConfigOk() {
if (_recoverRequired) return
try {
if (typeof __uniConfig !== 'undefined' && __uniConfig) {
_runtimeBroken = false
}
} catch (e) {}
}
export function isUniRuntimeBroken() {
return _recoverRequired || _runtimeBroken
}
export function isUniRuntimeBrokenMessage(msg) {
if (!msg) return false
const text = typeof msg === 'string' ? msg : msg.message || String(msg)
return /__uniConfig|addVData|r\[t\] is not a function/i.test(text)
}
export function isUniConfigMissing() {
try {
return typeof __uniConfig === 'undefined' || !__uniConfig
} catch (e) {
return true
}
}
export function markAppBackground() {
try {
uni.setStorageSync(BG_AT_KEY, String(Date.now()))
uni.setStorageSync(WAS_BG_KEY, '1')
} catch (e) {}
}
export function onAppColdLaunch() {
if (_isNewProcess) {
clearBackgroundMarks()
clearRecoverState()
_isNewProcess = false
}
try {
if (typeof __uniConfig !== 'undefined' && __uniConfig) {
persistConfig(__uniConfig)
}
} catch (e) {}
}
export function detectResumeAfterBackground() {
if (_recoverRequired) return true
try {
if (isRecentBackground() && isUniConfigMissing()) {
markUniRuntimeBroken('resume: __uniConfig missing')
return true
}
} catch (e) {}
return false
}
export function clearAppBackgroundMark() {
if (_recoverRequired) return
clearBackgroundMarks()
}
export function detectMainJsReEntry() {
if (!isRecentBackground()) return false
try {
const app = getApp()
if (app && app.globalData) {
markUniRuntimeBroken('main.js re-entry while App alive')
return true
}
} catch (e) {}
markUniRuntimeBroken('main.js re-init after background')
return true
}
export function ensureUniConfig() {
try {
if (typeof __uniConfig !== 'undefined' && __uniConfig) {
persistConfig(__uniConfig)
return true
}
} catch (e) {}
const cfg = loadConfig()
if (!cfg) {
return false
}
restoreGlobal(cfg)
if (typeof __uniConfig !== 'undefined') {
// 仅切后台恢复场景下,从 backup 恢复才视为 runtime 损坏;冷启动勿误判
if (isRecentBackground()) {
markUniRuntimeBroken('__uniConfig restored from backup')
}
return true
}
return false
}
export function backupUniConfigIfPresent() {
try {
if (typeof __uniConfig !== 'undefined' && __uniConfig) {
persistConfig(__uniConfig)
}
} catch (e) {}
}
function clearLoginState() {
try {
uni.$storage?.rm?.('userInfo', true)
} catch (e) {}
try {
uni.removeStorageSync('userInfo')
} catch (e) {}
}
function restartAppFallback() {
try {
if (typeof plus !== 'undefined' && plus.runtime && typeof plus.runtime.restart === 'function') {
plus.runtime.restart()
return true
}
} catch (e) {}
return false
}
export function recoverToLoginIfBroken(force = false) {
if (!force && !_recoverRequired && !isUniRuntimeBroken()) return
const now = Date.now()
if (_recoverPending && now - _lastRecoverAt < 800) return
_recoverPending = true
_lastRecoverAt = now
const done = () => {
_recoverPending = false
}
try {
const pages = getCurrentPages()
const route = pages.length ? pages[pages.length - 1].route : ''
if (route === 'pages/common/login') {
clearRecoverState()
done()
return
}
} catch (e) {}
clearLoginState()
console.warn('[ensureUniConfig] reLaunch -> login')
try {
uni.reLaunch({
url: LOGIN_URL,
success: () => {
clearRecoverState()
done()
},
fail: () => {
if (!restartAppFallback()) done()
},
complete: () => {
setTimeout(done, 3000)
}
})
} catch (e) {
if (!restartAppFallback()) done()
}
}
export function scheduleRecoverToLogin() {
if (!_recoverRequired && !isUniRuntimeBroken()) return
if (_recoverTimer) return
console.warn('[ensureUniConfig] schedule recover -> login')
const delays = [0, 50, 150, 400, 800, 1500, 3000, 5000]
delays.forEach((ms) => {
setTimeout(() => recoverToLoginIfBroken(true), ms)
})
_recoverTimer = true
setTimeout(() => {
_recoverTimer = null
}, 5500)
}
export function handleUniRuntimeError(msg) {
if (!isUniRuntimeBrokenMessage(msg)) return false
markUniRuntimeBroken(msg)
scheduleRecoverToLogin()
return true
}
function stringifyConsoleArgs(args) {
try {
return Array.prototype.map
.call(args, (a) => (typeof a === 'string' ? a : a && a.message ? a.message : JSON.stringify(a)))
.join(' ')
} catch (e) {
try {
return String(args && args[0])
} catch (e2) {
return ''
}
}
}
export function installConsoleProbeHooks() {
if (_consoleHookInstalled) return
_consoleHookInstalled = true
if (typeof console === 'undefined') return
;['error', 'warn'].forEach((level) => {
const prev = console[level]
if (typeof prev !== 'function') return
console[level] = function () {
try {
handleUniRuntimeError(stringifyConsoleArgs(arguments))
} catch (e) {}
return prev.apply(this, arguments)
}
})
}
export function installGlobalErrorHooks() {
if (typeof window === 'undefined') return
const prevOnError = window.onerror
window.onerror = function (message, source, lineno, colno, error) {
handleUniRuntimeError(error || message)
if (typeof prevOnError === 'function') {
return prevOnError.apply(this, arguments)
}
return false
}
window.addEventListener('unhandledrejection', (event) => {
handleUniRuntimeError(event.reason)
})
}
syncProcessStartupFlags()
detectMainJsReEntry()
ensureUniConfig()
installConsoleProbeHooks()
installGlobalErrorHooks()
console.warn('[boot] ensureUniConfig init done, recoverRequired=', _recoverRequired)