<commit_before>/*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true */
/*
 * stompit.Socket
 * Copyright (c) 2013 Graham Daws <graham.daws@gmail.com>
 * MIT licensed
 */

var OutgoingFrameStream = require('./outgoing_frame_stream');
var IncomingFrameStream = require('./incoming_frame_stream');
var util                = require('util');
var events              = require('events');

function Socket(transportSocket, options) {

  events.EventEmitter.call(this);

  this._commandHandlers = options.commandHandlers;
  this._unknownCommandHandler = options.unknownCommand || function() {
    this.destroy();
  };

  this._destroyed = false;
  this._destroy = this.destroy.bind(this);

  this._transportSocket = transportSocket;
  transportSocket.on('error', this._destroy);

  var incoming = new IncomingFrameStream();
  this._incoming = incoming;
  transportSocket.pipe(incoming);

  this._currentFrame = null;

  this._output = new OutgoingFrameStream(transportSocket);

  this._heartbeat = options.heartbeat || [0, 0];
  this._heartbeatDelayMargin = options.heartbeatDelayMargin || 100;

  var self = this;

  var readFrameBody = function(frame, callback) {

    frame.on('end', callback);

    var handler = self._commandHandlers[frame.command];

    var beforeSendResponseCallback = function(
      responseFrame, responseEndCallback) {

      return self._beforeSendResponse(frame, responseFrame,
        responseEndCallback || function() {});
    };

    if (typeof handler === 'function') {
      handler.apply(self, [frame, beforeSendResponseCallback]);
    }
    else {
      self._unknownCommandHandler.apply(
        self, [frame, beforeSendResponseCallback]
      );
    }
  };

  var readIncomingFrame = function() {

    if (!self._currentFrame) {
      var frame = incoming.read();
      if (frame) {
        readFrameBody(frame, function(error) {
          self._currentFrame = null;
          if (!error) {
            readIncomingFrame();
          }
        });
      }
    }
  };

  incoming.on('readable', readIncomingFrame);
  incoming.on('error', this._destroy);

  incoming.on('end', function() {
    self._onInputEnd();
  });

  readIncomingFrame();
}

util.inherits(Socket, events.EventEmitter);

Socket.prototype._onInputEnd = function() {
  this.emit('end');
  this.destroy();
};

Socket.prototype.destroy = function(exception) {
  if (!this._destroyed) {
    this._destroyed = true;
    this._transportSocket.destroy(exception);
    if (exception) {
      this.emit('error', exception);
    }
  }
};

Socket.prototype.finishOutput = function() {
  this._output.finish();
  this.emit('finish');
};

Socket.prototype.hasFinishedOutput = function() {
  return this._output.hasFinished();
};

Socket.prototype.setVersion = function(version) {
  this._incoming.setVersion(version);
};

Socket.prototype.getTransportSocket = function() {
  return this._transportSocket;
};

Socket.prototype.setCommandHandler = function(command, handler) {
  this._commandHandlers[command] = handler;
};

Socket.prototype.setCommandHandlers = function(handlers) {
  this._commandHandlers = handlers;
};

Socket.prototype.setUnknownCommandHandler = function(handler) {
  this._unknownCommandHandler = handler;
};

Socket.prototype.sendFrame = function(command, headers, streamOptions) {
  var frame = this._output.frame(command, headers, streamOptions);
  frame.on('error', this._destroy);
  return frame;
};

Socket.prototype.getHeartbeat = function() {
  return this._heartbeat;
};

Socket.prototype.setHeartbeat = function(heartbeat) {
  this._heartbeat = heartbeat;
};

Socket.prototype._runHeartbeat = function(output, input) {

  output = output === 0 || this._heartbeat[0] === 0 ?
    0 : Math.max(output, this._heartbeat[0]);

  input = input === 0 || this._heartbeat[1] === 0 ?
    0 : Math.max(input, this._heartbeat[1]) + this._heartbeatDelayMargin;

  var self = this;

  var intervals = [];

  var stop = function() {
    for (var i = 0; i < intervals.length; i++) {
      clearInterval(intervals[i]);
    }
  };

  this.once('error', stop);
  this.once('end', stop);

  if (output > 0) {

    if (this._transportSocket.setNoDelay) {
      this._transportSocket.setNoDelay(true);
    }

    intervals.push(setInterval(function() {
      self._output.heartbeat();
    }, output));
  }

  if (input > 0) {

    var lastBytesRead = 0;

    intervals.push(setInterval(function() {

      var bytesRead = self._transportSocket.bytesRead;

      if (bytesRead - lastBytesRead === 0) {
        self.destroy(new errors.TransportError('connection timed out'));
      }

      lastBytesRead = bytesRead;

    }, input));
  }
};

Socket.prototype.isTransportError = function(error) {
  return error instanceof errors.TransportError;
};

Socket.prototype.isProtocolError = function(error) {
  return error instanceof errors.ProtocolError;
};

Socket.prototype.isApplicationError = function(error) {
  return error instanceof errors.ApplicationError;
};

Socket.prototype.createTransportError = function(message) {
  var error = new Error('Transport error:' + message);
  return error;
};

Socket.prototype.createProtocolError = function(message) {
  var error = new Error('Protocol error:' + message);
  return error;
};

Socket.prototype.createApplicationError = function(message) {
  var error = new Error('Application error:' + message);
  return error;
};

module.exports = Socket;
<commit_msg>Remove isTransportError, isProtocolError and isApplicationError methods.<commit_after>/*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true */
/*
 * stompit.Socket
 * Copyright (c) 2013 Graham Daws <graham.daws@gmail.com>
 * MIT licensed
 */

var OutgoingFrameStream = require('./outgoing_frame_stream');
var IncomingFrameStream = require('./incoming_frame_stream');
var util                = require('util');
var events              = require('events');

function Socket(transportSocket, options) {

  events.EventEmitter.call(this);

  this._commandHandlers = options.commandHandlers;
  this._unknownCommandHandler = options.unknownCommand || function() {
    this.destroy();
  };

  this._destroyed = false;
  this._destroy = this.destroy.bind(this);

  this._transportSocket = transportSocket;
  transportSocket.on('error', this._destroy);

  var incoming = new IncomingFrameStream();
  this._incoming = incoming;
  transportSocket.pipe(incoming);

  this._currentFrame = null;

  this._output = new OutgoingFrameStream(transportSocket);

  this._heartbeat = options.heartbeat || [0, 0];
  this._heartbeatDelayMargin = options.heartbeatDelayMargin || 100;

  var self = this;

  var readFrameBody = function(frame, callback) {

    frame.on('end', callback);

    var handler = self._commandHandlers[frame.command];

    var beforeSendResponseCallback = function(
      responseFrame, responseEndCallback) {

      return self._beforeSendResponse(frame, responseFrame,
        responseEndCallback || function() {});
    };

    if (typeof handler === 'function') {
      handler.apply(self, [frame, beforeSendResponseCallback]);
    }
    else {
      self._unknownCommandHandler.apply(
        self, [frame, beforeSendResponseCallback]
      );
    }
  };

  var readIncomingFrame = function() {

    if (!self._currentFrame) {
      var frame = incoming.read();
      if (frame) {
        readFrameBody(frame, function(error) {
          self._currentFrame = null;
          if (!error) {
            readIncomingFrame();
          }
        });
      }
    }
  };

  incoming.on('readable', readIncomingFrame);
  incoming.on('error', this._destroy);

  incoming.on('end', function() {
    self._onInputEnd();
  });

  readIncomingFrame();
}

util.inherits(Socket, events.EventEmitter);

Socket.prototype._onInputEnd = function() {
  this.emit('end');
  this.destroy();
};

Socket.prototype.destroy = function(exception) {
  if (!this._destroyed) {
    this._destroyed = true;
    this._transportSocket.destroy(exception);
    if (exception) {
      this.emit('error', exception);
    }
  }
};

Socket.prototype.finishOutput = function() {
  this._output.finish();
  this.emit('finish');
};

Socket.prototype.hasFinishedOutput = function() {
  return this._output.hasFinished();
};

Socket.prototype.setVersion = function(version) {
  this._incoming.setVersion(version);
};

Socket.prototype.getTransportSocket = function() {
  return this._transportSocket;
};

Socket.prototype.setCommandHandler = function(command, handler) {
  this._commandHandlers[command] = handler;
};

Socket.prototype.setCommandHandlers = function(handlers) {
  this._commandHandlers = handlers;
};

Socket.prototype.setUnknownCommandHandler = function(handler) {
  this._unknownCommandHandler = handler;
};

Socket.prototype.sendFrame = function(command, headers, streamOptions) {
  var frame = this._output.frame(command, headers, streamOptions);
  frame.on('error', this._destroy);
  return frame;
};

