UNPKG

openchain-sdk-yxl

Version:

openchain sdk

90 lines (81 loc) 2.83 kB
'use strict'; function createBufferPolyfill() { if (typeof window !== 'undefined' && typeof Buffer === 'undefined') { const BufferPolyfill = { from: function(data, encoding) { if (typeof data === 'string') { if (encoding === 'hex') { // 确保十六进制字符串格式正确 if (data.length % 2 !== 0) { throw new Error('Invalid hex string'); } return Uint8Array.from(data.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); } else if (encoding === 'utf8' || !encoding) { return new TextEncoder().encode(data); } } else if (data instanceof Uint8Array) { return data; } else if (Array.isArray(data)) { return new Uint8Array(data); } throw new Error('Unsupported data type for Buffer.from'); }, isBuffer: function(obj) { return obj instanceof Uint8Array; }, // 添加concat方法 concat: function(list, length) { if (!Array.isArray(list)) { throw new Error('Usage: Buffer.concat(list[, length])'); } if (list.length === 0) { return new Uint8Array(0); } let totalLength = 0; for (const buf of list) { totalLength += buf.length; } const result = new Uint8Array(length !== undefined ? length : totalLength); let offset = 0; for (const buf of list) { result.set(buf, offset); offset += buf.length; } return result; } }; // 为Uint8Array原型添加toString方法 if (!Uint8Array.prototype.toString) { Uint8Array.prototype.toString = function(encoding) { if (encoding === 'hex') { // 添加手动转换备选方案 if (typeof Buffer === 'undefined') { return this.manualToHex(); } return Array.from(this).map(byte => byte.toString(16).padStart(2, '0')).join(''); } else if (encoding === 'utf8' || !encoding) { return new TextDecoder().decode(this); } throw new Error('Unsupported encoding for toString'); }; } // 将手动转换方法挂载到Uint8Array原型链 Uint8Array.prototype.manualToHex = function() { if (!(this instanceof Uint8Array)) { return Array.from(new Uint8Array(this)).map(byte => byte.toString(16).padStart(2, '0') ).join(''); } return Array.from(this).map(byte => byte.toString(16).padStart(2, '0') ).join(''); }; // 确保在浏览器环境中正确设置全局Buffer对象 if (typeof window !== 'undefined') { window.Buffer = BufferPolyfill; } else if (typeof global !== 'undefined') { global.Buffer = BufferPolyfill; } } } module.exports = createBufferPolyfill;