Socket
Socket
Sign inDemoInstall

@soundworks/core

Package Overview
Dependencies
Maintainers
1
Versions
64
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@soundworks/core - npm Package Compare versions

Comparing version 3.0.0-alpha.9 to 3.0.0

client/AbstractExperience.js

103

client/Client.js

@@ -8,20 +8,19 @@ "use strict";

var _ServiceManager = _interopRequireDefault(require("./ServiceManager"));
var _PluginManager = _interopRequireDefault(require("./PluginManager.js"));
var _ClientStateManager = _interopRequireDefault(require("../common/ClientStateManager"));
var _SharedStateManagerClient = _interopRequireDefault(require("../common/SharedStateManagerClient.js"));
var _Socket = _interopRequireDefault(require("./Socket"));
var _Socket = _interopRequireDefault(require("./Socket.js"));
var _Service = _interopRequireDefault(require("./Service"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a new client of *soundworks* application.
* Create a new client of a *soundworks* application.
*
* The `Client` is the main entry point to access *soundworks* components
* such as `serviceManager` or `stateManager`. It is also responsible for
* handling initialization lifecycle (e.g. communication,
* initialization of services)
* such as {@link client.Socket}, {@link client.PluginManager} or
* {@link client.SharedStateManagerClient}. It is also responsible for the
* initialization lifecycle.
*
* @memberof @soundworks/core/client
* @memberof client
*

@@ -35,8 +34,7 @@ * @example

* await client.init(config);
* // create application specific experience
* // must extends `soundworks.Experience`
* // create application specific experience (extends `client.AbstractExperience`
* const playerExperience = new PlayerExperience(client);
* // start the client
* await client.start();
* // when everything is ready, start the experience
* // when everything is ready, the experience can be safely started
* playerExperience.start();

@@ -53,4 +51,5 @@ */

/**
* Unique session id of the client (incremeted positive number),
* Session id of the client (incremeted positive number),
* generated and retrieved by the server on start.
* The counter is reset when the server restarts.
* @type {Number}

@@ -61,4 +60,4 @@ */

/**
* Unique session uuid of the client (uuidv4),
* generated and retrieved by the server on start.
* Unique session uuid of the client (uuidv4), generated and retrieved by
* the server on start.
* @type {String}

@@ -68,9 +67,14 @@ */

this.uuid = null;
/**
* Configuration object, typically contains the configuration sent by the
* server (cf. {@link server.Server#init}).
* @see {@link server.Server#init}.
* @type {Object}
*/
this.config = {};
/**
* Socket object that handle communications with the server, if any.
* This object is automatically created if the experience requires any service
* having a server-side counterpart.
*
* @type {module:soundworks/core/client.Socket}
* Instance of the `Socket` class that handle communications with the server.
* @see {@link client.Socket}
* @type {client.Socket}
*/

@@ -80,12 +84,12 @@

/**
* @todo - serviceManager
*
* @type {module:soundworks/core/client.ServiceManager}
* Instance of the `PluginManager` class.
* @see {@link client.PluginManager}
* @type {client.PluginManager}
*/
this.serviceManager = new _ServiceManager.default(this);
this.pluginManager = new _PluginManager.default(this);
/**
* @todo - stateManager
*
* @type {module:soundworks/core/client.StateManager}
* Instance of the `SharedStateManagerClient` class.
* @see {@link client.SharedStateManagerClient}
* @type {client.SharedStateManagerClient}
*/

@@ -96,3 +100,9 @@

/**
* @todo - init
* Method to be called before {@link client.Client#start} in the
* initialization lifecycle of the soundworks client.
*
* Basically waits for the socket to be connected.
* @see {@link server.Server#init}
*
* @param {Object} config - Configuration object (cf. {@link server.Server#init})
*/

@@ -102,4 +112,8 @@

async init(config) {
if (!(Object.prototype.toString.call(config) === '[object Object]')) {
throw new Error('[soundworks.init] must receive a config object as argument`');
}
if (!('clientType' in config)) {
throw new Error('soundworks.init config object "must" define a `clientType`');
throw new Error('[soundworks.init] config object "must" define a `clientType`');
} // handle config

@@ -121,3 +135,10 @@

/**
* @todo - start
* Method to be called when {@link client.Client#init} has finished in the
* initialization lifecycle of the soundworks client.
*
* Initilialize the {@link client.SharedStateManagerClient} and all required
* plugins. When done, the {@link client.AbstractExperience#start} method
* should be consider as being safely called.
*
* @see {@link server.Server#start}
*/

@@ -132,3 +153,3 @@

Object.assign(payload, {
requiredServices: Object.keys(this.serviceManager.getValues())
requiredPlugins: Object.keys(this.pluginManager.getValues())
});

@@ -151,9 +172,9 @@ } // wait for handshake response to mark client as `ready`

};
this.stateManager = new _ClientStateManager.default(this.id, transport); // everything is ready start service manager
this.stateManager = new _SharedStateManagerClient.default(this.id, transport); // everything is ready start plugin manager
this.serviceManager.start().then(() => resolve());
this.pluginManager.start().then(() => resolve());
});
this.socket.addListener('s:client:error', err => {
switch (err.type) {
case 'services':
case 'plugins':
// can only append if env !== 'production'

@@ -171,15 +192,3 @@ const msg = `"${err.data.join(', ')}" required client-side but not server-side`;

}
/**
* @example
* ```js
* soundworks.registerService('user-defined-name', serviceFactory);
* ```
*/
registerService(name, factory = null, options = {}, dependencies = []) {
const ctor = factory(_Service.default);
this.serviceManager.register(name, ctor, options, dependencies);
}
}

@@ -186,0 +195,0 @@

@@ -6,7 +6,7 @@ "use strict";

});
exports.default = exports.Client = exports.Experience = void 0;
exports.default = exports.Client = exports.AbstractExperience = void 0;
var _Experience2 = _interopRequireDefault(require("./Experience"));
var _AbstractExperience2 = _interopRequireDefault(require("./AbstractExperience.js"));
var _Client2 = _interopRequireDefault(require("./Client"));
var _Client2 = _interopRequireDefault(require("./Client.js"));