Socket.prototype.getHeartbeat = function() {
  return this._heartbeat;
};

Socket.prototype.setHeartbeat = function(heartbeat) {
  this._heartbeat = heartbeat;
};

Socket.prototype._runHeartbeat = function(output, input) {

  output = output === 0 || this._heartbeat[0] === 0 ?
    0 : Math.max(output, this._heartbeat[0]);

  input = input === 0 || this._heartbeat[1] === 0 ?
    0 : Math.max(input, this._heartbeat[1]) + this._heartbeatDelayMargin;

  var self = this;

  var intervals = [];

  var stop = function() {
    for (var i = 0; i < intervals.length; i++) {
      clearInterval(intervals[i]);
    }
  };

  this.once('error', stop);
  this.once('end', stop);

  if (output > 0) {

    if (this._transportSocket.setNoDelay) {
      this._transportSocket.setNoDelay(true);
    }

    intervals.push(setInterval(function() {
      self._output.heartbeat();
    }, output));
  }

  if (input > 0) {

    var lastBytesRead = 0;

    intervals.push(setInterval(function() {

      var bytesRead = self._transportSocket.bytesRead;

      if (bytesRead - lastBytesRead === 0) {
        self.destroy(self.createTransportError('connection timed out'));
      }

      lastBytesRead = bytesRead;

    }, input));
  }
};

Socket.prototype.createTransportError = function(message) {
  var error = new Error('Transport error: ' + message);
  return error;
};

Socket.prototype.createProtocolError = function(message) {
  var error = new Error('Protocol error: ' + message);
  return error;
};

Socket.prototype.createApplicationError = function(message) {
  var error = new Error('Application error: ' + message);
  return error;
};

module.exports = Socket;
<|endoftext|>


<commit_before>"use strict";

//var http = require('http');
var websocket = require('websocket-stream');
var http = require('flowhttp');
var Stream = require('stream');
var sockets = {};
var events = {};

exports.mux =  Multiplexer;
function Multiplexer () {

    /*
      header:
      - instance name
      - event name
      - request id
      - code 0 (data), 1 (error), // 2 (end) ??, read
      body:
      - data
    */

    var CoreInst = this;
    var multiplexer = Stream.Transform({
        transform: function (chunk, enc, next) {

            // parse chunk
            try {
                chunk = JSON.parse(chunk.toString());
            } catch (err) {
                console.log('CHUNK PARSE ERROR:', err);
            }

            let instance = chunk[0];
            let eventNme = chunk[1];
            let streamId = chunk[2];
            let type = chunk[3];
            let data = chunk[4];

            if (
                chunk.length < 4 ||
                typeof instance !== 'string' || !instance ||
                typeof eventNme !== 'string' || !eventNme ||
                typeof streamId !== 'string' || !streamId ||
                typeof type !== 'number' || type < 0 || type > 2
            ) {
                console.log(new Error('Socket.mux: Invalid frame.'));
                //this.push(/* send error frame */);
                return next();
            }

            console.log('FRAME:', chunk);

            // emit or get stream
            events[instance] = events[instance] || {};
            let event = events[instance][event] || (events[instance][event] = CoreInst.flow(eventNme, {to: instance, id: streamId}));

            // write chunk to stream
            event.write(data);

            // message type end
            // message type error
            // message type data

            // send data frame
            event.on('data', function (object) {
                let frame = [event.inst._name, event._name, event._id, object];
                multiplexer.push(JSON.stringify(frame));
            });

            // send error frame
            event.on('error', function (error) {
                let frame = [event.inst._name, event._name, event._id, object];
                multiplexer.push(JSON.stringify(frame));
            });

            next();
        }
    });

    return multiplexer;
};

exports.request = function (options) {

    var request;
    switch (options.net) {
        case '/':
        case 'http':

            /*
            var opts = {
                method: 'GET',
                path: '/' + instance._name + ':' + eventName.substr(1)
                headers: {},
                host: window.location.host,
                port: window.location.port
                responseType: 'response type to set on the underlying xhr object'
            };
            */

            let url = options.emit[0] === '/' || options.emit.indeOf('http') === 0 ? options.emit : '/' + options.to + ':' + options.emit

            // pipe http to flow event stream
            let method = options.method || (options.end ? 'get' : 'post');
            request = http[method](url);

            // collect all data for a classic request callback
            if (options.end) {
                var body = '';
                var error;
                request.on('response', function (res) {
                    if (res.statusCode !== 200) {
                        error = true;
                    }
                })
                request.on('data', function (chunk) {
                    body += chunk;
                })
                .on('error', function (err) {
                    body = err;
                })
                .on('end', function () {
                    if (error) {
                        error = body;
                        body = undefined;
                    }
                    options.end(error, body);
                });
                request.end();
            }
            break;

        case '>':
        case 'ws':

            let host = options.host || window.location.host;
            let socket = socket[host] || (socket[host] = websocket('wss://' + host));

            //CoreInst.flow();

            // TODO how to pipe multiplexer to socket and return the flow event?
            return sockets[host].pipe(Multiplexer()).pipe(sockets[host]);

            break;

        default:
            // TODO error
            return;
    }

    return request;
}

exports.reset = function () {

    // close all websockets
    for (var socket in sockets) {
        sockets[socket].close();
    }

    // remove socket refs
    sockets = {};
};

<commit_msg>websocket mux/demux to flow streams<commit_after>"use strict";

//var http = require('http');
var websocket = require('websocket-stream');
var http = require('flowhttp');
var Stream = require('stream');
var sockets = {};
var events = {};

exports.demux = Demux;
function Demux (CoreInst, socket) {

    /*
      header:
      - instance name
      - event name
      - request id
      - code 0 (data), 1 (error), // 2 (end) ??, read
      body:
      - data
    */

    var demux = Stream.Transform({
        transform: function (chunk, enc, next) {

            // parse chunk
            try {
                chunk = JSON.parse(chunk.toString());
            } catch (err) {
                return next(err);
            }

            let instance = chunk[0];
            let eventNme = chunk[1];
            let streamId = instance + eventNme + chunk[2];
            let type = chunk[3];
            let data = chunk[4];

            if (
                chunk.length < 4 ||
                typeof instance !== 'string' || !instance ||
                typeof eventNme !== 'string' || !eventNme ||
                typeof streamId !== 'string' || !streamId ||
                typeof type !== 'number' || type < 0 || type > 2
            ) {
                let err = new Error('Socket.mux: Invalid frame.');
                return next(err);
            }

            // emit or get stream
            socket._streams = socket._streams || {};
            let event = socket._streams[streamId];
            if (!event) {
                let options = {
                    to: instance,
                    emit: eventNme,
                    id: chunk[2]
                };
                event = socket._streams[streamId] = CoreInst.flow(eventNme, options);

                event.on('error', function (err) {
                    // TODO send error frame
                    console.log('DEMUX EVENT ERROR:', err);
                });

                // TODO pipe to mux
                event.pipe(Mux(socket, options));
            }

            // write chunk to stream
            // TODO event needs to write to the next correct section!
            event.write(data);

            // message type end
            // message type error
            // message type data

            next();
        }
    });

    return demux;
}

function Mux (socket, options) {

    var mux = Stream.Writable({
        objectMode: true,
        write: function (chunk, enc, next) {
            // create message
            // send message to socket

            let msg = [options.to, options.emit, options.id, 0, chunk];
            socket.write(JSON.stringify(msg));
            next();
        },
        read: function () {

        }
    });

    return mux;
}

exports.request = function (CoreInst, options) {

    var request;
    switch (options.net) {

        case '>':
        case 'ws':

            let host = options.host || window.location.host;
            let socket = sockets[host];
            if (!socket) {
                socket = websocket('wss://' + host);
                socket.pipe(Demux(CoreInst, socket));
                sockets[host] = socket;

                socket.on('close', function () {
                    for (var stream in socket._streams) {
                        socket._streams[stream].end();
                    }
                });

                socket.on('end', function () {
                    for (var stream in socket._streams) {
                        socket._streams[stream].end();
                    }
                });

                socket.on('error', function (err) {
                    for (var stream in socket._streams) {
                        socket._streams[stream].emit('error', err);
                    }
                });

                socket._streams = {};
            }

            // TODO save event stream with id
            options.id = 'truckenId';
            let streamId = options.to + options.emit + options.id;
            // TODO return a duplex stream and save readable to events
            socket._streams[streamId] = options.subStream;
            request = Mux(socket, options);
            break;

        case '/':
        case 'http':

            /*
            var opts = {
                method: 'GET',
                path: '/' + instance._name + ':' + eventName.substr(1)
                headers: {},
                host: window.location.host,
                port: window.location.port
                responseType: 'response type to set on the underlying xhr object'
            };
            */

            let url = options.emit[0] === '/' || options.emit.indeOf('http') === 0 ? options.emit : '/' + options.to + ':' + options.emit

            // pipe http to flow event stream
            let method = options.method || (options.end ? 'get' : 'post');
            request = http[method](url);

            // collect all data for a classic request callback
            if (options.end) {
                var body = '';
                var error;
                request.on('response', function (res) {
                    if (res.statusCode !== 200) {
                        error = true;
                    }
                })
                request.on('data', function (chunk) {
                    body += chunk;
                })
                .on('error', function (err) {
                    body = err;
                })
                .on('end', function () {
                    if (error) {
                        error = body;
                        body = undefined;
                    }
                    options.end(error, body);
                });
                request.end();
            }
            break;

        default:
            // TODO error
            return;
    }

    return request;
}

