Skip to content

Commit

Permalink
BREAKING CHANGE: Make id private and only accessible via getter, add …
Browse files Browse the repository at this point in the history
…hostMigration event and rename 'destroy' to 'instanceDestroyed' event
  • Loading branch information
therealPaulPlay committed Feb 3, 2025
1 parent 83bf0aa commit 55b8115
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 21 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ Creates a new PlayPeer instance with a specified peer ID and [PeerJS options](ht

- `status`: Connection status updates (returns status `string`)
- `error`: Error events (returns error `string`)
- `destroy`: Peer destruction event
- `instanceDestroyed`: Peer destruction event
- `storageUpdate`: Storage state changes (returns storage `object`)
- `hostMigration`: Host changes (returns host id / room code `string`)
- `incomingPeerConnected`: New peer connected (returns peer-id `string`)
- `incomingPeerDisconnected`: Peer disconnected (returns peer-id `string`)
- `incomingPeerError`: Peer connection error (returns peer-id `string`)
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "playpeerjs",
"version": "1.2.3",
"version": "1.2.4",
"description": "WebRTC-based wrapper for creating robust peer-2-peer multiplayer systems with ease.",
"type": "module",
"main": "dist/playpeer.js",
Expand Down
9 changes: 2 additions & 7 deletions src/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,9 @@

let peer;

// Function to generate a random 10-character ID
function generateId() {
return Math.random().toString(36).substring(2, 12);
}

// Automatically generate and display the ID
const peerId = generateId();
const peerId = Math.random().toString(36).substring(2, 12);

document.getElementById('peerIdDisplay').textContent = `Your peer ID: ${peerId}`;

async function initPeer(id) {
Expand All @@ -76,7 +72,6 @@
});

peer.onEvent('status', status => console.log('Status:', status));

await peer.init();
}

Expand Down
27 changes: 17 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const WARNING_PREFIX = "PlayPeer warning: ";
*/
export default class PlayPeer {
// Config properties
id;
#id;
#peer;
#options;
#initialized = false;
Expand All @@ -36,7 +36,7 @@ export default class PlayPeer {
* @param {object} [options] - Peer options (ice config, host, port etc.)
*/
constructor(id, options) {
this.id = id;
this.#id = id;
if (options) this.#options = options;
}

Expand All @@ -49,8 +49,9 @@ export default class PlayPeer {
const validEvents = [
"status",
"error",
"destroy",
"instanceDestroyed",
"storageUpdate",
"hostMigration",
"incomingPeerConnected",
"incomingPeerDisconnected",
"incomingPeerError",
Expand Down Expand Up @@ -92,12 +93,12 @@ export default class PlayPeer {
async init() {
return new Promise((resolve, reject) => {
this.destroy(); // If peer already exists, destroy
if (!this.id) console.warn(ERROR_PREFIX + "No id provided!");
if (!this.#id) console.warn(ERROR_PREFIX + "No id provided!");
if (!this.#options) console.warn(ERROR_PREFIX + "No config provided! Necessary stun and turn servers missing.");
this.#triggerEvent("status", "Initializing instance...");

try {
this.#peer = new Peer(this.id, this.#options);
this.#peer = new Peer(this.#id, this.#options);
} catch (error) {
console.error(ERROR_PREFIX + "Failed to initialize peer:", error);
this.#triggerEvent("error", "Failed to initialize peer: " + error);
Expand Down Expand Up @@ -279,7 +280,7 @@ export default class PlayPeer {
this.#maxSize = maxSize; // Store the maxSize value
this.#triggerEvent("storageUpdate", { ...this.#storage });
this.#triggerEvent("status", `Room created${maxSize ? ` with size ${maxSize}` : ''}.`);
resolve(this.id);
resolve(this.#id);
});
}

Expand Down Expand Up @@ -556,15 +557,17 @@ export default class PlayPeer {
const migrateToHostIndex = async (index) => {
if (index >= connectedPeerIds.length) return;

if (connectedPeerIds[index] === this.id) {
if (connectedPeerIds[index] === this.#id) {
this.#isHost = true;
this.#triggerEvent("status", `This peer (index ${index}) is now the host.`);
this.#outgoingConnection = null;
this.#triggerEvent("status", `This peer (index ${index}) is now the host.`);
this.#triggerEvent("hostMigration", this.#id);
} else {
this.#triggerEvent("status", `Attempting to connect to new host (index ${index}) in 1s...`);
try {
await new Promise(resolve => setTimeout(resolve, 1250));
await new Promise(resolve => setTimeout(resolve, 1250)); // Wait to give new host time to detect disconnection & open room
await this.joinRoom(connectedPeerIds[index]);
this.#triggerEvent("hostMigration", connectedPeerIds[index]);
} catch (error) {
this.#triggerEvent("error", "Error migrating host while connecting to new room: " + error);
console.warn(WARNING_PREFIX + `Error migrating host (index ${index}) while connecting to new room:`, error);
Expand All @@ -586,7 +589,7 @@ export default class PlayPeer {

// Trigger events
this.#triggerEvent("status", "Destroyed.");
this.#triggerEvent("destroy");
this.#triggerEvent("instanceDestroyed");
}

// Clear intervals
Expand Down Expand Up @@ -628,4 +631,8 @@ export default class PlayPeer {
get isHost() {
return this.#isHost;
}

get id() {
return this.#id;
}
}

0 comments on commit 55b8115

Please sign in to comment.