const globalScope = globalThis as Record; const stringPrototype = String.prototype as typeof String.prototype & { isWellFormed?: () => boolean; toWellFormed?: () => string; }; const arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')?.get; function toWellFormedString(value: string): string { let result = ''; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code >= 0xd800 && code <= 0xdbff) { const next = value.charCodeAt(index + 1); if (next >= 0xdc00 && next <= 0xdfff) { result += value[index] + value[index + 1]; index += 1; } else { result += '\uFFFD'; } } else if (code >= 0xdc00 && code <= 0xdfff) { result += '\uFFFD'; } else { result += value[index]; } } return result; } if (typeof stringPrototype.toWellFormed !== 'function') { Object.defineProperty(String.prototype, 'toWellFormed', { configurable: true, value() { return toWellFormedString(String(this)); }, }); } if (typeof stringPrototype.isWellFormed !== 'function') { Object.defineProperty(String.prototype, 'isWellFormed', { configurable: true, value() { const value = String(this); return toWellFormedString(value) === value; }, }); } if (!Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'resizable')) { Object.defineProperty(ArrayBuffer.prototype, 'resizable', { configurable: true, get() { return false; }, }); } if (typeof globalScope.SharedArrayBuffer === 'undefined') { class SharedArrayBufferPolyfill extends ArrayBuffer { get byteLength() { return arrayBufferByteLength?.call(this) ?? 0; } get growable() { return false; } } Object.defineProperty(SharedArrayBufferPolyfill.prototype, Symbol.toStringTag, { configurable: true, value: 'SharedArrayBuffer', }); globalScope.SharedArrayBuffer = SharedArrayBufferPolyfill; }