exports.reset = function () {

    // close all websockets
    for (var socket in sockets) {
        sockets[socket].close();
    }

    // remove socket refs
    sockets = {};
};

<|endoftext|>


<commit_before>(function() {

	var extend		= require('stratum-framework/lib/extend'),
		glob		= require('glob'),
		path		= require('path'),

		dirname		= path.dirname,
		basename	= path.basename,
		sep			= path.sep;

	var Sokkit = extend(function Sokkit(options) {
		this.failed		= [];
		this.plugins	= {};
		this.paths		= {};
		this.disabled	= {};

		this.configure(options);
	},

	Array,

	{

		configure: function(options) {
			options		= options || {};

			var path	= dirname(dirname(require.main.filename)),
				auto	= dirname(path);

			this.module		= options.module || basename(path);
			this.pattern	= options.pattern || (this.module + '-*');

			if (options.disable) {
				var disable = options.disable;
				for(var index = 0, length = disable.length; index < length; index++) {
					this.disabled[disable[index]] = {};
				}
			}

			var $DEFAULT = auto + sep + this.pattern;

			this.path		= options.path || $DEFAULT;

			if (this.path instanceof Array) {
				this.path = '{' + this.path.map(function(path) {
					return path === '$DEFAULT' ? $DEFAULT : path
				}).join(',') + '}';
			}
		},

		load: function(callback) {
			var sokkit	= this,
				prefix	= this.module + '-';

			function process(files) {
				for(var index = 0, length = files.length; index < length; index++) {
					var name = basename(files[index]);

					if (name.substring(name.length - 3) === '.js') {
						name = name.substring(0, name.length - 3);
					}

					if (name.substring(0, prefix.length) === prefix) {
						name = name.substring(prefix.length);
					}

					if (sokkit.disabled[name]) {
						sokkit.disabled[name].path = files[index];
						continue;
					}

					try{
						var result = require(files[index]);
						sokkit.push(result);
						sokkit.plugins[name] = result;
						sokkit.paths[name] = files[index];
					}catch(error) {
						sokkit.failed.push({
							name: name,
							error: error
						});
					}
				}
				if (callback) { callback(null, sokkit); }
			}

			if (callback) {
				glob(this.path, function(error, files) {
					if (error) {
						callback(error);
						return;
					}
					process(files);
				});
			}else{
				process(glob.sync(this.path));
			}
			return this;
		},

		subset: function(filter) {
			var clone = new Sokkit({
				module:		this.module,
				pattern:	this.pattern,
				path:		this.path
			});

			var plugins	= this.plugins,
				paths	= this.paths;
			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }
				var plugin = plugins[name];

				if (filter && filter(name, plugin)) {
					clone.push(plugin);
					clone.paths[name]	= paths[name];
					clone.plugins[name]	= plugin;
				}
			}
			return clone;
		},

		instantiate: function() {
			var args	= Array.prototype.slice.call(arguments, 1),
				errors	= [],
				plugins	= this.plugins;

			var index = 0;

			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }

				try{
					var plugin		= require(this.paths[name]),
						instance	= Object.create(plugin.prototype);

					plugin.apply(instance, args);
					this[index++]	= instance;
					plugins[name]	= instance;
				}catch(error) {
					errors.push({
						name:	name,
						error:	error
					});
					index++
				}
			}
			return errors;
		},

		call: function(method) {
			return this.apply(method, Array.prototype.slice.call(arguments, 1));
		},

		apply: function(method, args) {
			var result	= [],
				errors	= [],
				plugins	= this.plugins;

			result.errors = errors;

			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }
				var plugin = plugins[name];
				try{
					result.push(plugin[method].apply(plugin, args));
				}catch(error) {
					errors.push({
						name:	name,
						error:	error
					});
				}
			}
			return result;
		},

		disable: function(name) {
			var plugin	= this.plugins[name],
				path	= this.paths[name];

			if (!plugin) { return false; }

			var index = this.indexOf(plugin);
			this.splice(index, 1);

			delete this.plugins[name];
			delete this.paths[name];

			this.disabled[name] = {
				path:	this.paths[name],
				plugin:	plugin
			};

			return true;
		},

		enable: function(name) {
			var details = this.disabled[name];

			if (!details) { return false; }
			if (!details.plugin) { details.plugin = require(details.path); }

			this.push(details.plugin);

			this.paths[name]	= details.path;
			this.plugins[name]	= details.plugin;

			delete this.disabled[name];

			return true;
		},

		depend: function(retrieve) {
			var sokkit	= this,
				plugins	= this.plugins,
				errors	= [],
				done	= true;

			do{
				done = true;
				for(var name in plugins) {
					if (!plugins.hasOwnProperty(name)) { continue; }
					var required = retrieve(name, plugins[name]);
					if (!required) { continue; }

					for(var index = 0, length = required.length;
							index < length; index++) {
						var depend = required[index];
						if (!plugins[name]) {
							errors.push({
								name:	name,
								error:	new Error(name + ' requires ' + depend)
							});
							this.disable(name);
							done = false;
						}
					}
				}

			}while(!done);
			return errors;
		}

	});

	module.exports = Sokkit;

})();<commit_msg>Fix instantiate parameter passing to not skip the first param.<commit_after>(function() {

	var extend		= require('stratum-framework/lib/extend'),
		fs			= require('fs'),
		glob		= require('glob'),
		path		= require('path'),

		dirname		= path.dirname,
		basename	= path.basename,
		sep			= path.sep;

	var Sokkit = extend(function Sokkit(options) {
		this.failed		= [];
		this.plugins	= {};
		this.paths		= {};
		this.disabled	= {};

		this.configure(options);
	},

	Array,

	{

		configure: function(options) {
			options		= options || {};

			var path	= this.root(),
				auto	= dirname(path);

			this.module		= options.module || basename(path);
			this.pattern	= options.pattern || (this.module + '-*');

			if (options.disable) {
				var disable = options.disable;
				for(var index = 0, length = disable.length; index < length; index++) {
					this.disabled[disable[index]] = {};
				}
			}

			var $DEFAULT = auto + sep + this.pattern;

			this.path		= options.path || $DEFAULT;

			if (this.path instanceof Array) {
				this.path = '{' + this.path.map(function(path) {
					return path === '$DEFAULT' ? $DEFAULT : path
				}).join(',') + '}';
			}
		},

		root: function() {
			var path = dirname(require.main.filename);
			while(path.length) {
				if (fs.existsSync(path + sep + 'package.json')) { return path; }
				path = dirname(path);
			}
			throw new Error('Failed to find module root');
		},

		load: function(callback) {
			var sokkit	= this,
				prefix	= this.module + '-';

			function process(files) {
				for(var index = 0, length = files.length; index < length; index++) {
					var name = basename(files[index]);

					if (name.substring(name.length - 3) === '.js') {
						name = name.substring(0, name.length - 3);
					}

					if (name.substring(0, prefix.length) === prefix) {
						name = name.substring(prefix.length);
					}

					if (sokkit.disabled[name]) {
						sokkit.disabled[name].path = files[index];
						continue;
					}

					try{
						var result = require(files[index]);
						sokkit.push(result);
						sokkit.plugins[name] = result;
						sokkit.paths[name] = files[index];
					}catch(error) {
						sokkit.failed.push({
							name: name,
							error: error
						});
					}
				}
				if (callback) { callback(null, sokkit); }
			}

			if (callback) {
				glob(this.path, function(error, files) {
					if (error) {
						callback(error);
						return;
					}
					process(files);
				});
			}else{
				process(glob.sync(this.path));
			}
			return this;
		},

		subset: function(filter) {
			var clone = new Sokkit({
				module:		this.module,
				pattern:	this.pattern,
				path:		this.path
			});

			var plugins	= this.plugins,
				paths	= this.paths;
			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }
				var plugin = plugins[name];

				if (filter && filter(name, plugin)) {
					clone.push(plugin);
					clone.paths[name]	= paths[name];
					clone.plugins[name]	= plugin;
				}
			}
			return clone;
		},

		instantiate: function() {
			var errors	= [],
				plugins	= this.plugins;

			var index = 0;

			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }

				try{
					var plugin		= require(this.paths[name]),
						instance	= Object.create(plugin.prototype);

					plugin.apply(instance, arguments);
					this[index++]	= instance;
					plugins[name]	= instance;
				}catch(error) {
					errors.push({
						name:	name,
						error:	error
					});
					index++
				}
			}
			return errors;
		},

		call: function(method) {
			return this.apply(method, Array.prototype.slice.call(arguments, 1));
		},

		apply: function(method, args) {
			var result	= [],
				errors	= [],
				plugins	= this.plugins;

			result.errors = errors;

			for(var name in plugins) {
				if (!plugins.hasOwnProperty(name)) { continue; }
				var plugin = plugins[name];
				try{
					result.push(plugin[method].apply(plugin, args));
				}catch(error) {
					errors.push({
						name:	name,
						error:	error
					});
				}
			}
			return result;
		},

		disable: function(name) {
			var plugin	= this.plugins[name],
				path	= this.paths[name];

			if (!plugin) { return false; }

			var index = this.indexOf(plugin);
			this.splice(index, 1);

			delete this.plugins[name];
			delete this.paths[name];

			this.disabled[name] = {
				path:	this.paths[name],
				plugin:	plugin
			};

			return true;
		},

		enable: function(name) {
			var details = this.disabled[name];

			if (!details) { return false; }
			if (!details.plugin) { details.plugin = require(details.path); }

			this.push(details.plugin);

			this.paths[name]	= details.path;
			this.plugins[name]	= details.plugin;

			delete this.disabled[name];

			return true;
		},

		depend: function(retrieve) {
			var sokkit	= this,
				plugins	= this.plugins,
				errors	= [],
				done	= true;

			do{
				done = true;
				for(var name in plugins) {
					if (!plugins.hasOwnProperty(name)) { continue; }
					var required = retrieve(name, plugins[name]);
					if (!required) { continue; }

					for(var index = 0, length = required.length;
							index < length; index++) {
						var depend = required[index];
						if (!plugins[name]) {
							errors.push({
								name:	name,
								error:	new Error(name + ' requires ' + depend)
							});
							this.disable(name);
							done = false;
						}
					}
				}

			}while(!done);
			return errors;
		}

	});

	module.exports = Sokkit;

})();<|endoftext|>


