Skip to content

Commit

Permalink
add support for custom url builder. auto-detect when hosted under Dis…
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Jul 12, 2024
1 parent d9be33a commit 88a0ae2
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 6 deletions.
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": "colyseus.js",
"version": "0.15.24",
"version": "0.15.25",
"description": "Colyseus Multiplayer SDK for JavaScript/TypeScript",
"author": "Endel Dreyer",
"license": "MIT",
Expand Down
24 changes: 24 additions & 0 deletions src/3rd_party/discord.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Discord Embedded App SDK
* https://github.com/colyseus/colyseus/issues/707
*
* All URLs must go through the local proxy from
* https://<app_id>.discordsays.com/<backend>/...
*
* You must configure your URL Mappings with:
* - /colyseus/{subdomain} -> {subdomain}.colyseus.cloud
*
* Example:
* const client = new Client("https://xxxx.colyseus.cloud");
*
*/
export function discordURLBuilder (url: URL): string {
const localHostname = window?.location?.hostname || "localhost";

const remoteHostnameSplitted = url.hostname.split('.');
const subdomain = (remoteHostnameSplitted.length > 2)
? `/${remoteHostnameSplitted[0]}`
: '';

return `${url.protocol}//${localHostname}/colyseus${subdomain}${url.pathname}${url.search}`;
}
31 changes: 28 additions & 3 deletions src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Room, RoomAvailable } from './Room';
import { SchemaConstructor } from './serializer/SchemaSerializer';
import { HTTP } from "./HTTP";
import { Auth } from './Auth';
import { discordURLBuilder } from './3rd_party/discord';

export type JoinOptions = any;

Expand Down Expand Up @@ -33,8 +34,12 @@ export class Client {
public auth: Auth;

protected settings: EndpointSettings;
protected urlBuilder: (url: URL) => string;

constructor(settings: string | EndpointSettings = DEFAULT_ENDPOINT) {
constructor(
settings: string | EndpointSettings = DEFAULT_ENDPOINT,
customURLBuilder?: (url: URL) => string
) {
if (typeof (settings) === "string") {

//
Expand Down Expand Up @@ -74,6 +79,20 @@ export class Client {

this.http = new HTTP(this);
this.auth = new Auth(this.http);

this.urlBuilder = customURLBuilder;

//
// Discord Embedded SDK requires a custom URL builder
//
if (
!this.urlBuilder &&
typeof (window) !== "undefined" &&
window?.location?.hostname?.includes("discordsays.com")
) {
this.urlBuilder = discordURLBuilder;
console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder.");
}
}

public async joinOrCreate<T>(roomName: string, options: JoinOptions = {}, rootSchema?: SchemaConstructor<T>) {
Expand Down Expand Up @@ -231,12 +250,18 @@ export class Client {
endpoint += `${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;
}

return `${endpoint}/${room.processId}/${room.roomId}?${params.join('&')}`;
const endpointURL = `${endpoint}/${room.processId}/${room.roomId}?${params.join('&')}`;
return (this.urlBuilder)
? this.urlBuilder(new URL(endpointURL))
: endpointURL;
}

protected getHttpEndpoint(segments: string = '') {
const path = segments.startsWith("/") ? segments : `/${segments}`;
return `${(this.settings.secure) ? "https" : "http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${path}`;
const endpointURL = `${(this.settings.secure) ? "https" : "http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${path}`;
return (this.urlBuilder)
? this.urlBuilder(new URL(endpointURL))
: endpointURL;
}

protected getEndpointPort() {
Expand Down
37 changes: 37 additions & 0 deletions test/client_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import './util';
import { assert } from "chai";
import { Client } from "../src";
import { Schema, type } from '@colyseus/schema';
import { discordURLBuilder } from '../src/3rd_party/discord';

describe("Client", function () {
let client: Client;
Expand Down Expand Up @@ -68,6 +69,42 @@ describe("Client", function () {
assert.strictEqual(expected.wsEndpointPublicAddress, clientWithSettings['buildEndpoint'](roomWithPublicAddress));
}
});

it("discord url builder", () => {
const room = { roomId: "roomId", processId: "processId", sessionId: "sessionId", };
const roomWithPublicAddress = { publicAddress: "node-1.colyseus.cloud", roomId: "roomId", processId: "processId", sessionId: "sessionId", };

const settingsByUrl = {
'ws://example.com': {
httpEndpoint: "http://localhost/colyseus/",
wsEndpoint: "ws://localhost/colyseus/processId/roomId",
wsEndpointPublicAddress: "ws://localhost/colyseus/node-1/processId/roomId"
},
'ws://subdomain.colyseus.cloud': {
httpEndpoint: "http://localhost/colyseus/subdomain/",
wsEndpoint: "ws://localhost/colyseus/subdomain/processId/roomId",
wsEndpointPublicAddress: "ws://localhost/colyseus/node-1/processId/roomId"
},
'https://subdomain.colyseus.cloud/custom/path': {
httpEndpoint: "https://localhost/colyseus/subdomain/custom/path/",
wsEndpoint: "wss://localhost/colyseus/subdomain/custom/path/processId/roomId",
wsEndpointPublicAddress: "wss://localhost/colyseus/node-1/processId/roomId"
},
// '/api': {
// httpEndpoint: "http://127.0.0.1:2567/api/",
// wsEndpoint: "ws://127.0.0.1:2567/api/processId/roomId",
// wsEndpointPublicAddress: "ws://node-1.colyseus.cloud/processId/roomId"
// },
};

for (const url in settingsByUrl) {
const expected = settingsByUrl[url];
const client = new Client(url, discordURLBuilder);
assert.strictEqual(expected.httpEndpoint, client['getHttpEndpoint']());
assert.strictEqual(expected.wsEndpoint, client['buildEndpoint'](room));
assert.strictEqual(expected.wsEndpointPublicAddress, client['buildEndpoint'](roomWithPublicAddress));
}
});
});

xit("join", function () {
Expand Down

0 comments on commit 88a0ae2

Please sign in to comment.