/* 冒烟测试:在 Node 里用一套极简 DOM/BMapGL 桩加载 static/dist/app.js, * 只验证「模块图能求值 + bootstrap 能跑完」——用来抓 ES 模块化引入的 * ReferenceError / TDZ / 装错顺序问题。不做真实渲染。 * * node src-ts/tools/smoke.cjs */ const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const ROOT = path.resolve(__dirname, "..", ".."); const code = fs.readFileSync(path.join(ROOT, "static", "dist", "app.js"), "utf8"); const errors = []; function track(label, fn) { try { return fn(); } catch (e) { errors.push(`${label}: ${e && e.message}`); } } /* ---------------- DOM 桩 ---------------- */ const listeners = []; function makeEl(tag = "div") { const el = { tagName: String(tag).toUpperCase(), style: { setProperty() {}, getPropertyValue() { return ""; }, removeProperty() {}, cssText: "" }, dataset: {}, classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } }, children: [], childNodes: [], parentNode: null, innerHTML: "", innerText: "", textContent: "", value: "", checked: false, disabled: false, hidden: false, width: 0, height: 0, offsetWidth: 100, offsetHeight: 100, clientWidth: 100, clientHeight: 100, scrollTop: 0, appendChild(c) { this.children.push(c); return c; }, removeChild(c) { this.children = this.children.filter((x) => x !== c); return c; }, insertBefore(c) { this.children.push(c); return c; }, addEventListener(n, f) { listeners.push([this, n, f]); }, removeEventListener() {}, setAttribute(k, v) { this[k] = v; }, getAttribute() { return null; }, removeAttribute() {}, hasAttribute() { return false; }, querySelector() { return makeEl(); }, querySelectorAll() { return []; }, getElementsByClassName() { return []; }, getElementsByTagName() { return []; }, append() {}, before() {}, after() {}, replaceWith() {}, normalize() {}, setPointerCapture() {}, releasePointerCapture() {}, closest() { return makeEl(); }, insertAdjacentHTML() {}, focus() {}, blur() {}, click() {}, cloneNode() { return makeEl(tag); }, getBoundingClientRect() { return { top: 0, left: 0, right: 100, bottom: 100, width: 100, height: 100, x: 0, y: 0 }; }, scrollIntoView() {}, animate() { return { finished: Promise.resolve(), cancel() {}, onfinish: null }; }, getContext() { const noop = () => {}; return { beginPath: noop, arc: noop, fill: noop, stroke: noop, fillText: noop, measureText: () => ({ width: 10 }), clearRect: noop, drawImage: noop, createLinearGradient: () => ({ addColorStop: noop }), save: noop, restore: noop, translate: noop, rotate: noop, scale: noop, setTransform: noop, moveTo: noop, lineTo: noop, closePath: noop, rect: noop, fillRect: noop, strokeRect: noop, putImageData: noop, getImageData: () => ({ data: [] }), set fillStyle(v) {}, set strokeStyle(v) {}, set lineWidth(v) {}, set font(v) {}, set textAlign(v) {}, set textBaseline(v) {}, set shadowColor(v) {}, set shadowBlur(v) {}, set lineCap(v) {}, set globalAlpha(v) {}, set lineJoin(v) {}, }; }, toDataURL() { return "data:image/png;base64,AAA"; }, }; return el; } const byId = new Map(); const document = { readyState: "loading", body: makeEl("body"), head: makeEl("head"), documentElement: makeEl("html"), getElementById(id) { if (!byId.has(id)) byId.set(id, makeEl()); return byId.get(id); }, createElement: (t) => makeEl(t), createElementNS: (ns, t) => makeEl(t), createTextNode: () => makeEl("text"), querySelector: () => makeEl(), querySelectorAll: () => [], addEventListener(n, f) { listeners.push(["document", n, f]); }, removeEventListener() {}, dispatchEvent() { return true; }, cookie: "", }; /* ---------------- BMapGL 桩 ---------------- */ /** 未知方法一律返回空函数,避免桩漏方法就报错(真实 SDK 的方法我们并不校验) */ function tolerant(obj) { return new Proxy(obj, { get(t, k) { if (k in t) return t[k]; if (typeof k === "string") return function () { return undefined; }; return undefined; }, set(t, k, v) { t[k] = v; return true; }, }); } function overlayStub(kind) { return function (a, b, c) { const self = this; this.kind = kind; this.args = [a, b, c]; this.addEventListener = () => {}; this.removeEventListener = () => {}; this.setPosition = () => {}; this.getPosition = () => ({ lng: 116.98, lat: 36.67 }); this.show = () => {}; this.hide = () => {}; this.setIcon = () => {}; this.setContent = () => {}; this.setOffset = () => {}; this.setTitle = () => {}; this.setSize = () => {}; this.setFillColor = () => {}; this.setStrokeColor = () => {}; this.setStrokeWeight = () => {}; this.setStrokeOpacity = () => {}; this.setFillOpacity = () => {}; this.setPath = () => {}; this.setRaiseOnDrag = () => {}; this.setTop = () => {}; this.getMap = () => null; return tolerant(this); }; } const MapStub = function (container, opts) { this.container = container; this.opts = opts; this._listeners = {}; }; MapStub.prototype.addEventListener = function (n, f) { (this._listeners[n] = this._listeners[n] || []).push(f); }; MapStub.prototype.removeEventListener = function () {}; MapStub.prototype.centerAndZoom = function () {}; MapStub.prototype.setCenter = function () {}; MapStub.prototype.getCenter = function () { return { lng: 116.98, lat: 36.67 }; }; MapStub.prototype.getZoom = function () { return 17; }; MapStub.prototype.setZoom = function () {}; MapStub.prototype.enableScrollWheelZoom = function () {}; MapStub.prototype.disableScrollWheelZoom = function () {}; MapStub.prototype.enableDragging = function () {}; MapStub.prototype.disableDragging = function () {}; MapStub.prototype.enableDoubleClickZoom = function () {}; MapStub.prototype.addOverlay = function (o) { return o; }; MapStub.prototype.removeOverlay = function () {}; MapStub.prototype.clearOverlays = function () {}; MapStub.prototype.getOverlays = function () { return []; }; MapStub.prototype.addControl = function () {}; MapStub.prototype.setMapStyleV2 = function () {}; MapStub.prototype.setMapStyle = function () {}; MapStub.prototype.setViewport = function () {}; MapStub.prototype.getViewport = function () { return {}; }; MapStub.prototype.panTo = function () {}; MapStub.prototype.panBy = function () {}; MapStub.prototype.setHeading = function () {}; MapStub.prototype.getHeading = function () { return 0; }; MapStub.prototype.setTilt = function () {}; MapStub.prototype.startViewAnimation = function () {}; MapStub.prototype.pixelToPoint = function () { return { lng: 0, lat: 0 }; }; MapStub.prototype.pointToPixel = function () { return { x: 0, y: 0 }; }; MapStub.prototype.openInfoWindow = function () {}; MapStub.prototype.closeInfoWindow = function () {}; const BMapGL = { Map: function (container, opts) { return tolerant(new MapStub(container, opts)); }, Point: function (lng, lat) { this.lng = lng; this.lat = lat; this.equals = (o) => o && o.lng === lng && o.lat === lat; }, Size: function (w, h) { this.width = w; this.height = h; }, Icon: overlayStub("Icon"), Marker: overlayStub("Marker"), Polyline: overlayStub("Polyline"), Polygon: overlayStub("Polygon"), Circle: overlayStub("Circle"), Overlay: overlayStub("Overlay"), ScaleControl: overlayStub("ScaleControl"), ViewAnimation: overlayStub("ViewAnimation"), Convertor: overlayStub("Convertor"), WalkingRoute: function (map, opts) { this.map = map; this.opts = opts || {}; this.search = () => {}; }, }; /* ---------------- 其它外部全局 ---------------- */ const storage = { _d: new Map(), getItem(k) { return this._d.has(k) ? this._d.get(k) : null; }, setItem(k, v) { this._d.set(k, String(v)); }, removeItem(k) { this._d.delete(k); }, clear() { this._d.clear(); }, }; const noopTimer = () => 0; const requests = []; const sandbox = { console, document, navigator: { userAgent: "node-smoke", geolocation: { getCurrentPosition(cb) { cb({ coords: { latitude: 36.67, longitude: 116.98 } }); }, watchPosition() { return 1; }, clearWatch() {} }, deviceMemory: 4, language: "zh-CN" }, location: { href: "http://127.0.0.1/", origin: "http://127.0.0.1", hostname: "127.0.0.1", protocol: "http:", search: "", pathname: "/", replace() {}, assign() {} }, history: { replaceState() {}, pushState() {}, back() {} }, localStorage: storage, sessionStorage: storage, performance: { now: () => Date.now() }, setTimeout: noopTimer, clearTimeout: () => {}, setInterval: noopTimer, clearInterval: () => {}, requestAnimationFrame: () => 0, cancelAnimationFrame: () => {}, matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }), fetch: (url) => { requests.push(String(url)); return Promise.resolve({ ok: true, status: 200, headers: { get: () => null }, json: () => Promise.resolve({ rtn_code: 0, data: { logged_in: true, email: "smoke@example.com", nickname: "smoke" }, results: [], has_order: false, message: "", map_snapshot: { server_time: Math.floor(Date.now() / 1000) }, center_lat: 36.67, center_lng: 116.98 }), text: () => Promise.resolve(""), }); }, alert: () => {}, confirm: () => true, prompt: () => null, Image: function () { this.src = ""; this.onload = null; }, Event: function (t) { this.type = t; }, CustomEvent: function (t, o) { this.type = t; this.detail = o && o.detail; }, DeviceOrientationEvent: Object.assign(function () {}, { requestPermission: () => Promise.resolve("granted") }), BMapGL, QRCode: { CorrectLevel: { L: 1, M: 0, Q: 3, H: 2 }, toCanvas() {}, toDataURL() { return "data:image/png;base64,AAA"; } }, coordtransform: { gcj02tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006], bd09togcj02: (lng, lat) => [lng - 0.0065, lat - 0.006], wgs84togcj02: (lng, lat) => [lng, lat], wgs84tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006], }, SettingsPages: { open() {}, back() {}, requestBack() {}, close() {}, hide() {}, restore() {}, isOpen: () => false }, BikeClusters: { PREFERENCE_KEY: "xbniu_bike_clustering", readClusteringPreference: () => true, writeClusteringPreference: () => true, normalizeBikes: (b) => b || [], bikeId: (b) => (b && (b.bike_code || b.id)) || "", clusterBikes: () => ({ singles: [], clusters: [] }), createLayer: () => ({ render() {}, destroy() {}, setSelected() {}, setClusteringEnabled() {}, regroup() {}, requestRegroup() {}, expand() {}, listen() {}, }), }, }; sandbox.window = sandbox; sandbox.self = sandbox; sandbox.globalThis = sandbox; sandbox.window.top = sandbox; sandbox.window.parent = sandbox; sandbox.window.close = () => {}; sandbox.window.open = () => null; sandbox.window.scrollTo = () => {}; sandbox.window.addEventListener = (n, f) => listeners.push(["window", n, f]); sandbox.window.removeEventListener = () => {}; sandbox.window.dispatchEvent = () => true; sandbox.window.isSecureContext = true; sandbox.window.innerWidth = 390; sandbox.window.innerHeight = 844; sandbox.window.screen = { width: 390, height: 844 }; sandbox.window.devicePixelRatio = 2; const unhandled = []; process.on("unhandledRejection", (e) => unhandled.push(String((e && e.message) || e))); /* 先塞一个 token,让 bootstrap 里的 auth/order/rental 分支都真的跑起来 */ storage.setItem("auth_token", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE5MDAwMDAwMDAsInVpZCI6MX0.sig"); const ctx = vm.createContext(sandbox); track("bundle 求值", () => new vm.Script(code, { filename: "static/dist/app.js" }).runInContext(ctx)); (async () => { for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r)); /* 触发首屏初始化:DOMContentLoaded + xbniu-map-ready(原实现就是这么起来的) */ const call = (label, pred) => { for (const [target, name, fn] of listeners.slice()) { if (pred(target, name) && typeof fn === "function") track(label + ":" + name, () => fn({ type: name })); } }; call("DOMContentLoaded", (t, n) => (t === "document" || t === sandbox.window) && n === "DOMContentLoaded"); for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r)); call("xbniu-map-ready", (t, n) => (t === "window" || t === sandbox.window) && n === "xbniu-map-ready"); for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r)); /* ---------------- 断言 ---------------- */ const checks = [ ["window.initMap 是函数", typeof sandbox.initMap === "function"], ["window.showBikeDetail 是函数", typeof sandbox.showBikeDetail === "function"], ["window.doUnlockBike 是函数", typeof sandbox.doUnlockBike === "function"], ["window.toggleNavigation 是函数", typeof sandbox.toggleNavigation === "function"], ["window.openShareModal 是函数", typeof sandbox.openShareModal === "function"], ["window.offsetCoord 是函数", typeof sandbox.offsetCoord === "function"], ["offsetCoord 结果正确", (() => { const r = sandbox.offsetCoord(36.67, 116.98); return Math.abs(r.lat - 36.676) < 1e-6 && Math.abs(r.lng - 116.9865) < 1e-6; })()], ["calcDistance 有值", typeof sandbox.calcDistance(36.67, 116.98, 36.68, 116.99) === "number"], ["注册了 document 监听", listeners.some((l) => l[0] === "document")], ["注册了 window 监听", listeners.some((l) => l[0] === "window")], ["发了 /api 请求(带 token 时)", requests.some((u) => u.includes("/api/"))], ["异步链没有未捕获异常", unhandled.length === 0], ["initMap 后注册了地图监听", listeners.filter((l) => l[0] && l[0]._listeners).length >= 0], ["渲染流程拿到 /api/map", requests.some((u) => u.includes("/api/map"))], ["元素监听总数 >= 20(含卡片/扫码/寻车长按)", listeners.length >= 20], ]; console.log("=== bundle 冒烟测试 ==="); let failed = 0; for (const [name, ok] of checks) { console.log(` ${ok ? "✓" : "✗"} ${name}`); if (!ok) failed++; } if (errors.length) { console.log("\n求值期错误:"); for (const e of errors) console.log(" " + e); } console.log(`\n窗口监听数 ${listeners.filter((l) => l[0] === "window").length},document 监听数 ${listeners.filter((l) => l[0] === "document").length},元素监听数 ${listeners.length}`); console.log(`fetch 请求:${[...new Set(requests)].join(", ") || "无"}`); if (unhandled.length) console.log("未捕获的 promise 异常:\n " + unhandled.join("\n ")); process.exitCode = failed || errors.length ? 1 : 0; })();