Skip to content

Commit

Permalink
♻️ Try loading 'inherits' library if 'util' is missing
Browse files Browse the repository at this point in the history
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
  • Loading branch information
alecgibson committed Mar 28, 2024
1 parent 5259d0e commit bf8e735
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
3 changes: 1 addition & 2 deletions lib/op-stream.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
var inherits = require('util').inherits;
var Readable = require('stream').Readable;
var util = require('./util');

Expand All @@ -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
Expand Down
3 changes: 1 addition & 2 deletions lib/stream-socket.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
var Duplex = require('stream').Duplex;
var inherits = require('util').inherits;
var logger = require('./logger');
var util = require('./util');

Expand Down Expand Up @@ -47,7 +46,7 @@ function ServerStream(socket) {
socket.close('stopped');
});
}
inherits(ServerStream, Duplex);
util.inherits(ServerStream, Duplex);

ServerStream.prototype.isServer = true;

Expand Down
12 changes: 12 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}

0 comments on commit bf8e735

Please sign in to comment.