@@ -19,3 +19,3 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

*
* @module @soundworks/core/client
* @namespace client
*

@@ -27,4 +27,4 @@ * @example

* const client = new soundworks.Client();
* // register a pre-defined or user-defined service
* client.registerService('my-service', myServiceFactory);
* // register a pre-defined or user-defined plugin
* client.registerService('my-plugin', myServiceFactory);
* // initialize the client (mainly connect and initialize WebSockets)

@@ -35,3 +35,3 @@ * await client.init(config);

* const playerExperience = new PlayerExperience(client);
* // init required services, if any
* // init required plugins, if any
* await client.start();

@@ -42,14 +42,13 @@ * // when everything is ready, start the experience

// import { default as TmpService } from './Service';
// (very) weird workaround to be able to:
//
// `import * as soundworks from '@soundworks/core/client'``
// `import soundworks from '@soundworks/core/client'``
// or
// `import { Client } from '@soundworks/core/client'`
//
const Experience = _Experience2.default; // export const Service = TmpService;
exports.Experience = Experience;
const AbstractExperience = _AbstractExperience2.default;
exports.AbstractExperience = AbstractExperience;
const Client = _Client2.default;
exports.Client = Client;
var _default = undefined;
var _default = {
AbstractExperience: _AbstractExperience2.default,
Client: _Client2.default
};
exports.default = _default;

@@ -12,3 +12,3 @@ "use strict";

var _socketsEncoderDecoder = require("../common/sockets-encoder-decoder");
var _socketsEncoderDecoder = require("../common/sockets-encoder-decoder.js");

@@ -41,5 +41,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

