From bf8e735ecd77002ae5c1bf266f25ccb4829d4284 Mon Sep 17 00:00:00 2001 From: Alec Gibson <12036746+alecgibson@users.noreply.github.com> Date: Thu, 28 Mar 2024 16:22:35 +0000 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Try=20loading=20`'inherits?= =?UTF-8?q?'`=20library=20if=20`'util'`=20is=20missing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When running ShareDB in a browser environment, we have to polyfill the `util` library. However, we only use the `inherits` part of that library. This change will attempt to fall back to the browser-friendly [`inherits` library][1] if `util` can't be found, allowing for lighter polyfilling. [1]: https://github.com/isaacs/inherits --- lib/op-stream.js | 3 +-- lib/stream-socket.js | 3 +-- lib/util.js | 12 ++++++++++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/op-stream.js b/lib/op-stream.js index a2608fd28..6dd751a58 100644 --- a/lib/op-stream.js +++ b/lib/op-stream.js @@ -1,4 +1,3 @@ -var inherits = require('util').inherits; var Readable = require('stream').Readable; var util = require('./util'); @@ -10,7 +9,7 @@ function OpStream() { } module.exports = OpStream; -inherits(OpStream, Readable); +util.inherits(OpStream, Readable); // This function is for notifying us that the stream is empty and needs data. // For now, we'll just ignore the signal and assume the reader reads as fast diff --git a/lib/stream-socket.js b/lib/stream-socket.js index 057064c16..fa9b6f98b 100644 --- a/lib/stream-socket.js +++ b/lib/stream-socket.js @@ -1,5 +1,4 @@ var Duplex = require('stream').Duplex; -var inherits = require('util').inherits; var logger = require('./logger'); var util = require('./util'); @@ -47,7 +46,7 @@ function ServerStream(socket) { socket.close('stopped'); }); } -inherits(ServerStream, Duplex); +util.inherits(ServerStream, Duplex); ServerStream.prototype.isServer = true; diff --git a/lib/util.js b/lib/util.js index f991bbe41..57eb9bb20 100644 --- a/lib/util.js +++ b/lib/util.js @@ -113,3 +113,15 @@ Object.getOwnPropertyNames(Object.prototype).forEach(function(prop) { exports.isDangerousProperty = function(propName) { return propName === '__proto__' || objectProtoPropNames[propName]; }; + +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw new Error('Could not find util.inherits()'); + exports.inherits = util.inherits; +} catch (e) { + try { + exports.inherits = require('inherits'); + } catch (e) { + throw new Error('If running sharedb in a browser, please install the "inherits" or "util" package'); + } +}