├── docs ├── CNAME ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── lang-css.js │ │ ├── Apache-License-2.0.txt │ │ └── prettify.js ├── styles │ ├── prettify.css │ └── jsdoc.css ├── index.html ├── Node.html ├── global.html ├── Orchestration.html └── Bucket.server.html ├── index.js ├── .gitignore ├── .npmignore ├── examples ├── browser-id │ ├── index.html │ └── index.js ├── web │ ├── index.html │ └── main.js ├── embed_get_user.js ├── realtime_server.js └── standalone_get_user.js ├── constants.js ├── src ├── auth_strategies │ ├── standalone_strategy.js │ ├── strategy.js │ ├── browser_strategy.js │ └── embed_strategy.js ├── endpoint.js ├── namespace.js ├── keymetrics.js ├── utils │ ├── websocket.js │ └── validator.js └── network.js ├── test └── keymetrics.mocha.js ├── package.json ├── .drone.jsonnet ├── LICENSE └── README.md /docs/CNAME: -------------------------------------------------------------------------------- 1 | docs.api.cloud.pm2.io -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./src/keymetrics.js') 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | out 3 | package-lock.json 4 | dist 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | apps 3 | doc 4 | pres 5 | examples 6 | docs 7 | /docs 8 | -------------------------------------------------------------------------------- /examples/browser-id/index.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/browser-id/index.js: -------------------------------------------------------------------------------- 1 | 2 | var client = new window.Keymetrics() 3 | 4 | client.use('browser', { 5 | client_id: '4228578805' 6 | }) 7 | 8 | client.user.retrieve() 9 | .then((response) => { 10 | console.log(response.data) 11 | }) 12 | -------------------------------------------------------------------------------- /examples/web/main.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | var client = new window.Keymetrics() 4 | 5 | client.use('browser', { 6 | client_id: '4228578805' 7 | }) 8 | 9 | client.user.retrieve() 10 | .then((response) => { 11 | console.log(response.data) 12 | }) 13 | 14 | 15 | client.bucket.retrieveAll() 16 | .then((res) => { 17 | var bucket = res.data[0] 18 | 19 | client.realtime.subscribe(bucket._id).catch(console.error) 20 | 21 | client.realtime.on(`${bucket.public_id}:*:status`, (status) => { 22 | console.log(status) 23 | }) 24 | }) 25 | -------------------------------------------------------------------------------- /examples/embed_get_user.js: -------------------------------------------------------------------------------- 1 | const Keymetrics = require('../index.js') 2 | 3 | let km = new Keymetrics({ 4 | OAUTH_CLIENT_ID: '9459143721' 5 | }).use('embed') 6 | 7 | km.bucket.retrieveAll() 8 | .then((res) => { 9 | console.log(res.data.map(bucket => bucket._id)) 10 | km.bucket.retrieveUsers(res.data[1]._id) 11 | .then((res) => { 12 | console.log(res.data) 13 | }) 14 | }) 15 | .catch((err) => { 16 | delete err.response.request 17 | // console.log(err.response) 18 | console.log(err.response.data) 19 | }) 20 | -------------------------------------------------------------------------------- /constants.js: -------------------------------------------------------------------------------- 1 | 2 | const pkg = require('./package.json') 3 | 4 | const config = { 5 | headers: { 6 | 'X-JS-API-Version': pkg.version 7 | }, 8 | services: { 9 | API: 'https://api.keymetrics.io', 10 | OAUTH: 'https://id.keymetrics.io' 11 | }, 12 | OAUTH_AUTHORIZE_ENDPOINT: '/api/oauth/authorize', 13 | OAUTH_CLIENT_ID: '795984050', 14 | ENVIRONNEMENT: process && process.versions && process.versions.node ? 'node' : 'browser', 15 | VERSION: pkg.version, 16 | // put in debug when using km.io with browser OR when DEBUG=true with nodejs 17 | IS_DEBUG: (typeof window !== 'undefined' && window.location.host.match(/km.(io|local)/)) || 18 | (typeof process !== 'undefined' && (process.env.DEBUG === 'true')) 19 | } 20 | 21 | module.exports = Object.assign({}, config) 22 | -------------------------------------------------------------------------------- /examples/realtime_server.js: -------------------------------------------------------------------------------- 1 | 2 | var IO = require('..') 3 | 4 | var io = new IO().use('standalone', { 5 | refresh_token: 'refresh-token' 6 | }) 7 | 8 | io.bucket.retrieveAll() 9 | .then((res) => { 10 | var bucket = res.data[0] 11 | 12 | io.realtime.subscribe(bucket._id).catch(console.error) 13 | 14 | io.realtime.on(`${bucket.public_id}:*:status`, (status) => { 15 | console.log(status) 16 | }) 17 | 18 | io.realtime.on(`${bucket.public_id}:*:human:event`, (status) => { 19 | console.log(status) 20 | }) 21 | 22 | io.realtime.on(`${bucket.public_id}:*:process:exception`, (status) => { 23 | console.log(status) 24 | }) 25 | 26 | io.realtime.on(`${bucket.public_id}:*:process:event`, (status) => { 27 | console.log(status) 28 | }) 29 | }) 30 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (function() { 3 | var source = document.getElementsByClassName('prettyprint source linenums'); 4 | var i = 0; 5 | var lineNumber = 0; 6 | var lineId; 7 | var lines; 8 | var totalLines; 9 | var anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = 'line' + lineNumber; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n"]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /examples/standalone_get_user.js: -------------------------------------------------------------------------------- 1 | const Keymetrics = require('../index.js') 2 | 3 | process.on('unhandledRejection', (reason, promise) => console.log(reason)); 4 | 5 | let km = new Keymetrics({ 6 | OAUTH_CLIENT_ID: '795984050', 7 | services: { 8 | API: 'http://cl1.km.io:3000', 9 | OAUTH: 'http://cl1.km.io:3100' 10 | } 11 | }).use('standalone', { 12 | refresh_token: '7ny9ay0lnaocpb07cboubev32ytm4w3tl2eteah5h0cbwizac9itndsnmtag2dnm' 13 | }) 14 | 15 | // retrieve our buckets 16 | km.bucket.retrieveAll() 17 | .then((res) => { 18 | let bucket = res.data.filter(bucket => bucket.public_id === '96a1ph8ymmrycwr')[0] 19 | 20 | // attach handler on specific namespaces 21 | km.realtime.on(`${bucket.public_id}:connected`, () => console.log('connected to realtime')) 22 | km.realtime.on(`96a1ph8ymmrycwr:mercury-76b7346a:status`, (data) => console.log(data)) 23 | 24 | // connect to realtime data of a bucket 25 | km.realtime.subscribe(bucket._id, (err) => console.log(err)) 26 | }) 27 | .catch((err) => { 28 | console.log(err) 29 | }) 30 | -------------------------------------------------------------------------------- /src/auth_strategies/standalone_strategy.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const AuthStrategy = require('./strategy') 5 | 6 | module.exports = class StandaloneFlow extends AuthStrategy { 7 | retrieveTokens (km, cb) { 8 | if (this._opts.refresh_token && this._opts.access_token) { 9 | // if both access and refresh tokens are provided, we are good 10 | return cb(null, { 11 | access_token: this._opts.access_token, 12 | refresh_token: this._opts.refresh_token 13 | }) 14 | } else if (this._opts.refresh_token && this._opts.client_id) { 15 | // we can also make a request to get an access token 16 | km.auth.retrieveToken({ 17 | client_id: this._opts.client_id, 18 | refresh_token: this._opts.refresh_token 19 | }).then((res) => { 20 | let tokens = res.data 21 | return cb(null, tokens) 22 | }).catch(cb) 23 | } else { 24 | // otherwise the flow isn't used correctly 25 | throw new Error(`If you want to use the standalone flow you need to provide either 26 | a refresh and access token OR a refresh token and a client id`) 27 | } 28 | } 29 | 30 | deleteTokens (km) { 31 | return km.auth.revoke 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/endpoint.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const RequestValidator = require('./utils/validator') 5 | const debug = require('debug')('kmjs:endpoint') 6 | 7 | module.exports = class Endpoint { 8 | constructor (opts) { 9 | Object.assign(this, opts) 10 | } 11 | 12 | build (http) { 13 | let endpoint = this 14 | return function () { 15 | let callsite = new Error().stack.split('\n')[2] 16 | if (callsite && callsite.length > 0) { 17 | debug(`Call to '${endpoint.route.name}' from ${callsite.replace(' at ', '')}`) 18 | } 19 | return new Promise((resolve, reject) => { 20 | RequestValidator.extract(endpoint, Array.prototype.slice.call(arguments)) 21 | .then((opts) => { 22 | // Different service than default, setup base url in url 23 | if (endpoint.service && endpoint.service.baseURL) { 24 | let base = endpoint.service.baseURL 25 | base = base[base.length - 1] === '/' ? base.substr(0, base.length - 1) : base 26 | opts.url = base + opts.url 27 | } 28 | http.request(opts).then(resolve, reject) 29 | }) 30 | .catch(reject) 31 | }) 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /docs/styles/prettify.css: -------------------------------------------------------------------------------- 1 | .pln { 2 | color: #ddd; 3 | } 4 | 5 | /* string content */ 6 | .str { 7 | color: #61ce3c; 8 | } 9 | 10 | /* a keyword */ 11 | .kwd { 12 | color: #fbde2d; 13 | } 14 | 15 | /* a comment */ 16 | .com { 17 | color: #aeaeae; 18 | } 19 | 20 | /* a type name */ 21 | .typ { 22 | color: #8da6ce; 23 | } 24 | 25 | /* a literal value */ 26 | .lit { 27 | color: #fbde2d; 28 | } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #ddd; 33 | } 34 | 35 | /* lisp open bracket */ 36 | .opn { 37 | color: #000000; 38 | } 39 | 40 | /* lisp close bracket */ 41 | .clo { 42 | color: #000000; 43 | } 44 | 45 | /* a markup tag name */ 46 | .tag { 47 | color: #8da6ce; 48 | } 49 | 50 | /* a markup attribute name */ 51 | .atn { 52 | color: #fbde2d; 53 | } 54 | 55 | /* a markup attribute value */ 56 | .atv { 57 | color: #ddd; 58 | } 59 | 60 | /* a declaration */ 61 | .dec { 62 | color: #EF5050; 63 | } 64 | 65 | /* a variable name */ 66 | .var { 67 | color: #c82829; 68 | } 69 | 70 | /* a function name */ 71 | .fun { 72 | color: #4271ae; 73 | } 74 | 75 | /* Specify class=linenums on a pre to get line numbering */ 76 | ol.linenums { 77 | margin-top: 0; 78 | margin-bottom: 0; 79 | } 80 | -------------------------------------------------------------------------------- /src/auth_strategies/strategy.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const constants = require('../../constants.js') 5 | 6 | const AuthStrategy = class AuthStrategy { 7 | constructor (opts) { 8 | this._opts = opts 9 | this.client_id = opts.client_id || opts.OAUTH_CLIENT_ID 10 | if (!this.client_id) { 11 | throw new Error('You must always provide a application id for any of the strategies') 12 | } 13 | this.scope = opts.scope || 'all' 14 | this.response_mode = opts.reponse_mode || 'query' 15 | 16 | let optsOauthEndpoint = null 17 | if (opts && opts.services) { 18 | optsOauthEndpoint = opts.services.OAUTH || opts.services.API 19 | } 20 | const oauthEndpoint = constants.services.OAUTH || constants.services.API 21 | this.oauth_endpoint = `${optsOauthEndpoint || oauthEndpoint}` 22 | if (this.oauth_endpoint[this.oauth_endpoint.length - 1] === '/' && constants.OAUTH_AUTHORIZE_ENDPOINT[0] === '/') { 23 | this.oauth_endpoint = this.oauth_endpoint.substr(0, this.oauth_endpoint.length - 1) 24 | } 25 | this.oauth_endpoint += constants.OAUTH_AUTHORIZE_ENDPOINT 26 | this.oauth_query = `?client_id=${opts.client_id}&response_mode=${this.response_mode}` + 27 | `&response_type=token&scope=${this.scope}` 28 | } 29 | 30 | retrieveTokens () { 31 | throw new Error('You need to implement a retrieveTokens function inside your strategy') 32 | } 33 | 34 | deleteTokens () { 35 | throw new Error('You need to implement a deleteTokens function inside your strategy') 36 | } 37 | 38 | static implementations (name) { 39 | const flows = { 40 | 'embed': { 41 | nodule: require('./embed_strategy'), 42 | condition: 'node' 43 | }, 44 | 'browser': { 45 | nodule: require('./browser_strategy'), 46 | condition: 'browser' 47 | }, 48 | 'standalone': { 49 | nodule: require('./standalone_strategy'), 50 | condition: null 51 | } 52 | } 53 | return name ? flows[name] : null 54 | } 55 | } 56 | 57 | module.exports = AuthStrategy 58 | -------------------------------------------------------------------------------- /test/keymetrics.mocha.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const Keymetrics = require('..') 6 | const assert = require('assert') 7 | const async = require('async') 8 | 9 | describe('Keymetrics Integration', function () { 10 | this.timeout(5000) 11 | let km = null 12 | it('should instanciate keymetrics', () => { 13 | km = new Keymetrics().use('standalone', { 14 | refresh_token: process.env.KEYMETRICS_TOKEN 15 | }) 16 | 17 | assert(km.user !== null) 18 | assert(km.bucket !== null) 19 | assert(km.data !== null) 20 | }) 21 | 22 | it('should succesfully retrieve user data', (done) => { 23 | km.user.retrieve().then((res) => { 24 | assert(res.status === 200) 25 | assert(typeof res.data.username === 'string') 26 | assert(typeof res.data._id === 'string') 27 | assert(res.data.authorized_bucket instanceof Array) 28 | return done() 29 | }).catch(done) 30 | }) 31 | 32 | it('should succesfully retrieve user buckets', (done) => { 33 | km.bucket.retrieveAll().then((res) => { 34 | assert(res.status === 200) 35 | assert(res.data instanceof Array) 36 | let bucket = res.data[0] 37 | assert(res.data.length > 0) 38 | assert(typeof bucket._id === 'string') 39 | assert(typeof bucket.name === 'string') 40 | assert(typeof bucket.public_id === 'string') 41 | assert(typeof bucket.secret_id === 'string') 42 | return done() 43 | }).catch(done) 44 | }) 45 | 46 | it('should retrieve some data from bucket', (done) => { 47 | let bucket 48 | async.series([ 49 | next => { 50 | km.bucket.retrieveAll().then(res => { 51 | bucket = res.data[0] 52 | return next() 53 | }).catch(next) 54 | }, 55 | next => { 56 | km.data.status.retrieve(bucket._id).then(res => { 57 | let status = res.data 58 | assert(res.status === 200) 59 | assert(status instanceof Array) 60 | return next() 61 | }).catch(next) 62 | } 63 | ], done) 64 | }) 65 | }) 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@pm2/js-api", 3 | "version": "0.8.0", 4 | "description": "PM2.io API Client for Javascript", 5 | "main": "index.js", 6 | "unpkg": "dist/keymetrics.es5.min.js", 7 | "engines": { 8 | "node": ">=4.0" 9 | }, 10 | "scripts": { 11 | "test": "mocha test/*", 12 | "build": "mkdir -p dist; browserify -s Keymetrics -r ./ > ./dist/keymetrics.es5.js", 13 | "dist": "mkdir -p dist; browserify -s Keymetrics -r ./ | uglifyjs -c warnings=false -m > ./dist/keymetrics.es5.min.js", 14 | "doc": "jsdoc -r ./src --readme ./README.md -d doc -t ./node_modules/minami", 15 | "clean": "rm dist/*", 16 | "prepare": "npm run build && npm run dist" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "git+https://github.com/keymetrics/km.js.git" 21 | }, 22 | "keywords": [ 23 | "keymetrics", 24 | "api", 25 | "dashboard", 26 | "monitoring", 27 | "wrapper" 28 | ], 29 | "author": "Keymetrics Team", 30 | "license": "Apache-2", 31 | "bugs": { 32 | "url": "https://github.com/keymetrics/km.js/issues" 33 | }, 34 | "homepage": "https://github.com/keymetrics/km.js#readme", 35 | "dependencies": { 36 | "async": "^2.6.3", 37 | "extrareqp2": "^1.0.0", 38 | "debug": "~4.3.1", 39 | "eventemitter2": "^6.3.1", 40 | "ws": "^7.0.0" 41 | }, 42 | "devDependencies": { 43 | "@babel/core": "^7.0.0", 44 | "@babel/preset-env": "^7.0.0", 45 | "babelify": "10.0.0", 46 | "browserify": "^17.0.0", 47 | "jsdoc": "^3.4.2", 48 | "minami": "^1.1.1", 49 | "mocha": "^7.0.0", 50 | "should": "*", 51 | "uglify-es": "~3.3.9" 52 | }, 53 | "browserify": { 54 | "debug": true, 55 | "transform": [ 56 | [ 57 | "babelify", 58 | { 59 | "presets": [ 60 | [ 61 | "@babel/preset-env", 62 | { 63 | "debug": false, 64 | "forceAllTransforms": true 65 | } 66 | ] 67 | ], 68 | "sourceMaps": true 69 | } 70 | ] 71 | ] 72 | }, 73 | "browser": { 74 | "./src/auth_strategies/embed_strategy.js": false, 75 | "ws": false 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /.drone.jsonnet: -------------------------------------------------------------------------------- 1 | local pipeline(version) = { 2 | kind: "pipeline", 3 | name: "node-v" + version, 4 | steps: [ 5 | { 6 | name: "tests", 7 | image: "node:" + version, 8 | commands: [ 9 | "npm install", 10 | "npm run test", 11 | ], 12 | environment: { 13 | NODE_ENV: "test", 14 | KEYMETRICS_TOKEN: { 15 | from_secret: "keymetrics_token", 16 | }, 17 | }, 18 | }, 19 | ], 20 | trigger: { 21 | event: ["push", "tag"] 22 | }, 23 | }; 24 | 25 | [ 26 | pipeline("10"), 27 | pipeline("12"), 28 | pipeline("14"), 29 | { 30 | kind: "pipeline", 31 | name: "build & publish", 32 | trigger: { 33 | event: "tag" 34 | }, 35 | depends_on: [ 36 | "node-v10", 37 | "node-v12", 38 | "node-v14" 39 | ], 40 | steps: [ 41 | { 42 | name: "build", 43 | image: "node:12", 44 | commands: [ 45 | "npm install 2> /dev/null", 46 | "mkdir -p dist", 47 | "npm run build", 48 | "npm run dist", 49 | ], 50 | }, 51 | { 52 | name: "publish", 53 | image: "plugins/npm", 54 | settings: { 55 | username: { 56 | from_secret: "npm_username" 57 | }, 58 | password: { 59 | from_secret: "npm_password" 60 | }, 61 | email: { 62 | from_secret: "npm_email" 63 | }, 64 | }, 65 | }, 66 | ], 67 | }, 68 | { 69 | kind: "secret", 70 | name: "npm_username", 71 | get: { 72 | path: "secret/drone/npm", 73 | name: "username", 74 | }, 75 | }, 76 | { 77 | kind: "secret", 78 | name: "npm_email", 79 | get: { 80 | path: "secret/drone/npm", 81 | name: "email", 82 | }, 83 | }, 84 | { 85 | kind: "secret", 86 | name: "npm_password", 87 | get: { 88 | path: "secret/drone/npm", 89 | name: "password", 90 | }, 91 | }, 92 | { 93 | kind: "secret", 94 | name: "keymetrics_token", 95 | get: { 96 | path: "secret/drone/keymetrics", 97 | name: "token", 98 | }, 99 | }, 100 | ] 101 | -------------------------------------------------------------------------------- /src/auth_strategies/browser_strategy.js: -------------------------------------------------------------------------------- 1 | /* global URLSearchParams, URL, localStorage */ 2 | 'use strict' 3 | 4 | const AuthStrategy = require('./strategy') 5 | 6 | module.exports = class BrowserFlow extends AuthStrategy { 7 | removeUrlToken (refreshToken) { 8 | let url = window.location.href 9 | let params = `?access_token=${refreshToken}&token_type=refresh_token` 10 | let newUrl = url.replace(params, '') 11 | window.history.pushState('', '', newUrl) 12 | } 13 | 14 | retrieveTokens (km, cb) { 15 | let verifyToken = (refresh) => { 16 | return km.auth.retrieveToken({ 17 | client_id: this.client_id, 18 | refresh_token: refresh 19 | }) 20 | } 21 | 22 | // parse the url since it can contain tokens 23 | let url = new URL(window.location) 24 | this.response_mode = this.response_mode === 'query' ? 'search' : this.response_mode 25 | let params = new URLSearchParams(url[this.response_mode]) 26 | 27 | if (params.get('access_token') !== null) { 28 | // verify that the access_token in parameters is valid 29 | verifyToken(params.get('access_token')) 30 | .then((res) => { 31 | this.removeUrlToken(res.data.refresh_token) 32 | // Save refreshToken in localstorage 33 | localStorage.setItem('km_refresh_token', params.get('access_token')) 34 | let tokens = res.data 35 | return cb(null, tokens) 36 | }).catch(cb) 37 | } else if (typeof localStorage !== 'undefined' && localStorage.getItem('km_refresh_token') !== null) { 38 | // maybe in the local storage ? 39 | verifyToken(localStorage.getItem('km_refresh_token')) 40 | .then((res) => { 41 | this.removeUrlToken(res.data.refresh_token) 42 | let tokens = res.data 43 | return cb(null, tokens) 44 | }).catch(cb) 45 | } else { 46 | // otherwise we need to get a refresh token 47 | window.location = `${this.oauth_endpoint}${this.oauth_query}&redirect_uri=${window.location}` 48 | } 49 | } 50 | 51 | deleteTokens (km) { 52 | return new Promise((resolve, reject) => { 53 | // revoke the refreshToken 54 | km.auth.revoke() 55 | .then(res => console.log('Token successfuly revoked!')) 56 | .catch(err => console.error(`Error when trying to revoke token: ${err.message}`)) 57 | // We need to remove from storage and redirect user in every case (cf. https://github.com/keymetrics/pm2-io-js-api/issues/49) 58 | // remove the token from the localStorage 59 | localStorage.removeItem('km_refresh_token') 60 | setTimeout(_ => { 61 | // redirect after few miliseconds so any user code will run 62 | window.location = `${this.oauth_endpoint}${this.oauth_query}` 63 | }, 500) 64 | return resolve() 65 | }) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/namespace.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const Endpoint = require('./endpoint') 5 | const logger = require('debug')('kmjs:namespace') 6 | 7 | module.exports = class Namespace { 8 | constructor (mapping, opts) { 9 | logger(`initialization namespace ${opts.name}`) 10 | this.name = opts.name 11 | this.http = opts.http 12 | this.endpoints = [] 13 | this.namespaces = [] 14 | 15 | logger(`building namespace ${opts.name}`) 16 | for (let name in mapping) { 17 | let child = mapping[name] 18 | if (typeof mapping === 'object' && !child.route) { 19 | // ignore the 'default' namespace that should bind to the parent namespace 20 | if (name === 'default') { 21 | // create the namespace 22 | const defaultNamespace = new Namespace(child, { name, http: this.http, services: opts.services }) 23 | this.namespaces.push(defaultNamespace) 24 | // bind property of the default namespace to this namespace 25 | for (let key in defaultNamespace) { 26 | if (key === 'name' || key === 'opts') continue 27 | this[key] = defaultNamespace[key] 28 | } 29 | continue 30 | } 31 | // if the parent namespace is a object, the child are namespace too 32 | this.addNamespace(new Namespace(child, { name, http: this.http, services: opts.services })) 33 | } else { 34 | // otherwise its an endpoint 35 | if (child.service && opts.services && opts.services[child.service.name]) { 36 | child.service.baseURL = opts.services[child.service.name] 37 | } 38 | this.addEndpoint(new Endpoint(child)) 39 | } 40 | } 41 | 42 | // logging namespaces 43 | if (this.namespaces.length > 0) { 44 | logger(`namespace ${this.name} contains namespaces : \n${this.namespaces.map(namespace => namespace.name).join('\n')}\n`) 45 | } 46 | 47 | // logging endpoints 48 | if (this.endpoints.length > 0) { 49 | logger(`Namespace ${this.name} contains endpoints : \n${this.endpoints.map(endpoint => endpoint.route.name).join('\n')}\n`) 50 | } 51 | } 52 | 53 | addNamespace (namespace) { 54 | if (!namespace || namespace.name === this.name) { 55 | throw new Error(`A namespace must not have the same name as the parent namespace`) 56 | } 57 | if (!(namespace instanceof Namespace)) { 58 | throw new Error(`addNamespace only accept Namespace instance`) 59 | } 60 | 61 | this.namespaces.push(namespace) 62 | this[namespace.name] = namespace 63 | } 64 | 65 | addEndpoint (endpoint) { 66 | if (!endpoint || endpoint.name === this.name) { 67 | throw new Error(`A endpoint must not have the same name as a namespace`) 68 | } 69 | if (!(endpoint instanceof Endpoint)) { 70 | throw new Error(`addNamespace only accept Namespace instance`) 71 | } 72 | 73 | this.endpoints.push(endpoint) 74 | this[endpoint.name] = endpoint.build(this.http) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/keymetrics.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const Namespace = require('./namespace') 5 | const constants = require('../constants') 6 | const NetworkWrapper = require('./network') 7 | const logger = require('debug')('kmjs') 8 | 9 | const Keymetrics = class Keymetrics { 10 | /** 11 | * @constructor 12 | * Keymetrics 13 | * 14 | * @param {Object} [opts] 15 | * @param {String} [opts.OAUTH_CLIENT_ID] the oauth client ID used to authenticate to KM 16 | * @param {Object} [opts.services] base url for differents services 17 | * @param {String} [opts.mappings] api mappings 18 | */ 19 | constructor (opts) { 20 | logger('init keymetrics instance') 21 | this.opts = Object.assign(constants, opts) 22 | 23 | logger('init network client (http/ws)') 24 | this._network = new NetworkWrapper(this, this.opts) 25 | 26 | const mapping = opts && opts.mappings ? opts.mappings : require('./api_mappings.json') 27 | logger(`Using mappings provided in ${opts && opts.mappings ? 'options' : 'package'}`) 28 | 29 | // build namespaces at startup 30 | logger('building namespaces') 31 | let root = new Namespace(mapping, { 32 | name: 'root', 33 | http: this._network, 34 | services: this.opts.services 35 | }) 36 | logger('exposing namespaces') 37 | for (let key in root) { 38 | if (key === 'name' || key === 'opts') continue 39 | this[key] = root[key] 40 | } 41 | logger(`attached namespaces : ${Object.keys(this)}`) 42 | 43 | this.realtime = this._network.realtime 44 | } 45 | 46 | /** 47 | * Use a specific flow to retrieve an access token on behalf the user 48 | * @param {String|Function} flow either a flow name or a custom implementation 49 | * @param {Object} [opts] 50 | * @param {String} [opts.client_id] the OAuth client ID to use to identify the application 51 | * default to the one defined when instancing Keymetrics and fallback to 795984050 (custom tokens) 52 | * @throws invalid use of this function, either the flow don't exist or isn't correctly implemented 53 | */ 54 | use (flow, opts) { 55 | logger(`using ${flow} authentication strategy`) 56 | this._network.useStrategy(flow, opts) 57 | // the logout is dependent of the auth flow so we need it to be initialize 58 | // but also we need to give the access of the instance, so we inject it here 59 | this.auth.logout = () => { 60 | return this._network.oauth_flow.deleteTokens(this) 61 | } 62 | return this 63 | } 64 | 65 | /** 66 | * API date lag, in millisecond. This is the difference between the current browser date and the 67 | * approximated API date. This is useful to compute duration between dates returned by the API 68 | * and "now". 69 | * @example 70 | * const apiDate = moment().add(km.apiDateLag) 71 | * const timeSinceLastUpdate = apiDate.diff(server.updated_at) 72 | */ 73 | get apiDateLag () { 74 | return this._network.apiDateLag 75 | } 76 | } 77 | 78 | module.exports = Keymetrics 79 | -------------------------------------------------------------------------------- /src/auth_strategies/embed_strategy.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | const AuthStrategy = require('./strategy.js') 5 | const http = require('http') 6 | const fs = require('fs') 7 | const url = require('url') 8 | const exec = require('child_process').exec 9 | const async = require('async') 10 | const path = require('path') 11 | const os = require('os') 12 | 13 | module.exports = class EmbedStrategy extends AuthStrategy { 14 | // try to find a token 15 | retrieveTokens (km, cb) { 16 | let verifyToken = (refresh) => { 17 | return km.auth.retrieveToken({ 18 | client_id: this.client_id, 19 | refresh_token: refresh 20 | }) 21 | } 22 | async.tryEach([ 23 | // try to find the token via the environement 24 | (next) => { 25 | if (!process.env.KM_TOKEN) { 26 | return next(new Error('No token in env')) 27 | } 28 | verifyToken(process.env.KM_TOKEN) 29 | .then((res) => { 30 | return next(null, res.data) 31 | }) 32 | .catch(next) 33 | }, 34 | // try to find it in the file system 35 | (next) => { 36 | fs.readFile(path.resolve(os.homedir(), '.keymetrics-tokens'), (err, tokens) => { 37 | if (err) return next(err) 38 | 39 | // verify that the token is valid 40 | tokens = JSON.parse(tokens || '{}') 41 | if (new Date(tokens.expire_at) > new Date(new Date().toISOString())) { 42 | return next(null, tokens) 43 | } 44 | 45 | verifyToken(tokens.refresh_token) 46 | .then((res) => { 47 | return next(null, res.data) 48 | }) 49 | .catch(next) 50 | }) 51 | }, 52 | // otherwise make the whole flow 53 | (next) => { 54 | return this.launch((data) => { 55 | // verify that the token is valid 56 | verifyToken(data.access_token) 57 | .then((res) => { 58 | return next(null, res.data) 59 | }) 60 | .catch(next) 61 | }) 62 | } 63 | ], (err, result) => { 64 | if (result.refresh_token) { 65 | let file = path.resolve(os.homedir(), '.keymetrics-tokens') 66 | fs.writeFile(file, JSON.stringify(result), () => { 67 | return cb(err, result) 68 | }) 69 | } else { 70 | return cb(err, result) 71 | } 72 | }) 73 | } 74 | 75 | launch (cb) { 76 | let shutdown = false 77 | let server = http.createServer((req, res) => { 78 | // only handle one request 79 | if (shutdown === true) return res.end() 80 | shutdown = true 81 | 82 | let query = url.parse(req.url, true).query 83 | 84 | res.write(` You can go back to your terminal now :) `) 85 | res.end() 86 | server.close() 87 | return cb(query) 88 | }) 89 | server.listen(43532, () => { 90 | this.open(`${this.oauth_endpoint}${this.oauth_query}`) 91 | }) 92 | } 93 | 94 | open (target, appName, callback) { 95 | let opener 96 | const escape = function (s) { 97 | return s.replace(/"/g, '\\"') 98 | } 99 | 100 | if (typeof (appName) === 'function') { 101 | callback = appName 102 | appName = null 103 | } 104 | 105 | switch (process.platform) { 106 | case 'darwin': { 107 | opener = appName ? `open -a "${escape(appName)}"` : `open` 108 | break 109 | } 110 | case 'win32': { 111 | opener = appName ? `start "" ${escape(appName)}"` : `start ""` 112 | break 113 | } 114 | default: { 115 | opener = appName ? escape(appName) : `xdg-open` 116 | break 117 | } 118 | } 119 | 120 | if (process.env.SUDO_USER) { 121 | opener = 'sudo -u ' + process.env.SUDO_USER + ' ' + opener 122 | } 123 | return exec(`${opener} "${escape(target)}"`, callback) 124 | } 125 | 126 | deleteTokens (km) { 127 | return new Promise((resolve, reject) => { 128 | // revoke the refreshToken 129 | km.auth.revoke() 130 | .then(res => { 131 | // remove the token from the filesystem 132 | let file = path.resolve(os.homedir(), '.keymetrics-tokens') 133 | fs.unlinkSync(file) 134 | return resolve(res) 135 | }).catch(reject) 136 | }) 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/utils/websocket.js: -------------------------------------------------------------------------------- 1 | /* global WebSocket */ 2 | 3 | 'use strict' 4 | 5 | const ws = require('ws') 6 | const debug = require('debug')('kmjs:network:_ws') 7 | 8 | const _WebSocket = typeof ws !== 'function' ? WebSocket : ws 9 | 10 | const defaultOptions = { 11 | debug: false, 12 | automaticOpen: true, 13 | reconnectOnError: true, 14 | reconnectInterval: 1000, 15 | maxReconnectInterval: 10000, 16 | reconnectDecay: 1, 17 | timeoutInterval: 2000, 18 | maxReconnectAttempts: Infinity, 19 | randomRatio: 3, 20 | reconnectOnCleanClose: false 21 | } 22 | 23 | const ReconnectableWebSocket = function (url, token, protocols, options) { 24 | if (!protocols) protocols = [] 25 | if (!options) options = [] 26 | 27 | this.CONNECTING = 0 28 | this.OPEN = 1 29 | this.CLOSING = 2 30 | this.CLOSED = 3 31 | 32 | this._url = url 33 | this._token = token 34 | this._protocols = protocols 35 | this._options = Object.assign({}, defaultOptions, options) 36 | this._messageQueue = [] 37 | this._reconnectAttempts = 0 38 | this.readyState = this.CONNECTING 39 | 40 | if (typeof this._options.debug === 'function') { 41 | this._debug = this._options.debug 42 | } else if (this._options.debug) { 43 | this._debug = console.log.bind(console) 44 | } else { 45 | this._debug = function () {} 46 | } 47 | 48 | if (this._options.automaticOpen) this.open() 49 | } 50 | 51 | ReconnectableWebSocket.prototype.updateAuthorization = function (authorization) { 52 | this._token = authorization 53 | } 54 | 55 | ReconnectableWebSocket.prototype.open = function () { 56 | debug('open') 57 | var socket = this._socket = new _WebSocket(`${this._url}?token=${this._token}`, this._protocols) 58 | 59 | if (this._options.binaryType) { 60 | socket.binaryType = this._options.binaryType 61 | } 62 | 63 | if (this._options.maxReconnectAttempts && this._options.maxReconnectAttempts < this._reconnectAttempts) { 64 | return this.onmaxreconnect() 65 | } 66 | 67 | this._syncState() 68 | 69 | if (socket.on) { 70 | socket.on('unexpected-response', this._onunexpectedresponse) 71 | } 72 | socket.onmessage = this._onmessage.bind(this) 73 | socket.onopen = this._onopen.bind(this) 74 | socket.onclose = this._onclose.bind(this) 75 | socket.onerror = this._onerror.bind(this) 76 | } 77 | 78 | ReconnectableWebSocket.prototype.send = function (data) { 79 | debug('send') 80 | if (this._socket && this._socket.readyState === _WebSocket.OPEN && this._messageQueue.length === 0) { 81 | this._socket.send(data) 82 | } else { 83 | this._messageQueue.push(data) 84 | } 85 | } 86 | 87 | ReconnectableWebSocket.prototype.ping = function () { 88 | debug('ping') 89 | if (this._socket.ping && this._socket && this._socket.readyState === _WebSocket.OPEN && this._messageQueue.length === 0) { 90 | this._socket.ping() 91 | } 92 | } 93 | 94 | ReconnectableWebSocket.prototype.close = function (code, reason) { 95 | debug('close') 96 | if (typeof code === 'undefined') code = 1000 97 | 98 | if (this._socket) this._socket.close(code, reason) 99 | } 100 | 101 | ReconnectableWebSocket.prototype._onunexpectedresponse = function (req, res) { 102 | debug('unexpected-response') 103 | this.onunexpectedresponse && this.onunexpectedresponse(req, res) 104 | } 105 | 106 | ReconnectableWebSocket.prototype._onmessage = function (message) { 107 | debug('onmessage') 108 | this.onmessage && this.onmessage(message) 109 | } 110 | 111 | ReconnectableWebSocket.prototype._onopen = function (event) { 112 | debug('onopen') 113 | this._syncState() 114 | this._flushQueue() 115 | if (this._reconnectAttempts !== 0) { 116 | this.onreconnect && this.onreconnect() 117 | } 118 | this._reconnectAttempts = 0 119 | 120 | this.onopen && this.onopen(event) 121 | } 122 | 123 | ReconnectableWebSocket.prototype._onclose = function (event) { 124 | debug('onclose', event) 125 | this._syncState() 126 | this._debug('WebSocket: connection is broken', event) 127 | 128 | this.onclose && this.onclose(event) 129 | 130 | this._tryReconnect(event) 131 | } 132 | 133 | ReconnectableWebSocket.prototype._onerror = function (event) { 134 | debug('onerror', event) 135 | // To avoid undetermined state, we close socket on error 136 | this._socket.close() 137 | this._syncState() 138 | 139 | this._debug('WebSocket: error', event) 140 | 141 | this.onerror && this.onerror(event) 142 | 143 | if (this._options.reconnectOnError) this._tryReconnect(event) 144 | } 145 | 146 | ReconnectableWebSocket.prototype._tryReconnect = function (event) { 147 | var self = this 148 | debug('Trying to reconnect') 149 | if (event.wasClean && !this._options.reconnectOnCleanClose) { 150 | return 151 | } 152 | setTimeout(function () { 153 | if (self.readyState === self.CLOSING || self.readyState === self.CLOSED) { 154 | self._reconnectAttempts++ 155 | self.open() 156 | } 157 | }, this._getTimeout()) 158 | } 159 | 160 | ReconnectableWebSocket.prototype._flushQueue = function () { 161 | while (this._messageQueue.length !== 0) { 162 | var data = this._messageQueue.shift() 163 | this._socket.send(data) 164 | } 165 | } 166 | 167 | ReconnectableWebSocket.prototype._getTimeout = function () { 168 | var timeout = this._options.reconnectInterval * Math.pow(this._options.reconnectDecay, this._reconnectAttempts) 169 | timeout = timeout > this._options.maxReconnectInterval ? this._options.maxReconnectInterval : timeout 170 | return this._options.randomRatio ? getRandom(timeout / this._options.randomRatio, timeout) : timeout 171 | } 172 | 173 | ReconnectableWebSocket.prototype._syncState = function () { 174 | this.readyState = this._socket.readyState 175 | } 176 | 177 | function getRandom (min, max) { 178 | return Math.random() * (max - min) + min 179 | } 180 | 181 | module.exports = ReconnectableWebSocket 182 | -------------------------------------------------------------------------------- /src/utils/validator.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | 4 | module.exports = class RequestValidator { 5 | /** 6 | * Extract httpOptions from the endpoint definition 7 | * and the data given by the user 8 | * 9 | * @param {Object} endpoint endpoint definition 10 | * @param {Array} args arguments given by the user 11 | * @return {Promise} resolve to the http options need to make the request 12 | */ 13 | static extract (endpoint, args) { 14 | let isDefined = val => val !== null && typeof val !== 'undefined' 15 | 16 | return new Promise((resolve, reject) => { 17 | let httpOpts = { 18 | params: {}, 19 | data: {}, 20 | url: endpoint.route.name + '', 21 | method: endpoint.route.type, 22 | authentication: endpoint.authentication || false 23 | } 24 | 25 | switch (endpoint.route.type) { 26 | // GET request, we assume data will only be in the query or url params 27 | case 'GET': { 28 | for (let param of (endpoint.params || [])) { 29 | let value = args.shift() 30 | // params should always be a string since they will be replaced in the url 31 | if (typeof value !== 'string' && param.optional === false) { 32 | return reject(new Error(`Expected to receive string argument for ${param.name} to match but got ${value}`)) 33 | } 34 | if (value) { 35 | // if value is given, use it 36 | httpOpts.url = httpOpts.url.replace(param.name, value) 37 | } else if (param.optional === false && param.defaultvalue !== null) { 38 | // use default value if available 39 | httpOpts.url = httpOpts.url.replace(param.name, param.defaultvalue) 40 | } 41 | } 42 | for (let param of (endpoint.query || [])) { 43 | let value = args.shift() 44 | // query should always be a string since they will be replaced in the url 45 | if (typeof value !== 'string' && param.optional === false) { 46 | return reject(new Error(`Expected to receive string argument for ${param.name} query but got ${value}`)) 47 | } 48 | // set query value 49 | if (value) { 50 | // if value is given, use it 51 | httpOpts.params[param.name] = value 52 | } else if (param.optional === false && param.defaultvalue !== null) { 53 | // use default value if available 54 | httpOpts.params[param.name] = param.defaultvalue 55 | } 56 | } 57 | break 58 | } 59 | // for PUT, POST and PATCH request, only params and body are authorized 60 | case 'PUT': 61 | case 'POST': 62 | case 'PATCH': { 63 | for (let param of (endpoint.params || [])) { 64 | let value = args.shift() 65 | // params should always be a string since they will be replaced in the url 66 | if (typeof value !== 'string' && param.optional === false) { 67 | return reject(new Error(`Expected to receive string argument for ${param.name} to match but got ${value}`)) 68 | } 69 | // replace param in url 70 | if (value) { 71 | // if value is given, use it 72 | httpOpts.url = httpOpts.url.replace(param.name, value) 73 | } else if (param.optional === false && param.defaultvalue !== null) { 74 | // use default value if available 75 | httpOpts.url = httpOpts.url.replace(param.name, param.defaultvalue) 76 | } 77 | } 78 | for (let param of (endpoint.query || [])) { 79 | let value = args.shift() 80 | // query should always be a string since they will be replaced in the url 81 | if (typeof value !== 'string' && param.optional === false) { 82 | return reject(new Error(`Expected to receive string argument for ${param.name} query but got ${value}`)) 83 | } 84 | // set query value 85 | if (value) { 86 | // if value is given, use it 87 | httpOpts.params[param.name] = value 88 | } else if (param.optional === false && param.defaultvalue !== null) { 89 | // use default value if available 90 | httpOpts.params[param.name] = param.defaultvalue 91 | } 92 | } 93 | // if we don't have any arguments, break 94 | if (args.length === 0) break 95 | let data = args[0] 96 | if (typeof data !== 'object' && endpoint.body.length > 0) { 97 | return reject(new Error(`Expected to receive an object for post data but received ${typeof data}`)) 98 | } 99 | for (let field of (endpoint.body || [])) { 100 | let isSubfield = field.name.includes('[]') === true 101 | 102 | // verify that the mandatory field are here 103 | if (!isDefined(data[field.name]) && isSubfield === false && field.optional === false && field.defaultvalue === null) { 104 | return reject(new Error(`Missing mandatory field ${field.name} to make a POST request on ${endpoint.route.name}`)) 105 | } 106 | // verify that the mandatory field are the good type 107 | if (typeof data[field.name] !== field.type && isSubfield === false && field.optional === false && field.defaultvalue === null) { // eslint-disable-line 108 | return reject(new Error(`Invalid type for field ${field.name}, expected ${field.type} but got ${typeof data[field.name]}`)) 109 | } 110 | 111 | // add it to the request only when its present 112 | if (isDefined(data[field.name])) { 113 | httpOpts.data[field.name] = data[field.name] 114 | } 115 | 116 | // or else its not optional and has a default value 117 | if (field.optional === false && field.defaultvalue !== null) { 118 | httpOpts.data[field.name] = field.defaultvalue 119 | } 120 | } 121 | break 122 | } 123 | // DELETE can have params or query parameters 124 | case 'DELETE': { 125 | for (let param of (endpoint.params || [])) { 126 | let value = args.shift() 127 | // params should always be a string since they will be replaced in the url 128 | if (typeof value !== 'string' && param.optional === false) { 129 | return reject(new Error(`Expected to receive string argument for ${param.name} to match but got ${value}`)) 130 | } 131 | // replace param in url 132 | if (value) { 133 | // if value is given, use it 134 | httpOpts.url = httpOpts.url.replace(param.name, value) 135 | } else if (param.optional === false && param.defaultvalue !== null) { 136 | // use default value if available 137 | httpOpts.url = httpOpts.url.replace(param.name, param.defaultvalue) 138 | } 139 | } 140 | for (let param of (endpoint.query || [])) { 141 | let value = args.shift() 142 | // query should always be a string 143 | if (typeof value !== 'string' && param.optional === false) { 144 | return reject(new Error(`Expected to receive string argument for ${param.name} query but got ${value}`)) 145 | } 146 | // replace param in url 147 | if (value) { 148 | // if value is given, use it 149 | httpOpts.params[param.name] = value 150 | } else if (param.optional === false && param.defaultvalue !== null) { 151 | // use default value if available 152 | httpOpts.params[param.name] = param.defaultvalue 153 | } 154 | } 155 | break 156 | } 157 | default: { 158 | return reject(new Error(`Invalid endpoint declaration, invalid method ${endpoint.route.type} found`)) 159 | } 160 | } 161 | return resolve(httpOpts) 162 | }) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c