<commit_before>/**
 * Scans a source JS file for its provided and required namespaces.
 *
 * Simple class to scan a JavaScript file and express its dependencies.
 */

var esprima = require('esprima');
var fs = require('fs');

/**
 * Matches a multiline comment.
 * Note: We can't definitively distinguish a "/*" in a string literal without a
 * state machine tokenizer. We'll assume that a line starting with whitespace
 * and "/*" is a comment.
 * @const {RegExp}
 */
var COMMENT_REGEX = new RegExp('/\\*[\\s\\S]*?\\*/', 'gm');

/**
 * Scans a JavaScript source for its provided and required namespaces.
 *
 * @param {string} path Path to a JavaScript file.
 * @param {Array.<string>} provides
 * @param {Array.<string>} requires
 * @param {Object} syntaxTree
 * @constructor
 */
var Source = module.exports = function(path, provides, requires, syntaxTree) {
  /** @type {!Array.<string>} */
  this.provides = provides || [];
  /** @type {!Array.<string>} */
  this.requires = requires || [];
  /** @type (string) */
  this.path = path;
  /** @type {Object} */
  this.syntaxTree = syntaxTree;
};

/**
 * @param {string} path
 * @param {boolean} opt_saveSyntaxTree
 * @return {!Source}
 */
Source.createFromFile = function(path, opt_saveSyntaxTree) {
  var source;
  var syntaxTree = null;
  var tokens;
  var provides = [];
  var requires = [];

  try {
    source = fs.readFileSync(path, 'utf8');

    if (opt_saveSyntaxTree) {
      syntaxTree = esprima.parse(source, {
        comment: true,
        tokens: true
      });

      if (syntaxTree) {
        syntaxTree.body = null;
      }
    }

    tokens = esprima.tokenize(source);
  } catch (e) {
    console.error(path);

    throw e;
  }

  if (tokens) {
    for (var i = 4; i < tokens.length; i++) {
      if (
        'String' == tokens[i].type &&
        'Punctuator' == tokens[i - 1].type && '(' == tokens[i - 1].value &&
        'Identifier' == tokens[i - 2].type &&
        'Punctuator' == tokens[i - 3].type && '.' == tokens[i - 3].value &&
        'Identifier' == tokens[i - 4].type && 'goog' == tokens[i - 4].value
      ) {
        if ('provide' == tokens[i - 2].value) {
          provides.push(tokens[i].value.substr(1, tokens[i].value.length - 2));
        } else if ('require' == tokens[i - 2].value) {
          requires.push(tokens[i].value.substr(1, tokens[i].value.length - 2));
        }
      }
    }
  }

  // Closure's base file implicitly provides 'goog'.
  // This is indicated with the @provideGoog flag.
  if (Source.hasProvideGoogFlag(source)) {
    provides.push('goog');
  }

  return new Source(path, provides, requires, syntaxTree);
};

/**
 * Determines whether the @provideGoog flag is in a comment.
 * @param {string} source
 * @return {boolean}
 */
Source.hasProvideGoogFlag = function(source) {
  var match;

  while (match = COMMENT_REGEX.exec(source)) {
    if (-1 < match[0].indexOf('@provideGoog')) {
      return true;
    }
  }

  return false;
};

/**
 * @return {string}
 */
Source.prototype.toString = function() {
  return 'Source ' + this.path;
};
<commit_msg>Excludes files with 'goog.setTestOnly'.<commit_after>/**
 * Scans a source JS file for its provided and required namespaces.
 *
 * Simple class to scan a JavaScript file and express its dependencies.
 */

var esprima = require('esprima');
var fs = require('fs');

/**
 * Matches a multiline comment.
 * Note: We can't definitively distinguish a "/*" in a string literal without a
 * state machine tokenizer. We'll assume that a line starting with whitespace
 * and "/*" is a comment.
 * @const {RegExp}
 */
var COMMENT_REGEX = new RegExp('/\\*[\\s\\S]*?\\*/', 'gm');

/**
 * Scans a JavaScript source for its provided and required namespaces.
 *
 * @param {string} path Path to a JavaScript file.
 * @param {Array.<string>} provides
 * @param {Array.<string>} requires
 * @param {Object} syntaxTree
 * @constructor
 */
var Source = module.exports = function(path, provides, requires, syntaxTree) {
  /** @type {!Array.<string>} */
  this.provides = provides || [];
  /** @type {!Array.<string>} */
  this.requires = requires || [];
  /** @type (string) */
  this.path = path;
  /** @type {Object} */
  this.syntaxTree = syntaxTree;
};

/**
 * @param {string} path
 * @param {boolean} opt_saveSyntaxTree
 * @return {!Source}
 */
Source.createFromFile = function(path, opt_saveSyntaxTree) {
  var source;
  var syntaxTree = null;
  var tokens;
  var provides = [];
  var requires = [];

  try {
    source = fs.readFileSync(path, 'utf8');

    if (opt_saveSyntaxTree) {
      syntaxTree = esprima.parse(source, {
        comment: true,
        tokens: true
      });

      if (syntaxTree) {
        syntaxTree.body = null;
      }
    }

    tokens = esprima.tokenize(source);
  } catch (e) {
    console.error(path);

    throw e;
  }

  if (tokens) {
    var testOnly = false;

    for (var i = 4; i < tokens.length; i++) {
      if (
        'String' == tokens[i].type &&
        'Punctuator' == tokens[i - 1].type && '(' == tokens[i - 1].value &&
        'Identifier' == tokens[i - 2].type &&
        'Punctuator' == tokens[i - 3].type && '.' == tokens[i - 3].value &&
        'Identifier' == tokens[i - 4].type && 'goog' == tokens[i - 4].value &&
        'setTestOnly' == tokens[i - 2].value
      ) {
        testOnly = true;
        break;
      }
    }

    if (!testOnly) {
      for (var i = 4; i < tokens.length; i++) {
        if (
          'String' == tokens[i].type &&
          'Punctuator' == tokens[i - 1].type && '(' == tokens[i - 1].value &&
          'Identifier' == tokens[i - 2].type &&
          'Punctuator' == tokens[i - 3].type && '.' == tokens[i - 3].value &&
          'Identifier' == tokens[i - 4].type && 'goog' == tokens[i - 4].value
        ) {
          if ('provide' == tokens[i - 2].value) {
            provides.push(tokens[i].value.substr(1, tokens[i].value.length - 2));
          } else if ('require' == tokens[i - 2].value) {
            requires.push(tokens[i].value.substr(1, tokens[i].value.length - 2));
          }
        }
      }
    }
  }

  // Closure's base file implicitly provides 'goog'.
  // This is indicated with the @provideGoog flag.
  if (Source.hasProvideGoogFlag(source)) {
    provides.push('goog');
  }

  return new Source(path, provides, requires, syntaxTree);
};

/**
 * Determines whether the @provideGoog flag is in a comment.
 * @param {string} source
 * @return {boolean}
 */
Source.hasProvideGoogFlag = function(source) {
  var match;

  while (match = COMMENT_REGEX.exec(source)) {
    if (-1 < match[0].indexOf('@provideGoog')) {
      return true;
    }
  }

  return false;
};

/**
 * @return {string}
 */
Source.prototype.toString = function() {
  return 'Source ' + this.path;
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/* eslint-disable no-var */

// TODO: Currently there's only a single priority level, Deferred. Will add
// additional priorities.
var DEFERRED_TIMEOUT = 5000;

// Callbacks are stored as a circular, doubly linked list.
var firstCallbackNode = null;

var isPerformingWork = false;

var isHostCallbackScheduled = false;

var hasNativePerformanceNow =
  typeof performance === 'object' && typeof performance.now === 'function';

var timeRemaining;
if (hasNativePerformanceNow) {
  timeRemaining = function() {
    // We assume that if we have a performance timer that the rAF callback
    // gets a performance timer value. Not sure if this is always true.
    var remaining = getFrameDeadline() - performance.now();
    return remaining > 0 ? remaining : 0;
  };
} else {
  timeRemaining = function() {
    // Fallback to Date.now()
    var remaining = getFrameDeadline() - Date.now();
    return remaining > 0 ? remaining : 0;
  };
}

var deadlineObject = {
  timeRemaining,
  didTimeout: false,
};

function ensureHostCallbackIsScheduled() {
  if (isPerformingWork) {
    // Don't schedule work yet; wait until the next time we yield.
    return;
  }
  // Schedule the host callback using the earliest timeout in the list.
  var timesOutAt = firstCallbackNode.timesOutAt;
  if (!isHostCallbackScheduled) {
    isHostCallbackScheduled = true;
  } else {
    // Cancel the existing host callback.
    cancelCallback();
  }
  requestCallback(flushWork, timesOutAt);
}

function flushFirstCallback(node) {
  var flushedNode = firstCallbackNode;

  // Remove the node from the list before calling the callback. That way the
  // list is in a consistent state even if the callback throws.
  var next = firstCallbackNode.next;
  if (firstCallbackNode === next) {
    // This is the last callback in the list.
    firstCallbackNode = null;
    next = null;
  } else {
    var previous = firstCallbackNode.previous;
    firstCallbackNode = previous.next = next;
    next.previous = previous;
  }

  flushedNode.next = flushedNode.previous = null;

  // Now it's safe to call the callback.
  var callback = flushedNode.callback;
  callback(deadlineObject);
}

function flushWork(didTimeout) {
  isPerformingWork = true;
  deadlineObject.didTimeout = didTimeout;
  try {
    if (didTimeout) {
      // Flush all the timed out callbacks without yielding.
      while (firstCallbackNode !== null) {
        // Read the current time. Flush all the callbacks that expire at or
        // earlier than that time. Then read the current time again and repeat.
        // This optimizes for as few performance.now calls as possible.
        var currentTime = getCurrentTime();
        if (firstCallbackNode.timesOutAt <= currentTime) {
          do {
            flushFirstCallback();
          } while (
            firstCallbackNode !== null &&
            firstCallbackNode.timesOutAt <= currentTime
          );
          continue;
        }
        break;
      }
    } else {
      // Keep flushing callbacks until we run out of time in the frame.
      if (firstCallbackNode !== null) {
        do {
          flushFirstCallback();
        } while (
          firstCallbackNode !== null &&
          getFrameDeadline() - getCurrentTime() > 0
        );
      }
    }
  } finally {
    isPerformingWork = false;
    if (firstCallbackNode !== null) {
      // There's still work remaining. Request another callback.
      ensureHostCallbackIsScheduled(firstCallbackNode);
    } else {
      isHostCallbackScheduled = false;
    }
  }
}

function unstable_scheduleWork(callback, options) {
  var currentTime = getCurrentTime();

  var timesOutAt;
  if (
    options !== undefined &&
    options !== null &&
    options.timeout !== null &&
    options.timeout !== undefined
  ) {
    // Check for an explicit timeout
    timesOutAt = currentTime + options.timeout;
  } else {
    // Compute an absolute timeout using the default constant.
    timesOutAt = currentTime + DEFERRED_TIMEOUT;
  }

  var newNode = {
    callback,
    timesOutAt,
    next: null,
    previous: null,
  };

  // Insert the new callback into the list, sorted by its timeout.
  if (firstCallbackNode === null) {
    // This is the first callback in the list.
    firstCallbackNode = newNode.next = newNode.previous = newNode;
    ensureHostCallbackIsScheduled(firstCallbackNode);
  } else {
    var next = null;
    var node = firstCallbackNode;
    do {
      if (node.timesOutAt > timesOutAt) {
        // The new callback times out before this one.
        next = node;
        break;
      }
      node = node.next;
    } while (node !== firstCallbackNode);

    if (next === null) {
      // No callback with a later timeout was found, which means the new
      // callback has the latest timeout in the list.
      next = firstCallbackNode;
    } else if (next === firstCallbackNode) {
      // The new callback has the earliest timeout in the entire list.
      firstCallbackNode = newNode;
      ensureHostCallbackIsScheduled(firstCallbackNode);
    }

    var previous = next.previous;
    previous.next = next.previous = newNode;
    newNode.next = next;
    newNode.previous = previous;
  }

  return newNode;
}

function unstable_cancelScheduledWork(callbackNode: CallbackNode): void {
  var next = callbackNode.next;
  if (next === null) {
    // Already cancelled.
    return;
  }

  if (next === callbackNode) {
    // This is the only scheduled callback. Clear the list.
    firstCallbackNode = null;
  } else {
    // Remove the callback from its position in the list.
    if (callbackNode === firstCallbackNode) {
      firstCallbackNode = next;
    }
    var previous = callbackNode.previous;
    previous.next = next;
    next.previous = previous;
  }

  callbackNode.next = callbackNode.previous = null;
}

// The remaining code is essentially a polyfill for requestIdleCallback. It
// works by scheduling a requestAnimationFrame, storing the time for the start
// of the frame, then scheduling a postMessage which gets scheduled after paint.
// Within the postMessage handler do as much work as possible until time + frame
// rate. By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

// We capture a local reference to any global, in case it gets polyfilled after
// this module is initially evaluated. We want to be using a
// consistent implementation.
var localDate = Date;

// This initialization code may run even on server environments if a component
// just imports ReactDOM (e.g. for findDOMNode). Some environments might not
// have setTimeout or clearTimeout. However, we always expect them to be defined
// on the client. https://github.com/facebook/react/pull/13088
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
var localClearTimeout =
  typeof clearTimeout === 'function' ? clearTimeout : undefined;

// We don't expect either of these to necessarily be defined, but we will error
// later if they are missing on the client.
var localRequestAnimationFrame =
  typeof requestAnimationFrame === 'function'
    ? requestAnimationFrame
    : undefined;
var localCancelAnimationFrame =
  typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : undefined;

var getCurrentTime;

// requestAnimationFrame does not run when the tab is in the background. If
// we're backgrounded we prefer for that work to happen so that the page
// continues to load in the background. So we also schedule a 'setTimeout' as
// a fallback.
// TODO: Need a better heuristic for backgrounded work.
var ANIMATION_FRAME_TIMEOUT = 100;
var rAFID;
var rAFTimeoutID;
var requestAnimationFrameWithTimeout = function(callback) {
  // schedule rAF and also a setTimeout
  rAFID = localRequestAnimationFrame(function(timestamp) {
    // cancel the setTimeout
    localClearTimeout(rAFTimeoutID);
    callback(timestamp);
  });
  rAFTimeoutID = localSetTimeout(function() {
    // cancel the requestAnimationFrame
    localCancelAnimationFrame(rAFID);
    callback(getCurrentTime());
  }, ANIMATION_FRAME_TIMEOUT);
};

if (hasNativePerformanceNow) {
  var Performance = performance;
  getCurrentTime = function() {
    return Performance.now();
  };
} else {
  getCurrentTime = function() {
    return localDate.now();
  };
}

var requestCallback;
var cancelCallback;
var getFrameDeadline;

if (typeof window === 'undefined') {
  // If this accidentally gets imported in a non-browser environment, fallback
  // to a naive implementation.
  var timeoutID = -1;
  requestCallback = function(callback, absoluteTimeout) {
    timeoutID = setTimeout(callback, 0, true);
  };
  cancelCallback = function() {
    clearTimeout(timeoutID);
  };
  getFrameDeadline = function() {
    return 0;
  };
} else if (window._schedMock) {
  // Dynamic injection, only for testing purposes.
  var impl = window._schedMock;
  requestCallback = impl[0];
  cancelCallback = impl[1];
  getFrameDeadline = impl[2];
} else {
  if (typeof console !== 'undefined') {
    if (typeof localRequestAnimationFrame !== 'function') {
      console.error(
        "This browser doesn't support requestAnimationFrame. " +
          'Make sure that you load a ' +
          'polyfill in older browsers. https://fb.me/react-polyfills',
      );
    }
    if (typeof localCancelAnimationFrame !== 'function') {
      console.error(
        "This browser doesn't support cancelAnimationFrame. " +
          'Make sure that you load a ' +
          'polyfill in older browsers. https://fb.me/react-polyfills',
      );
    }
  }

  var scheduledCallback = null;
  var isIdleScheduled = false;
  var timeoutTime = -1;

  var isAnimationFrameScheduled = false;

  var isPerformingIdleWork = false;

  var frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  var previousFrameTime = 33;
  var activeFrameTime = 33;

  getFrameDeadline = function() {
    return frameDeadline;
  };

  // We use the postMessage trick to defer idle work until after the repaint.
  var messageKey =
    '__reactIdleCallback$' +
    Math.random()
      .toString(36)
      .slice(2);
  var idleTick = function(event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }

    isIdleScheduled = false;

    var currentTime = getCurrentTime();

    var didTimeout = false;
    if (frameDeadline - currentTime <= 0) {
      // There's no time left in this idle period. Check if the callback has
      // a timeout and whether it's been exceeded.
      if (timeoutTime !== -1 && timeoutTime <= currentTime) {
        // Exceeded the timeout. Invoke the callback even though there's no
        // time left.
        didTimeout = true;
      } else {
        // No timeout.
        if (!isAnimationFrameScheduled) {
          // Schedule another animation callback so we retry later.
          isAnimationFrameScheduled = true;
          requestAnimationFrameWithTimeout(animationTick);
        }
        // Exit without invoking the callback.
        return;
      }
    }

    timeoutTime = -1;
    var callback = scheduledCallback;
    scheduledCallback = null;
    if (callback !== null) {
      isPerformingIdleWork = true;
      try {
        callback(didTimeout);
      } finally {
        isPerformingIdleWork = false;
      }
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  var animationTick = function(rafTime) {
    isAnimationFrameScheduled = false;
    var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (
      nextFrameTime < activeFrameTime &&
      previousFrameTime < activeFrameTime
    ) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime =
        nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
  };

  requestCallback = function(callback, absoluteTimeout) {
    scheduledCallback = callback;
    timeoutTime = absoluteTimeout;
    if (isPerformingIdleWork) {
      // If we're already performing idle work, an error must have been thrown.
      // Don't wait for the next frame. Continue working ASAP, in a new event.
      window.postMessage(messageKey, '*');
    } else if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger rIC as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      requestAnimationFrameWithTimeout(animationTick);
    }
  };

  cancelCallback = function() {
    scheduledCallback = null;
    isIdleScheduled = false;
    timeoutTime = -1;
  };
}

export {
  unstable_scheduleWork,
  unstable_cancelScheduledWork,
  getCurrentTime as unstable_now,
};
<commit_msg>remove flow typings from Schedule.js (#13662)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/* eslint-disable no-var */

// TODO: Currently there's only a single priority level, Deferred. Will add
// additional priorities.
var DEFERRED_TIMEOUT = 5000;

// Callbacks are stored as a circular, doubly linked list.
var firstCallbackNode = null;

var isPerformingWork = false;

var isHostCallbackScheduled = false;

var hasNativePerformanceNow =
  typeof performance === 'object' && typeof performance.now === 'function';

var timeRemaining;
if (hasNativePerformanceNow) {
  timeRemaining = function() {
    // We assume that if we have a performance timer that the rAF callback
    // gets a performance timer value. Not sure if this is always true.
    var remaining = getFrameDeadline() - performance.now();
    return remaining > 0 ? remaining : 0;
  };
} else {
  timeRemaining = function() {
    // Fallback to Date.now()
    var remaining = getFrameDeadline() - Date.now();
    return remaining > 0 ? remaining : 0;
  };
}

var deadlineObject = {
  timeRemaining,
  didTimeout: false,
};

function ensureHostCallbackIsScheduled() {
  if (isPerformingWork) {
    // Don't schedule work yet; wait until the next time we yield.
    return;
  }
  // Schedule the host callback using the earliest timeout in the list.
  var timesOutAt = firstCallbackNode.timesOutAt;
  if (!isHostCallbackScheduled) {
    isHostCallbackScheduled = true;
  } else {
    // Cancel the existing host callback.
    cancelCallback();
  }
  requestCallback(flushWork, timesOutAt);
}

function flushFirstCallback(node) {
  var flushedNode = firstCallbackNode;

  // Remove the node from the list before calling the callback. That way the
  // list is in a consistent state even if the callback throws.
  var next = firstCallbackNode.next;
  if (firstCallbackNode === next) {
    // This is the last callback in the list.
    firstCallbackNode = null;
    next = null;
  } else {
    var previous = firstCallbackNode.previous;
    firstCallbackNode = previous.next = next;
    next.previous = previous;
  }

  flushedNode.next = flushedNode.previous = null;

  // Now it's safe to call the callback.
  var callback = flushedNode.callback;
  callback(deadlineObject);
}

function flushWork(didTimeout) {
  isPerformingWork = true;
  deadlineObject.didTimeout = didTimeout;
  try {
    if (didTimeout) {
      // Flush all the timed out callbacks without yielding.
      while (firstCallbackNode !== null) {
        // Read the current time. Flush all the callbacks that expire at or
        // earlier than that time. Then read the current time again and repeat.
        // This optimizes for as few performance.now calls as possible.
        var currentTime = getCurrentTime();
        if (firstCallbackNode.timesOutAt <= currentTime) {
          do {
            flushFirstCallback();
          } while (
            firstCallbackNode !== null &&
            firstCallbackNode.timesOutAt <= currentTime
          );
          continue;
        }
        break;
      }
    } else {
      // Keep flushing callbacks until we run out of time in the frame.
      if (firstCallbackNode !== null) {
        do {
          flushFirstCallback();
        } while (
          firstCallbackNode !== null &&
          getFrameDeadline() - getCurrentTime() > 0
        );
      }
    }
  } finally {
    isPerformingWork = false;
    if (firstCallbackNode !== null) {
      // There's still work remaining. Request another callback.
      ensureHostCallbackIsScheduled(firstCallbackNode);
    } else {
      isHostCallbackScheduled = false;
    }
  }
}

function unstable_scheduleWork(callback, options) {
  var currentTime = getCurrentTime();

  var timesOutAt;
  if (
    options !== undefined &&
    options !== null &&
    options.timeout !== null &&
    options.timeout !== undefined
  ) {
    // Check for an explicit timeout
    timesOutAt = currentTime + options.timeout;
  } else {
    // Compute an absolute timeout using the default constant.
    timesOutAt = currentTime + DEFERRED_TIMEOUT;
  }

  var newNode = {
    callback,
    timesOutAt,
    next: null,
    previous: null,
  };

  // Insert the new callback into the list, sorted by its timeout.
  if (firstCallbackNode === null) {
    // This is the first callback in the list.
    firstCallbackNode = newNode.next = newNode.previous = newNode;
    ensureHostCallbackIsScheduled(firstCallbackNode);
  } else {
    var next = null;
    var node = firstCallbackNode;
    do {
      if (node.timesOutAt > timesOutAt) {
        // The new callback times out before this one.
        next = node;
        break;
      }
      node = node.next;
    } while (node !== firstCallbackNode);

    if (next === null) {
      // No callback with a later timeout was found, which means the new
      // callback has the latest timeout in the list.
      next = firstCallbackNode;
    } else if (next === firstCallbackNode) {
      // The new callback has the earliest timeout in the entire list.
      firstCallbackNode = newNode;
      ensureHostCallbackIsScheduled(firstCallbackNode);
    }

    var previous = next.previous;
    previous.next = next.previous = newNode;
    newNode.next = next;
    newNode.previous = previous;
  }

  return newNode;
}

function unstable_cancelScheduledWork(callbackNode) {
  var next = callbackNode.next;
  if (next === null) {
    // Already cancelled.
    return;
  }

  if (next === callbackNode) {
    // This is the only scheduled callback. Clear the list.
    firstCallbackNode = null;
  } else {
    // Remove the callback from its position in the list.
    if (callbackNode === firstCallbackNode) {
      firstCallbackNode = next;
    }
    var previous = callbackNode.previous;
    previous.next = next;
    next.previous = previous;
  }

  callbackNode.next = callbackNode.previous = null;
}

// The remaining code is essentially a polyfill for requestIdleCallback. It
// works by scheduling a requestAnimationFrame, storing the time for the start
// of the frame, then scheduling a postMessage which gets scheduled after paint.
// Within the postMessage handler do as much work as possible until time + frame
// rate. By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

// We capture a local reference to any global, in case it gets polyfilled after
// this module is initially evaluated. We want to be using a
// consistent implementation.
var localDate = Date;

// This initialization code may run even on server environments if a component
// just imports ReactDOM (e.g. for findDOMNode). Some environments might not
// have setTimeout or clearTimeout. However, we always expect them to be defined
// on the client. https://github.com/facebook/react/pull/13088
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
var localClearTimeout =
  typeof clearTimeout === 'function' ? clearTimeout : undefined;

// We don't expect either of these to necessarily be defined, but we will error
// later if they are missing on the client.
var localRequestAnimationFrame =
  typeof requestAnimationFrame === 'function'
    ? requestAnimationFrame
    : undefined;
var localCancelAnimationFrame =
  typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : undefined;

var getCurrentTime;

// requestAnimationFrame does not run when the tab is in the background. If
// we're backgrounded we prefer for that work to happen so that the page
// continues to load in the background. So we also schedule a 'setTimeout' as
// a fallback.
// TODO: Need a better heuristic for backgrounded work.
var ANIMATION_FRAME_TIMEOUT = 100;
var rAFID;
var rAFTimeoutID;
var requestAnimationFrameWithTimeout = function(callback) {
  // schedule rAF and also a setTimeout
  rAFID = localRequestAnimationFrame(function(timestamp) {
    // cancel the setTimeout
    localClearTimeout(rAFTimeoutID);
    callback(timestamp);
  });
  rAFTimeoutID = localSetTimeout(function() {
    // cancel the requestAnimationFrame
    localCancelAnimationFrame(rAFID);
    callback(getCurrentTime());
  }, ANIMATION_FRAME_TIMEOUT);
};

if (hasNativePerformanceNow) {
  var Performance = performance;
  getCurrentTime = function() {
    return Performance.now();
  };
} else {
  getCurrentTime = function() {
    return localDate.now();
  };
}

var requestCallback;
var cancelCallback;
var getFrameDeadline;

if (typeof window === 'undefined') {
  // If this accidentally gets imported in a non-browser environment, fallback
  // to a naive implementation.
  var timeoutID = -1;
  requestCallback = function(callback, absoluteTimeout) {
    timeoutID = setTimeout(callback, 0, true);
  };
  cancelCallback = function() {
    clearTimeout(timeoutID);
  };
  getFrameDeadline = function() {
    return 0;
  };
} else if (window._schedMock) {
  // Dynamic injection, only for testing purposes.
  var impl = window._schedMock;
  requestCallback = impl[0];
  cancelCallback = impl[1];
  getFrameDeadline = impl[2];
} else {
  if (typeof console !== 'undefined') {
    if (typeof localRequestAnimationFrame !== 'function') {
      console.error(
        "This browser doesn't support requestAnimationFrame. " +
          'Make sure that you load a ' +
          'polyfill in older browsers. https://fb.me/react-polyfills',
      );
    }
    if (typeof localCancelAnimationFrame !== 'function') {
      console.error(
        "This browser doesn't support cancelAnimationFrame. " +
          'Make sure that you load a ' +
          'polyfill in older browsers. https://fb.me/react-polyfills',
      );
    }
  }

  var scheduledCallback = null;
  var isIdleScheduled = false;
  var timeoutTime = -1;

  var isAnimationFrameScheduled = false;

  var isPerformingIdleWork = false;

  var frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  var previousFrameTime = 33;
  var activeFrameTime = 33;

  getFrameDeadline = function() {
    return frameDeadline;
  };

  // We use the postMessage trick to defer idle work until after the repaint.
  var messageKey =
    '__reactIdleCallback$' +
    Math.random()
      .toString(36)
      .slice(2);
  var idleTick = function(event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }

    isIdleScheduled = false;

    var currentTime = getCurrentTime();

    var didTimeout = false;
    if (frameDeadline - currentTime <= 0) {
      // There's no time left in this idle period. Check if the callback has
      // a timeout and whether it's been exceeded.
      if (timeoutTime !== -1 && timeoutTime <= currentTime) {
        // Exceeded the timeout. Invoke the callback even though there's no
        // time left.
        didTimeout = true;
      } else {
        // No timeout.
        if (!isAnimationFrameScheduled) {
          // Schedule another animation callback so we retry later.
          isAnimationFrameScheduled = true;
          requestAnimationFrameWithTimeout(animationTick);
        }
        // Exit without invoking the callback.
        return;
      }
    }

    timeoutTime = -1;
    var callback = scheduledCallback;
    scheduledCallback = null;
    if (callback !== null) {
      isPerformingIdleWork = true;
      try {
        callback(didTimeout);
      } finally {
        isPerformingIdleWork = false;
      }
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  var animationTick = function(rafTime) {
    isAnimationFrameScheduled = false;
    var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (
      nextFrameTime < activeFrameTime &&
      previousFrameTime < activeFrameTime
    ) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime =
        nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
  };

  requestCallback = function(callback, absoluteTimeout) {
    scheduledCallback = callback;
    timeoutTime = absoluteTimeout;
    if (isPerformingIdleWork) {
      // If we're already performing idle work, an error must have been thrown.
      // Don't wait for the next frame. Continue working ASAP, in a new event.
      window.postMessage(messageKey, '*');
    } else if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger rIC as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      requestAnimationFrameWithTimeout(animationTick);
    }
  };

  cancelCallback = function() {
    scheduledCallback = null;
    isIdleScheduled = false;
    timeoutTime = -1;
  };
}

export {
  unstable_scheduleWork,
  unstable_cancelScheduledWork,
  getCurrentTime as unstable_now,
};
<|endoftext|>


<commit_before>import css from '@emotion/css'
import { mq, fonts } from './style'
import prismStyles from 'react-live/lib/constants/css.js'

const globalStyles = css`
  ${prismStyles
    .replace('prism-code', 'prism-code,pre[class*="language-"]')
    .replace(/0\.5rem/g, '')} html, body, #___gatsby {
    font-family: ${fonts.primary};
    color: #fffeff;
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    -webkit-font-smoothing: antialiased;
  }
  ${{
    'p code': {
      backgroundColor: '#CEF6FF',
      fontSize: 16
    },
    'a code': {
      backgroundColor: 'inherit'
    }
  }};
  pre[class*='language-'] {
    ${mq({
      marginLeft: [-32, -30],
      marginRight: [-32, -30],
      marginTop: 16,
      marginBottom: 16,
      borderRadius: [0, 8],
      whiteSpace: 'pre-wrap',
      wordBreak: 'break-word',
      paddingLeft: [32, 30],
      paddingRight: [32, 30]
    })};
  }

  code,
  pre[class*='language-'],
  .prism-code {
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    font-family: ${fonts.code};
  }

  pre[class*='language-'],
  .prism-code {
    ${mq({
      borderRadius: [0, 8]
    })};
    white-space: pre-wrap;
    word-break: break-word;
    word-wrap: normal;
  }
  .gatsy-highlight {
    overflow: hidden;
  }
  * {
    box-sizing: border-box;
  }
`

export default globalStyles
<commit_msg>This is why globals are bad.<commit_after>import css from '@emotion/css'
import { mq, fonts } from './style'
import prismStyles from 'react-live/lib/constants/css.js'

const globalStyles = css`
  ${prismStyles
    .replace('prism-code', 'prism-code,pre[class*="language-"]')
    .replace(/0\.5rem/g, '')} html, body, #___gatsby {
    font-family: ${fonts.primary};
    color: #fffeff;
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    -webkit-font-smoothing: antialiased;
  }
  ${{
    'p code': {
      backgroundColor: '#CEF6FF',
      fontSize: 16
    },
    'a code': {
      backgroundColor: 'inherit'
    }
  }};
  pre[class*='language-'] {
    ${mq({
      marginLeft: [-32, -30],
      marginRight: [-32, -30],
      marginTop: 16,
      marginBottom: 16,
      borderRadius: [0, 8],
      whiteSpace: 'pre-wrap',
      wordBreak: 'break-word',
      paddingLeft: [32, 30],
      paddingRight: [32, 30]
    })};
  }

  code,
  pre[class*='language-'],
  .prism-code {
    font-family: ${fonts.code};
  }

  pre[class*='language-'],
  .prism-code {
    ${mq({
      borderRadius: [0, 8]
    })};
    white-space: pre-wrap;
    word-break: break-word;
    word-wrap: normal;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
  }
  .gatsy-highlight {
    overflow: hidden;
  }
  * {
    box-sizing: border-box;
  }
`

export default globalStyles
<|endoftext|>


<commit_before>// Load modules

var Any = require('./any');
var Errors = require('./errors');
var Hoek = require('hoek');

// Declare internals

var internals = {};

module.exports = internals.String = function () {

    Any.call(this);
    this._type = 'string';
    this._invalids.add('');

    this._base(function (value, state, options) {

        if (value &&
            typeof value === 'string') {

            return null;
        }

        return Errors.create('string.base', null, state, options);
    });
};

Hoek.inherits(internals.String, Any);

internals.String.create = function () {

    return new internals.String();
};

internals.String.prototype.insensitive = function () {

    var obj = this.clone();
    obj._flags.insensitive = true;
    return obj;
};

internals.String.prototype.min = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('min', limit, function (value, state, options) {

        if (value.length >= limit) {
            return null;
        }

        return Errors.create('string.min', { value: limit }, state, options);
    });
};

internals.String.prototype.max = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('max', limit, function (value, state, options) {

        if (value.length <= limit) {
            return null;
        }

        return Errors.create('string.max', { value: limit }, state, options);
    });
};

