Skip to content

Commit

Permalink
addEventListener
Browse files Browse the repository at this point in the history
  • Loading branch information
dimdenGD committed Oct 3, 2024
1 parent 31f378d commit 9cb2285
Show file tree
Hide file tree
Showing 4 changed files with 355 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ WIP

### Client

This category only describes server clients. Client-side (`new ws.WebSocket`) just uses original `ws` module, and therefore supports everything.
This category only describes server clients. Client-side (`new ws.WebSocket()`) just uses original `ws` module, and therefore supports everything.

#### Client events

Expand All @@ -90,7 +90,7 @@ This category only describes server clients. Client-side (`new ws.WebSocket`) ju

#### Client properties

- client.addEventListener(type, listener, options)
- client.addEventListener(type, listener, options)
- ❌ client.binaryType
- ❌ client.bufferedAmount
- ❌ client.close(code, reason)
Expand Down
315 changes: 315 additions & 0 deletions src/event-target.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
/*
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
Copyright (c) 2016 Luigi Pinca and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

'use strict';

const kForOnEventAttribute = Symbol('kForOnEventAttribute');
const kListener = Symbol('kListener');
const kCode = Symbol('kCode');
const kData = Symbol('kData');
const kError = Symbol('kError');
const kMessage = Symbol('kMessage');
const kReason = Symbol('kReason');
const kTarget = Symbol('kTarget');
const kType = Symbol('kType');
const kWasClean = Symbol('kWasClean');

/**
* Class representing an event.
*/
class Event {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}

/**
* @type {*}
*/
get target() {
return this[kTarget];
}

/**
* @type {String}
*/
get type() {
return this[kType];
}
}

Object.defineProperty(Event.prototype, 'target', { enumerable: true });
Object.defineProperty(Event.prototype, 'type', { enumerable: true });

/**
* Class representing a close event.
*
* @extends Event
*/
class CloseEvent extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);

this[kCode] = options.code === undefined ? 0 : options.code;
this[kReason] = options.reason === undefined ? '' : options.reason;
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
}

/**
* @type {Number}
*/
get code() {
return this[kCode];
}

/**
* @type {String}
*/
get reason() {
return this[kReason];
}

/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
}

Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });

/**
* Class representing an error event.
*
* @extends Event
*/
class ErrorEvent extends Event {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);

this[kError] = options.error === undefined ? null : options.error;
this[kMessage] = options.message === undefined ? '' : options.message;
}

/**
* @type {*}
*/
get error() {
return this[kError];
}

/**
* @type {String}
*/
get message() {
return this[kMessage];
}
}

Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });

/**
* Class representing a message event.
*
* @extends Event
*/
class MessageEvent extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);

this[kData] = options.data === undefined ? null : options.data;
}

/**
* @type {*}
*/
get data() {
return this[kData];
}
}

Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });

/**
* This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly.
*
* @mixin
*/
const EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (
!options[kForOnEventAttribute] &&
listener[kListener] === handler &&
!listener[kForOnEventAttribute]
) {
return;
}
}

let wrapper;

if (type === 'message') {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent('message', {
data: isBinary ? data : data.toString()
});

event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'close') {
wrapper = function onClose(code, message) {
const event = new CloseEvent('close', {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});

event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'error') {
wrapper = function onError(error) {
const event = new ErrorEvent('error', {
error,
message: error.message
});

event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'open') {
wrapper = function onOpen() {
const event = new Event('open');

event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}

wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;

if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},

/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};

module.exports = {
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};

/**
* Call an event listener
*
* @param {(Function|Object)} listener The listener to call
* @param {*} thisArg The value to use as `this`` when calling the listener
* @param {Event} event The event to pass to the listener
* @private
*/
function callListener(listener, thisArg, event) {
if (typeof listener === 'object' && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
15 changes: 13 additions & 2 deletions src/websocket.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
const { EventEmitter } = require("tseep");
const { EventTarget } = require("./event-target.js");

module.exports = class WebSocket extends EventEmitter {
class WebSocket extends EventEmitter {
constructor(ws) {
super();
this.ws = ws;
}
}

addEventListener(type, listener, options) {
return EventTarget.addEventListener.call(this, type, listener, options);
}

removeEventListener(type, listener, options) {
return EventTarget.removeEventListener.call(this, type, listener, options);
}
}

module.exports = WebSocket;
25 changes: 25 additions & 0 deletions tests/tests/client/addEventListener.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// must support client addEventListener

const ws = require("ws");

const wss = new ws.WebSocketServer({ port: 8080 }, client);

wss.on("connection", (ws, req) => {
ws.addEventListener("message", (event) => {
console.log(event.data);

process.exit(0);
});
});

function client() {
const c = new ws.WebSocket("ws://localhost:8080");

c.on('open', () => {
c.send("Hello from client");
c.send(new TextEncoder().encode("Binary hello from client"));
setTimeout(() => {
process.exit(0);
}, 100);
});
}

0 comments on commit 9cb2285

Please sign in to comment.