commit 0289cc3ee5add8b806f3e8090d510380cedb826e Author: Julien Fontanet Date: Sat Jul 26 10:15:29 2014 +0200 Initial commit. diff --git a/packages/xo-lib/.editorconfig b/packages/xo-lib/.editorconfig new file mode 100644 index 000000000..e35119a31 --- /dev/null +++ b/packages/xo-lib/.editorconfig @@ -0,0 +1,12 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +trim_trailing_whitespaces = true diff --git a/packages/xo-lib/.gitignore b/packages/xo-lib/.gitignore new file mode 100644 index 000000000..2ccbe4656 --- /dev/null +++ b/packages/xo-lib/.gitignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/packages/xo-lib/.jshintrc b/packages/xo-lib/.jshintrc new file mode 100644 index 000000000..efb65216f --- /dev/null +++ b/packages/xo-lib/.jshintrc @@ -0,0 +1,118 @@ +{ + // -------------------------------------------------------------------- + // JSHint Configuration, Node.js Edition + // -------------------------------------------------------------------- + // + // This is an options template for [JSHint][1], forked from + // haschek's [JSHint template][2]: + // + // * the environment has been changed to `node`; + // * recent options were added; + // * coding style has been adapted to node (e.g. 2 spaces + // indenting, global use strict). + // + // [1]: http://www.jshint.com/ + // [2]: https://gist.github.com/haschek/2595796 + // + // @author Julien Fontanet + // @license http://unlicense.org/ + + // == Enforcing Options =============================================== + // + // These options tell JSHint to be more strict towards your code. Use + // them if you want to allow only a safe subset of JavaScript, very + // useful when your codebase is shared with a big number of developers + // with different skill levels. + + "bitwise" : true, // Prohibit bitwise operators (&, |, ^, etc.). + "camelcase" : true, // Require variable names to use either camelCase or UPPER_CASE styles. + "curly" : true, // Require {} for every new block or scope. + "eqeqeq" : true, // Require triple equals i.e. `===`. + "forin" : true, // Tolerate `for in` loops without `hasOwnPrototype`. + "freeze" : true, // Prohibit modification of native objects' prototypes. + "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` + "indent" : 2, // Specify indentation spacing + "latedef" : true, // Prohibit variable use before definition. + "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`. + "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`. + "noempty" : true, // Prohibit use of empty blocks. + "nonew" : true, // Prohibit use of constructors for side-effects. + "plusplus" : false, // Prohibit the use of `++` & `--`. + "quotmark" : "'", // Require single quotes. + "undef" : true, // Require all non-global variables be declared before they are used. + "unused" : true, // Prohibit unused variables. + "strict" : true, // Require `use strict` pragma in every function. + "trailing" : true, // Prohibit trailing whitespaces. + "maxparams" : 4, // Prohibit more than 4 parameters per function definition. + "maxdepth" : 3, // Prohibit nesting more than 3 control blocks. + "maxstatements" : 20, // Prohibit more than 20 statements per function. + "maxcomplexity" : 7, // Prohibit having to much branches in your code. + "maxlen" : 80, // Prohibit line with more than 80 characters. + + // == Relaxing Options ================================================ + // + // These options allow you to suppress certain types of warnings. Use + // them only if you are absolutely positive that you know what you are + // doing. + + "asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons). + "boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments. + "debug" : false, // Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // Tolerate use of `== null`. + "esnext" : false, // Allow ES.next specific features such as `const` and `let`. + "evil" : false, // Tolerate use of `eval`. + "expr" : true, // Tolerate `ExpressionStatement` as Programs. (Allowed for Mocha.) + "funcscope" : false, // Tolerate declarations of variables inside of control structures while accessing them later from the outside. + "gcl" : false, // Makes JSHint compatible with Google Closure Compiler. + "globalstrict" : true, // Allow global "use strict" (also enables 'strict'). + "iterator" : false, // Allow usage of __iterator__ property. + "lastsemic" : false, // Tolerate missing semicolons when the it is omitted for the last statement in a one-line block. + "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons. + "laxcomma" : false, // Suppress warnings about comma-first coding style. + "loopfunc" : false, // Allow functions to be defined within loops. + "maxerr" : 50, // Maximum errors before stopping. + "moz" : false, // Tolerate Mozilla JavaScript extensions. + "notypeof" : false, // Tolerate invalid typeof values. + "multistr" : false, // Tolerate multi-line strings. + "proto" : false, // Tolerate __proto__ property. This property is deprecated. + "scripturl" : false, // Tolerate script-targeted URLs. + "smarttabs" : false, // Tolerate mixed tabs and spaces when the latter are used for alignment only. + "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`. + "sub" : false, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`. + "supernew" : false, // Tolerate `new function () { ... };` and `new Object;`. + "validthis" : false, // Tolerate strict violations when the code is running in strict mode and you use this in a non-constructor function. + + // == Environments ==================================================== + // + // These options pre-define global variables that are exposed by + // popular JavaScript libraries and runtime environments—such as + // browser or node.js. + + "browser" : false, // Standard browser globals e.g. `window`, `document`. + "couch" : false, // Enable globals exposed by CouchDB. + "devel" : false, // Allow development statements e.g. `console.log();`. + "dojo" : false, // Enable globals exposed by Dojo Toolkit. + "jquery" : false, // Enable globals exposed by jQuery JavaScript library. + "mocha" : true, // Enable globals exposed by the mocha test runner. + "mootools" : false, // Enable globals exposed by MooTools JavaScript framework. + "node" : true, // Enable globals available when code is running inside of the NodeJS runtime environment. + "nonstandard" : false, // Define non-standard but widely adopted globals such as escape and unescape. + "phantom" : false, // Enable globals exposed by PhantomJS. + "prototypejs" : false, // Enable globals exposed by Prototype JavaScript framework. + "rhino" : false, // Enable globals available when your code is running inside of the Rhino runtime environment. + "worker" : false, // Enable globals exposed when running inside a Web Worker. + "wsh" : false, // Enable globals available when your code is running as a script for the Windows Script Host. + "yui" : false, // Enable globals exposed by YUI. + + // == JSLint Legacy =================================================== + // + // These options are legacy from JSLint. Aside from bug fixes they will + // not be improved in any way and might be removed at any point. + + "nomen" : false, // Prohibit use of initial or trailing underbars in names. + "onevar" : false, // Allow only one `var` statement per function. + "passfail" : false, // Stop on first error. + "white" : false, // Check against strict whitespace and indentation rules. + + "globals": {} +} diff --git a/packages/xo-lib/README.md b/packages/xo-lib/README.md new file mode 100644 index 000000000..4f045eaec --- /dev/null +++ b/packages/xo-lib/README.md @@ -0,0 +1,58 @@ +# xo-lib + +[![Build Status](https://img.shields.io/travis/vatesfr/xo-lib/master.svg)](http://travis-ci.org/vatesfr/xo-lib) +[![Dependency Status](https://david-dm.org/vatesfr/xo-lib/status.svg?theme=shields.io)](https://david-dm.org/vatesfr/xo-lib) +[![devDependency Status](https://david-dm.org/vatesfr/xo-lib/dev-status.svg?theme=shields.io)](https://david-dm.org/vatesfr/xo-lib#info=devDependencies) + +> Library to connect to XO-Server. + + +## Install + +Download [manually](https://github.com/vatesfr/xo-lib/releases) or with package-manager. + +#### [npm](https://npmjs.org/package/xo-lib) + +``` +npm install --save xo-lib +``` + +#### bower + +``` +bower install --save xo-lib +``` + +## Example + +```javascript +var Xo = require('xo-lib'); + +var xo = new Xo('https://xo.company.tld/api/'); + +xo.call('session.signInWithPassword', { + email: 'admin@admin.net', + password: 'admin', +}).then(function () { + return xo.call('session.getUser'); +}).then(function (user) { + console.log(user); + + xo.close(); +}); +``` + +## Contributions + +Contributions are *very* welcomed, either on the documentation or on +the code. + +You may: + +- report any [issue](https://github.com/vatesfr/xo-lib/issues) + you've encountered; +- fork and create a pull request. + +## License + +ISC © [Vates SAS](http://vates.fr) diff --git a/packages/xo-lib/index.js b/packages/xo-lib/index.js new file mode 100644 index 000000000..74b155e7c --- /dev/null +++ b/packages/xo-lib/index.js @@ -0,0 +1,153 @@ +'use strict'; + +//==================================================================== + +var assign = require('lodash.assign'); +var forEach = require('lodash.foreach'); + +var Promise = require('bluebird'); + +// Support browsers. +var WebSocket = (function (root) { + return (root && 'WebSocket' in root) ? + root.WebSocket : + require('ws') + ; +})(this); + +//==================================================================== + +var notConnected = function () { + throw new Error('not connected'); +}; + +//==================================================================== + +var Xo = function (url) { + this._url = url; + + // Identifier of the next request. + this._nextId = 0; + + // Promises linked to the requests. + this._deferreds = {}; + + // Current WebSocket. + this._socket = null; + + // Current status which may be: + // - disconnected + // - connecting + // - connected + this.status = 'disconnected'; +}; + +assign(Xo.prototype, { + close: function () { + if (this._socket) + { + this._socket.close(); + } + }, + + connect: function () { + if (this.status === 'connected') + { + return Promise.cast(); + } + + var deferred = Promise.defer(); + + this.status = 'connecting'; + + var socket = this._socket = new WebSocket(this._url); + + // When the socket opens, send any queued requests. + socket.on('open', function () { + this.status = 'connected'; + + // (Re)Opens accesses. + delete this.send; + + // Resolves the promise. + deferred.resolve(); + }.bind(this)); + + socket.on('message', function (data) { + // `ws` API is lightly different from standard API. + if (data.data) + { + data = data.data; + } + + // TODO: Wraps in a promise to prevent releasing the Zalgo. + var response = JSON.parse(data); + + var id = response.id; + + var deferred = this._deferreds[id]; + if (!deferred) + { + // Response already handled. + return; + } + delete this._deferreds[id]; + + if ('error' in response) + { + return deferred.reject(response.error); + } + + if ('result' in response) + { + return deferred.resolve(response.result); + } + + deferred.reject({ + message: 'invalid response received', + object: response, + }); + }.bind(this)); + + socket.on('close', function () { + // Closes accesses. + this.send = notConnected; + + // Fails all waiting requests. + forEach(this._deferreds, function (deferred) { + deferred.reject('not connected'); + }); + this._deferreds = {}; + }.bind(this)); + + socket.on('error', function (error) { + // Fails the connect promise if possible. + deferred.reject(error); + }); + + return deferred.promise; + }, + + call: function (method, params) { + return this.connect().then(function () { + var socket = this._socket; + + var id = this._nextId++; + + socket.send(JSON.stringify({ + jsonrpc: '2.0', + id: id, + method: method, + params: params || [], + })); + + var deferred = this._deferreds[id] = Promise.defer(); + + return deferred.promise; + }.bind(this)); + }, +}); + +//==================================================================== + +module.exports = Xo; diff --git a/packages/xo-lib/package.json b/packages/xo-lib/package.json new file mode 100644 index 000000000..7d121e530 --- /dev/null +++ b/packages/xo-lib/package.json @@ -0,0 +1,33 @@ +{ + "name": "xo-lib", + "version": "0.0.0", + "description": "Library to connect to XO-Server", + "keywords": [ + "xen", + "orchestra", + "xen-orchestra" + ], + "repository": { + "type": "git", + "url": "https://github.com/vatesfr/xo-lib" + }, + "author": { + "name": "Julien Fontanet", + "email": "julien.fontanet@vates.fr" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "test": "gulp test" + }, + "files": [ + "index.js" + ], + "dependencies": { + "bluebird": "^2.2.2", + "lodash.assign": "^2.4.1", + "lodash.foreach": "^2.4.1", + "ws": "^0.4.31" + } +}