*
* An instance of `Socket` is automatically created by the `soundworks.Client`.
* @see {@link client.Client#socket}
*
* @see https://github.com/websockets/ws
*
* @memberof @soundworks/core/client
* @memberof client
*/

@@ -202,3 +205,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to execute when a message is received
* @param {Function} callback - Callback to execute when a message is received
*/

@@ -214,3 +217,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to remove
* @param {Function} callback - Callback to remove
*/

@@ -248,3 +251,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to execute when a message is received
* @param {Function} callback - Callback to execute when a message is received
*/

@@ -260,3 +263,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to cancel
* @param {Function} callback - Callback to cancel
*/

@@ -263,0 +266,0 @@

@@ -8,6 +8,3 @@ "use strict";

/**
*
*
*/
/** @private */
class Signal {

@@ -14,0 +11,0 @@ constructor() {

@@ -8,3 +8,3 @@ "use strict";

var _Signal = _interopRequireDefault(require("./Signal"));
var _Signal = _interopRequireDefault(require("./Signal.js"));

@@ -11,0 +11,0 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -19,5 +19,5 @@ "use strict";

const decoder = new _windowOrGlobal.default.TextDecoder('utf-8');
const types = ['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array']; // @todo - probably some room for optimizations
const types = ['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array']; // @note - probably some room for optimizations
/** private */
/** @private */

@@ -44,3 +44,3 @@ function packBinaryMessage(channel, data) {

}
/** private */
/** @private */

@@ -64,3 +64,3 @@

}
/** private */
/** @private */

@@ -71,3 +71,3 @@

}
/** private */
/** @private */

@@ -74,0 +74,0 @@

{
"name": "@soundworks/core",
"version": "3.0.0-alpha.9",
"version": "3.0.0",
"description": "full-stack javascript framework for distributed audio visual experiences on the web",

@@ -21,8 +21,6 @@ "authors": [

"clean": "rm -Rf client && rm -Rf server && rm -Rf common",
"graphs": "madge --image resources/graph-client.svg src/client && madge --image resources/graph-server.svg src/server",
"deploy": "np --yolo",
"docs:build": "vuepress build docs",
"docs": "jsdoc -c jsdoc.json",
"docs": "rm -Rf docs && jsdoc -c .jsdoc.json --verbose && cp -R assets docs/",
"prepublishOnly": "npm run build",
"version": "npm run clean && npm run build && npm run doc && git add docs",
"toc": "markdown-toc -i README.md",
"version": "npm run toc && npm run docs && git add docs",
"build:client": "babel src/client --out-dir client",

@@ -35,6 +33,7 @@ "build:server": "babel src/server --out-dir server",

"dev:common": "chokidar src/common/ -c \"npm run build:common\"",
"dev": "npm run build && concurrently \"npm run dev:client\" \"npm run dev:server\" \"npm run dev:common\""
"dev": "npm run build && (npm run dev:client & npm run dev:server & npm run dev:common)"
},
"dependencies": {
"@ircam/parameters": "^1.2.2",
"braintree-jsdoc-template": "^3.3.0",
"chalk": "^2.4.2",

@@ -46,5 +45,7 @@ "columnify": "^1.5.4",

"isomorphic-ws": "^4.0.1",
"jsdoc-template": "^1.2.0",
"keyv": "^3.1.0",
"keyv-file": "^0.1.13",
"lodash.clonedeep": "^4.5.0",
"lodash.merge": "^4.6.2",
"pem": "^1.12.5",

@@ -62,10 +63,8 @@ "polka": "^0.5.2",

"@babel/preset-env": "^7.4.5",
"@ircam/jsdoc-template": "^1.0.2",
"chokidar": "^3.0.1",
"chokidar-cli": "^1.2.2",
"concurrently": "^4.1.0",
"docdash": "^1.2.0",
"jsdoc": "^3.6.2",
"np": "^5.0.3",
"vuepress": "^1.4.0"
"markdown-toc": "^1.2.0"
}
}

@@ -7,4 +7,23 @@ # `soundworks`

## Table of Contents
<!-- toc -->
- [Documentation](#documentation)
- [API](#api)
- [Overview](#overview)
- [Installation](#installation)
- [Application Template](#application-template)
- [Academic Papers](#academic-papers)
- [Credits](#credits)
- [License](#license)
<!-- tocstop -->
## Documentation
[https://collective-soundworks.github.io](https://collective-soundworks.github.io)
## API
[http://collective-soundworks.github.io/soundworks/](http://collective-soundworks.github.io/soundworks/)

@@ -14,3 +33,3 @@

`soundworks` follows a client / server architecture where the server is written using [Node.js](https://nodejs.org/) and clients can be either regular browser clients or Node.js clients running for example on a Raspberry Pi.
`soundworks` follows a client / server architecture where the server is written using [Node.js](https://nodejs.org/) and clients can be either regular browser clients or Node.js clients running for example on a Raspberry Pi.

@@ -24,7 +43,9 @@ ![high-level-architecture](./assets/high-level-architecture.png)

- Distributed state management
`soundworks` can be extended with services to reuse common logic such as audio file loading, clock synchronisation, etc. Each service leaves in a separate repo for better modularity and to simplify version management.
`soundworks` can be extended with plugins to reuse common logic such as audio file loading, clock synchronisation, etc. Each plugin leaves in a separate repo for better modularity and to simplify version management.
## Installation
_Note: most of the time you won't need to install `soundworks` manually, consider using the [application template](#application-template) instead._
```

@@ -34,15 +55,7 @@ npm install @soundworks/core

## Getting Started
[@link to tutorial]()
## Application Template
The simplest way to start a new `soundworks` application is using the application template:
The simplest way to start a new `soundworks` application is using the application template:
[https://github.com/collective-soundworks/soundworks-template](https://github.com/collective-soundworks/soundworks-template).
## List of Available Services
@todo
## Academic Papers

@@ -56,10 +69,10 @@

`soundworks` has been initiated by [NorbertSchnell](https://github.com/NorbertSchnell), [i-Robi](https://github.com/i-Robi), and [b-ma](https://github.com/b-ma) at the [ISMM](http://ismm.ircam.fr/) team at [Ircam - Centre Pompidou](http://www.ircam.fr/) in the framework of the [*CoSiMa*](http://cosima.ircam.fr/) research project supported by the [French National Research Agency (ANR)](http://www.agence-nationale-recherche.fr/en/).
`soundworks` has been initiated by [Norbert Schnell](https://github.com/NorbertSchnell), [Sébastien Robaszkiewicz](https://github.com/i-Robi), and [Benjamin Matuszewski](https://github.com/b-ma) at the [ISMM](http://ismm.ircam.fr/) team at [Ircam - Centre Pompidou](http://www.ircam.fr/) in the framework of the [*CoSiMa*](http://cosima.ircam.fr/) research project supported by the [French National Research Agency (ANR)](http://www.agence-nationale-recherche.fr/en/).
Futher developments has been supported in the framework of:
- The [RAPID-MIX project](http://rapidmix.goldsmithsdigital.com/), funded by the European Union’s Horizon 2020 research and innovation programme.
- The Ircam project _BeCoMe_
- The [RAPID-MIX project](http://rapidmix.goldsmithsdigital.com/), funded by the European Union’s Horizon 2020 research and innovation program
- The Ircam project _BeCoMe_
- The _Constella(c)tions_ residency of the STARTS program of the European Commission.
Development is pursued in the [Interaction Music Mouvement Team](https://www.stms-lab.fr/team/interaction-son-musique-mouvement/) from the Ircam's STMS-LAB.
Development is pursued, led by Benjamin Matuszewski, in the [Interaction Music Movement Team](https://www.stms-lab.fr/team/interaction-son-musique-mouvement/) from the Ircam's STMS-LAB.

@@ -66,0 +79,0 @@ ## License

@@ -22,3 +22,3 @@ "use strict";

*
* @memberof @soundworks/core/server
* @memberof server
*/

@@ -28,21 +28,17 @@

/**
* @param {String} clientType - Client type of the connected client.
* @param {Socket} socket - Socket object used to comminuate with the client.
* @private
* @param {String} clientType - Type of the client
* @param {server.Socket} socket - Socket connection with the client
*/
constructor(clientType, socket) {
/**
* Client type (specified when initializing the {@link client} object on the client side with {@link client.init}).
* @name type
* Client type, as specified when initializing the client side {@link client.Client}.
*
* @see {@link client.Client#init}
* @type {String}
* @memberof module:soundworks/server.Client
* @instance
*/
this.type = clientType;
/**
* Unique session id (ever increasing number)
* @name id
* Session id (incremeted positive number).
* The counter is reset when the server restarts.
* @type {Number}
* @memberof module:soundworks/server.Client
* @instance
*/

@@ -53,6 +49,3 @@

* Unique session id (uuidv4).
* @name uuid
* @type {String}
* @memberof module:soundworks/server.Client
* @instance
*/

@@ -62,5 +55,4 @@

/**
* Socket used to communicate with the client.
* @type {Socket}
* @private
* Socket connection with the remote {@link client.Client}.
* @type {server.Socket}
*/

@@ -72,2 +64,3 @@

* Destroy the client.
* @private
*/

@@ -74,0 +67,0 @@

@@ -6,19 +6,45 @@ "use strict";

});
Object.defineProperty(exports, "Server", {
enumerable: true,
get: function () {
return _Server.default;
}
});
Object.defineProperty(exports, "Experience", {
enumerable: true,
get: function () {
return _Experience.default;
}
});
exports.default = exports.Server = exports.AbstractExperience = void 0;
var _Server = _interopRequireDefault(require("./Server"));
var _Server2 = _interopRequireDefault(require("./Server.js"));
var _Experience = _interopRequireDefault(require("./Experience"));
var _AbstractExperience2 = _interopRequireDefault(require("./AbstractExperience.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Server-side part of the *soundworks* framework.
*
* @namespace server
*
* @example
* import soundworks from '@soundworks/core/server';
*
* const server = new soundworks.Server();
*
* server.registerService('delay-1', delayServiceFactory, { delayTime: 1 }, []);
* server.registerService('delay-2', delayServiceFactory, { delayTime: 2 }, ['delay-1']);
*
* await server.init(envConfig, (clientType, config, httpRequest) => {
* return { ...clientConfig };
* });
*
* // serve static files
* await server.router.use(serveStatic('public'));
* await server.router.use('build', serveStatic('.build/public'));
*
* const playerExperience = new PlayerExperience(server, 'player');
*
* await server.start();
* playerExperience.start();
*
*/
const AbstractExperience = _AbstractExperience2.default;
exports.AbstractExperience = AbstractExperience;
const Server = _Server2.default;
exports.Server = Server;
var _default = {
AbstractExperience: _AbstractExperience2.default,
Client: _Server2.default
};
exports.default = _default;

@@ -28,16 +28,14 @@ "use strict";

var _Client = _interopRequireDefault(require("./Client"));
var _Client = _interopRequireDefault(require("./Client.js"));
var _Service = _interopRequireDefault(require("./Service"));
var _PluginManager = _interopRequireDefault(require("./PluginManager.js"));
var _ServiceManager = _interopRequireDefault(require("./ServiceManager"));
var _Sockets = _interopRequireDefault(require("./Sockets.js"));
var _Sockets = _interopRequireDefault(require("./Sockets"));
var _SharedStateManagerServer = _interopRequireDefault(require("../common/SharedStateManagerServer.js"));
var _ServerStateManager = _interopRequireDefault(require("../common/ServerStateManager"));
var _Db = _interopRequireDefault(require("./utils/Db.js"));
var _Db = _interopRequireDefault(require("./Db"));
var _logger = _interopRequireDefault(require("./utils/logger.js"));
var _logger = _interopRequireDefault(require("./utils/logger"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -52,3 +50,3 @@

*
* @memberof @soundworks/core/server
* @memberof server
*

@@ -66,3 +64,4 @@ * @example

/**
* Configuration informations. Defaults to:
* Configuration informations.
* Defaults to:
* ```

@@ -91,5 +90,7 @@ * {

this.router = null;
this.router = (0, _polka.default)(); // compression (must be set before serve-static)
this.router.use((0, _compression.default)());
/**
* http(s) server instance. The node `http` or `https` module instance
* Http(s) server instance. The node `http` or `https` module instance
* (cf. {@link https://nodejs.org/api/http.html})

@@ -105,7 +106,8 @@ */

this.db = null;
this.db = new _Db.default();
/**
* Wrapper around `ws` server.
* cf. {@link @soundworks/core/server.Sockets}
* @type {soundworks/core/server.Sockets}
* The {@link server.Sockets} instance. A small wrapper around
* [`ws`](https://github.com/websockets/ws) server.
* @see {@link server.Sockets}
* @type {server.Sockets}
*/

@@ -115,17 +117,40 @@

/**
* The `serviceManager` instance.
* cf. {@link @soundworks/core/server.ServiceManager}
* @type {soundworks/core/server.ServiceManager}
* The {@link server.PluginManager} instance.
* @see {@link server.PluginManager}
* @type {server.PluginManager}
*/
this.serviceManager = new _ServiceManager.default(this);
this.pluginManager = new _PluginManager.default(this);
/**
* The `StateManager` instance.
* cf. {@link @soundworks/core/server.StateManager}
* @type {soundworks/core/server.StateManager}
* The {@link server.SharedStateManagerServer} instance.
* @see {@link server.SharedStateManagerServer}
* @type {server.SharedStateManagerServer}
*/
this.stateManager = null;
this.stateManager = new _SharedStateManagerServer.default();
/**
* key and certificates (may be generated and self-signed) for https server.
* Template engine that should implement a `compile` method.
* @type {Object}
*/
this.templateEngine = null;
/**
* Path to the directory containing the templates.
* Any filename corresponding to a registered browser client type will be used
* in priority, if not present fallback to `default`, i.e `${clientType}.tmpl`
* fallbacks to `default.tmpl`. Template files should have the `.tmpl` extension.
* @param {String}
*/
this.templateDirectory = null; // private stuff
/**
* Required activities that must be started. Only used in Experience
* and Plugin - do not expose.
* @private
*/
this.activities = new Set();
/**
* Key and certificates (may be generated and self-signed) for https server.
* @todo - put in config...

@@ -143,9 +168,2 @@ * @private

/**
* Required activities that must be started. Only used in Experience
* and Service - do not expose.
* @private
*/
this.activities = new Set();
/**
* Optionnal routing defined for each client.

@@ -167,22 +185,48 @@ * @type {Object}

/**
*
* server config:
*
* @param {String} [options.defaultClient='player'] - Client that can access
* the application at its root url.
* @param {String} [options.env='development']
* @param {String} [options.port=8000] - Port on which the http(s) server will
* listen
* @param {Boolean} [options.useHttps=false] - Define wheter to use or not an
* an https server.
* @param {Object} [options.httpsInfos=null] - if `useHttps` is `true`, object
* that give the path to `cert` and `key` files (`{ cert, key }`). If `null`
* an auto generated certificate will be generated, be aware that browsers
* will consider the application as not safe in the case.
* @param {Object} [options.websocket={}] - TBD
* @param {String} [options.templateDirectory='src/server/tmpl'] - Folder in
* which the server will look for the `index.html` template.
*
* @param {Function} clientConfigFunction -
*/
*
* Method to be called before `start` in the initialization lifecycle of the
* soundworks server.
*
* @param {Object} config
* @param {String} [config.defaultClient='player'] - Client that can access
* the application at its root url.
* @param {String} [config.env='development']
* @param {String} [config.port=8000] - Port on which the http(s) server will
* listen
* @param {Boolean} [config.useHttps=false] - Define wheter to use or not an
* an https server.
* @param {Object} [config.httpsInfos=null] - if `useHttps` is `true`, object
* that give the path to `cert` and `key` files (`{ cert, key }`). If `null`
* an auto generated certificate will be generated, be aware that browsers
* will consider the application as not safe in the case.
* @param {Object} [config.websocket={}] - TBD
* @param {String} [config.templateDirectory='src/server/tmpl'] - Folder in
* which the server will look for the `index.html` template.
*
* @param {Function} clientConfigFunction - function that filters / defines
* the configuration object that will be sent to a connecting client.
*
* @example
* // defaults to
* await server.init(
* {
* env: {
* type: 'development',
* port: 8000,
* "websockets": {
* "path": "socket",
* "pingInterval": 5000
* },
* "useHttps": false,
* },
* app: {
* name: 'soundworks',
* author: 'someone'
* }
* },
* (clientType, serverConfig, httpRequest) => {
* return { clientType, ...serverConfig };
* }
* );
*/

@@ -206,27 +250,13 @@

})) {
// must be done this way to keep the instance shared (??)
this.config = config;
this._clientConfigFunction = clientConfigFunction;
this.serviceManager.init(); // allows to hook middleware and routes (e.g. cors) in the router
// between `server.init` and `server.start`
this.router = (0, _polka.default)(); // compression (must be set before serve-static)
this.router.use((0, _compression.default)());
this.stateManager = new _ServerStateManager.default(); // const transport = new EventEmitter();
// transport.send = transport.emit.bind(transport);
// serverStateManager.addClient({ id: -1, transport });
// this.stateManager = new ClientStateManager(-1, transport);
// // should be a mixin
// this.stateManager.registerSchema = (name, schema) => {
// serverStateManager.registerSchema(name, schema);
// }
// this.stateManager.deleteSchema = (name, schema) => {
// serverStateManager.deleteSchema(name, schema);
// }
this.db = new _Db.default();
return Promise.resolve();
}
/**
* Method to be called when `init` step is done in the initialization
* lifecycle of the soundworks server. Basically initialize plugins,
* define the routing and start the http-server.
*/
async start() {

@@ -326,4 +356,8 @@ try {

}).then(() => {
if (this._htmlTemplateConfig.engine === null || this._htmlTemplateConfig.directory === null) {
throw new Error('Invalid html template configuration, please call `server.configureHtmlTemplates(engine, directory)`');
if (this.templateEngine === null) {
throw new Error('Undefined "server.templateEngine": please provide a valid template engine');
}
if (this.templateDirectory === null) {
throw new Error('Undefined "server.templateDirectory": please provide a valid template directory');
} // ------------------------------------------------------------

@@ -382,3 +416,3 @@ // INIT ROUTING

// ------------------------------------------------------------
return this.serviceManager.start();
return this.pluginManager.start();
}).then(() => {

@@ -409,3 +443,3 @@ // ------------------------------------------------------------

});
await this.serviceManager.start();
await this.pluginManager.start();
return Promise.resolve();

@@ -417,30 +451,2 @@ } catch (err) {

/**
* @example
* ```js
* soundworks.registerService(serviceFactory); // do not document that, maybe remove
* // or
* soundworks.registerService('user-defined-name', serviceFactory);
* ```
*/
registerService(name, factory = null, config = {}, deps = []) {
const ctor = factory(_Service.default);
this.serviceManager.register(name, ctor, config, deps);
}
/**
* Configure html template informations
* @param {Object} engine - Template engine that should implement a `compile` method.
* @param {String} directory - Path to the directory containing the templates,
* any filename corresponding to a registered browser client type will be used
* in priority, in not present fallback to `default` (i.e `${clientType}.tmpl`
* with fallback to `default.tmpl`. Template files must have the `.tmpl` extension.
*/
configureHtmlTemplates(engine, directory) {
this._htmlTemplateConfig.engine = engine;
this._htmlTemplateConfig.directory = directory;
}
/**
* Open the route for the given client.

@@ -463,3 +469,3 @@ * @private

const templateDirectory = this._htmlTemplateConfig.directory;
const templateDirectory = this.templateDirectory;

@@ -483,5 +489,4 @@ const clientTmpl = _path.default.join(templateDirectory, `${clientType}.tmpl`);

const tmpl = this._htmlTemplateConfig.engine.compile(tmplString); // http request
const tmpl = this.templateEngine.compile(tmplString); // http request
router.get(route, (req, res) => {

@@ -514,19 +519,19 @@ const data = this._clientConfigFunction(clientType, this.config, req);

socket.addListener('s:client:handshake', data => {
// in development, if service required client-side but not server-side,
// in development, if plugin required client-side but not server-side,
// complain properly client-side.
if (this.config.env.type !== 'production') {
// check coherence between client-side and server-side service requirements
const clientRequiredServices = data.requiredServices || [];
const serverRequiredServices = this.serviceManager.getRequiredServices(clientType);
const missingServices = [];
clientRequiredServices.forEach(serviceId => {
if (serverRequiredServices.indexOf(serviceId) === -1) {
missingServices.push(serviceId);
// check coherence between client-side and server-side plugin requirements
const clientRequiredPlugins = data.requiredPlugins || [];
const serverRequiredPlugins = this.pluginManager.getRequiredPlugins(clientType);
const missingPlugins = [];
clientRequiredPlugins.forEach(pluginId => {
if (serverRequiredPlugins.indexOf(pluginId) === -1) {
missingPlugins.push(pluginId);
}
});
if (missingServices.length > 0) {
if (missingPlugins.length > 0) {
const err = {
type: 'services',
data: missingServices
type: 'plugins',
data: missingPlugins
};

@@ -533,0 +538,0 @@ socket.send('s:client:error', err);

@@ -8,3 +8,3 @@ "use strict";

var _socketsEncoderDecoder = require("../common/sockets-encoder-decoder");
var _socketsEncoderDecoder = require("../common/sockets-encoder-decoder.js");

@@ -20,16 +20,14 @@ const noop = () => {};

/**
* Simple wrapper with simple pubsub system built on top of `ws` socket.
* The abstraction actually contains two different socket:
* Simple wrapper with simple pubsub system built on top of `ws` sockets.
* The abstraction contains two different socket:
* - one configured for string (JSON compatible) messages
* - one configured with `binaryType=arraybuffer` for streaming data more
* efficiently.
* The socket re-emits all "native" ws events.
*
* @see https://github.com/websockets/ws
*
* @memberof @soundworks/core/server
* @memberof server
*/
class Socket {
/** @private */
constructor(ws, binaryWs, rooms, sockets, options = {}) {

@@ -39,6 +37,3 @@ /**

* broadcasting from a given socket instance.
* @type {module:soundworks/server.sockets}
* @name sockets
* @instance
* @memberof module:soundworks/server.Socket
* @type {server.Sockets}
* @example

@@ -52,5 +47,2 @@ * socket.sockets.broadcast('my-room', this, 'update-value', 1);

* @type {Object}
* @name _ws
* @instance
* @memberof module:soundworks/server.Socket
*/

@@ -63,5 +55,2 @@

* @type {Object}
* @name _binaryWs
* @instance
* @memberof module:soundworks/server.Socket
*/

@@ -74,5 +63,2 @@

* @type {Map}
* @name _rooms
* @instance
* @memberof module:soundworks/server.Socket
*/

@@ -84,5 +70,2 @@

* @type {Object}
* @name _config
* @instance
* @memberof module:soundworks/server.Socket
*/

@@ -249,3 +232,3 @@

*
* @param {String} channel - The channel of the message
* @param {String} channel - Channel of the message
* @param {...*} args - Arguments of the message (as many as needed, of any type)

@@ -267,3 +250,3 @@ */

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to execute when a message is received
* @param {Function} callback - Callback to execute when a message is received
*/

@@ -279,3 +262,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to cancel
* @param {Function} callback - Callback to cancel
*/

@@ -317,3 +300,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to execute when a message is received
* @param {Function} callback - Callback to execute when a message is received
*/

@@ -329,3 +312,3 @@

* @param {String} channel - Channel of the message
* @param {...*} callback - Callback to cancel
* @param {Function} callback - Callback to cancel
*/

@@ -332,0 +315,0 @@

@@ -12,3 +12,3 @@ "use strict";

var _Socket = _interopRequireDefault(require("./Socket"));
var _Socket = _interopRequireDefault(require("./Socket.js"));

@@ -18,10 +18,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
* Internal base class for services and scenes.
* Websocket server that creates and host all {@link server.Socket} instance.
*
* @todo - remove all `send`, `addListener`, `removeListener` methods,
* use `client.socket` instead.
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* will be more simple to document.
*
* @memberof @soundworks/core/server
* @memberof server
*/

@@ -127,3 +124,3 @@ class Sockets {

*
* @param {Socket} module:soundworks/server.Socket - Socket to register in the room.
* @param {server.Socket} socket - Socket to add to the room.
* @param {String} roomId - Id of the room

@@ -139,3 +136,3 @@ */

*
* @param {Socket} module:soundworks/server.Socket - Socket to register in the room.
* @param {server.Socket} socket - Socket to remove from the room.
* @param {String} [roomId=null] - Id of the room

@@ -154,3 +151,3 @@ */

* the message. If null the message is sent to all clients
* @param {module:soundworks/server.Socket} excludeSocket - Optionnal
* @param {server.Socket} excludeSocket - Optionnal
* socket to ignore when broadcasting the message, typically the client

@@ -172,3 +169,3 @@ * at the origin of the message

* the message. If null the message is sent to all clients
* @param {module:soundworks/server.Socket} excludeSocket - Optionnal
* @param {server.Socket} excludeSocket - Optionnal
* socket to ignore when broadcasting the message, typically the client

@@ -175,0 +172,0 @@ * at the origin of the message

@@ -66,11 +66,16 @@ "use strict";

// serviceStart(name) {
// console.log(` ${name} ${chalk.cyan('start')}`);
// },
serviceStarted(name) {
console.log(` ${name} ${_chalk.default.cyan('started...')}`);
pluginStart(name) {
console.log(` ${name} ${_chalk.default.yellow('start...')}`);
},
serviceReady(name) {
pluginStarted(name) {
console.log(` ${name} ${_chalk.default.cyan('started')}`);
},
pluginReady(name) {
console.log(` ${name} ${_chalk.default.green('ready')}`);
},
pluginErrored(name) {
console.log(` ${name} ${_chalk.default.red('errors')}`);
}

@@ -77,0 +82,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc