How to use this._server.open method in Cypress

Best JavaScript code snippet using cypress

faye-node.js

Source:faye-node.js Github

copy

Full Screen

1var Faye = (typeof Faye === 'object') ? Faye : {};2if (typeof window !== 'undefined') window.Faye = Faye;3Faye.extend = function(dest, source, overwrite) {4 if (!source) return dest;5 for (var key in source) {6 if (!source.hasOwnProperty(key)) continue;7 if (dest.hasOwnProperty(key) && overwrite === false) continue;8 if (dest[key] !== source[key])9 dest[key] = source[key];10 }11 return dest;12};13Faye.extend(Faye, {14 VERSION: '0.8.0',15 16 BAYEUX_VERSION: '1.0',17 ID_LENGTH: 128,18 JSONP_CALLBACK: 'jsonpcallback',19 CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'],20 21 MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],22 23 ENV: (function() { return this })(),24 25 random: function(bitlength) {26 bitlength = bitlength || this.ID_LENGTH;27 if (bitlength > 32) {28 var parts = Math.ceil(bitlength / 32),29 string = '';30 while (parts--) string += this.random(32);31 return string;32 }33 var limit = Math.pow(2, bitlength) - 1,34 maxSize = limit.toString(36).length,35 string = Math.floor(Math.random() * limit).toString(36);36 37 while (string.length < maxSize) string = '0' + string;38 return string;39 },40 41 copyObject: function(object) {42 var clone, i, key;43 if (object instanceof Array) {44 clone = [];45 i = object.length;46 while (i--) clone[i] = Faye.copyObject(object[i]);47 return clone;48 } else if (typeof object === 'object') {49 clone = {};50 for (key in object) clone[key] = Faye.copyObject(object[key]);51 return clone;52 } else {53 return object;54 }55 },56 57 commonElement: function(lista, listb) {58 for (var i = 0, n = lista.length; i < n; i++) {59 if (this.indexOf(listb, lista[i]) !== -1)60 return lista[i];61 }62 return null;63 },64 65 indexOf: function(list, needle) {66 if (list.indexOf) return list.indexOf(needle);67 68 for (var i = 0, n = list.length; i < n; i++) {69 if (list[i] === needle) return i;70 }71 return -1;72 },73 74 map: function(object, callback, context) {75 if (object.map) return object.map(callback, context);76 var result = [];77 78 if (object instanceof Array) {79 for (var i = 0, n = object.length; i < n; i++) {80 result.push(callback.call(context || null, object[i], i));81 }82 } else {83 for (var key in object) {84 if (!object.hasOwnProperty(key)) continue;85 result.push(callback.call(context || null, key, object[key]));86 }87 }88 return result;89 },90 91 filter: function(array, callback, context) {92 var result = [];93 for (var i = 0, n = array.length; i < n; i++) {94 if (callback.call(context || null, array[i], i))95 result.push(array[i]);96 }97 return result;98 },99 100 asyncEach: function(list, iterator, callback, context) {101 var n = list.length,102 i = -1,103 calls = 0,104 looping = false;105 var iterate = function() {106 calls -= 1;107 i += 1;108 if (i === n) return callback && callback.call(context);109 iterator(list[i], resume);110 };111 var loop = function() {112 if (looping) return;113 looping = true;114 while (calls > 0) iterate();115 looping = false;116 };117 var resume = function() {118 calls += 1;119 loop();120 };121 resume();122 },123 124 // http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/125 toJSON: function(object) {126 if (this.stringify)127 return this.stringify(object, function(key, value) {128 return (this[key] instanceof Array)129 ? this[key]130 : value;131 });132 133 return JSON.stringify(object);134 },135 136 timestamp: function() {137 var date = new Date(),138 year = date.getFullYear(),139 month = date.getMonth() + 1,140 day = date.getDate(),141 hour = date.getHours(),142 minute = date.getMinutes(),143 second = date.getSeconds();144 145 var pad = function(n) {146 return n < 10 ? '0' + n : String(n);147 };148 149 return pad(year) + '-' + pad(month) + '-' + pad(day) + ' ' +150 pad(hour) + ':' + pad(minute) + ':' + pad(second);151 }152});153Faye.Class = function(parent, methods) {154 if (typeof parent !== 'function') {155 methods = parent;156 parent = Object;157 }158 159 var klass = function() {160 if (!this.initialize) return this;161 return this.initialize.apply(this, arguments) || this;162 };163 164 var bridge = function() {};165 bridge.prototype = parent.prototype;166 167 klass.prototype = new bridge();168 Faye.extend(klass.prototype, methods);169 170 return klass;171};172Faye.Namespace = Faye.Class({173 initialize: function() {174 this._used = {};175 },176 177 exists: function(id) {178 return this._used.hasOwnProperty(id);179 },180 181 generate: function() {182 var name = Faye.random();183 while (this._used.hasOwnProperty(name))184 name = Faye.random();185 return this._used[name] = name;186 },187 188 release: function(id) {189 delete this._used[id];190 }191});192Faye.Error = Faye.Class({193 initialize: function(code, params, message) {194 this.code = code;195 this.params = Array.prototype.slice.call(params);196 this.message = message;197 },198 199 toString: function() {200 return this.code + ':' +201 this.params.join(',') + ':' +202 this.message;203 }204});205Faye.Error.parse = function(message) {206 message = message || '';207 if (!Faye.Grammar.ERROR.test(message)) return new this(null, [], message);208 var parts = message.split(':'),209 code = parseInt(parts[0]),210 params = parts[1].split(','),211 message = parts[2];212 return new this(code, params, message);213};214Faye.Error.versionMismatch = function() {215 return new this(300, arguments, "Version mismatch").toString();216};217Faye.Error.conntypeMismatch = function() {218 return new this(301, arguments, "Connection types not supported").toString();219};220Faye.Error.extMismatch = function() {221 return new this(302, arguments, "Extension mismatch").toString();222};223Faye.Error.badRequest = function() {224 return new this(400, arguments, "Bad request").toString();225};226Faye.Error.clientUnknown = function() {227 return new this(401, arguments, "Unknown client").toString();228};229Faye.Error.parameterMissing = function() {230 return new this(402, arguments, "Missing required parameter").toString();231};232Faye.Error.channelForbidden = function() {233 return new this(403, arguments, "Forbidden channel").toString();234};235Faye.Error.channelUnknown = function() {236 return new this(404, arguments, "Unknown channel").toString();237};238Faye.Error.channelInvalid = function() {239 return new this(405, arguments, "Invalid channel").toString();240};241Faye.Error.extUnknown = function() {242 return new this(406, arguments, "Unknown extension").toString();243};244Faye.Error.publishFailed = function() {245 return new this(407, arguments, "Failed to publish").toString();246};247Faye.Error.serverError = function() {248 return new this(500, arguments, "Internal server error").toString();249};250Faye.Deferrable = {251 callback: function(callback, context) {252 if (!callback) return;253 254 if (this._deferredStatus === 'succeeded')255 return callback.apply(context, this._deferredArgs);256 257 this._callbacks = this._callbacks || [];258 this._callbacks.push([callback, context]);259 },260 261 timeout: function(seconds, message) {262 var _this = this;263 var timer = Faye.ENV.setTimeout(function() {264 _this.setDeferredStatus('failed', message);265 }, seconds * 1000);266 this._timer = timer;267 },268 269 errback: function(callback, context) {270 if (!callback) return;271 if (this._deferredStatus === 'failed')272 return callback.apply(context, this._deferredArgs);273 this._errbacks = this._errbacks || [];274 this._errbacks.push([callback, context]);275 },276 setDeferredStatus: function() {277 if (this._timer)278 Faye.ENV.clearTimeout(this._timer);279 var args = Array.prototype.slice.call(arguments),280 status = args.shift(),281 callbacks;282 283 this._deferredStatus = status;284 this._deferredArgs = args;285 286 if (status === 'succeeded')287 callbacks = this._callbacks;288 else if (status === 'failed')289 callbacks = this._errbacks;290 291 if (!callbacks) return;292 293 var callback;294 while (callback = callbacks.shift())295 callback[0].apply(callback[1], this._deferredArgs);296 }297};298Faye.Publisher = {299 countListeners: function(eventType) {300 if (!this._subscribers || !this._subscribers[eventType]) return 0;301 return this._subscribers[eventType].length;302 },303 304 bind: function(eventType, listener, context) {305 this._subscribers = this._subscribers || {};306 var list = this._subscribers[eventType] = this._subscribers[eventType] || [];307 list.push([listener, context]);308 },309 310 unbind: function(eventType, listener, context) {311 if (!this._subscribers || !this._subscribers[eventType]) return;312 313 if (!listener) {314 delete this._subscribers[eventType];315 return;316 }317 var list = this._subscribers[eventType],318 i = list.length;319 320 while (i--) {321 if (listener !== list[i][0]) continue;322 if (context && list[i][1] !== context) continue;323 list.splice(i,1);324 }325 },326 327 trigger: function() {328 var args = Array.prototype.slice.call(arguments),329 eventType = args.shift();330 331 if (!this._subscribers || !this._subscribers[eventType]) return;332 333 var listeners = this._subscribers[eventType],334 listener;335 336 for (var i = 0, n = listeners.length; i < n; i++) {337 listener = listeners[i];338 listener[0].apply(listener[1], args);339 }340 }341};342Faye.Timeouts = {343 addTimeout: function(name, delay, callback, context) {344 this._timeouts = this._timeouts || {};345 if (this._timeouts.hasOwnProperty(name)) return;346 var self = this;347 this._timeouts[name] = Faye.ENV.setTimeout(function() {348 delete self._timeouts[name];349 callback.call(context);350 }, 1000 * delay);351 },352 353 removeTimeout: function(name) {354 this._timeouts = this._timeouts || {};355 var timeout = this._timeouts[name];356 if (!timeout) return;357 clearTimeout(timeout);358 delete this._timeouts[name];359 }360};361Faye.Logging = {362 LOG_LEVELS: {363 error: 3,364 warn: 2,365 info: 1,366 debug: 0367 },368 369 logLevel: 'error',370 371 log: function(messageArgs, level) {372 if (!Faye.logger) return;373 374 var levels = Faye.Logging.LOG_LEVELS;375 if (levels[Faye.Logging.logLevel] > levels[level]) return;376 377 var messageArgs = Array.prototype.slice.apply(messageArgs),378 banner = ' [' + level.toUpperCase() + '] [Faye',379 klass = this.className,380 381 message = messageArgs.shift().replace(/\?/g, function() {382 try {383 return Faye.toJSON(messageArgs.shift());384 } catch (e) {385 return '[Object]';386 }387 });388 389 for (var key in Faye) {390 if (klass) continue;391 if (typeof Faye[key] !== 'function') continue;392 if (this instanceof Faye[key]) klass = key;393 }394 if (klass) banner += '.' + klass;395 banner += '] ';396 397 Faye.logger(Faye.timestamp() + banner + message);398 }399};400(function() {401 for (var key in Faye.Logging.LOG_LEVELS)402 (function(level, value) {403 Faye.Logging[level] = function() {404 this.log(arguments, level);405 };406 })(key, Faye.Logging.LOG_LEVELS[key]);407})();408Faye.Grammar = {409 LOWALPHA: /^[a-z]$/,410 UPALPHA: /^[A-Z]$/,411 ALPHA: /^([a-z]|[A-Z])$/,412 DIGIT: /^[0-9]$/,413 ALPHANUM: /^(([a-z]|[A-Z])|[0-9])$/,414 MARK: /^(\-|\_|\!|\~|\(|\)|\$|\@)$/,415 STRING: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,416 TOKEN: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,417 INTEGER: /^([0-9])+$/,418 CHANNEL_SEGMENT: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,419 CHANNEL_SEGMENTS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,420 CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,421 WILD_CARD: /^\*{1,2}$/,422 CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,423 VERSION_ELEMENT: /^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,424 VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,425 CLIENT_ID: /^((([a-z]|[A-Z])|[0-9]))+$/,426 ID: /^((([a-z]|[A-Z])|[0-9]))+$/,427 ERROR_MESSAGE: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,428 ERROR_ARGS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,429 ERROR_CODE: /^[0-9][0-9][0-9]$/,430 ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/431};432Faye.Extensible = {433 addExtension: function(extension) {434 this._extensions = this._extensions || [];435 this._extensions.push(extension);436 if (extension.added) extension.added(this);437 },438 439 removeExtension: function(extension) {440 if (!this._extensions) return;441 var i = this._extensions.length;442 while (i--) {443 if (this._extensions[i] !== extension) continue;444 this._extensions.splice(i,1);445 if (extension.removed) extension.removed(this);446 }447 },448 449 pipeThroughExtensions: function(stage, message, callback, context) {450 this.debug('Passing through ? extensions: ?', stage, message);451 if (!this._extensions) return callback.call(context, message);452 var extensions = this._extensions.slice();453 454 var pipe = function(message) {455 if (!message) return callback.call(context, message);456 457 var extension = extensions.shift();458 if (!extension) return callback.call(context, message);459 460 if (extension[stage]) extension[stage](message, pipe);461 else pipe(message);462 };463 pipe(message);464 }465};466Faye.extend(Faye.Extensible, Faye.Logging);467Faye.Channel = Faye.Class({468 initialize: function(name) {469 this.id = this.name = name;470 },471 472 push: function(message) {473 this.trigger('message', message);474 },475 476 isUnused: function() {477 return this.countListeners('message') === 0;478 }479});480Faye.extend(Faye.Channel.prototype, Faye.Publisher);481Faye.extend(Faye.Channel, {482 HANDSHAKE: '/meta/handshake',483 CONNECT: '/meta/connect',484 SUBSCRIBE: '/meta/subscribe',485 UNSUBSCRIBE: '/meta/unsubscribe',486 DISCONNECT: '/meta/disconnect',487 488 META: 'meta',489 SERVICE: 'service',490 491 expand: function(name) {492 var segments = this.parse(name),493 channels = ['/**', name];494 495 var copy = segments.slice();496 copy[copy.length - 1] = '*';497 channels.push(this.unparse(copy));498 499 for (var i = 1, n = segments.length; i < n; i++) {500 copy = segments.slice(0, i);501 copy.push('**');502 channels.push(this.unparse(copy));503 }504 505 return channels;506 },507 508 isValid: function(name) {509 return Faye.Grammar.CHANNEL_NAME.test(name) ||510 Faye.Grammar.CHANNEL_PATTERN.test(name);511 },512 513 parse: function(name) {514 if (!this.isValid(name)) return null;515 return name.split('/').slice(1);516 },517 518 unparse: function(segments) {519 return '/' + segments.join('/');520 },521 522 isMeta: function(name) {523 var segments = this.parse(name);524 return segments ? (segments[0] === this.META) : null;525 },526 527 isService: function(name) {528 var segments = this.parse(name);529 return segments ? (segments[0] === this.SERVICE) : null;530 },531 532 isSubscribable: function(name) {533 if (!this.isValid(name)) return null;534 return !this.isMeta(name) && !this.isService(name);535 },536 537 Set: Faye.Class({538 initialize: function() {539 this._channels = {};540 },541 542 getKeys: function() {543 var keys = [];544 for (var key in this._channels) keys.push(key);545 return keys;546 },547 548 remove: function(name) {549 delete this._channels[name];550 },551 552 hasSubscription: function(name) {553 return this._channels.hasOwnProperty(name);554 },555 556 subscribe: function(names, callback, context) {557 if (!callback) return;558 var name;559 for (var i = 0, n = names.length; i < n; i++) {560 name = names[i];561 var channel = this._channels[name] = this._channels[name] || new Faye.Channel(name);562 channel.bind('message', callback, context);563 }564 },565 566 unsubscribe: function(name, callback, context) {567 var channel = this._channels[name];568 if (!channel) return false;569 channel.unbind('message', callback, context);570 571 if (channel.isUnused()) {572 this.remove(name);573 return true;574 } else {575 return false;576 }577 },578 579 distributeMessage: function(message) {580 var channels = Faye.Channel.expand(message.channel);581 582 for (var i = 0, n = channels.length; i < n; i++) {583 var channel = this._channels[channels[i]];584 if (channel) channel.trigger('message', message.data);585 }586 }587 })588});589Faye.Publication = Faye.Class(Faye.Deferrable);590Faye.Subscription = Faye.Class({591 initialize: function(client, channels, callback, context) {592 this._client = client;593 this._channels = channels;594 this._callback = callback;595 this._context = context;596 this._cancelled = false;597 },598 599 cancel: function() {600 if (this._cancelled) return;601 this._client.unsubscribe(this._channels, this._callback, this._context);602 this._cancelled = true;603 },604 605 unsubscribe: function() {606 this.cancel();607 }608});609Faye.extend(Faye.Subscription.prototype, Faye.Deferrable);610Faye.Client = Faye.Class({611 UNCONNECTED: 1,612 CONNECTING: 2,613 CONNECTED: 3,614 DISCONNECTED: 4,615 616 HANDSHAKE: 'handshake',617 RETRY: 'retry',618 NONE: 'none',619 620 CONNECTION_TIMEOUT: 60.0,621 DEFAULT_RETRY: 5.0,622 623 DEFAULT_ENDPOINT: '/bayeux',624 INTERVAL: 0.0,625 626 initialize: function(endpoint, options) {627 this.info('New client created for ?', endpoint);628 629 this.endpoint = endpoint || this.DEFAULT_ENDPOINT;630 this._cookies = Faye.CookieJar && new Faye.CookieJar();631 this._headers = {};632 this._options = options || {};633 this._disabled = [];634 this.retry = this._options.retry || this.DEFAULT_RETRY;635 636 this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);637 638 this._state = this.UNCONNECTED;639 this._channels = new Faye.Channel.Set();640 this._messageId = 0;641 642 this._responseCallbacks = {};643 644 this._advice = {645 reconnect: this.RETRY,646 interval: 1000 * (this._options.interval || this.INTERVAL),647 timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)648 };649 650 if (Faye.Event)651 Faye.Event.on(Faye.ENV, 'beforeunload', function() {652 if (Faye.indexOf(this._disabled, 'autodisconnect') < 0)653 this.disconnect();654 }, this);655 },656 657 disable: function(feature) {658 this._disabled.push(feature);659 },660 661 setHeader: function(name, value) {662 this._headers[name] = value;663 },664 665 getClientId: function() {666 return this._clientId;667 },668 getState: function() {669 switch (this._state) {670 case this.UNCONNECTED: return 'UNCONNECTED';671 case this.CONNECTING: return 'CONNECTING';672 case this.CONNECTED: return 'CONNECTED';673 case this.DISCONNECTED: return 'DISCONNECTED';674 }675 },676 // Request677 // MUST include: * channel678 // * version679 // * supportedConnectionTypes680 // MAY include: * minimumVersion681 // * ext682 // * id683 // 684 // Success Response Failed Response685 // MUST include: * channel MUST include: * channel686 // * version * successful687 // * supportedConnectionTypes * error688 // * clientId MAY include: * supportedConnectionTypes689 // * successful * advice690 // MAY include: * minimumVersion * version691 // * advice * minimumVersion692 // * ext * ext693 // * id * id694 // * authSuccessful695 handshake: function(callback, context) {696 if (this._advice.reconnect === this.NONE) return;697 if (this._state !== this.UNCONNECTED) return;698 699 this._state = this.CONNECTING;700 var self = this;701 702 this.info('Initiating handshake with ?', this.endpoint);703 704 this._send({705 channel: Faye.Channel.HANDSHAKE,706 version: Faye.BAYEUX_VERSION,707 supportedConnectionTypes: [this._transport.connectionType]708 709 }, function(response) {710 711 if (response.successful) {712 this._state = this.CONNECTED;713 this._clientId = response.clientId;714 715 var connectionTypes = Faye.filter(response.supportedConnectionTypes, function(connType) {716 return Faye.indexOf(this._disabled, connType) < 0;717 }, this);718 this._selectTransport(connectionTypes);719 720 this.info('Handshake successful: ?', this._clientId);721 722 this.subscribe(this._channels.getKeys(), true);723 if (callback) callback.call(context);724 725 } else {726 this.info('Handshake unsuccessful');727 Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._advice.interval);728 this._state = this.UNCONNECTED;729 }730 }, this);731 },732 733 // Request Response734 // MUST include: * channel MUST include: * channel735 // * clientId * successful736 // * connectionType * clientId737 // MAY include: * ext MAY include: * error738 // * id * advice739 // * ext740 // * id741 // * timestamp742 connect: function(callback, context) {743 if (this._advice.reconnect === this.NONE) return;744 if (this._state === this.DISCONNECTED) return;745 746 if (this._state === this.UNCONNECTED)747 return this.handshake(function() { this.connect(callback, context) }, this);748 749 this.callback(callback, context);750 if (this._state !== this.CONNECTED) return;751 752 this.info('Calling deferred actions for ?', this._clientId);753 this.setDeferredStatus('succeeded');754 this.setDeferredStatus('deferred');755 756 if (this._connectRequest) return;757 this._connectRequest = true;758 759 this.info('Initiating connection for ?', this._clientId);760 761 this._send({762 channel: Faye.Channel.CONNECT,763 clientId: this._clientId,764 connectionType: this._transport.connectionType765 766 }, this._cycleConnection, this);767 },768 769 // Request Response770 // MUST include: * channel MUST include: * channel771 // * clientId * successful772 // MAY include: * ext * clientId773 // * id MAY include: * error774 // * ext775 // * id776 disconnect: function() {777 if (this._state !== this.CONNECTED) return;778 this._state = this.DISCONNECTED;779 780 this.info('Disconnecting ?', this._clientId);781 782 this._send({783 channel: Faye.Channel.DISCONNECT,784 clientId: this._clientId785 786 }, function(response) {787 if (response.successful) this._transport.close();788 }, this);789 790 this.info('Clearing channel listeners for ?', this._clientId);791 this._channels = new Faye.Channel.Set();792 },793 794 // Request Response795 // MUST include: * channel MUST include: * channel796 // * clientId * successful797 // * subscription * clientId798 // MAY include: * ext * subscription799 // * id MAY include: * error800 // * advice801 // * ext802 // * id803 // * timestamp804 subscribe: function(channel, callback, context) {805 if (channel instanceof Array) {806 for (var i = 0, n = channel.length; i < n; i++) {807 this.subscribe(channel[i], callback, context);808 }809 return;810 }811 812 var subscription = new Faye.Subscription(this, channel, callback, context),813 force = (callback === true),814 hasSubscribe = this._channels.hasSubscription(channel);815 816 if (!force) {817 this._channels.subscribe([channel], callback, context);818 if (hasSubscribe) {819 subscription.setDeferredStatus('succeeded');820 return subscription;821 }822 }823 824 this.connect(function() {825 this.info('Client ? attempting to subscribe to ?', this._clientId, channel);826 827 this._send({828 channel: Faye.Channel.SUBSCRIBE,829 clientId: this._clientId,830 subscription: channel831 832 }, function(response) {833 if (!response.successful) {834 subscription.setDeferredStatus('failed', Faye.Error.parse(response.error));835 return this._channels.unsubscribe(channel, callback, context);836 }837 838 var channels = [].concat(response.subscription);839 this.info('Subscription acknowledged for ? to ?', this._clientId, channels);840 subscription.setDeferredStatus('succeeded');841 }, this);842 }, this);843 844 return subscription;845 },846 847 // Request Response848 // MUST include: * channel MUST include: * channel849 // * clientId * successful850 // * subscription * clientId851 // MAY include: * ext * subscription852 // * id MAY include: * error853 // * advice854 // * ext855 // * id856 // * timestamp857 unsubscribe: function(channel, callback, context) {858 if (channel instanceof Array) {859 for (var i = 0, n = channel.length; i < n; i++) {860 this.unsubscribe(channel[i], callback, context);861 }862 return;863 }864 865 var dead = this._channels.unsubscribe(channel, callback, context);866 if (!dead) return;867 868 this.connect(function() {869 this.info('Client ? attempting to unsubscribe from ?', this._clientId, channel);870 871 this._send({872 channel: Faye.Channel.UNSUBSCRIBE,873 clientId: this._clientId,874 subscription: channel875 876 }, function(response) {877 if (!response.successful) return;878 879 var channels = [].concat(response.subscription);880 this.info('Unsubscription acknowledged for ? from ?', this._clientId, channels);881 }, this);882 }, this);883 },884 885 // Request Response886 // MUST include: * channel MUST include: * channel887 // * data * successful888 // MAY include: * clientId MAY include: * id889 // * id * error890 // * ext * ext891 publish: function(channel, data) {892 var publication = new Faye.Publication();893 894 this.connect(function() {895 this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);896 897 this._send({898 channel: channel,899 data: data,900 clientId: this._clientId901 }, function(response) {902 if (response.successful)903 publication.setDeferredStatus('succeeded');904 else905 publication.setDeferredStatus('failed', Faye.Error.parse(response.error));906 }, this);907 }, this);908 909 return publication;910 },911 912 receiveMessage: function(message) {913 this.pipeThroughExtensions('incoming', message, function(message) {914 if (!message) return;915 916 if (message.advice) this._handleAdvice(message.advice);917 918 var callback = this._responseCallbacks[message.id];919 if (callback) {920 delete this._responseCallbacks[message.id];921 callback[0].call(callback[1], message);922 }923 924 this._deliverMessage(message);925 }, this);926 },927 928 _selectTransport: function(transportTypes) {929 Faye.Transport.get(this, transportTypes, function(transport) {930 this._transport = transport;931 this._transport.cookies = this._cookies;932 this._transport.headers = this._headers;933 934 transport.bind('down', function() {935 if (this._transportUp !== undefined && !this._transportUp) return;936 this._transportUp = false;937 this.trigger('transport:down');938 }, this);939 940 transport.bind('up', function() {941 if (this._transportUp !== undefined && this._transportUp) return;942 this._transportUp = true;943 this.trigger('transport:up');944 }, this);945 }, this);946 },947 948 _send: function(message, callback, context) {949 message.id = this._generateMessageId();950 if (callback) this._responseCallbacks[message.id] = [callback, context];951 this.pipeThroughExtensions('outgoing', message, function(message) {952 if (!message) return;953 this._transport.send(message, this._advice.timeout / 1000);954 }, this);955 },956 957 _generateMessageId: function() {958 this._messageId += 1;959 if (this._messageId >= Math.pow(2,32)) this._messageId = 0;960 return this._messageId.toString(36);961 },962 _handleAdvice: function(advice) {963 Faye.extend(this._advice, advice);964 965 if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {966 this._state = this.UNCONNECTED;967 this._clientId = null;968 this._cycleConnection();969 }970 },971 972 _deliverMessage: function(message) {973 if (!message.channel || message.data === undefined) return;974 this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);975 this._channels.distributeMessage(message);976 },977 978 _teardownConnection: function() {979 if (!this._connectRequest) return;980 this._connectRequest = null;981 this.info('Closed connection for ?', this._clientId);982 },983 984 _cycleConnection: function() {985 this._teardownConnection();986 var self = this;987 Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);988 }989});990Faye.extend(Faye.Client.prototype, Faye.Deferrable);991Faye.extend(Faye.Client.prototype, Faye.Publisher);992Faye.extend(Faye.Client.prototype, Faye.Logging);993Faye.extend(Faye.Client.prototype, Faye.Extensible);994Faye.Transport = Faye.extend(Faye.Class({995 MAX_DELAY: 0.0,996 batching: true,997 initialize: function(client, endpoint) {998 this.debug('Created new ? transport for ?', this.connectionType, endpoint);999 this._client = client;1000 this._endpoint = endpoint;1001 this._outbox = [];1002 },1003 1004 close: function() {},1005 1006 send: function(message, timeout) {1007 this.debug('Client ? sending message to ?: ?',1008 this._client._clientId, this._endpoint, message);1009 if (!this.batching) return this.request([message], timeout);1010 this._outbox.push(message);1011 this._timeout = timeout;1012 if (message.channel === Faye.Channel.HANDSHAKE)1013 return this.flush();1014 if (message.channel === Faye.Channel.CONNECT)1015 this._connectMessage = message;1016 this.addTimeout('publish', this.MAX_DELAY, this.flush, this);1017 },1018 flush: function() {1019 this.removeTimeout('publish');1020 if (this._outbox.length > 1 && this._connectMessage)1021 this._connectMessage.advice = {timeout: 0};1022 this.request(this._outbox, this._timeout);1023 1024 this._connectMessage = null;1025 this._outbox = [];1026 },1027 1028 receive: function(responses) {1029 this.debug('Client ? received from ?: ?',1030 this._client._clientId, this._endpoint, responses);1031 1032 for (var i = 0, n = responses.length; i < n; i++) {1033 this._client.receiveMessage(responses[i]);1034 }1035 },1036 1037 retry: function(message, timeout) {1038 var called = false,1039 retry = this._client.retry * 1000,1040 self = this;1041 1042 return function() {1043 if (called) return;1044 called = true;1045 Faye.ENV.setTimeout(function() { self.request(message, timeout) }, retry);1046 };1047 }1048 1049}), {1050 get: function(client, connectionTypes, callback, context) {1051 var endpoint = client.endpoint;1052 if (connectionTypes === undefined) connectionTypes = this.supportedConnectionTypes();1053 1054 Faye.asyncEach(this._transports, function(pair, resume) {1055 var connType = pair[0], klass = pair[1];1056 if (Faye.indexOf(connectionTypes, connType) < 0) return resume();1057 1058 klass.isUsable(endpoint, function(isUsable) {1059 if (isUsable) callback.call(context, new klass(client, endpoint));1060 else resume();1061 });1062 }, function() {1063 throw new Error('Could not find a usable connection type for ' + endpoint);1064 });1065 },1066 1067 register: function(type, klass) {1068 this._transports.push([type, klass]);1069 klass.prototype.connectionType = type;1070 },1071 1072 _transports: [],1073 1074 supportedConnectionTypes: function() {1075 return Faye.map(this._transports, function(pair) { return pair[0] });1076 }1077});1078Faye.extend(Faye.Transport.prototype, Faye.Logging);1079Faye.extend(Faye.Transport.prototype, Faye.Publisher);1080Faye.extend(Faye.Transport.prototype, Faye.Timeouts);1081Faye.Set = Faye.Class({1082 initialize: function() {1083 this._index = {};1084 },1085 1086 add: function(item) {1087 var key = (item.id !== undefined) ? item.id : item;1088 if (this._index.hasOwnProperty(key)) return false;1089 this._index[key] = item;1090 return true;1091 },1092 1093 forEach: function(block, context) {1094 for (var key in this._index) {1095 if (this._index.hasOwnProperty(key))1096 block.call(context, this._index[key]);1097 }1098 },1099 1100 isEmpty: function() {1101 for (var key in this._index) {1102 if (this._index.hasOwnProperty(key)) return false;1103 }1104 return true;1105 },1106 1107 member: function(item) {1108 for (var key in this._index) {1109 if (this._index[key] === item) return true;1110 }1111 return false;1112 },1113 1114 remove: function(item) {1115 var key = (item.id !== undefined) ? item.id : item;1116 var removed = this._index.hasOwnProperty(key);1117 delete this._index[key];1118 return removed;1119 },1120 1121 toArray: function() {1122 var array = [];1123 this.forEach(function(item) { array.push(item) });1124 return array;1125 }1126});1127Faye.Engine = {1128 get: function(options) {1129 return new Faye.Engine.Proxy(options);1130 },1131 1132 METHODS: ['createClient', 'clientExists', 'destroyClient', 'ping', 'subscribe', 'unsubscribe']1133};1134Faye.Engine.Proxy = Faye.Class({1135 MAX_DELAY: 0.0,1136 INTERVAL: 0.0,1137 TIMEOUT: 60.0,1138 1139 className: 'Engine',1140 1141 initialize: function(options) {1142 this._options = options || {};1143 this._connections = {};1144 this.interval = this._options.interval || this.INTERVAL;1145 this.timeout = this._options.timeout || this.TIMEOUT;1146 1147 var engineClass = this._options.type || Faye.Engine.Memory;1148 this._engine = engineClass.create(this, this._options);1149 1150 this.debug('Created new engine: ?', this._options);1151 },1152 1153 connect: function(clientId, options, callback, context) {1154 this.debug('Accepting connection from ?', clientId);1155 this._engine.ping(clientId);1156 var conn = this.connection(clientId, true);1157 conn.connect(options, callback, context);1158 this._engine.emptyQueue(clientId);1159 },1160 1161 hasConnection: function(clientId) {1162 return this._connections.hasOwnProperty(clientId);1163 },1164 1165 connection: function(clientId, create) {1166 var conn = this._connections[clientId];1167 if (conn || !create) return conn;1168 return this._connections[clientId] = new Faye.Engine.Connection(this, clientId);1169 },1170 1171 closeConnection: function(clientId) {1172 this.debug('Closing connection for ?', clientId);1173 delete this._connections[clientId];1174 },1175 1176 openSocket: function(clientId, socket) {1177 var conn = this.connection(clientId, true);1178 conn.socket = socket;1179 },1180 1181 deliver: function(clientId, messages) {1182 if (!messages || messages.length === 0) return false;1183 1184 var conn = this.connection(clientId, false);1185 if (!conn) return false;1186 1187 for (var i = 0, n = messages.length; i < n; i++) {1188 conn.deliver(messages[i]);1189 }1190 return true;1191 },1192 1193 generateId: function() {1194 return Faye.random();1195 },1196 1197 flush: function(clientId) {1198 this.debug('Flushing connection queue for ?', clientId);1199 var conn = this.connection(clientId, false);1200 if (conn) conn.flush(true);1201 },1202 1203 disconnect: function() {1204 if (this._engine.disconnect) return this._engine.disconnect();1205 },1206 1207 publish: function(message) {1208 var channels = Faye.Channel.expand(message.channel);1209 return this._engine.publish(message, channels);1210 }1211});1212Faye.Engine.METHODS.forEach(function(method) {1213 Faye.Engine.Proxy.prototype[method] = function() {1214 return this._engine[method].apply(this._engine, arguments);1215 };1216})1217Faye.extend(Faye.Engine.Proxy.prototype, Faye.Publisher);1218Faye.extend(Faye.Engine.Proxy.prototype, Faye.Logging);1219Faye.Engine.Connection = Faye.Class({1220 initialize: function(engine, id, options) {1221 this._engine = engine;1222 this._id = id;1223 this._options = options;1224 this._inbox = [];1225 },1226 1227 deliver: function(message) {1228 if (this.socket) return this.socket.send(JSON.stringify([message]));1229 this._inbox.push(message);1230 this._beginDeliveryTimeout();1231 },1232 1233 connect: function(options, callback, context) {1234 options = options || {};1235 var timeout = (options.timeout !== undefined) ? options.timeout / 1000 : this._engine.timeout;1236 1237 this.setDeferredStatus('deferred');1238 this.callback(callback, context);1239 1240 this._beginDeliveryTimeout();1241 this._beginConnectionTimeout(timeout);1242 },1243 1244 flush: function(force) {1245 this._releaseConnection(force);1246 this.setDeferredStatus('succeeded', this._inbox);1247 this._inbox = [];1248 },1249 1250 _releaseConnection: function(force) {1251 if (force || !this.socket) this._engine.closeConnection(this._id);1252 this.removeTimeout('connection');1253 this.removeTimeout('delivery');1254 },1255 1256 _beginDeliveryTimeout: function() {1257 if (this._inbox.length === 0) return;1258 this.addTimeout('delivery', this._engine.MAX_DELAY, this.flush, this);1259 },1260 1261 _beginConnectionTimeout: function(timeout) {1262 this.addTimeout('connection', timeout, this.flush, this);1263 }1264});1265Faye.extend(Faye.Engine.Connection.prototype, Faye.Deferrable);1266Faye.extend(Faye.Engine.Connection.prototype, Faye.Timeouts);1267Faye.Engine.Memory = function(server, options) {1268 this._server = server;1269 this._options = options || {};1270 this._namespace = new Faye.Namespace();1271 this._clients = {};1272 this._channels = {};1273 this._messages = {};1274};1275Faye.Engine.Memory.create = function(server, options) {1276 return new this(server, options);1277};1278Faye.Engine.Memory.prototype = {1279 createClient: function(callback, context) {1280 var clientId = this._namespace.generate();1281 this._server.debug('Created new client ?', clientId);1282 this.ping(clientId);1283 this._server.trigger('handshake', clientId);1284 callback.call(context, clientId);1285 },1286 1287 destroyClient: function(clientId, callback, context) {1288 if (!this._namespace.exists(clientId)) return;1289 var clients = this._clients;1290 1291 if (clients[clientId])1292 clients[clientId].forEach(function(channel) { this.unsubscribe(clientId, channel) }, this);1293 1294 this.removeTimeout(clientId);1295 this._namespace.release(clientId);1296 delete this._messages[clientId];1297 this._server.debug('Destroyed client ?', clientId);1298 this._server.trigger('disconnect', clientId);1299 if (callback) callback.call(context);1300 },1301 1302 clientExists: function(clientId, callback, context) {1303 callback.call(context, this._namespace.exists(clientId));1304 },1305 1306 ping: function(clientId) {1307 var timeout = this._server.timeout;1308 if (typeof timeout !== 'number') return;1309 1310 this._server.debug('Ping ?, ?', clientId, timeout);1311 this.removeTimeout(clientId);1312 this.addTimeout(clientId, 2 * timeout, function() {1313 this.destroyClient(clientId);1314 }, this);1315 },1316 1317 subscribe: function(clientId, channel, callback, context) {1318 var clients = this._clients, channels = this._channels;1319 1320 clients[clientId] = clients[clientId] || new Faye.Set();1321 var trigger = clients[clientId].add(channel);1322 1323 channels[channel] = channels[channel] || new Faye.Set();1324 channels[channel].add(clientId);1325 1326 this._server.debug('Subscribed client ? to channel ?', clientId, channel);1327 if (trigger) this._server.trigger('subscribe', clientId, channel);1328 if (callback) callback.call(context, true);1329 },1330 1331 unsubscribe: function(clientId, channel, callback, context) {1332 var clients = this._clients,1333 channels = this._channels,1334 trigger = false;1335 1336 if (clients[clientId]) {1337 trigger = clients[clientId].remove(channel);1338 if (clients[clientId].isEmpty()) delete clients[clientId];1339 }1340 1341 if (channels[channel]) {1342 channels[channel].remove(clientId);1343 if (channels[channel].isEmpty()) delete channels[channel];1344 }1345 1346 this._server.debug('Unsubscribed client ? from channel ?', clientId, channel);1347 if (trigger) this._server.trigger('unsubscribe', clientId, channel);1348 if (callback) callback.call(context, true);1349 },1350 1351 publish: function(message, channels) {1352 this._server.debug('Publishing message ?', message);1353 var messages = this._messages,1354 clients = new Faye.Set(),1355 subs;1356 1357 for (var i = 0, n = channels.length; i < n; i++) {1358 subs = this._channels[channels[i]];1359 if (!subs) continue;1360 subs.forEach(clients.add, clients);1361 }1362 1363 clients.forEach(function(clientId) {1364 this._server.debug('Queueing for client ?: ?', clientId, message);1365 messages[clientId] = messages[clientId] || [];1366 messages[clientId].push(Faye.copyObject(message));1367 this.emptyQueue(clientId);1368 }, this);1369 1370 this._server.trigger('publish', message.clientId, message.channel, message.data);1371 },1372 1373 emptyQueue: function(clientId) {1374 if (!this._server.hasConnection(clientId)) return;1375 this._server.deliver(clientId, this._messages[clientId]);1376 delete this._messages[clientId];1377 }1378};1379Faye.extend(Faye.Engine.Memory.prototype, Faye.Timeouts);1380Faye.Server = Faye.Class({1381 initialize: function(options) {1382 this._options = options || {};1383 var engineOpts = this._options.engine || {};1384 engineOpts.timeout = this._options.timeout;1385 this._engine = Faye.Engine.get(engineOpts);1386 this.info('Created new server: ?', this._options);1387 },1388 1389 flushConnection: function(messages) {1390 var clientId = [].concat(messages)[0].clientId;1391 if (!clientId) return;1392 this.info('Flushing connection for ?', clientId);1393 this._engine.flush(clientId);1394 },1395 1396 openSocket: function(clientId, socket) {1397 this._engine.openSocket(clientId, socket);1398 },1399 1400 closeSocket: function(clientId) {1401 this._engine.flush(clientId);1402 },1403 1404 process: function(messages, local, callback, context) {1405 messages = [].concat(messages);1406 this.info('Processing messages: ? (local: ?)', messages, local);1407 if (messages.length === 0) return callback.call(context, []);1408 var processed = 0, responses = [], self = this;1409 1410 var gatherReplies = function(replies) {1411 responses = responses.concat(replies);1412 processed += 1;1413 if (processed < messages.length) return;1414 1415 var n = responses.length;1416 while (n--) {1417 if (!responses[n]) responses.splice(n,1);1418 }1419 self.info('Returning replies: ?', responses);1420 callback.call(context, responses);1421 };1422 1423 var handleReply = function(replies) {1424 var extended = 0, expected = replies.length;1425 if (expected === 0) gatherReplies(replies);1426 1427 for (var i = 0, n = replies.length; i < n; i++) {1428 this.debug('Processing reply: ?', replies[i]);1429 this.pipeThroughExtensions('outgoing', replies[i], function(message) {1430 replies[i] = message;1431 extended += 1;1432 if (extended === expected) gatherReplies(replies);1433 });1434 }1435 };1436 1437 for (var i = 0, n = messages.length; i < n; i++) {1438 this.pipeThroughExtensions('incoming', messages[i], function(pipedMessage) {1439 this._handle(pipedMessage, local, handleReply, this);1440 }, this);1441 }1442 },1443 1444 _makeResponse: function(message) {1445 var response = {};1446 1447 if (message.id) response.id = message.id;1448 if (message.clientId) response.clientId = message.clientId;1449 if (message.channel) response.channel = message.channel;1450 if (message.error) response.error = message.error;1451 1452 response.successful = !response.error;1453 return response;1454 },1455 1456 _handle: function(message, local, callback, context) {1457 if (!message) return callback.call(context, []);1458 this.info('Handling message: ? (local: ?)', message, local);1459 1460 var channelName = message.channel,1461 error = message.error,1462 response;1463 1464 if (Faye.Channel.isMeta(channelName))1465 return this._handleMeta(message, local, callback, context);1466 1467 if (!Faye.Grammar.CHANNEL_NAME.test(channelName))1468 error = Faye.Error.channelInvalid(channelName);1469 1470 if (!error) this._engine.publish(message);1471 1472 response = this._makeResponse(message);1473 if (error) response.error = error;1474 response.successful = !response.error;1475 callback.call(context, [response]);1476 },1477 1478 _handleMeta: function(message, local, callback, context) {1479 var method = Faye.Channel.parse(message.channel)[1],1480 clientId = message.clientId;1481 1482 this[method](message, local, function(responses) {1483 responses = [].concat(responses);1484 for (var i = 0, n = responses.length; i < n; i++) this._advize(responses[i], message.connectionType);1485 callback.call(context, responses);1486 }, this);1487 },1488 1489 _advize: function(response, connectionType) {1490 if (Faye.indexOf([Faye.Channel.HANDSHAKE, Faye.Channel.CONNECT], response.channel) < 0)1491 return;1492 1493 var interval, timeout;1494 if (connectionType === 'eventsource') {1495 interval = Math.floor(this._engine.timeout * 1000);1496 timeout = 0;1497 } else {1498 interval = Math.floor(this._engine.interval * 1000);1499 timeout = Math.floor(this._engine.timeout * 1000);1500 }1501 1502 response.advice = response.advice || {};1503 if (response.error) {1504 Faye.extend(response.advice, {reconnect: 'handshake'}, false);1505 } else {1506 Faye.extend(response.advice, {1507 reconnect: 'retry',1508 interval: interval,1509 timeout: timeout1510 }, false);1511 }1512 },1513 1514 // MUST contain * version1515 // * supportedConnectionTypes1516 // MAY contain * minimumVersion1517 // * ext1518 // * id1519 handshake: function(message, local, callback, context) {1520 var response = this._makeResponse(message);1521 response.version = Faye.BAYEUX_VERSION;1522 1523 if (!message.version)1524 response.error = Faye.Error.parameterMissing('version');1525 1526 var clientConns = message.supportedConnectionTypes,1527 commonConns;1528 1529 response.supportedConnectionTypes = Faye.CONNECTION_TYPES;1530 1531 if (clientConns) {1532 commonConns = Faye.filter(clientConns, function(conn) {1533 return Faye.indexOf(Faye.CONNECTION_TYPES, conn) >= 0;1534 });1535 if (commonConns.length === 0)1536 response.error = Faye.Error.conntypeMismatch(clientConns);1537 } else {1538 response.error = Faye.Error.parameterMissing('supportedConnectionTypes');1539 }1540 1541 response.successful = !response.error;1542 if (!response.successful) return callback.call(context, response);1543 1544 this._engine.createClient(function(clientId) {1545 response.clientId = clientId;1546 callback.call(context, response);1547 }, this);1548 },1549 1550 // MUST contain * clientId1551 // * connectionType1552 // MAY contain * ext1553 // * id1554 connect: function(message, local, callback, context) {1555 var response = this._makeResponse(message),1556 clientId = message.clientId,1557 connectionType = message.connectionType;1558 1559 this._engine.clientExists(clientId, function(exists) {1560 if (!exists) response.error = Faye.Error.clientUnknown(clientId);1561 if (!clientId) response.error = Faye.Error.parameterMissing('clientId');1562 1563 if (Faye.indexOf(Faye.CONNECTION_TYPES, connectionType) < 0)1564 response.error = Faye.Error.conntypeMismatch(connectionType);1565 1566 if (!connectionType) response.error = Faye.Error.parameterMissing('connectionType');1567 1568 response.successful = !response.error;1569 1570 if (!response.successful) {1571 delete response.clientId;1572 return callback.call(context, response);1573 }1574 1575 if (message.connectionType === 'eventsource') {1576 message.advice = message.advice || {};1577 message.advice.timeout = 0;1578 }1579 this._engine.connect(response.clientId, message.advice, function(events) {1580 callback.call(context, [response].concat(events));1581 });1582 }, this);1583 },1584 1585 // MUST contain * clientId1586 // MAY contain * ext1587 // * id1588 disconnect: function(message, local, callback, context) {1589 var response = this._makeResponse(message),1590 clientId = message.clientId;1591 1592 this._engine.clientExists(clientId, function(exists) {1593 if (!exists) response.error = Faye.Error.clientUnknown(clientId);1594 if (!clientId) response.error = Faye.Error.parameterMissing('clientId');1595 1596 response.successful = !response.error;1597 if (!response.successful) delete response.clientId;1598 1599 if (response.successful) this._engine.destroyClient(clientId);1600 callback.call(context, response);1601 }, this);1602 },1603 1604 // MUST contain * clientId1605 // * subscription1606 // MAY contain * ext1607 // * id1608 subscribe: function(message, local, callback, context) {1609 var response = this._makeResponse(message),1610 clientId = message.clientId,1611 subscription = message.subscription,1612 channel;1613 1614 subscription = subscription ? [].concat(subscription) : [];1615 1616 this._engine.clientExists(clientId, function(exists) {1617 if (!exists) response.error = Faye.Error.clientUnknown(clientId);1618 if (!clientId) response.error = Faye.Error.parameterMissing('clientId');1619 if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');1620 1621 response.subscription = message.subscription || [];1622 1623 for (var i = 0, n = subscription.length; i < n; i++) {1624 channel = subscription[i];1625 1626 if (response.error) return;1627 if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);1628 if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);1629 1630 if (response.error) return;1631 this._engine.subscribe(clientId, channel);1632 }1633 1634 response.successful = !response.error;1635 callback.call(context, response);1636 }, this);1637 },1638 1639 // MUST contain * clientId1640 // * subscription1641 // MAY contain * ext1642 // * id1643 unsubscribe: function(message, local, callback, context) {1644 var response = this._makeResponse(message),1645 clientId = message.clientId,1646 subscription = message.subscription,1647 channel;1648 1649 subscription = subscription ? [].concat(subscription) : [];1650 1651 this._engine.clientExists(clientId, function(exists) {1652 if (!exists) response.error = Faye.Error.clientUnknown(clientId);1653 if (!clientId) response.error = Faye.Error.parameterMissing('clientId');1654 if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');1655 1656 response.subscription = message.subscription || [];1657 1658 for (var i = 0, n = subscription.length; i < n; i++) {1659 channel = subscription[i];1660 1661 if (response.error) return;1662 if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);1663 if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);1664 1665 if (response.error) return;1666 this._engine.unsubscribe(clientId, channel);1667 }1668 1669 response.successful = !response.error;1670 callback.call(context, response);1671 }, this);1672 }1673});1674Faye.extend(Faye.Server.prototype, Faye.Logging);1675Faye.extend(Faye.Server.prototype, Faye.Extensible);1676Faye.Transport.NodeLocal = Faye.extend(Faye.Class(Faye.Transport, {1677 batching: false,1678 1679 request: function(message, timeout) {1680 message = Faye.copyObject(message);1681 this._endpoint.process(message, true, function(responses) {1682 this.receive(Faye.copyObject(responses));1683 }, this);1684 }1685}), {1686 isUsable: function(endpoint, callback, context) {1687 callback.call(context, endpoint instanceof Faye.Server);1688 }1689});1690Faye.Transport.register('in-process', Faye.Transport.NodeLocal);1691Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {1692 UNCONNECTED: 1,1693 CONNECTING: 2,1694 CONNECTED: 3,1695 batching: false,1696 1697 request: function(messages, timeout) {1698 this._messages = this._messages || {};1699 for (var i = 0, n = messages.length; i < n; i++) {1700 this._messages[messages[i].id] = messages[i];1701 }1702 this.withSocket(function(socket) { socket.send(Faye.toJSON(messages)) });1703 },1704 1705 withSocket: function(callback, context) {1706 this.callback(callback, context);1707 this.connect();1708 },1709 1710 close: function() {1711 if (this._closed) return;1712 this._closed = true;1713 if (this._socket) this._socket.close();1714 },1715 1716 connect: function() {1717 if (this._closed) return;1718 1719 this._state = this._state || this.UNCONNECTED;1720 if (this._state !== this.UNCONNECTED) return;1721 1722 this._state = this.CONNECTING;1723 1724 var ws = Faye.Transport.WebSocket.getClass();1725 this._socket = new ws(Faye.Transport.WebSocket.getSocketUrl(this._endpoint));1726 var self = this;1727 1728 this._socket.onopen = function() {1729 self._state = self.CONNECTED;1730 self.setDeferredStatus('succeeded', self._socket);1731 self.trigger('up');1732 };1733 1734 this._socket.onmessage = function(event) {1735 var messages = [].concat(JSON.parse(event.data));1736 for (var i = 0, n = messages.length; i < n; i++) {1737 delete self._messages[messages[i].id];1738 }1739 self.receive(messages);1740 };1741 1742 this._socket.onclose = function() {1743 var wasConnected = (self._state === self.CONNECTED);1744 self.setDeferredStatus('deferred');1745 self._state = self.UNCONNECTED;1746 delete self._socket;1747 1748 if (wasConnected) return self.resend();1749 1750 var retry = self._client.retry * 1000;1751 Faye.ENV.setTimeout(function() { self.connect() }, retry);1752 self.trigger('down');1753 };1754 },1755 1756 resend: function() {1757 var messages = Faye.map(this._messages, function(id, msg) { return msg });1758 this.request(messages);1759 }1760}), {1761 WEBSOCKET_TIMEOUT: 1000,1762 1763 getSocketUrl: function(endpoint) {1764 if (Faye.URI) endpoint = Faye.URI.parse(endpoint).toURL();1765 return endpoint.replace(/^http(s?):/ig, 'ws$1:');1766 },1767 1768 getClass: function() {1769 return (Faye.WebSocket && Faye.WebSocket.Client) ||1770 Faye.ENV.WebSocket ||1771 Faye.ENV.MozWebSocket;1772 },1773 1774 isUsable: function(endpoint, callback, context) {1775 var ws = this.getClass();1776 if (!ws) return callback.call(context, false);1777 1778 var connected = false,1779 called = false,1780 socketUrl = this.getSocketUrl(endpoint),1781 socket = new ws(socketUrl);1782 1783 socket.onopen = function() {1784 connected = true;1785 socket.close();1786 callback.call(context, true);1787 called = true;1788 socket = null;1789 };1790 1791 var notconnected = function() {1792 if (!called && !connected) callback.call(context, false);1793 called = true;1794 };1795 1796 socket.onclose = socket.onerror = notconnected;1797 Faye.ENV.setTimeout(notconnected, this.WEBSOCKET_TIMEOUT);1798 }1799});1800Faye.extend(Faye.Transport.WebSocket.prototype, Faye.Deferrable);1801Faye.Transport.register('websocket', Faye.Transport.WebSocket);1802Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {1803 request: function(message, timeout) {1804 var uri = url.parse(this._endpoint),1805 secure = (uri.protocol === 'https:'),1806 client = secure ? https : http,1807 content = new Buffer(JSON.stringify(message), 'utf8'),1808 retry = this.retry(message, timeout),1809 self = this;1810 1811 var cookies = this.cookies.getCookies({domain: uri.hostname, path: uri.pathname}),1812 params = this._buildParams(uri, content, cookies, secure),1813 request = client.request(params);1814 1815 request.addListener('response', function(response) {1816 self._handleResponse(response, retry);1817 self._storeCookies(uri.hostname, response.headers['set-cookie']);1818 });1819 1820 request.addListener('error', function() {1821 retry();1822 self.trigger('down');1823 });1824 request.write(content);1825 request.end();1826 },1827 1828 _buildParams: function(uri, content, cookies, secure) {1829 return {1830 method: 'POST',1831 host: uri.hostname,1832 port: uri.port || (secure ? 443 : 80),1833 path: uri.pathname,1834 headers: Faye.extend({1835 'Content-Length': content.length,1836 'Content-Type': 'application/json',1837 'Cookie': cookies.toValueString(),1838 'Host': uri.hostname1839 }, this.headers)1840 };1841 },1842 1843 _handleResponse: function(response, retry) {1844 var message = null,1845 body = '',1846 self = this;1847 1848 response.addListener('data', function(c) { body += c.toString('utf8', 0, c.length) });1849 response.addListener('end', function() {1850 try {1851 message = JSON.parse(body);1852 } catch (e) {}1853 1854 if (message) {1855 self.receive(message);1856 self.trigger('up');1857 } else {1858 retry();1859 self.trigger('down');1860 }1861 });1862 },1863 1864 _storeCookies: function(hostname, cookies) {1865 if (!cookies) return;1866 var cookie;1867 1868 for (var i = 0, n = cookies.length; i < n; i++) {1869 cookie = this.cookies.setCookie(cookies[i]);1870 cookie = cookie[0] || cookie;1871 cookie.domain = cookie.domain || hostname;1872 }1873 }1874 1875}), {1876 isUsable: function(endpoint, callback, context) {1877 callback.call(context, typeof endpoint === 'string');1878 }1879});1880Faye.Transport.register('long-polling', Faye.Transport.NodeHttp);1881var crypto = require('crypto'),1882 fs = require('fs'),1883 http = require('http'),1884 https = require('https'),1885 net = require('net'),1886 path = require('path'),1887 tls = require('tls'),1888 url = require('url'),1889 querystring = require('querystring');1890Faye.WebSocket = require('faye-websocket');1891Faye.EventSource = Faye.WebSocket.EventSource;1892Faye.CookieJar = require('cookiejar').CookieJar;1893Faye.logger = function(message) {1894 console.log(message);1895};1896Faye.withDataFor = function(transport, callback, context) {1897 var data = '';1898 transport.addListener('data', function(chunk) { data += chunk });1899 transport.addListener('end', function() {1900 callback.call(context, data);1901 });1902};1903Faye.NodeAdapter = Faye.Class({1904 DEFAULT_ENDPOINT: '/bayeux',1905 SCRIPT_PATH: path.dirname(__filename) + '/faye-browser-min.js',1906 1907 TYPE_JSON: {'Content-Type': 'application/json'},1908 TYPE_SCRIPT: {'Content-Type': 'text/javascript'},1909 TYPE_TEXT: {'Content-Type': 'text/plain'},1910 1911 initialize: function(options) {1912 this._options = options || {};1913 this._endpoint = this._options.mount || this.DEFAULT_ENDPOINT;1914 this._endpointRe = new RegExp('^' + this._endpoint + '(/[^/]*)*(\\.js)?$');1915 this._server = new Faye.Server(this._options);1916 1917 var extensions = this._options.extensions;1918 if (!extensions) return;1919 1920 extensions = [].concat(extensions);1921 for (var i = 0, n = extensions.length; i < n; i++)1922 this.addExtension(extensions[i]);1923 },1924 1925 addExtension: function(extension) {1926 return this._server.addExtension(extension);1927 },1928 1929 removeExtension: function(extension) {1930 return this._server.removeExtension(extension);1931 },1932 1933 bind: function() {1934 return this._server._engine.bind.apply(this._server._engine, arguments);1935 },1936 1937 unbind: function() {1938 return this._server._engine.unbind.apply(this._server._engine, arguments);1939 },1940 1941 getClient: function() {1942 return this._client = this._client || new Faye.Client(this._server);1943 },1944 1945 listen: function(port, sslOptions, callback, context) {1946 var ssl = sslOptions && sslOptions.cert1947 ? { key: fs.readFileSync(sslOptions.key),1948 cert: fs.readFileSync(sslOptions.cert)1949 }1950 : null;1951 1952 if (ssl && sslOptions.ca)1953 ssl.ca = Faye.map(sslOptions.ca, function(ca) { return fs.readFileSync(ca) });1954 1955 var httpServer = ssl1956 ? https.createServer(ssl, function() {})1957 : http.createServer(function() {});1958 1959 this.attach(httpServer);1960 httpServer.listen(port, function() {1961 if (callback) callback.call(context);1962 });1963 this._httpServer = httpServer;1964 },1965 1966 stop: function(callback, context) {1967 this._httpServer.addListener('close', function() {1968 if (callback) callback.call(context);1969 });1970 this._httpServer.close();1971 },1972 1973 attach: function(httpServer) {1974 this._overrideListeners(httpServer, 'request', 'handle');1975 this._overrideListeners(httpServer, 'upgrade', 'handleUpgrade');1976 },1977 1978 _overrideListeners: function(httpServer, event, method) {1979 var listeners = httpServer.listeners(event),1980 self = this;1981 1982 httpServer.removeAllListeners(event);1983 1984 httpServer.addListener(event, function(request) {1985 if (self.check(request)) return self[method].apply(self, arguments);1986 1987 for (var i = 0, n = listeners.length; i < n; i++)1988 listeners[i].apply(this, arguments);1989 });1990 },1991 1992 check: function(request) {1993 var path = url.parse(request.url, true).pathname;1994 return !!this._endpointRe.test(path);1995 },1996 1997 handle: function(request, response) {1998 var requestUrl = url.parse(request.url, true),1999 requestMethod = request.method,2000 self = this;2001 2002 if (/\.js$/.test(requestUrl.pathname))2003 return this._serveClientScript(request, response);2004 2005 if (requestMethod === 'OPTIONS')2006 return this._handleOptions(request, response);2007 2008 if (Faye.EventSource.isEventSource(request))2009 return this.handleEventSource(request, response);2010 2011 if (requestMethod === 'GET')2012 return this._callWithParams(request, response, requestUrl.query);2013 2014 if (requestMethod === 'POST')2015 return Faye.withDataFor(request, function(data) {2016 var type = (request.headers['content-type'] || '').split(';')[0],2017 params = (type === 'application/json')2018 ? {message: data}2019 : querystring.parse(data);2020 2021 self._callWithParams(request, response, params);2022 });2023 2024 this._returnError(response);2025 },2026 2027 handleUpgrade: function(request, socket, head) {2028 var ws = new Faye.WebSocket(request, socket, head, null, {ping: this._options.ping}),2029 clientId = null,2030 self = this;2031 2032 ws.onmessage = function(event) {2033 try {2034 var message = JSON.parse(event.data);2035 clientId = [].concat(message)[0].clientId;2036 2037 self.debug('Received via WebSocket[' + ws.version + ']: ?', message);2038 self._server.openSocket(clientId, ws);2039 2040 self._server.process(message, false, function(replies) {2041 if (ws) ws.send(JSON.stringify(replies));2042 });2043 } catch (e) {2044 self.error(e.message + '\nBacktrace:\n' + e.stack);2045 }2046 };2047 2048 ws.onclose = function(event) {2049 self._server.closeSocket(clientId);2050 ws = null;2051 };2052 },2053 2054 handleEventSource: function(request, response) {2055 var es = new Faye.EventSource(request, response, {ping: this._options.ping}),2056 clientId = es.url.split('/').pop(),2057 self = this;2058 2059 this.debug('Opened EventSource connection for ?', clientId);2060 this._server.openSocket(clientId, es);2061 2062 es.onclose = function(event) {2063 self._server.closeSocket(clientId);2064 es = null;2065 };2066 },2067 2068 _serveClientScript: function(request, response) {2069 this._clientScript = this._clientScript || fs.readFileSync(this.SCRIPT_PATH);2070 this._clientDigest = this._clientDigest || crypto.createHash('sha1').update(this._clientScript).digest('hex');2071 this._clientMtime = this._clientMtime || fs.statSync(this.SCRIPT_PATH).mtime;2072 2073 var headers = Faye.extend({}, this.TYPE_SCRIPT),2074 ims = request.headers['if-modified-since'];2075 2076 headers['ETag'] = this._clientDigest;2077 headers['Last-Modified'] = this._clientMtime.toGMTString();2078 2079 if (request.headers['if-none-match'] === this._clientDigest) {2080 response.writeHead(304, headers);2081 response.end();2082 } else if (ims && this._clientMtime <= new Date(ims)) {2083 response.writeHead(304, headers);2084 response.end();2085 } else {2086 response.writeHead(200, headers);2087 response.write(this._clientScript);2088 response.end();2089 }2090 },2091 2092 _callWithParams: function(request, response, params) {2093 try {2094 var message = JSON.parse(params.message),2095 jsonp = params.jsonp || Faye.JSONP_CALLBACK,2096 isGet = (request.method === 'GET'),2097 type = isGet ? this.TYPE_SCRIPT : this.TYPE_JSON;2098 this.debug('Received ?: ?', request.method, message);2099 if (isGet) this._server.flushConnection(message);2100 2101 this._server.process(message, false, function(replies) {2102 var body = JSON.stringify(replies),2103 headers = Faye.extend({}, type),2104 origin = request.headers.origin;2105 2106 if (isGet) {2107 body = jsonp + '(' + body + ');';2108 headers['Cache-Control'] = 'no-cache, no-store';2109 }2110 if (origin) headers['Access-Control-Allow-Origin'] = origin;2111 2112 this.debug('Returning ?', body);2113 response.writeHead(200, headers);2114 response.write(body);2115 response.end();2116 }, this);2117 } catch (e) {2118 this.error(e.message + '\nBacktrace:\n' + e.stack);2119 this._returnError(response);2120 }2121 },2122 2123 _handleOptions: function(request, response) {2124 var headers = {2125 'Access-Control-Allow-Origin': '*',2126 'Access-Control-Allow-Credentials': 'false',2127 'Access-Control-Max-Age': '86400',2128 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',2129 'Access-Control-Allow-Headers': 'Accept, Content-Type, X-Requested-With'2130 };2131 response.writeHead(200, headers);2132 response.write('');2133 response.end();2134 },2135 2136 _returnError: function(response) {2137 response.writeHead(400, this.TYPE_TEXT);2138 response.write('Bad request');2139 response.end();2140 }2141});2142Faye.extend(Faye.NodeAdapter.prototype, Faye.Logging);...

Full Screen

Full Screen

project-base.js

Source:project-base.js Github

copy

Full Screen

...121 const { specsStore, startSpecWatcher, ctDevServerPort, } = yield this.initializeSpecStore(cfg);122 if (this.testingType === 'component') {123 cfg.baseUrl = `http://localhost:${ctDevServerPort}`;124 }125 const [port, warning] = yield this._server.open(cfg, {126 getCurrentBrowser: () => this.browser,127 getSpec: () => this.spec,128 exit: (_a = this.options.args) === null || _a === void 0 ? void 0 : _a.exit,129 onError: this.options.onError,130 onWarning: this.options.onWarning,131 shouldCorrelatePreRequests: this.shouldCorrelatePreRequests,132 testingType: this.testingType,133 SocketCtor: this.testingType === 'e2e' ? socket_e2e_1.SocketE2E : socket_ct_1.SocketCt,134 specsStore,135 });136 this._isServerOpen = true;137 // if we didnt have a cfg.port138 // then get the port once we139 // open the server...

Full Screen

Full Screen

osc.js

Source:osc.js Github

copy

Full Screen

...30 port: this.portReplies // @param {number} Port of udp client for messaging31 }32 })33 })34 this._server.open()35 this._server.on('*', message => {36 if (message.args.length > 0) {37 log.info("OSC Received :: " + message.address + " with argument: " + message.args[0])38 } else {39 log.info("OSC Received :: " + message.address)40 }41 })42 // Special endpoints43 this._server.on('/get/audioDevices', message => {44 this._reply(message.address, JSON.stringify(this.audioDevices))45 })46 this._server.on('/get/screens', message => {47 this._reply(message.address, JSON.stringify(this.screens))48 })...

Full Screen

Full Screen

server-base.js

Source:server-base.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.ServerBase = void 0;4const tslib_1 = require("tslib");5require("./cwd");6const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));7const compression_1 = (0, tslib_1.__importDefault)(require("compression"));8const debug_1 = (0, tslib_1.__importDefault)(require("debug"));9const evil_dns_1 = (0, tslib_1.__importDefault)(require("evil-dns"));10const express_1 = (0, tslib_1.__importDefault)(require("express"));11const http_1 = (0, tslib_1.__importDefault)(require("http"));12const http_proxy_1 = (0, tslib_1.__importDefault)(require("http-proxy"));13const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));14const url_1 = (0, tslib_1.__importDefault)(require("url"));15const lazy_ass_1 = (0, tslib_1.__importDefault)(require("lazy-ass"));16const net_stubbing_1 = require("../../net-stubbing");17const network_1 = require("../../network");18const proxy_1 = require("../../proxy");19const errors_1 = (0, tslib_1.__importDefault)(require("./errors"));20const logger_1 = (0, tslib_1.__importDefault)(require("./logger"));21const request_1 = (0, tslib_1.__importDefault)(require("./request"));22const template_engine_1 = (0, tslib_1.__importDefault)(require("./template_engine"));23const class_helpers_1 = require("./util/class-helpers");24const origin_1 = (0, tslib_1.__importDefault)(require("./util/origin"));25const server_destroy_1 = require("./util/server_destroy");26const socket_allowed_1 = require("./util/socket_allowed");27const rewriter_1 = require("../../rewriter");28const routes_1 = require("./routes");29const routes_e2e_1 = require("./routes-e2e");30const routes_ct_1 = require("./routes-ct");31const ALLOWED_PROXY_BYPASS_URLS = [32 '/',33 '/__cypress/runner/cypress_runner.css',34 '/__cypress/runner/cypress_runner.js',35 '/__cypress/runner/favicon.ico',36];37const DEFAULT_DOMAIN_NAME = 'localhost';38const fullyQualifiedRe = /^https?:\/\//;39const debug = (0, debug_1.default)('cypress:server:server-base');40const _isNonProxiedRequest = (req) => {41 // proxied HTTP requests have a URL like: "http://example.com/foo"42 // non-proxied HTTP requests have a URL like: "/foo"43 return req.proxiedUrl.startsWith('/');44};45const _forceProxyMiddleware = function (clientRoute) {46 // normalize clientRoute to help with comparison47 const trimmedClientRoute = lodash_1.default.trimEnd(clientRoute, '/');48 return function (req, res, next) {49 const trimmedUrl = lodash_1.default.trimEnd(req.proxiedUrl, '/');50 if (_isNonProxiedRequest(req) && !ALLOWED_PROXY_BYPASS_URLS.includes(trimmedUrl) && (trimmedUrl !== trimmedClientRoute)) {51 // this request is non-proxied and non-allowed, redirect to the runner error page52 return res.redirect(clientRoute);53 }54 return next();55 };56};57const setProxiedUrl = function (req) {58 // proxiedUrl is the full URL with scheme, host, and port59 // it will only be fully-qualified if the request was proxied.60 // this function will set the URL of the request to be the path61 // only, which can then be used to proxy the request.62 // bail if we've already proxied the url63 if (req.proxiedUrl) {64 return;65 }66 // backup the original proxied url67 // and slice out the host/origin68 // and only leave the path which is69 // how browsers would normally send70 // use their url71 req.proxiedUrl = network_1.uri.removeDefaultPort(req.url).format();72 req.url = network_1.uri.getPath(req.url);73};74const notSSE = (req, res) => {75 return (req.headers.accept !== 'text/event-stream') && compression_1.default.filter(req, res);76};77class ServerBase {78 constructor() {79 this.ensureProp = class_helpers_1.ensureProp;80 this.isListening = false;81 // @ts-ignore82 this.request = (0, request_1.default)();83 this.socketAllowed = new socket_allowed_1.SocketAllowed();84 this._middleware = null;85 this._baseUrl = null;86 this._fileServer = null;87 }88 get server() {89 return this.ensureProp(this._server, 'open');90 }91 get socket() {92 return this.ensureProp(this._socket, 'open');93 }94 get nodeProxy() {95 return this.ensureProp(this._nodeProxy, 'open');96 }97 get networkProxy() {98 return this.ensureProp(this._networkProxy, 'open');99 }100 get netStubbingState() {101 return this.ensureProp(this._netStubbingState, 'open');102 }103 get httpsProxy() {104 return this.ensureProp(this._httpsProxy, 'open');105 }106 open(config, { getSpec, getCurrentBrowser, onError, onWarning, shouldCorrelatePreRequests, specsStore, testingType, SocketCtor, exit, }) {107 debug('server open');108 (0, lazy_ass_1.default)(lodash_1.default.isPlainObject(config), 'expected plain config object', config);109 return bluebird_1.default.try(() => {110 if (!config.baseUrl && testingType === 'component') {111 throw new Error('ServerCt#open called without config.baseUrl.');112 }113 const app = this.createExpressApp(config);114 logger_1.default.setSettings(config);115 this._nodeProxy = http_proxy_1.default.createProxyServer({116 target: config.baseUrl && testingType === 'component' ? config.baseUrl : undefined,117 });118 this._socket = new SocketCtor(config);119 network_1.clientCertificates.loadClientCertificateConfig(config);120 const getRemoteState = () => {121 return this._getRemoteState();122 };123 this.createNetworkProxy(config, getRemoteState, shouldCorrelatePreRequests);124 if (config.experimentalSourceRewriting) {125 (0, rewriter_1.createInitialWorkers)();126 }127 this.createHosts(config.hosts);128 const routeOptions = {129 config,130 specsStore,131 getRemoteState,132 nodeProxy: this.nodeProxy,133 networkProxy: this._networkProxy,134 onError,135 getSpec,136 getCurrentBrowser,137 testingType,138 exit,139 };140 const runnerSpecificRouter = testingType === 'e2e'141 ? (0, routes_e2e_1.createRoutesE2E)(routeOptions)142 : (0, routes_ct_1.createRoutesCT)(routeOptions);143 app.use(runnerSpecificRouter);144 app.use((0, routes_1.createCommonRoutes)(routeOptions));145 return this.createServer(app, config, onWarning);146 });147 }148 createExpressApp(config) {149 const { morgan, clientRoute } = config;150 const app = (0, express_1.default)();151 // set the cypress config from the cypress.json file152 app.set('view engine', 'html');153 // since we use absolute paths, configure express-handlebars to not automatically find layouts154 // https://github.com/cypress-io/cypress/issues/2891155 app.engine('html', template_engine_1.default.render);156 // handle the proxied url in case157 // we have not yet started our websocket server158 app.use((req, res, next) => {159 setProxiedUrl(req);160 // useful for tests161 if (this._middleware) {162 this._middleware(req, res);163 }164 // always continue on165 return next();166 });167 app.use(_forceProxyMiddleware(clientRoute));168 app.use(require('cookie-parser')());169 app.use((0, compression_1.default)({ filter: notSSE }));170 if (morgan) {171 app.use(require('morgan')('dev'));172 }173 // errorhandler174 app.use(require('errorhandler')());175 // remove the express powered-by header176 app.disable('x-powered-by');177 return app;178 }179 getHttpServer() {180 return this._server;181 }182 portInUseErr(port) {183 const e = errors_1.default.get('PORT_IN_USE_SHORT', port);184 e.port = port;185 e.portInUse = true;186 return e;187 }188 createNetworkProxy(config, getRemoteState, shouldCorrelatePreRequests) {189 const getFileServerToken = () => {190 return this._fileServer.token;191 };192 this._netStubbingState = (0, net_stubbing_1.netStubbingState)();193 // @ts-ignore194 this._networkProxy = new proxy_1.NetworkProxy({195 config,196 shouldCorrelatePreRequests,197 getRemoteState,198 getFileServerToken,199 socket: this.socket,200 netStubbingState: this.netStubbingState,201 request: this.request,202 });203 }204 startWebsockets(automation, config, options = {}) {205 var _a;206 options.onRequest = this._onRequest.bind(this);207 options.netStubbingState = this.netStubbingState;208 options.getRenderedHTMLOrigins = (_a = this._networkProxy) === null || _a === void 0 ? void 0 : _a.http.getRenderedHTMLOrigins;209 options.onResetServerState = () => {210 this.networkProxy.reset();211 this.netStubbingState.reset();212 };213 const io = this.socket.startListening(this.server, automation, config, options);214 this._normalizeReqUrl(this.server);215 return io;216 }217 createHosts(hosts = []) {218 return lodash_1.default.each(hosts, (ip, host) => {219 return evil_dns_1.default.add(host, ip);220 });221 }222 addBrowserPreRequest(browserPreRequest) {223 this.networkProxy.addPendingBrowserPreRequest(browserPreRequest);224 }225 emitRequestEvent(eventName, data) {226 this.socket.toDriver('request:event', eventName, data);227 }228 _createHttpServer(app) {229 const svr = http_1.default.createServer(network_1.httpUtils.lenientOptions, app);230 (0, server_destroy_1.allowDestroy)(svr);231 // @ts-ignore232 return svr;233 }234 _port() {235 return this.server.address().port;236 }237 _listen(port, onError) {238 return new bluebird_1.default((resolve) => {239 const listener = () => {240 const address = this.server.address();241 this.isListening = true;242 debug('Server listening on ', address);243 this.server.removeListener('error', onError);244 return resolve(address.port);245 };246 return this.server.listen(port || 0, '127.0.0.1', listener);247 });248 }249 _onRequest(headers, automationRequest, options) {250 // @ts-ignore251 return this.request.sendPromise(headers, automationRequest, options);252 }253 _callRequestListeners(server, listeners, req, res) {254 return listeners.map((listener) => {255 return listener.call(server, req, res);256 });257 }258 _normalizeReqUrl(server) {259 // because socket.io removes all of our request260 // events, it forces the socket.io traffic to be261 // handled first.262 // however we need to basically do the same thing263 // it does and after we call into socket.io go264 // through and remove all request listeners265 // and change the req.url by slicing out the host266 // because the browser is in proxy mode267 const listeners = server.listeners('request').slice(0);268 server.removeAllListeners('request');269 server.on('request', (req, res) => {270 setProxiedUrl(req);271 this._callRequestListeners(server, listeners, req, res);272 });273 }274 _getRemoteState() {275 // {276 // origin: "http://localhost:2020"277 // fileServer:278 // strategy: "file"279 // domainName: "localhost"280 // props: null281 // }282 // {283 // origin: "https://foo.google.com"284 // strategy: "http"285 // domainName: "google.com"286 // props: {287 // port: 443288 // tld: "com"289 // domain: "google"290 // }291 // }292 const props = lodash_1.default.extend({}, {293 auth: this._remoteAuth,294 props: this._remoteProps,295 origin: this._remoteOrigin,296 strategy: this._remoteStrategy,297 visiting: this._remoteVisitingUrl,298 domainName: this._remoteDomainName,299 fileServer: this._remoteFileServer,300 });301 debug('Getting remote state: %o', props);302 return props;303 }304 _onDomainSet(fullyQualifiedUrl, options = {}) {305 const l = (type, val) => {306 return debug('Setting', type, val);307 };308 this._remoteAuth = options.auth;309 l('remoteAuth', this._remoteAuth);310 // if this isn't a fully qualified url311 // or if this came to us as <root> in our tests312 // then we know to go back to our default domain313 // which is the localhost server314 if ((fullyQualifiedUrl === '<root>') || !fullyQualifiedRe.test(fullyQualifiedUrl)) {315 this._remoteOrigin = `http://${DEFAULT_DOMAIN_NAME}:${this._port()}`;316 this._remoteStrategy = 'file';317 this._remoteFileServer = `http://${DEFAULT_DOMAIN_NAME}:${(this._fileServer != null ? this._fileServer.port() : undefined)}`;318 this._remoteDomainName = DEFAULT_DOMAIN_NAME;319 this._remoteProps = null;320 l('remoteOrigin', this._remoteOrigin);321 l('remoteStrategy', this._remoteStrategy);322 l('remoteHostAndPort', this._remoteProps);323 l('remoteDocDomain', this._remoteDomainName);324 l('remoteFileServer', this._remoteFileServer);325 }326 else {327 this._remoteOrigin = (0, origin_1.default)(fullyQualifiedUrl);328 this._remoteStrategy = 'http';329 this._remoteFileServer = null;330 // set an object with port, tld, and domain properties331 // as the remoteHostAndPort332 this._remoteProps = network_1.cors.parseUrlIntoDomainTldPort(this._remoteOrigin);333 // @ts-ignore334 this._remoteDomainName = lodash_1.default.compact([this._remoteProps.domain, this._remoteProps.tld]).join('.');335 l('remoteOrigin', this._remoteOrigin);336 l('remoteHostAndPort', this._remoteProps);337 l('remoteDocDomain', this._remoteDomainName);338 }339 return this._getRemoteState();340 }341 proxyWebsockets(proxy, socketIoRoute, req, socket, head) {342 // bail if this is our own namespaced socket.io request343 if (req.url.startsWith(socketIoRoute)) {344 if (!this.socketAllowed.isRequestAllowed(req)) {345 socket.write('HTTP/1.1 400 Bad Request\r\n\r\nRequest not made via a Cypress-launched browser.');346 socket.end();347 }348 // we can return here either way, if the socket is still valid socket.io will hook it up349 return;350 }351 const host = req.headers.host;352 if (host) {353 // get the protocol using req.connection.encrypted354 // get the port & hostname from host header355 const fullUrl = `${req.connection.encrypted ? 'https' : 'http'}://${host}`;356 const { hostname, protocol } = url_1.default.parse(fullUrl);357 const { port } = network_1.cors.parseUrlIntoDomainTldPort(fullUrl);358 const onProxyErr = (err, req, res) => {359 return debug('Got ERROR proxying websocket connection', { err, port, protocol, hostname, req });360 };361 return proxy.ws(req, socket, head, {362 secure: false,363 target: {364 host: hostname,365 port,366 protocol,367 },368 agent: network_1.agent,369 }, onProxyErr);370 }371 // we can't do anything with this socket372 // since we don't know how to proxy it!373 if (socket.writable) {374 return socket.end();375 }376 }377 reset() {378 var _a, _b;379 (_a = this._networkProxy) === null || _a === void 0 ? void 0 : _a.reset();380 const baseUrl = (_b = this._baseUrl) !== null && _b !== void 0 ? _b : '<root>';381 return this._onDomainSet(baseUrl);382 }383 _close() {384 // bail early we dont have a server or we're not385 // currently listening386 if (!this._server || !this.isListening) {387 return bluebird_1.default.resolve(true);388 }389 this.reset();390 logger_1.default.unsetSettings();391 evil_dns_1.default.clear();392 return this._server.destroyAsync()393 .then(() => {394 this.isListening = false;395 });396 }397 close() {398 var _a, _b, _c;399 return bluebird_1.default.all([400 this._close(),401 (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(),402 (_b = this._fileServer) === null || _b === void 0 ? void 0 : _b.close(),403 (_c = this._httpsProxy) === null || _c === void 0 ? void 0 : _c.close(),404 ])405 .then((res) => {406 this._middleware = null;407 return res;408 });409 }410 end() {411 return this._socket && this._socket.end();412 }413 changeToUrl(url) {414 return this._socket && this._socket.changeToUrl(url);415 }416 onRequest(fn) {417 this._middleware = fn;418 }419 onNextRequest(fn) {420 return this.onRequest((...args) => {421 fn.apply(this, args);422 this._middleware = null;423 });424 }425 onUpgrade(req, socket, head, socketIoRoute) {426 debug('Got UPGRADE request from %s', req.url);427 return this.proxyWebsockets(this.nodeProxy, socketIoRoute, req, socket, head);428 }429 callListeners(req, res) {430 const listeners = this.server.listeners('request').slice(0);431 return this._callRequestListeners(this.server, listeners, req, res);432 }433 onSniUpgrade(req, socket, head) {434 const upgrades = this.server.listeners('upgrade').slice(0);435 return upgrades.map((upgrade) => {436 return upgrade.call(this.server, req, socket, head);437 });438 }439 onConnect(req, socket, head) {440 debug('Got CONNECT request from %s', req.url);441 socket.once('upstream-connected', this.socketAllowed.add);442 return this.httpsProxy.connect(req, socket, head);443 }444 sendSpecList(specs, testingType) {445 return this.socket.sendSpecList(specs, testingType);446 }447}...

Full Screen

Full Screen

node_adapter.js

Source:node_adapter.js Github

copy

Full Screen

1'use strict';2var Buffer = require('safe-buffer').Buffer,3 path = require('path'),4 querystring = require('querystring'),5 url = require('url'),6 WebSocket = require('faye-websocket'),7 EventSource = WebSocket.EventSource;8var constants = require('../util/constants'),9 assign = require('../util/assign'),10 idFromMessages = require('../util/id_from_messages'),11 toJSON = require('../util/to_json'),12 validateOptions = require('../util/validate_options'),13 Class = require('../util/class'),14 Logging = require('../mixins/logging'),15 Publisher = require('../mixins/publisher'),16 Client = require('../protocol/client'),17 Server = require('../protocol/server'),18 contenttypes = require('./content_types'),19 StaticServer = require('./static_server');20var NodeAdapter = Class({ className: 'NodeAdapter',21 DEFAULT_ENDPOINT: '/bayeux',22 SCRIPT_PATH: 'faye-browser-min.js',23 VALID_JSONP_CALLBACK: /^[a-z_\$][a-z0-9_\$]*(\.[a-z_\$][a-z0-9_\$]*)*$/i,24 initialize: function(options) {25 this._options = options || {};26 validateOptions(this._options, ['engine', 'mount', 'ping', 'timeout', 'extensions', 'websocketExtensions']);27 this._extensions = [];28 this._endpoint = this._options.mount || this.DEFAULT_ENDPOINT;29 this._endpointRe = new RegExp('^' + this._endpoint.replace(/\/$/, '') + '(/[^/]*)*(\\.[^\\.]+)?$');30 this._server = Server.create(this._options);31 this._static = new StaticServer(path.join(__dirname, '..', '..', 'client'), /\.(?:js|map)$/);32 this._static.map(path.basename(this._endpoint) + '.js', this.SCRIPT_PATH);33 this._static.map('client.js', this.SCRIPT_PATH);34 var extensions = this._options.extensions,35 websocketExtensions = this._options.websocketExtensions,36 i, n;37 if (extensions) {38 extensions = [].concat(extensions);39 for (i = 0, n = extensions.length; i < n; i++)40 this.addExtension(extensions[i]);41 }42 if (websocketExtensions) {43 websocketExtensions = [].concat(websocketExtensions);44 for (i = 0, n = websocketExtensions.length; i < n; i++)45 this.addWebsocketExtension(websocketExtensions[i]);46 }47 },48 listen: function() {49 throw new Error('The listen() method is deprecated - use the attach() method to bind Faye to an http.Server');50 },51 addExtension: function(extension) {52 return this._server.addExtension(extension);53 },54 removeExtension: function(extension) {55 return this._server.removeExtension(extension);56 },57 addWebsocketExtension: function(extension) {58 this._extensions.push(extension);59 },60 close: function() {61 return this._server.close();62 },63 getClient: function() {64 return this._client = this._client || new Client(this._server);65 },66 attach: function(httpServer) {67 this._overrideListeners(httpServer, 'request', 'handle');68 this._overrideListeners(httpServer, 'upgrade', 'handleUpgrade');69 },70 _overrideListeners: function(httpServer, event, method) {71 var listeners = httpServer.listeners(event),72 self = this;73 httpServer.removeAllListeners(event);74 httpServer.on(event, function(request) {75 if (self.check(request)) return self[method].apply(self, arguments);76 for (var i = 0, n = listeners.length; i < n; i++)77 listeners[i].apply(this, arguments);78 });79 },80 check: function(request) {81 var path = url.parse(request.url, true).pathname;82 return !!this._endpointRe.test(path);83 },84 handle: function(request, response) {85 var requestUrl = url.parse(request.url, true),86 requestMethod = request.method,87 self = this;88 request.originalUrl = request.url;89 request.on('error', function(error) { self._returnError(response, error) });90 response.on('error', function(error) { self._returnError(null, error) });91 if (this._static.test(requestUrl.pathname))92 return this._static.call(request, response);93 // http://groups.google.com/group/faye-users/browse_thread/thread/4a01bb7d25d3636a94 if (requestMethod === 'OPTIONS' || request.headers['access-control-request-method'] === 'POST')95 return this._handleOptions(request, response);96 if (EventSource.isEventSource(request))97 return this.handleEventSource(request, response);98 if (requestMethod === 'GET')99 return this._callWithParams(request, response, requestUrl.query);100 if (requestMethod === 'POST')101 return this._concatStream(request, function(data) {102 var type = (request.headers['content-type'] || '').split(';')[0],103 params = (type === 'application/json')104 ? { message: data }105 : querystring.parse(data);106 request.body = data;107 this._callWithParams(request, response, params);108 }, this);109 this._returnError(response, { message: 'Unrecognized request type' });110 },111 _callWithParams: function(request, response, params) {112 if (!params.message)113 return this._returnError(response, { message: 'Received request with no message: ' + this._formatRequest(request) });114 try {115 this.debug('Received message via HTTP ' + request.method + ': ?', params.message);116 var message = this._parseJSON(params.message),117 jsonp = params.jsonp || constants.JSONP_CALLBACK,118 isGet = (request.method === 'GET'),119 type = isGet ? contenttypes.TYPE_SCRIPT : contenttypes.TYPE_JSON,120 headers = assign({}, type),121 origin = request.headers.origin;122 if (!this.VALID_JSONP_CALLBACK.test(jsonp))123 return this._returnError(response, { message: 'Invalid JSON-P callback: ' + jsonp });124 headers['Cache-Control'] = 'no-cache, no-store';125 headers['X-Content-Type-Options'] = 'nosniff';126 if (origin) {127 headers['Access-Control-Allow-Credentials'] = 'true';128 headers['Access-Control-Allow-Origin'] = origin;129 }130 this._server.process(message, request, function(replies) {131 var body = toJSON(replies);132 if (isGet) {133 body = '/**/' + jsonp + '(' + this._jsonpEscape(body) + ');';134 headers['Content-Disposition'] = 'attachment; filename=f.txt';135 }136 headers['Content-Length'] = Buffer.from(body, 'utf8').length.toString();137 this.debug('HTTP response: ?', body);138 response.writeHead(200, headers);139 response.end(body);140 }, this);141 } catch (error) {142 this._returnError(response, error);143 }144 },145 _jsonpEscape: function(json) {146 return json.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');147 },148 handleUpgrade: function(request, socket, head) {149 var options = { extensions: this._extensions, ping: this._options.ping },150 ws = new WebSocket(request, socket, head, [], options),151 clientId = null,152 self = this;153 request.originalUrl = request.url;154 ws.onmessage = function(event) {155 try {156 self.debug('Received message via WebSocket[' + ws.version + ']: ?', event.data);157 var message = self._parseJSON(event.data),158 cid = idFromMessages(message);159 if (clientId && cid && cid !== clientId) self._server.closeSocket(clientId, false);160 self._server.openSocket(cid, ws, request);161 if (cid) clientId = cid;162 self._server.process(message, request, function(replies) {163 if (ws) ws.send(toJSON(replies));164 });165 } catch (error) {166 console.log(error.stack);167 self.error(error.message + '\nBacktrace:\n' + error.stack);168 }169 };170 ws.onclose = function(event) {171 self._server.closeSocket(clientId);172 ws = null;173 };174 },175 handleEventSource: function(request, response) {176 var es = new EventSource(request, response, { ping: this._options.ping }),177 clientId = es.url.split('/').pop(),178 self = this;179 this.debug('Opened EventSource connection for ?', clientId);180 this._server.openSocket(clientId, es, request);181 es.onclose = function(event) {182 self._server.closeSocket(clientId);183 es = null;184 };185 },186 _handleOptions: function(request, response) {187 var origin = request.headers.origin || request.headers.referer;188 var headers = {189 'Access-Control-Allow-Credentials': 'true',190 'Access-Control-Allow-Headers': 'Accept, Authorization, Content-Type, Pragma, X-Requested-With',191 'Access-Control-Allow-Methods': 'POST, GET',192 'Access-Control-Allow-Origin': origin || '*',193 'Access-Control-Max-Age': '86400'194 };195 response.writeHead(200, headers);196 response.end('');197 },198 _concatStream: function(stream, callback, context) {199 var chunks = [],200 length = 0;201 stream.on('data', function(chunk) {202 chunks.push(chunk);203 length += chunk.length;204 });205 stream.on('end', function() {206 var buffer = Buffer.alloc(length),207 offset = 0;208 for (var i = 0, n = chunks.length; i < n; i++) {209 chunks[i].copy(buffer, offset);210 offset += chunks[i].length;211 }212 callback.call(context, buffer.toString('utf8'));213 });214 },215 _parseJSON: function(json) {216 var data = JSON.parse(json);217 if (typeof data === 'object') return data;218 throw new SyntaxError('JSON messages must contain an object or array');219 },220 _formatRequest: function(request) {221 var method = request.method.toUpperCase(),222 string = 'curl -X ' + method;223 string += " 'http://" + request.headers.host + request.url + "'";224 if (method === 'POST') {225 string += " -H 'Content-Type: " + request.headers['content-type'] + "'";226 string += " -d '" + request.body + "'";227 }228 return string;229 },230 _returnError: function(response, error) {231 var message = error.message;232 if (error.stack) message += '\nBacktrace:\n' + error.stack;233 this.error(message);234 if (!response) return;235 response.writeHead(400, contenttypes.TYPE_TEXT);236 response.end('Bad request');237 }238});239for (var method in Publisher) (function(method) {240 NodeAdapter.prototype[method] = function() {241 return this._server._engine[method].apply(this._server._engine, arguments);242 };243})(method);244assign(NodeAdapter.prototype, Logging);...

Full Screen

Full Screen

connector.js

Source:connector.js Github

copy

Full Screen

1"use strict";2var Subscribable = require("../lib/utils/subscribable");3var Handler = require("../lib/wDispatcher/handler");4var String = require("../lib/wType/string");5var Address = require("../lib/wType/address");6var Uint64 = require("../lib/wType/uint64");7var Object = require("../lib/wType/object");8var Vocabulary = require("../lib/wType/vocabulary");9var Socket = require("../lib/wSocket/socket");10var Connector = Subscribable.inherit({11 "className": "Connector",12 "constructor": function(dp, srv, cmds) {13 Subscribable.fn.constructor.call(this);14 15 this._dispatcher = dp;16 this._server = srv;17 this._commands = cmds;18 this._nodes = global.Object.create(null);19 this._ignoredNodes = global.Object.create(null);20 21 this._server.on("newConnection", this._onNewConnection, this);22 this._server.on("closedConnection", this._onClosedConnection, this);23 24 var cn = new Address(["connect"]);25 var ch = new Handler(this._commands.getAddress()["+"](cn), this, this._h_connect);26 var vc = new Vocabulary();27 vc.insert("address", new Uint64(Object.objectType.String));28 vc.insert("port", new Uint64(Object.objectType.Uint64));29 this._commands.addCommand("connect", ch, vc);30 this._commands.enableCommand("connect", true);31 cn.destructor();32 },33 "destructor": function() {34 this._server.off("newConnection", this._onNewConnection, this);35 this._server.off("closedConnection", this._onClosedConnection, this);36 37 this._commands.removeCommand("connect");38 39 for (var key in this._nodes) {40 this._commands.removeCommand("disconnect" + key);41 }42 43 Subscribable.fn.destructor.call(this);44 },45 "addIgnoredNode": function(name) {46 this._ignoredNodes[name] = true;47 },48 "sendTo": function(key, event) {49 var id = this._nodes[key];50 if (!id) {51 throw new Error("An attempt to access non existing node in connector");52 }53 this._server.getConnection(id).send(event);54 },55 "_onNewConnection": function(socket) {56 var name = socket.getRemoteName().toString();57 58 if (this._ignoredNodes[name] === undefined) {59 if (this._nodes[name] === undefined) {60 if (this._server.getName().toString() === name) {61 this.trigger("serviceMessage", "An attempt to connect node to itself, closing connection", 1);62 setTimeout(this._server.closeConnection.bind(this._server, socket.getId()));63 } else {64 var dc = "disconnect";65 var dn = dc + name;66 var dh = new Handler(this._commands.getAddress()["+"](new Address([dc, name])), this, this._h_disconnect);67 this._commands.addCommand(dn, dh, new Vocabulary());68 this._commands.enableCommand(dn, true);69 70 this._nodes[name] = socket.getId();71 72 this.trigger("serviceMessage", "New connection, id: " + socket.getId().toString(), 0);73 socket.on("message", this._dispatcher.pass, this._dispatcher);74 this.trigger("nodeConnected", name);75 }76 } else {77 this.trigger("serviceMessage", "Node " + name + " tried to connect, but connection with that node is already open, closing new connection", 1);78 setTimeout(this._server.closeConnection.bind(this._server, socket.getId()));79 }80 } else {81 this.trigger("serviceMessage", "New connection, id: " + socket.getId().toString(), 0);82 socket.on("message", this._dispatcher.pass, this._dispatcher);83 }84 },85 "_onClosedConnection": function(socket) {86 this.trigger("serviceMessage", "Connection closed, id: " + socket.getId().toString());87 88 var name = socket.getRemoteName().toString();89 if (this._ignoredNodes[name] === undefined) {90 if (this._nodes[name]) {91 this._commands.removeCommand("disconnect" + name);92 delete this._nodes[name];93 this.trigger("nodeDisconnected", name);94 }95 }96 },97 "getNodeSocket": function(key) {98 var id = this._nodes[key];99 if (!id) {100 throw new Error("An attempt to access non existing node in connector");101 }102 return this._server.getConnection(id);103 },104 "_h_connect": function(ev) {105 var vc = ev.getData();106 this._server.openConnection(vc.at("address"), vc.at("port"));107 },108 "_h_disconnect": function(ev) {109 var addr = ev.getDestination();110 var id = this._nodes[addr.back().toString()];111 if (id) {112 this._server.closeConnection(id);113 }114 115 }116});...

Full Screen

Full Screen

wedding_app.js

Source:wedding_app.js Github

copy

Full Screen

...29 //then connect server30 this._server.addApi(require('./frontend')())31 this._server.addApi(require('./guest_api')())32 this._server.addApi(require('./photobooth')())33 this._server.open(this.port)34 return Promise.all([this.guestList(),this.userList()])35 }).then((results)=>{36 log.verbose(JSON.stringify(results)) 37 }).catch( err =>{38 log.channel('WeddingApp').errorTrace('Database sync error: ',err)39 })40 }41 shutdown() {42 if(this._server){43 this._server.close().then(()=>{44 if(this.db){45 return this.db.close().then(()=>{46 super.shutdown()47 }).catch(error=>{...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('button').click()2describe('My First Test', function() {3 it('Does not do much!', function() {4 cy.get('button').click()5 })6})7I am using the cy.fixture() method to get the file and then I am using the cy.get() method to get the input element that will allow me to upload the file. I am using the cy.get() method to get the input element and then I am using the .attachFile() method to upload the file. I am using the cy.get() method to get the input element and then I am using the .attachFile()

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.server({2})3cy.route({4})5cy.request('/api/v1/users')6 .its('status')7 .should('eq', 401)8cy.intercept({9}, {10})11cy.visit('/api/v1/users')12 .its('status')13 .should('eq', 401)

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('open', (options) => {2 const {url, width, height} = options;3 cy.task('open', {url, width, height}).then((browser) => {4 cy.wrap(browser, {log: false}).as('browser');5 });6 });7const open = require('open');8module.exports = (on, config) => {9 on('task', {10 open(options) {11 return open(options.url, {12 app: {13 },14 });15 },16 });17};

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.server();2cy.route('POST', '**/api/v1/organization/organizations').as('orgCreate');3cy.route('POST', '**/api/v1/organization/users').as('orgUserCreate');4cy.route('POST', '**/api/v1/organization/roles').as('orgRoleCreate');5cy.route('POST', '**/api/v1/organization/permissions').as('orgPermissionCreate');6cy.route('POST', '**/api/v1/organization/roles/permissions').as('orgRolePermissionCreate');7cy.route('POST', '**/api/v1/organization/users/roles').as('orgUserRoleCreate');8cy.get('input[name=organizationName]').type('Test Org');9cy.get('input[name=organizationCode]').type('testorg');10cy.get('input[name=organizationDescription]').type('Test Org');11cy.get('button[type=submit]').click();12cy.wait('@orgCreate').then((xhr) => {13 cy.wrap(xhr.requestBody).as('orgCreateBody');14 cy.wrap(xhr.responseBody).as('orgCreateResponse');15});16cy.get('@orgCreateBody').then((orgCreateBody) => {17 expect(orgCreateBody).to.have.property('name', 'Test Org');18 expect(orgCreateBody).to.have.property('code', 'testorg');19 expect(orgCreateBody).to.have.property('description', 'Test Org');20});21cy.get('@orgCreateResponse').then((orgCreateResponse) => {22 expect(orgCreateResponse).to.have.property('id');23 expect(orgCreateResponse).to.have.property('name', 'Test Org');24 expect(orgCreateResponse).to.have.property('code', 'testorg');25 expect(orgCreateResponse).to.have.property('description', 'Test Org');26});27cy.get('@orgCreateResponse').then((orgCreateResponse) => {28 cy.wrap(orgCreateResponse.id).as('orgId');29});30cy.get('@orgId').then((orgId) => {31 cy.get('input[name=firstName]').type('Test');32 cy.get('input[name=lastName]').type('User');33 cy.get('input[name=email]').type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function() {2 it('test', function() {3 cy.server()4 cy.route('GET', '/api/v1/users/1', 'fixture:users/1.json')5 })6})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful