Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
266 lines (249 loc) · 10.3 KB
/
Copy pathmain.ts
File metadata and controls
266 lines (249 loc) · 10.3 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
import './styles/base-layer.css';
import './styles/happy-theme.css';
import 'maplibre-gl/dist/maplibre-gl.css';
import * as Sentry from '@sentry/browser';
import { inject } from '@vercel/analytics';
import { App } from './App';
const sentryDsn = import.meta.env.VITE_SENTRY_DSN?.trim();
// Initialize Sentry error tracking (early as possible)
Sentry.init({
dsn: sentryDsn || undefined,
release: `worldmonitor@${__APP_VERSION__}`,
environment: location.hostname === 'worldmonitor.app' ? 'production'
: location.hostname.includes('vercel.app') ? 'preview'
: 'development',
enabled: Boolean(sentryDsn) && !location.hostname.startsWith('localhost') && !('__TAURI_INTERNALS__' in window),
sendDefaultPii: true,
tracesSampleRate: 0.1,
ignoreErrors: [
'Invalid WebGL2RenderingContext',
'WebGL context lost',
/imageManager/,
/ResizeObserver loop/,
/NotAllowedError/,
/InvalidAccessError/,
/importScripts/,
/^TypeError: Load failed( \(.*\))?$/,
/^TypeError: Failed to fetch( \(.*\))?$/,
/^TypeError: cancelled$/,
/^TypeError: NetworkError/,
/runtime\.sendMessage\(\)/,
/Java object is gone/,
/^Object captured as promise rejection with keys:/,
/Unable to load image/,
/Non-Error promise rejection captured with value:/,
/Connection to Indexed Database server lost/,
/webkit\.messageHandlers/,
/(?:unsafe-eval.*Content Security Policy|Content Security Policy.*unsafe-eval)/,
/Fullscreen request denied/,
/requestFullscreen/,
/webkitEnterFullscreen/,
/vc_text_indicators_context/,
/Program failed to link/,
/too much recursion/,
/zaloJSV2/,
/Java bridge method invocation error/,
/Could not compile fragment shader/,
/can't redefine non-configurable property/,
/Can.t find variable: (CONFIG|currentInset|NP)/,
/invalid origin/,
/\.data\.split is not a function/,
/signal is aborted without reason/,
/Failed to fetch dynamically imported module/,
/Importing a module script failed/,
/contentWindow\.postMessage/,
/Could not compile vertex shader/,
/objectStoreNames/,
/Unexpected identifier 'https'/,
/Can't find variable: _0x/,
/WKWebView was deallocated/,
/Unexpected end of input/,
/window\.android\.\w+ is not a function/,
/Attempted to assign to readonly property/,
/Cannot assign to read only property/,
/FetchEvent\.respondWith/,
/e\.toLowerCase is not a function/,
/\.trim is not a function/,
/\.(indexOf|findIndex) is not a function/,
/QuotaExceededError/,
/^TypeError: 已取消$/,
/Maximum call stack size exceeded/,
/^fetchError: Network request failed$/,
/window\.ethereum/,
/^SyntaxError: Unexpected token/,
/^Operation timed out\.?$/,
/setting 'luma'/,
/ML request .* timed out/,
/^Element not found$/,
/(?:AbortError: )?The operation was aborted\.?\s*$/,
/Unexpected end of script/,
/error loading dynamically imported module/,
/Style is not done loading/,
/Event `CustomEvent`.*captured as promise rejection/,
/getProgramInfoLog/,
/__firefox__/,
/ifameElement\.contentDocument/,
/Invalid video id/,
/Fetch is aborted/,
/Stylesheet append timeout/,
/Worker is not a constructor/,
/_pcmBridgeCallbackHandler/,
/UCShellJava/,
/Cannot define multiple custom elements/,
/maxTextureDimension2D/,
/Container app not found/,
/this\.St\.unref/,
/Invalid or unexpected token/,
/evaluating 'elemFound\.value'/,
/[Cc]an(?:'t|not) access (?:'\w+'|lexical declaration '\w+') before initialization/,
/^Uint8Array$/,
/createObjectStore/,
/The database connection is closing/,
/shortcut icon/,
/Attempting to change value of a readonly property/,
/reading 'nodeType'/,
/feature named .pageContext. was not found/,
/a2z\.onStatusUpdate/,
/Attempting to run\(\), but is already running/,
/this\.player\.destroy is not a function/,
/isReCreate is not defined/,
/reading 'style'.*HTMLImageElement/,
/can't access property "write", \w+ is undefined/,
/AbortError: The user aborted a request/,
/\w+ is not a function.*\/uv\/service\//,
/__isInQueue__/,
],
beforeSend(event) {
const msg = event.exception?.values?.[0]?.value ?? '';
if (msg.length <= 3 && /^[a-zA-Z_$]+$/.test(msg)) return null;
const frames = event.exception?.values?.[0]?.stacktrace?.frames ?? [];
// Suppress maplibre internal null-access crashes (light, placement) only when stack is in map chunk
if (/this\.style\._layers|reading '_layers'|this\.light is null|can't access property "(id|type|setFilter)", \w+ is (null|undefined)|Cannot read properties of null \(reading '(id|type|setFilter|_layers)'\)|null is not an object \(evaluating '\w{1,3}\.(id|style)|^\w{1,2} is null$/.test(msg)) {
if (frames.some(f => /\/(map|maplibre|deck-stack)-[A-Za-z0-9-]+\.js/.test(f.filename ?? ''))) return null;
}
// Suppress any TypeError that happens entirely within maplibre or deck.gl internals
if (/^TypeError:/.test(msg) && frames.length > 0) {
const nonSentryFrames = frames.filter(f => !/\/sentry-[A-Za-z0-9-]+\.js/.test(f.filename ?? ''));
if (nonSentryFrames.length > 0 && nonSentryFrames.every(f => /\/(map|maplibre|deck-stack)-[A-Za-z0-9-]+\.js/.test(f.filename ?? ''))) return null;
}
// Suppress errors originating entirely from blob: URLs (browser extensions)
if (frames.length > 0 && frames.every(f => /^blob:/.test(f.filename ?? ''))) return null;
// Suppress YouTube IFrame widget API internal errors
if (frames.some(f => /www-widgetapi\.js/.test(f.filename ?? ''))) return null;
// Suppress Sentry SDK internal crashes (logs.js)
if (frames.some(f => /\/ingest\/static\/logs\.js/.test(f.filename ?? ''))) return null;
return event;
},
});
// Suppress NotAllowedError from YouTube IFrame API's internal play() — browser autoplay policy,
// not actionable. The YT IFrame API doesn't expose the play() promise so it leaks as unhandled.
window.addEventListener('unhandledrejection', (e) => {
if (e.reason?.name === 'NotAllowedError') e.preventDefault();
});
import { debugGetCells, getCellCount } from '@/services/geo-convergence';
import { initMetaTags } from '@/services/meta-tags';
import { installRuntimeFetchPatch, installWebApiRedirect } from '@/services/runtime';
import { loadDesktopSecrets } from '@/services/runtime-config';
import { initAnalytics, trackApiKeysSnapshot } from '@/services/analytics';
import { applyStoredTheme } from '@/utils/theme-manager';
import { SITE_VARIANT } from '@/config/variant';
import { clearChunkReloadGuard, installChunkReloadGuard } from '@/bootstrap/chunk-reload';
// Auto-reload on stale chunk 404s after deployment (Vite fires this for modulepreload failures).
const chunkReloadStorageKey = installChunkReloadGuard(__APP_VERSION__);
// Initialize Vercel Analytics
inject();
// Initialize PostHog product analytics
void initAnalytics();
// Initialize dynamic meta tags for sharing
initMetaTags();
// In desktop mode, route /api/* calls to the local Tauri sidecar backend.
installRuntimeFetchPatch();
// In web production, route RPC calls through api.worldmonitor.app (Cloudflare edge).
installWebApiRedirect();
loadDesktopSecrets().then(async () => {
await initAnalytics();
trackApiKeysSnapshot();
}).catch(() => {});
// Apply stored theme preference before app initialization (safety net for inline script)
applyStoredTheme();
// Set data-variant on <html> so CSS theme overrides activate (inline script handles hostname/localStorage,
// this catches the VITE_VARIANT env var path used during local dev and Vercel deployments)
if (SITE_VARIANT && SITE_VARIANT !== 'full') {
document.documentElement.dataset.variant = SITE_VARIANT;
}
// Remove no-transition class after first paint to enable smooth theme transitions
requestAnimationFrame(() => {
document.documentElement.classList.remove('no-transition');
});
// Clear stale settings-open flag (survives ungraceful shutdown)
localStorage.removeItem('wm-settings-open');
// Standalone windows: ?settings=1 = panel display settings, ?live-channels=1 = channel management
// Both need i18n initialized so t() does not return undefined.
const urlParams = new URL(location.href).searchParams;
if (urlParams.get('settings') === '1') {
void Promise.all([import('./services/i18n'), import('./settings-window')]).then(
async ([i18n, m]) => {
await i18n.initI18n();
m.initSettingsWindow();
}
);
} else if (urlParams.get('live-channels') === '1') {
void Promise.all([import('./services/i18n'), import('./live-channels-window')]).then(
async ([i18n, m]) => {
await i18n.initI18n();
m.initLiveChannelsWindow();
}
);
} else {
const app = new App('app');
app
.init()
.then(() => {
clearChunkReloadGuard(chunkReloadStorageKey);
})
.catch(console.error);
}
// Debug helpers for geo-convergence testing (remove in production)
(window as unknown as Record<string, unknown>).geoDebug = {
cells: debugGetCells,
count: getCellCount,
};
// Beta mode toggle: type `beta=true` / `beta=false` in console
Object.defineProperty(window, 'beta', {
get() {
const on = localStorage.getItem('worldmonitor-beta-mode') === 'true';
console.log(`[Beta] ${on ? 'ON' : 'OFF'}`);
return on;
},
set(v: boolean) {
if (v) localStorage.setItem('worldmonitor-beta-mode', 'true');
else localStorage.removeItem('worldmonitor-beta-mode');
location.reload();
},
});
// Suppress native WKWebView context menu in Tauri — allows custom JS context menus
if ('__TAURI_INTERNALS__' in window || '__TAURI__' in window) {
document.addEventListener('contextmenu', (e) => {
const target = e.target as HTMLElement;
// Allow native menu on text inputs/textareas for copy/paste
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) return;
e.preventDefault();
});
}
if (!('__TAURI_INTERNALS__' in window) && !('__TAURI__' in window)) {
import('virtual:pwa-register').then(({ registerSW }) => {
registerSW({
onRegisteredSW(_swUrl, registration) {
if (registration) {
setInterval(async () => {
if (!navigator.onLine) return;
try { await registration.update(); } catch {}
}, 60 * 60 * 1000);
}
},
onOfflineReady() {
console.log('[PWA] App ready for offline use');
},
});
});
}