internals.String.prototype.length = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('length', limit, function (value, state, options) {

        if (value.length === limit) {
            return null;
        }

        return Errors.create('string.length', { value: limit }, state, options);
    });
};

internals.String.prototype.regex = function (pattern) {

    Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp');

    return this._test('regex', pattern, function (value, state, options) {

        if (value.match(pattern)) {
            return null;
        }

        return Errors.create('string.regex', { value: pattern.toString() }, state, options);
    });
};

internals.String.prototype.alphanum = function () {

    return this._test('alphanum', undefined, function (value, state, options) {

        if (value.match(/^[a-zA-Z0-9]+$/)) {
            return null;
        }

        return Errors.create('string.alphanum', null, state, options);
    });
};

internals.String.prototype.token = function () {

    return this._test('token', undefined, function (value, state, options) {

        if (value.match(/^\w+$/)) {
            return null;
        }

        return Errors.create('string.token', null, state, options);
    });
};

internals.String.prototype.email = function () {

    var regex = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;

    return this._test('email', undefined, function (value, state, options) {

        if (value.match(regex)) {
            return null;
        }

        return Errors.create('string.email', null, state, options);
    });
};

internals.String.prototype.isoDate = function () {

    var regex = /^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/;

    return this._test('isoDate', undefined, function (value, state, options) {

        if (value.match(regex)) {
            return null;
        }

        return Errors.create('string.isoDate', null, state, options);
    });
};

