Conveying messages over MQTT protocol, in Node.JS.

@namespace webduino.transport
@class NodeMqttTransport
@constructor
@param {Object} options Options to build a proper transport
@extends webduino.Transport
547279
function NodeMqttTransport(options) {
  Transport.call(this, options);

  this._options = options;
  this._client = null;
  this._sendTimer = null;
  this._buf = [];

  this._status = '';

  this._connHandler = onConnect.bind(this);
  this._messageHandler = onMessage.bind(this);
  this._sendOutHandler = sendOut.bind(this);
  this._disconnHandler = onDisconnect.bind(this);
  this._errorHandler = onError.bind(this);

  init(this);
}
891292
function SocketServices( options ){
	options = options || {};

	var self = this;

	this.logger = Logger.createLogger( 'socket', {'socket-services': VERSION}, options.logger );

	self.server = options.server || { };

	this.messageValidator = options.messageValidator || isCommunication;

	this.channel = options.channel || 'api';
	this.event = options.event || 'rester';

	self.logger.info('Will accepting communication on channel \'' + self.channel + '\' emitting to event \'' + self.event + '\'' );

	this.inflicter = new Inflicter( { logger: self.logger, idLength: options.idLength || 16 } );

	self.logger.info( 'Event system activated.' );
}
680208
function SockJS(url, protocols, options) {
  if (!(this instanceof SockJS)) {
    return new SockJS(url, protocols, options);
  }
  if (arguments.length < 1) {
    throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  }
  EventTarget.call(this);

  this.readyState = SockJS.CONNECTING;
  this.extensions = '';
  this.protocol = '';

  // non-standard extension
  options = options || {};
  if (options.protocols_whitelist) {
    log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  }
  this._transportsWhitelist = options.transports;
  this._transportOptions = options.transportOptions || {};

  var sessionId = options.sessionId || 8;
  if (typeof sessionId === 'function') {
    this._generateSessionId = sessionId;
  } else if (typeof sessionId === 'number') {
    this._generateSessionId = function() {
      return random.string(sessionId);
    };
  } else {
    throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  }

  this._server = options.server || random.numberString(1000);

  // Step 1 of WS spec - parse and validate the url. Issue #8
  var parsedUrl = new URL(url);
  if (!parsedUrl.host || !parsedUrl.protocol) {
    throw new SyntaxError("The URL '" + url + "' is invalid");
  } else if (parsedUrl.hash) {
    throw new SyntaxError('The URL must not contain a fragment');
  } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
    throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  }

  var secure = parsedUrl.protocol === 'https:';
  // Step 2 - don't allow secure origin with an insecure protocol
  if (loc.protocol === 'https:' && !secure) {
    throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  }

  // Step 3 - check port access - no need here
  // Step 4 - parse protocols argument
  if (!protocols) {
    protocols = [];
  } else if (!Array.isArray(protocols)) {
    protocols = [protocols];
  }

  // Step 5 - check protocols argument
  var sortedProtocols = protocols.sort();
  sortedProtocols.forEach(function(proto, i) {
    if (!proto) {
      throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
    }
    if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
      throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
    }
  });

  // Step 6 - convert origin
  var o = urlUtils.getOrigin(loc.href);
  this._origin = o ? o.toLowerCase() : null;

  // remove the trailing slash
  parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));

  // store the sanitized url
  this.url = parsedUrl.href;

  // Step 7 - start connection in background
  // obtain server info
  // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  this._urlInfo = {
    nullOrigin: !browser.hasDomain()
  , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  };

  this._ir = new InfoReceiver(this.url, this._urlInfo);
  this._ir.once('finish', this._receiveInfo.bind(this));
}
336708
function publish(topic, msg) {
  if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') {
    throw new Error('A `topic` (string) and `msg` (object) property must be defined');
  }

  if (module.exports.client && BUS_MODULE) {
    module.exports.client.publish(`${NAMESPACE}:${topic}`, msg);
  } else if (module.exports.client) {
    module.exports.client.publish(`${NAMESPACE}:${topic}`, JSON.stringify(msg));
  }
}
996097
function MSPassportStrategy(options) {
  Strategy.call(this);
  this.name = "mspassport";
  
  var default_options = {
        protocol : "querystring",
        protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") }        
  };
    
  this.options = _defaults(default_options, options);
}
608879
function bridge(destination, options) {
  return transformer

  function transformer(node, file, next) {
    destination.run(mdast2hast(node, options), file, done)

    function done(err) {
      next(err)
    }
  }
}
77302
function (msgStr) {
            if (this._ws) {
                // See comment in `connect()` above about why we wrap the message in a transport message
                // object.
                this._ws.send(JSON.stringify({
                    type: "message",
                    message: msgStr
                }));
            } else {
                console.log("[Brackets LiveDev] Tried to send message over closed connection: " + msgStr);
            }
        }
