const EUV_VENDOR = '{{VENDOR}}';
const EUV_API_NS = '{{API_NS}}';
const EUV_ALIPAY_STYLE = {{ALIPAY_SYNTAX}} === 1;
const EUV_WASM_GLOBAL = '{{WASM_GLOBAL}}';
function resolveHost() {
if (typeof {{API_NS}} !== 'undefined' && {{API_NS}}) return {{API_NS}};
if (typeof globalThis !== 'undefined' && globalThis.{{API_NS}}) return globalThis.{{API_NS}};
if (typeof wx !== 'undefined' && wx) return wx;
if (typeof my !== 'undefined' && my) return my;
if (typeof tt !== 'undefined' && tt) return tt;
return null;
}
const HOST = resolveHost();
let wasmGlue = null;
try {
wasmGlue = require('./euv_wasm_glue');
} catch (_ignored) {
wasmGlue = (typeof globalThis !== 'undefined' && globalThis.__euvWasmBindgen) || null;
}
let activePage = null;
let activeCanvas = null;
let activeCtx = null;
let cachedImageData = null;
let cachedImgW = 0;
let cachedImgH = 0;
let wasmApi = null;
let wasmMemory = null;
let running = false;
let rafId = 0;
let rafIsTimeout = false;
let readyResolve = null;
let readyPromise = new Promise((resolve) => {
readyResolve = resolve;
});
let latestMetrics = null;
let lastAccel = [0, 9.80665, 0];
let lastGyro = [0, 0, 0];
let sensorsSubscribed = false;
function installOffscreenFontFactory() {
const g = typeof globalThis !== 'undefined' ? globalThis : null;
if (!g) return;
g.__EUV_HOST_MODE = 'miniapp';
if (typeof g.__euvCreateOffscreenCanvas !== 'function') {
g.__euvCreateOffscreenCanvas = function (width, height) {
const w = Math.max(1, Math.round(width || 128));
const h = Math.max(1, Math.round(height || 128));
const host = resolveHost();
if (host && typeof host.createOffscreenCanvas === 'function') {
try {
return host.createOffscreenCanvas({ type: '2d', width: w, height: h });
} catch (_e) {}
}
if (typeof OffscreenCanvas !== 'undefined') {
try {
return new OffscreenCanvas(w, h);
} catch (_e) {}
}
if (typeof document !== 'undefined' && typeof document.createElement === 'function') {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
return null;
};
}
}
function readSystemMetrics() {
const host = resolveHost();
const sys = host && typeof host.getWindowInfo === 'function'
? Object.assign({}, host.getDeviceInfo ? host.getDeviceInfo() : {}, host.getWindowInfo())
: (host && typeof host.getSystemInfoSync === 'function' ? host.getSystemInfoSync() : {});
const capsule = host && typeof host.getMenuButtonBoundingClientRect === 'function'
? host.getMenuButtonBoundingClientRect()
: { top: 48, right: 368, bottom: 80, left: 281, width: 87, height: 32 };
const windowWidth = Math.max(120, Math.round(Number(sys.windowWidth || 390)));
const windowHeight = Math.max(120, Math.round(Number(sys.windowHeight || 844)));
const pixelRatio = Math.min(4.5, Math.max(0.5, Number(sys.pixelRatio || 2)));
const statusBarHeight = Number(sys.statusBarHeight || 44);
const capsuleBottom = Number((capsule && capsule.bottom) || 80);
const safeTop = Math.max(statusBarHeight, capsuleBottom + 6);
const safeBottom = sys.safeArea && sys.windowHeight
? Math.max(0, Number(sys.windowHeight) - Number(sys.safeArea.bottom || sys.windowHeight))
: 24;
return {
vendor: EUV_VENDOR,
namespace: EUV_API_NS,
wasmGlobal: EUV_WASM_GLOBAL,
windowWidth,
windowHeight,
pixelRatio,
statusBarHeight,
isDark: sys.theme === 'dark',
safeArea: { top: safeTop, right: 0, bottom: safeBottom, left: 0 },
capsule
};
}
function executeHostCommand(cmd) {
const host = resolveHost();
if (!cmd) return;
switch (cmd.kind) {
case 'setNavigationBarTitle':
case 'setTitle':
if (host && typeof host.setNavigationBarTitle === 'function') {
host.setNavigationBarTitle({ title: cmd.value || '' });
} else if (host && typeof host.setNavigationBar === 'function') {
host.setNavigationBar({ title: cmd.value || '' });
}
break;
case 'setClipboardData':
if (host && typeof host.setClipboardData === 'function') {
host.setClipboardData({ data: cmd.value || '' });
} else if (host && typeof host.setClipboard === 'function') {
host.setClipboard({ text: cmd.value || '' });
}
break;
case 'setStorageSync':
if (host && typeof host.setStorageSync === 'function') {
if (EUV_ALIPAY_STYLE) {
host.setStorageSync({ key: cmd.key, data: cmd.value });
} else {
host.setStorageSync(cmd.key, cmd.value);
}
}
break;
case 'removeStorageSync':
if (host && typeof host.removeStorageSync === 'function') {
if (EUV_ALIPAY_STYLE) {
host.removeStorageSync({ key: cmd.key });
} else {
host.removeStorageSync(cmd.key);
}
}
break;
case 'clearStorageSync':
if (host && typeof host.clearStorageSync === 'function') {
host.clearStorageSync();
}
break;
case 'navigateTo':
if (host && typeof host.navigateTo === 'function') {
host.navigateTo({ url: cmd.url || '' });
}
break;
case 'navigateBack':
if (host && typeof host.navigateBack === 'function') {
host.navigateBack({ delta: cmd.delta || 1 });
}
break;
case 'showKeyboard':
if (activePage && typeof activePage.setData === 'function') {
activePage.setData({ imeFocused: Boolean(cmd.enabled) });
}
break;
case 'vibrateShort':
if (host && typeof host.vibrateShort === 'function') {
host.vibrateShort({});
}
break;
case 'showToast':
if (host && typeof host.showToast === 'function') {
if (EUV_ALIPAY_STYLE) {
host.showToast({ content: cmd.message || '', type: 'none' });
} else {
host.showToast({ title: cmd.message || '', icon: 'none' });
}
}
break;
case 'openUrl':
if (host && typeof host.setClipboardData === 'function') {
host.setClipboardData({ data: cmd.url || '' });
}
if (host && typeof host.showToast === 'function') {
if (EUV_ALIPAY_STYLE) {
host.showToast({ content: 'Link copied', type: 'none' });
} else {
host.showToast({ title: 'Link copied', icon: 'none' });
}
}
break;
default:
break;
}
}
function drainCommands() {
if (!wasmApi || typeof wasmApi.euv_host_drain_commands_json !== 'function') return [];
const raw = wasmApi.euv_host_drain_commands_json();
if (!raw || raw === '[]') return [];
try {
const list = JSON.parse(raw);
if (Array.isArray(list)) {
for (let i = 0; i < list.length; i += 1) {
executeHostCommand(list[i]);
}
return list;
}
} catch (_ignored) {}
return [];
}
function ensureImageData(pw, ph) {
if (cachedImageData && cachedImgW === pw && cachedImgH === ph) {
return cachedImageData;
}
if (activeCtx && typeof activeCtx.createImageData === 'function') {
cachedImageData = activeCtx.createImageData(pw, ph);
} else if (typeof ImageData !== 'undefined') {
cachedImageData = new ImageData(pw, ph);
} else {
cachedImageData = { width: pw, height: ph, data: new Uint8ClampedArray(pw * ph * 4) };
}
cachedImgW = pw;
cachedImgH = ph;
return cachedImageData;
}
function blitFrame(forceFull) {
if (!wasmApi || !wasmMemory || !activeCtx || !activeCanvas) return false;
const ptr = wasmApi.euv_host_framebuffer_ptr();
const len = wasmApi.euv_host_framebuffer_len();
const pw = wasmApi.euv_host_framebuffer_width();
const ph = wasmApi.euv_host_framebuffer_height();
if (!ptr || !len || !pw || !ph) return false;
if (activeCanvas.width !== pw) activeCanvas.width = pw;
if (activeCanvas.height !== ph) activeCanvas.height = ph;
const dx = forceFull ? 0 : wasmApi.euv_host_dirty_x();
const dy = forceFull ? 0 : wasmApi.euv_host_dirty_y();
const dw = forceFull ? pw : wasmApi.euv_host_dirty_w();
const dh = forceFull ? ph : wasmApi.euv_host_dirty_h();
if (!dw || !dh) return false;
const rgba = new Uint8ClampedArray(wasmMemory.buffer, ptr, len);
const imgData = ensureImageData(pw, ph);
if (dx === 0 && dy === 0 && dw === pw && dh === ph) {
imgData.data.set(rgba);
activeCtx.putImageData(imgData, 0, 0);
} else {
const dst = imgData.data;
const stride = pw * 4;
const rowBytes = dw * 4;
for (let row = 0; row < dh; row += 1) {
const off = (dy + row) * stride + dx * 4;
dst.set(rgba.subarray(off, off + rowBytes), off);
}
activeCtx.putImageData(imgData, 0, 0, dx, dy, dw, dh);
}
return true;
}
function scheduleNextFrame(cb) {
if (activeCanvas && typeof activeCanvas.requestAnimationFrame === 'function') {
rafIsTimeout = false;
rafId = activeCanvas.requestAnimationFrame(cb);
} else if (typeof requestAnimationFrame === 'function') {
rafIsTimeout = false;
rafId = requestAnimationFrame(cb);
} else {
rafIsTimeout = true;
rafId = setTimeout(() => cb(Date.now()), 16);
}
}
function cancelScheduledFrame() {
if (!rafId) return;
if (rafIsTimeout) {
clearTimeout(rafId);
} else if (activeCanvas && typeof activeCanvas.cancelAnimationFrame === 'function') {
activeCanvas.cancelAnimationFrame(rafId);
} else if (typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(rafId);
}
rafId = 0;
}
function stepNow(dtSecs, forceRender) {
if (!wasmApi) return false;
const rendered = wasmApi.euv_host_step(dtSecs, Boolean(forceRender));
drainCommands();
if (rendered) {
return blitFrame(Boolean(forceRender));
}
return false;
}
function startLoop() {
if (running || !activeCanvas) return;
running = true;
let lastTs = 0;
const tick = (ts) => {
if (!running) return;
const now = typeof ts === 'number' && ts > 0 ? ts : Date.now();
const dt = lastTs > 0 ? Math.min(0.05, Math.max(0.002, (now - lastTs) / 1000)) : (1 / 60);
lastTs = now;
stepNow(dt, false);
if (running) {
scheduleNextFrame(tick);
}
};
scheduleNextFrame(tick);
}
function stopLoop() {
running = false;
cancelScheduledFrame();
}
function subscribeHostEvents() {
const host = resolveHost();
if (!host || sensorsSubscribed) return;
sensorsSubscribed = true;
if (typeof host.onWindowResize === 'function') {
host.onWindowResize((ev) => {
const sz = (ev && ev.size) || ev || {};
if (sz.windowWidth && sz.windowHeight) {
dispatchResize(Number(sz.windowWidth), Number(sz.windowHeight), Number(sz.pixelRatio || 0));
}
});
}
if (typeof host.onThemeChange === 'function') {
host.onThemeChange((ev) => dispatchTheme((ev && ev.theme) === 'dark'));
}
if (typeof host.onMemoryWarning === 'function') {
host.onMemoryWarning((ev) => dispatchMemoryWarning(ev && typeof ev.level === 'number' ? ev.level : 5));
}
if (typeof host.onKeyboardHeightChange === 'function') {
host.onKeyboardHeightChange((ev) => dispatchKeyboardHeight(Number((ev && ev.height) || 0)));
}
if (typeof host.onNetworkStatusChange === 'function') {
host.onNetworkStatusChange((ev) => {
const status = ev && ev.isConnected === false ? 'offline' : String((ev && ev.networkType) || 'wifi');
dispatchNetworkStatus(status);
});
}
if (typeof host.onAccelerometerChange === 'function') {
host.onAccelerometerChange((ev) => {
if (!ev) return;
lastAccel = [Number(ev.x || 0) * 9.80665, Number(ev.y || 0) * 9.80665, Number(ev.z || 0) * 9.80665];
if (wasmApi && typeof wasmApi.euv_host_device_motion === 'function') {
wasmApi.euv_host_device_motion(lastAccel[0], lastAccel[1], lastAccel[2], lastGyro[0], lastGyro[1], lastGyro[2]);
}
});
}
if (typeof host.onGyroscopeChange === 'function') {
host.onGyroscopeChange((ev) => {
if (!ev) return;
lastGyro = [Number(ev.x || 0), Number(ev.y || 0), Number(ev.z || 0)];
if (wasmApi && typeof wasmApi.euv_host_device_motion === 'function') {
wasmApi.euv_host_device_motion(lastAccel[0], lastAccel[1], lastAccel[2], lastGyro[0], lastGyro[1], lastGyro[2]);
}
});
}
}
async function initWasmIfPresent(metrics) {
installOffscreenFontFactory();
if (!wasmGlue || typeof wasmGlue.__euvInitHost !== 'function') {
if (readyResolve) readyResolve(false);
return false;
}
const wasmSource = (typeof globalThis !== 'undefined' && globalThis.__EUV_WASM_SOURCE) || '/runtime/euv_app.wasm';
try {
const initialized = await wasmGlue.__euvInitHost(wasmSource);
wasmApi = initialized.api;
wasmMemory = initialized.memory;
wasmApi.euv_host_init(
1,
EUV_VENDOR,
metrics.windowWidth,
metrics.windowHeight,
metrics.pixelRatio,
metrics.safeArea.top,
metrics.safeArea.bottom
);
wasmApi.euv_host_safe_area(
metrics.safeArea.top,
metrics.safeArea.right,
metrics.safeArea.bottom,
metrics.safeArea.left
);
if (metrics.isDark) {
wasmApi.euv_host_theme(true);
wasmApi.euv_host_step(1 / 60, true);
}
blitFrame(true);
drainCommands();
startLoop();
if (readyResolve) readyResolve(true);
return true;
} catch (err) {
if (typeof console !== 'undefined' && console.error) {
console.error('[euv-miniapp] WASM init failed for ' + EUV_VENDOR + ':', err);
}
if (readyResolve) readyResolve(false);
return false;
}
}
function mountPage(page, selector) {
activePage = page;
latestMetrics = readSystemMetrics();
subscribeHostEvents();
const host = resolveHost();
if (!host || typeof host.createSelectorQuery !== 'function') return;
const query = host.createSelectorQuery();
const sel = query.select(selector || '#euv-canvas');
const finishMount = (res) => {
const entry = Array.isArray(res) ? res[0] : res;
if (!entry || !entry.node) return;
activeCanvas = entry.node;
activeCanvas.width = Math.max(1, Math.round(latestMetrics.windowWidth * latestMetrics.pixelRatio));
activeCanvas.height = Math.max(1, Math.round(latestMetrics.windowHeight * latestMetrics.pixelRatio));
activeCtx = activeCanvas.getContext('2d');
initWasmIfPresent(latestMetrics);
};
if (typeof sel.fields === 'function') {
sel.fields({ node: true, size: true }).exec(finishMount);
} else if (typeof sel.node === 'function') {
sel.node().exec(finishMount);
}
}
function unmountPage() {
stopLoop();
if (wasmApi && typeof wasmApi.euv_host_destroy === 'function') {
wasmApi.euv_host_destroy();
}
activeCanvas = null;
activeCtx = null;
cachedImageData = null;
cachedImgW = 0;
cachedImgH = 0;
activePage = null;
}
function dispatchLifecycle(hook, payload) {
if (hook === 'onHide' || hook === 'onUnload') {
stopLoop();
} else if (hook === 'onShow' && activeCanvas && wasmApi) {
startLoop();
}
if (wasmApi && typeof wasmApi.euv_host_lifecycle === 'function') {
const tag = hook === 'onLaunch' ? 1 : hook === 'onShow' ? 2 : hook === 'onHide' ? 3 : 4;
wasmApi.euv_host_lifecycle(tag, String(payload || ''));
if (hook === 'onShow') {
stepNow(1 / 60, true);
}
}
}
function dispatchResize(width, height, pixelRatio) {
const dpr = pixelRatio > 0 ? pixelRatio : (latestMetrics ? latestMetrics.pixelRatio : 2);
if (latestMetrics) {
latestMetrics.windowWidth = width;
latestMetrics.windowHeight = height;
latestMetrics.pixelRatio = dpr;
}
if (wasmApi && typeof wasmApi.euv_host_resize === 'function') {
wasmApi.euv_host_resize(width, height, dpr);
stepNow(1 / 60, true);
}
}
function dispatchTouch(phase, event) {
const touches = (event && (event.changedTouches || event.touches)) || [];
const phaseTag = phase === 'down' ? 0 : phase === 'move' ? 1 : phase === 'up' ? 2 : 3;
if (wasmApi && typeof wasmApi.euv_host_touch === 'function') {
for (let i = 0; i < touches.length; i += 1) {
const t = touches[i];
const lx = Number(typeof t.x === 'number' ? t.x : (typeof t.clientX === 'number' ? t.clientX : (t.pageX || 0)));
const ly = Number(typeof t.y === 'number' ? t.y : (typeof t.clientY === 'number' ? t.clientY : (t.pageY || 0)));
wasmApi.euv_host_touch(phaseTag, Number(t.identifier || 0), lx, ly);
}
stepNow(1 / 60, false);
}
}
function dispatchIme(text, confirmed) {
if (wasmApi && typeof wasmApi.euv_host_ime === 'function') {
wasmApi.euv_host_ime(String(text || ''), Boolean(confirmed));
stepNow(1 / 60, false);
}
}
function dispatchTheme(isDark) {
if (wasmApi && typeof wasmApi.euv_host_theme === 'function') {
wasmApi.euv_host_theme(Boolean(isDark));
stepNow(1 / 60, true);
}
}
function dispatchMemoryWarning(level) {
if (wasmApi && typeof wasmApi.euv_host_memory_warning === 'function') {
wasmApi.euv_host_memory_warning(Number(level || 5));
}
}
function dispatchKeyboardHeight(height) {
if (wasmApi && typeof wasmApi.euv_host_keyboard_height === 'function') {
wasmApi.euv_host_keyboard_height(Number(height || 0));
stepNow(1 / 60, false);
}
}
function dispatchNetworkStatus(status) {
if (wasmApi && typeof wasmApi.euv_host_network === 'function') {
wasmApi.euv_host_network(String(status || 'wifi'));
}
}
function navigate(route) {
if (!wasmApi || typeof wasmApi.euv_host_navigate !== 'function') return 0;
const hash = wasmApi.euv_host_navigate(String(route || '/'));
blitFrame(true);
drainCommands();
return hash;
}
function getStats() {
if (!wasmApi || typeof wasmApi.euv_host_stats_json !== 'function') return null;
try {
return JSON.parse(wasmApi.euv_host_stats_json());
} catch (_ignored) {
return null;
}
}
module.exports = {
EUV_VENDOR,
EUV_API_NS,
EUV_WASM_GLOBAL,
readyPromise,
readSystemMetrics,
executeHostCommand,
drainCommands,
mountPage,
unmountPage,
stepNow,
navigate,
getStats,
dispatchLifecycle,
dispatchResize,
dispatchTouch,
dispatchIme,
dispatchTheme,
dispatchMemoryWarning,
dispatchKeyboardHeight,
dispatchNetworkStatus
};