internals.String.prototype.guid = function () {

    var regex = /^[A-F0-9]{8}(?:-?[A-F0-9]{4}){3}-?[A-F0-9]{12}$/i;
    var regex2 = /^\{[A-F0-9]{8}(?:-?[A-F0-9]{4}){3}-?[A-F0-9]{12}\}$/i;

    return this._test('guid', undefined, function (value, state, options) {

        if (value.match(regex) || value.match(regex2)) {
            return null;
        }

        return Errors.create('string.guid', null, state, options);
    });
};
<commit_msg>match() -> test()<commit_after>// Load modules

var Any = require('./any');
var Errors = require('./errors');
var Hoek = require('hoek');

// Declare internals

var internals = {};

module.exports = internals.String = function () {

    Any.call(this);
    this._type = 'string';
    this._invalids.add('');

    this._base(function (value, state, options) {

        if (value &&
            typeof value === 'string') {

            return null;
        }

        return Errors.create('string.base', null, state, options);
    });
};

Hoek.inherits(internals.String, Any);

internals.String.create = function () {

    return new internals.String();
};

internals.String.prototype.insensitive = function () {

    var obj = this.clone();
    obj._flags.insensitive = true;
    return obj;
};

internals.String.prototype.min = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('min', limit, function (value, state, options) {

        if (value.length >= limit) {
            return null;
        }

        return Errors.create('string.min', { value: limit }, state, options);
    });
};