255952
function resolve(opt) {
	if (opt instanceof Transporters.Base) {
		return opt;
	} else if (_.isString(opt)) {
		let TransporterClass = getByName(opt);
		if (TransporterClass)
			return new TransporterClass();

		if (opt.startsWith("nats://"))
			TransporterClass = Transporters.NATS;
		else if (opt.startsWith("mqtt://") || opt.startsWith("mqtts://"))
			TransporterClass = Transporters.MQTT;
		else if (opt.startsWith("redis://") || opt.startsWith("rediss://"))
			TransporterClass = Transporters.Redis;
		else if (opt.startsWith("amqp://") || opt.startsWith("amqps://"))
			TransporterClass = Transporters.AMQP;
		else if (opt.startsWith("kafka://"))
			TransporterClass = Transporters.Kafka;
		else if (opt.startsWith("stan://"))
			TransporterClass = Transporters.STAN;
		else if (opt.startsWith("tcp://"))
			TransporterClass = Transporters.TCP;

		if (TransporterClass)
			return new TransporterClass(opt);
		else
			throw new BrokerOptionsError(`Invalid transporter type '${opt}'.`, { type: opt });

	} else if (_.isObject(opt)) {
		let TransporterClass = getByName(opt.type || "NATS");

		if (TransporterClass)
			return new TransporterClass(opt.options);
		else
			throw new BrokerOptionsError(`Invalid transporter type '${opt.type}'.`, { type: opt.type });
	}

	return null;
}
809928
function MQTTMsgBusStatusInNode(config) {
        RED.nodes.createNode(this, config)

        this.qos = parseInt(config.qos)

        if (isNaN(this.qos) || this.qos < 0 || this.qos > 2) {
            this.qos = 2
        }

        this.source = config.source
        
        if (typeof this.source === 'undefined'){
            this.source = "+"
        } else if (this.source == "") {
            this.source = "+"
        }

        this.client     = config.client
        this.clientConn = RED.nodes.getNode(this.client)

        this.broker     = this.clientConn.broker
        this.brokerConn = RED.nodes.getNode(this.broker)

        var node = this

        if (this.brokerConn) {
            this.status({fill:"red", shape:"ring", text:"node-red:common.status.disconnected"})

            this.topic = topicStatusSubscribe(this.clientConn, this.source)

            node.brokerConn.register(this)

            this.brokerConn.subscribe(this.topic, this.qos, function(topic, payload, packet) {
                onStatusHandler(node, node.brokerConn, topic, payload)
            }, this.id)

            if (this.brokerConn.connected) {
                node.status({fill:"green", shape:"dot", text:"node-red:common.status.connected"})
            }

            this.on('close', function(done) {
                if (node.brokerConn) {
                    node.brokerConn.unsubscribe(node.topic, node.id)
                    node.brokerConn.deregister(node, done)
                }
            })
        } else {
            this.error(RED._("msgbus.errors.missing-config"))
        }
    }
126039
function amqpResponderNode(config) {

        RED.nodes.createNode(this, config);

        // get endpoint configuration
        this.endpoint = RED.nodes.getNode(config.endpoint);
        // get all other configuration
        this.address = config.address;

        var node = this;
        // node not yet connected
        this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });

        if (this.endpoint) {

            node.endpoint.connect(function(connection) {
                setup(connection);
            });

            /**
             * Node setup for creating receiver link for receiving the request
             * and the sender for sending reply
             *
             * @param connection    Connection instance
             */
            function setup(connection) {

                var request = undefined;
                var reply_to = undefined;
                var response = undefined;

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                node.sender = node.connection.open_sender({ target: {} });

                // build receiver options
                var receiver_options = {
                    source: {
                        address: node.address
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {

                    // save request and reply_to address on AMQP message received
                    request = context.message;
                    reply_to = request.reply_to;

                    // provides the request and delivery as node output
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (reply_to) {

                            // fill the response with the provided one as input
                            response = msg.payload;
                            response.to = reply_to;

                            node.sender.send(response);
                        }
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })

            }

        }
    }
