const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); const assert = require('node:assert/strict'); const { test } = require('node:test'); const { TextEncoder, TextDecoder } = require('node:util'); const ts = require(process.env.UNIMP_TYPESCRIPT || 'C:/Program Files/Huawei/DevEco Studio/tools/hvigor/hvigor/node_modules/typescript'); const root = path.resolve(__dirname, '..'); const bootstrap = fs.readFileSync(path.join(root, 'common/src/main/resources/rawfile/unimp-harmony-compat.js'), 'utf8'); function sandbox(plus = { runtime: {} }) { return { plus, uni: { getSystemInfoSync: () => ({ osVersion: '5.1', system: 'HarmonyOS 5.1', language: 'zh-CN', brand: 'HUAWEI', model: 'test-model' }), getLaunchOptionsSync: () => ({ referrerInfo: { extraData: { 'x-version': '1.0.1' } } }), getAppBaseInfo: () => ({ hostVersion: 'fallback-version' }) }}; } test('legacy plus.os.name startup crashes without compatibility and mounts after it', () => { const source = 'var platform = plus.os.name.toLowerCase(); var mounted = true;'; assert.throws(() => vm.runInNewContext(source, sandbox()), /name/); const context = sandbox(); vm.runInNewContext(bootstrap + '\n' + source, context); assert.equal(context.platform, 'harmonyos'); assert.equal(context.mounted, true); assert.equal(context.plus.device.vendor, 'HUAWEI'); assert.equal(context.plus.runtime.version, '1.0.1'); assert.equal(context.plus.android, undefined); }); test('existing SDK metadata and runtime APIs remain intact across repeated evaluation', () => { const os = { name: 'HarmonyOS', version: 'native-version' }; const device = { model: 'native-model' }; const runtime = { version: 'native-host', openURL() {} }; const context = sandbox({ os, device, runtime }); vm.runInNewContext(bootstrap, context); vm.runInNewContext(bootstrap, context); assert.equal(context.plus.os, os); assert.equal(context.plus.device, device); assert.equal(context.plus.runtime, runtime); assert.equal(runtime.version, 'native-host'); }); test('missing metadata APIs do not introduce another startup exception', () => { const context = { plus: { runtime: {} }, uni: { getSystemInfoSync: () => { throw new Error('not supported'); }, getLaunchOptionsSync: () => { throw new Error('not ready'); } }}; vm.runInNewContext(bootstrap, context); assert.equal(context.plus.os.name, 'HarmonyOS'); assert.equal(context.plus.runtime.version, ''); vm.runInNewContext(bootstrap, {}); }); test('host version is evaluated lazily with API fallback', () => { const context = sandbox(); context.uni.getLaunchOptionsSync = () => ({}); vm.runInNewContext(bootstrap, context); assert.equal(context.plus.runtime.version, 'fallback-version'); context.uni.getLaunchOptionsSync = () => ({ referrerInfo: { extraData: { 'x-version': '2.0.0' } } }); assert.equal(context.plus.runtime.version, '2.0.0'); }); test('Vue apps receive the missing platform before rendering without overriding WGT configuration', () => { const context = sandbox(), calls = []; const create = function (...args) { calls.push({ owner: this, args }); return { config: { globalProperties: args[0] } }; }; context.Vue = { createApp: create, createSSRApp: create, createVueApp: create }; vm.runInNewContext(bootstrap, context); const props = {}, custom = { $system: 'custom' }; assert.equal(context.Vue.createApp(props).config.globalProperties, props); assert.equal(props.$system, 'HarmonyOS'); assert.equal(context.Vue.createSSRApp(custom).config.globalProperties.$system, 'custom'); assert.equal(context.Vue.createVueApp({}).config.globalProperties.$system, 'HarmonyOS'); assert.equal(calls[0].owner, context.Vue); assert.equal(calls[0].args[0], props); }); test('read-only Vue exports do not introduce a startup exception', () => { const context = sandbox(), createApp = () => ({}); context.Vue = Object.freeze({ createApp }); assert.doesNotThrow(() => vm.runInNewContext(bootstrap, context)); assert.equal(context.Vue.createApp, createApp); }); test('Vue proxy warnings cannot recursively re-enter WGT console forwarding', () => { let nativeCalls = 0, forwarded = 0; const context = sandbox(); context.console = { warn: () => { nativeCalls++; } }; vm.runInNewContext(bootstrap, context); const original = context.console.warn; context.console.warn = function (...args) { original(...args); forwarded++; for (const value of args) JSON.stringify(value); }; const component = new Proxy({}, { ownKeys: () => { context.console.warn('Avoid enumerating component keys', component); return []; }}); context.console.warn(component); assert.equal(nativeCalls, 1); assert.equal(forwarded, 1); context.console.warn('next independent message'); assert.equal(nativeCalls, 2); assert.equal(forwarded, 2); }); test('console and uni.__log__ never enumerate component trees, including later bridge wrappers', () => { const context = sandbox(); const logs = [], forwarded = []; let enumerations = 0; context.console = { warn: (...args) => logs.push(args), log: (...args) => logs.push(args) }; context.uni.__log__ = (level, file, ...args) => context.console[level](...args, file); vm.runInNewContext(bootstrap, context); const originalLog = context.uni.__log__; context.uni.__log__ = function (...args) { originalLog(...args); forwarded.push(args.map(value => JSON.stringify(value)).join(' ')); }; const originalWarn = context.console.warn; context.console.warn = function (...args) { originalWarn(...args); forwarded.push(args.map(value => JSON.stringify(value)).join(' ')); }; const component = new Proxy({}, { ownKeys() { enumerations++; context.console.warn('component enumeration', component); return []; } }); context.uni.__log__('log', 'at page.vue:1', component); context.console.warn('render warning', component); assert.equal(enumerations, 0); assert.equal(logs.length, 2); assert.equal(forwarded.length, 2); assert.ok(forwarded.every(line => line.includes('[Object]'))); }); test('object logs do not invoke getters or toJSON, and strings are bounded', () => { const context = sandbox(), logs = []; context.console = { log: (...args) => logs.push(args) }; vm.runInNewContext(bootstrap, context); const value = { get secret() { assert.fail('getter invoked'); }, toJSON() { assert.fail('toJSON invoked'); } }; context.console.log(value, 'x'.repeat(100000), 42, null); assert.equal(logs[0][0], '[Object]'); assert.equal(logs[0][1].length, 2048); assert.equal(logs[0][2], 42); assert.equal(logs[0][3], null); // Non-logging API payloads retain their original identity and contents. context.uni.sendNativeEvent = (_, data) => assert.equal(data, value); context.uni.sendNativeEvent('business', value); }); test('a late uni.__log__ implementation remains callable and self-assignment does not stack guards', () => { const context = sandbox(), calls = []; vm.runInNewContext(bootstrap, context); assert.equal(context.uni.__log__, undefined); context.uni.__log__ = (...args) => calls.push(args); const guarded = context.uni.__log__; context.uni.__log__ = context.uni.__log__; assert.equal(context.uni.__log__, guarded); context.uni.__log__('error', 'at page.vue:2', 'failure'); assert.deepEqual(calls, [['error', 'at page.vue:2', 'failure']]); }); function fixture(options = {}) { const source = 'var title = "中文页面"; var mounted = plus.os.name;'; const service = '/apps/__UNI__WX/www/app-service.js'; const files = new Map([[service, Buffer.from(options.source ?? source)]]); const handles = new Map(); let resources = 0, writes = 0; const fileIo = { OpenMode: { CREATE: 1, WRITE_ONLY: 2, TRUNC: 4 }, readText: async p => { if (!files.has(p)) throw new Error('missing script'); return files.get(p).toString('utf8'); }, open: async p => { files.set(p, Buffer.alloc(0)); handles.set(1, p); return { fd: 1 }; }, write: async (fd, input) => { writes++; if (options.failWrite) throw new Error('disk full'); const data = Buffer.from(input); const count = options.shortWrite ? Math.min(data.length, 7) : data.length; const p = handles.get(fd); files.set(p, Buffer.concat([files.get(p), data.subarray(0, count)])); return count; }, close: async () => {}, rename: async (from, to) => { if (options.failRename) throw new Error('rename failed'); files.set(to, files.get(from)); files.delete(from); }, accessSync: p => files.has(p), unlink: async p => { files.delete(p); } }; const mocks = { '@kit.CoreFileKit': { fileIo }, '@kit.ArkTS': { util: { TextDecoder: { create: () => ({ decodeWithStream: data => new TextDecoder().decode(data) }) }, TextEncoder: class { encodeInto(text) { return new TextEncoder().encode(text); } } } }, '@dcloudio/uni-app-runtime': { getUniMPRunPath: () => '/apps/__UNI__WX' }, './Logger': { Logger: { info: () => {} } } }; const exports = {}; const filename = path.join(root, 'common/src/main/ets/utils/UniMpRuntimeCompat.ets'); const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), { fileName: 'UniMpRuntimeCompat.ts', compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText; vm.runInNewContext(code, { exports, require: name => { if (mocks[name]) return mocks[name]; throw new Error('Unmocked dependency: ' + name); }}); const context = { resourceManager: { getRawFileContent: async name => { resources++; assert.equal(name, 'unimp-harmony-compat.js'); return Buffer.from(options.invalidResource ? 'invalid' : bootstrap); }}}; return { source, service, files, prepare: () => exports.UniMpRuntimeCompat.prepare(context, '__UNI__WX'), get writes() { return writes; }, get resources() { return resources; } }; } test('existing decrypted script is patched once, preserving its original Unicode source', async () => { const f = fixture(); await f.prepare(); const result = f.files.get(f.service).toString('utf8'); assert.equal(result, bootstrap + '\n' + f.source); assert.equal(f.files.has(f.service + '.compat-tmp'), false); await f.prepare(); assert.equal(f.resources, 1); assert.equal(f.writes, 1); }); test('partial filesystem writes still produce a complete executable UTF-8 script', async () => { const f = fixture({ shortWrite: true }); await f.prepare(); const context = sandbox(); vm.runInNewContext(f.files.get(f.service).toString('utf8'), context); assert.equal(context.title, '中文页面'); assert.equal(context.mounted, 'HarmonyOS'); assert.ok(f.writes > 1); }); test('write and rename errors preserve the original script and clean temporary output', async () => { for (const failure of ['failWrite', 'failRename']) { const f = fixture({ [failure]: true }); await assert.rejects(f.prepare()); assert.equal(f.files.get(f.service).toString('utf8'), f.source); assert.equal(f.files.has(f.service + '.compat-tmp'), false); } }); test('empty startup scripts and invalid compatibility assets are rejected before replacement', async () => { for (const options of [{ source: ' ' }, { invalidResource: true }]) { const f = fixture(options); await assert.rejects(f.prepare()); assert.equal(f.writes, 0); } }); test('older compatibility bootstrap is upgraded without stacking or changing business code', async () => { const business = 'var mounted = plus.os.name;'; for (const version of ['v1', 'v2', 'v3', 'v4', 'v5']) { const f = fixture({ source: '/* rabbit-unimp-harmony-compat:' + version + ' */\noldShim();\n/* end-rabbit-unimp-harmony-compat */\n' + business }); await f.prepare(); assert.equal(f.files.get(f.service).toString('utf8'), bootstrap + '\n' + business); } }); test('known no-op safeBottom diagnostic is removed without changing initialization', async () => { const f = fixture({ source: 'var extra={safeBottom:"28"};uni.showModal({title:"safeBottom",showCancel:!1,content:extra.safeBottom,success:function(e){}});var mounted=true;' }); await f.prepare(); const context = sandbox(); context.uni.showModal = () => assert.fail('debug dialog must not appear'); vm.runInNewContext(f.files.get(f.service).toString('utf8'), context); assert.equal(context.mounted, true); }); test('business modal callbacks are preserved even when the title is safeBottom', async () => { const source = 'uni.showModal({title:"safeBottom",showCancel:!1,content:extra.safeBottom,success:function(e){save(e)}});'; const f = fixture({ source }); await f.prepare(); assert.ok(f.files.get(f.service).toString('utf8').endsWith(source)); });