internals.String.prototype.max = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('max', limit, function (value, state, options) {

        if (value.length <= limit) {
            return null;
        }

        return Errors.create('string.max', { value: limit }, state, options);
    });
};

internals.String.prototype.length = function (limit) {

    Hoek.assert(!isNaN(limit) && ((limit | 0) === parseFloat(limit)) && limit >= 0, 'limit must be a positive integer');

    return this._test('length', limit, function (value, state, options) {

        if (value.length === limit) {
            return null;
        }

        return Errors.create('string.length', { value: limit }, state, options);
    });
};

internals.String.prototype.regex = function (pattern) {

    Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp');

    return this._test('regex', pattern, function (value, state, options) {

        if (pattern.test(value)) {
            return null;
        }

        return Errors.create('string.regex', { value: pattern.toString() }, state, options);
    });
};

internals.String.prototype.alphanum = function () {

    return this._test('alphanum', undefined, function (value, state, options) {

        if (/^[a-zA-Z0-9]+$/.test(value)) {
            return null;
        }

        return Errors.create('string.alphanum', null, state, options);
    });
};

internals.String.prototype.token = function () {

    return this._test('token', undefined, function (value, state, options) {

        if (/^\w+$/.test(value)) {
            return null;
        }

        return Errors.create('string.token', null, state, options);
    });
};

internals.String.prototype.email = function () {

    var regex = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;

    return this._test('email', undefined, function (value, state, options) {

        if (regex.test(value)) {
            return null;
        }

        return Errors.create('string.email', null, state, options);
    });
};

internals.String.prototype.isoDate = function () {

    var regex = /^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/;

    return this._test('isoDate', undefined, function (value, state, options) {

        if (regex.test(value)) {
            return null;
        }

        return Errors.create('string.isoDate', null, state, options);
    });
};

internals.String.prototype.guid = function () {

    var regex = /^[A-F0-9]{8}(?:-?[A-F0-9]{4}){3}-?[A-F0-9]{12}$/i;
    var regex2 = /^\{[A-F0-9]{8}(?:-?[A-F0-9]{4}){3}-?[A-F0-9]{12}\}$/i;

    return this._test('guid', undefined, function (value, state, options) {

        if (regex.test(value) || regex2.test(value)) {
            return null;
        }

        return Errors.create('string.guid', null, state, options);
    });
};
<|endoftext|>


<commit_before>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',

             //material
            '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
            '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js',
            '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
            '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
            '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
            '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
            '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
            '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
            '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
            '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
            '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
            '@angular/cdk/accordion' : 'npm:@angular/cdk/bundles/cdk-accordion.umd.js',
            '@angular/cdk/layout' : 'npm:@angular/cdk/bundles/cdk-layout.umd.js',
            '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
            '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
            '@angular/cdk/stepper': 'npm:@angular/cdk/bundles/cdk-stepper.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'hammerjs': 'npm:hammerjs',
            'tslib': 'npm:tslib/tslib.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            "rxjs/operators": {
                "main": "index.js",
                "defaultExtension": "js"
           },
             hammerjs:  {
                main: './hammer.js',
                defaultExtension: 'js'}
        }
    });
})(this);
<commit_msg>rxjs 5.5.6<commit_after>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',

             //material
            '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
            '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js',
            '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
            '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
            '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
            '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
            '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
            '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
            '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
            '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
            '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
            '@angular/cdk/accordion' : 'npm:@angular/cdk/bundles/cdk-accordion.umd.js',
            '@angular/cdk/layout' : 'npm:@angular/cdk/bundles/cdk-layout.umd.js',
            '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
            '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
            '@angular/cdk/stepper': 'npm:@angular/cdk/bundles/cdk-stepper.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'hammerjs': 'npm:hammerjs',
            'tslib': 'npm:tslib/tslib.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
             hammerjs:  {
                main: './hammer.js',
                defaultExtension: 'js'}
        }
    });
})(this);
<|endoftext|>