415757
function(options) {

    var self = this;

    console.log('options are', options);

    this.connected = false;

    this.config = this.getConfig(options);

    this.cbSocketWrapper = new CBSocketWrapper(this.config);

    this.cbSocketWrapper.on('connect', function(message) {
        self.connected = true;
        self.emit('connect');
        logger.log('debug', 'Client connect');
    });

    this.cbSocketWrapper.on('disconnect', function(message) {
        self.connected = false;
        self.emit('disconnect');
    });

    this.cbSocketWrapper.on('message', function(message) {

        self.emit('message', message);

        var source = message.get('source');
        self.emit(source, message);
        //logger.info('CB => Client: ', message)
    });

    // Restart connection process on 'giveUp'
    this.cbSocketWrapper.on('fail', function() {
        self.cbSocketWrapper.giveUp();
        self.connect();
    });

    this.faultTolerantAuth = retry.operation()

    this.connect();
}
767232
function createMiddleware(options) {
  /**
   * Express middleware handling Git (Smart) Transfer Protocol requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols
   * @see https://github.com/git/git/blob/master/Documentation/technical/http-protocol.txt
   */
  return (req, res, next) => {
    const { owner, repo } = req.params;

    const repPath = resolveRepositoryPath(options, owner, repo);
    const reqStream = req.headers['content-encoding'] === 'gzip' ? req.pipe(zlib.createGunzip()) : req;
    reqStream.pipe(backend(req.originalUrl, (err, service) => {
      if (err) {
        logger.error(err);
        next(err);
        return;
      }

      res.setHeader('content-type', service.type);
      logger.info(service.action, repo, service.fields);

      const ps = spawn(service.cmd, service.args.concat(repPath));
      ps.stdout.pipe(service.createStream()).pipe(ps.stdin);
    })).pipe(res);
  };
}
497695
function( options ) {
  this.options = options;
  this.wpt = new WPT( this.options.wpt.server );

  this.data  = [];
  this.queue = new Queue();
}
448768
function MQTTMsgBusDebugInNode(config) {
        RED.nodes.createNode(this, config)

        this.qos = 0
        this.source = config.source
        
        if (typeof this.source === 'undefined'){
            this.source = "+"
        } else if (this.source == "") {
            this.source = "+"
        }

        this.client     = config.client
        this.clientConn = RED.nodes.getNode(this.client)

        this.broker     = this.clientConn.broker
        this.brokerConn = RED.nodes.getNode(this.broker)

        var node = this

        if (this.brokerConn) {
            this.status({fill:"red", shape:"ring", text:"node-red:common.status.disconnected"})

            this.topic = topicDebugSubscribe(this.clientConn, this.source)

            node.brokerConn.register(this)

            this.brokerConn.subscribe(this.topic, this.qos, function(topic, payload, packet) {
                onDebugHandler(node, node.brokerConn, topic, payload)
            }, this.id)

            if (this.brokerConn.connected) {
                node.status({fill:"green", shape:"dot", text:"node-red:common.status.connected"})
            }

            this.on('close', function(done) {
                if (node.brokerConn) {
                    node.brokerConn.unsubscribe(node.topic, node.id)
                    node.brokerConn.deregister(node, done)
                }
            })
        } else {
            this.error(RED._("msgbus.errors.missing-config"))
        }

    }
101898
function init(options) {
  options = options || {}
  var port = options.port || 6466
  global.client = global.client || socketIOClient(`http://localhost:${port}`)
  client = global.client
  log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
  client.emit('join', ioid) // first join for serialization
  client.on('disconnect', client.disconnect)
  client.on('take', hasher.handle) // add listener
  
  // add methods
  client.pass = pass
  client.clientPass = clientPass
  return client
}
1117144
function WebServer(options) {
  EventEmitter.call(this);

  this._options = options;

  this._username = options['username'];
  this._ip = options['ip'];
  this._port = options['port'];
  this._secret = options['secret'];
  this._triggerString = options['trigger_string'];

  this._server = null;
}
371257
function send() {
  var message = arguments.length <= 0 || arguments[0] === undefined ? 'hello mqtt-controls' : arguments[0];
  var topic = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];

  var t = undefined;
  if (topic === null) {
    t = topics.publish;
  } else {
    t = topic;
  }
  client.publish(t, message);
}