function loadScene(sceneId, targetPitch, targetYaw, targetHfov, fadeDone) {
    loaded = false;
    animatedMove = {};

    // Set up fade if specified
    var fadeImg, workingPitch, workingYaw, workingHfov;
    if (config.sceneFadeDuration && !fadeDone) {
        var data = renderer.render(config.pitch * Math.PI / 180, config.yaw * Math.PI / 180, config.hfov * Math.PI / 180, {returnImage: true});
        if (data !== undefined) {
            fadeImg = new Image();
            fadeImg.className = 'pnlm-fade-img';
            fadeImg.style.transition = 'opacity ' + (config.sceneFadeDuration / 1000) + 's';
            fadeImg.style.width = '100%';
            fadeImg.style.height = '100%';
            fadeImg.onload = function() {
                loadScene(sceneId, targetPitch, targetYaw, targetHfov, true);
            };
            fadeImg.src = data;
            renderContainer.appendChild(fadeImg);
            renderer.fadeImg = fadeImg;
            return;
        }
    }

    // Set new pointing
    if (targetPitch === 'same') {
        workingPitch = config.pitch;
    } else {
        workingPitch = targetPitch;
    }
    if (targetYaw === 'same') {
        workingYaw = config.yaw;
    } else if (targetYaw === 'sameAzimuth') {
        workingYaw = config.yaw + (config.northOffset || 0) - (initialConfig.scenes[sceneId].northOffset || 0);
    } else {
        workingYaw = targetYaw;
    }
    if (targetHfov === 'same') {
        workingHfov = config.hfov;
    } else {
        workingHfov = targetHfov;
    }

    // Destroy hot spots from previous scene
    destroyHotSpots();

    // Create the new config for the scene
    mergeConfig(sceneId);

    // Stop motion
    speed.yaw = speed.pitch = speed.hfov = 0;

    // Reload scene
    processOptions();
    if (workingPitch !== undefined) {
        config.pitch = workingPitch;
    }
    if (workingYaw !== undefined) {
        config.yaw = workingYaw;
    }
    if (workingHfov !== undefined) {
        config.hfov = workingHfov;
    }
    fireEvent('scenechange', sceneId);
    load();

    // Properly handle switching to dynamic scenes
    update = config.dynamicUpdate === true;
    if (config.dynamic) {
        panoImage = config.panorama;
        onImageLoad();
    }
}

Loads scene.
@private
@param {string} sceneId - Identifier of scene configuration to merge in.
@param {number} targetPitch - Pitch viewer should be centered on once scene loads.
@param {number} targetYaw - Yaw viewer should be centered on once scene loads.
@param {number} targetHfov - HFOV viewer should use once scene loads.
@param {boolean} [fadeDone] - If `true`, fade setup is skipped.


function stopOrientation() {
    window.removeEventListener('deviceorientation', orientationListener);
    controls.orientation.classList.remove('pnlm-orientation-button-active');
    orientation = false;
}

function stopOrientation ( ) { window . removeEventListener ( 'deviceorientation' , orientationListener ) ; controls . orientation . classList . remove ( 'pnlm-orientation-button-active' ) ; orientation = false ; }


function fireEvent(type) {
    if (type in externalEventListeners) {
        // Reverse iteration is useful, if event listener is removed inside its definition
        for (var i = externalEventListeners[type].length; i > 0; i--) {
            externalEventListeners[type][externalEventListeners[type].length - i].apply(null, [].slice.call(arguments, 1));
        }
    }
}

Fire listeners attached to specified event.
@private
@param {string} [type] - Type of event to fire listeners for.

Fire listeners attached to specified event .


function(latchFunction, optional_timeoutMessage, optional_timeout) {
  jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
}

function ( latchFunction , optional_timeoutMessage , optional_timeout ) { jasmine . getEnv ( ) . currentSpec . waitsFor . apply ( jasmine . getEnv ( ) . currentSpec , arguments ) ; }

Waits for the latchFunction to return true before proceeding to the next block.

@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout

Waits for the latchFunction to return true before proceeding to the next block .


function $getMouseOffset(target, ev){
    ev = ev || _window.event;
    var docPos    = $getPosition(target);
    var mousePos  = $mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function $getMouseOffset ( target , ev ) { ev = ev || _window . event ; var docPos = $getPosition ( target ) ; var mousePos = $mouseCoords ( ev ) ; return { x : mousePos . x - docPos . x , y : mousePos . y - docPos . y } ; }


function(val, flags){
    number_check(val)
    if(! flags.precision){
        if(! flags.decimal_point){
            flags.precision = 6
        }else{
            flags.precision = 0
        }
    }else{
        flags.precision = parseInt(flags.precision, 10)
        validate_precision(flags.precision)
    }
    return parseFloat(val)
}

function ( val , flags ) { number_check ( val ) if ( ! flags . precision ) { if ( ! flags . decimal_point ) { flags . precision = 6 } else { flags . precision = 0 } } else { flags . precision = parseInt ( flags . precision , 10 ) validate_precision ( flags . precision ) } return parseFloat ( val ) }

converts val to float and sets precision if missing


function(self, other){
    if(_b_.isinstance(other, int)) {
        if(other.__class__ === $B.long_int){
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
        other = int_value(other)
        if(self > $B.max_int32 || self < $B.min_int32 ||
                other > $B.max_int32 || other < $B.min_int32){
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
        return self - other
    }
    if(_b_.isinstance(other, _b_.bool)){return self - other}
    var rsub = $B.$getattr(other, "__rsub__", _b_.None)
    if(rsub !== _b_.None){return rsub(self)}
    $err("-", other)
}

function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { if ( other . __class__ === $B . long_int ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } other = int_value ( other ) if ( self > $B . max_int32 || self < $B . min_int32 || other > $B . max_int32 || other < $B . min_int32 ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } return self - other } if ( _b_ . isinstance ( other , _b_ . bool ) ) { return self - other } var rsub = $B . $getattr ( other , "__rsub__" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } $err ( "-" , other ) }


function(self, other){
    if(_b_.isinstance(other, int)){
        other = int_value(other)
        if(typeof other == "number"){
            var res = self.valueOf() - other.valueOf()
            if(res > $B.min_int && res < $B.max_int){return res}
            else{return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))}
        }else if(typeof other == "boolean"){
            return other ? self - 1 : self
        }else{
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
    }
    if(_b_.isinstance(other, _b_.float)){
        return new Number(self - other)
    }
    if(_b_.isinstance(other, _b_.complex)){
        return $B.make_complex(self - other.$real, -other.$imag)
    }
    if(_b_.isinstance(other, _b_.bool)){
         var bool_value = 0;
         if(other.valueOf()){bool_value = 1}
         return self - bool_value
    }
    if(_b_.isinstance(other, _b_.complex)){
        return $B.make_complex(self.valueOf() - other.$real, other.$imag)
    }
    var rsub = $B.$getattr(other, "__rsub__", _b_.None)
    if(rsub !== _b_.None){return rsub(self)}
    throw $err("-", other)
}

function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { other = int_value ( other ) if ( typeof other == "number" ) { var res = self . valueOf ( ) - other . valueOf ( ) if ( res > $B . min_int && res < $B . max_int ) { return res } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } else if ( typeof other == "boolean" ) { return other ? self - 1 : self } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } if ( _b_ . isinstance ( other , _b_ . float ) ) { return new Number ( self - other ) } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self - other . $real , - other . $imag ) } if ( _b_ . isinstance ( other , _b_ . bool ) ) { var bool_value = 0 ; if ( other . valueOf ( ) ) { bool_value = 1 } return self - bool_value } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self . valueOf ( ) - other . $real , other . $imag ) } var rsub = $B . $getattr ( other , "__rsub__" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } throw $err ( "-" , other ) }


function inlineResourcesFromString(content, urlResolver) {
  // Curry through the inlining functions.
  return [
    inlineTemplate,
    inlineStyle,
    removeModuleId
  ].reduce((content, fn) => fn(content, urlResolver), content);
}

Inline resources from a string content.
@param content {string} The source file's content.
@param urlResolver {Function} A resolver that takes a URL and return a path.
@returns {string} The content with resources inlined.

Inline resources from a string content .


function buildSass(content, sourceFile) {
  try {
    const result = sass.renderSync({
      data: content,
      file: sourceFile,
      importer: tildeImporter
    });
    return result.css.toString()
  } catch (e) {
    console.error('\x1b[41m');
    console.error('at ' + sourceFile + ':' + e.line + ":" + e.column);
    console.error(e.formatted);
    console.error('\x1b[0m');
    return "";
  }
}

function
buildSass
(
content
,
sourceFile
)
{
try
{
const
result
=
sass
.
renderSync
(
{
data
:
content
,
file
:
sourceFile
,
importer
:
tildeImporter
}
)
;
return
result
.
css
.
toString
(
)
}
catch
(
e
)
{
console
.
error
(
'\x1b[41m'
)
;
console
.
error
(
'at '
+
sourceFile
+
':'
+
e
.
line
+
":"
+
e
.
column
)
;
console
.
error
(
e
.
formatted
)
;
console
.
error
(
'\x1b[0m'
)
;
return
""
;
}
}

build sass content to css
@param content {string} the css content
@param sourceFile {string} the scss file sourceFile
@return {string} the generated css, empty string if error occured


function FormioResourceRoutes(config) {
    config = config || {};
    return [
        {
            path: '',
            component: config.index || index_component_1.FormioResourceIndexComponent
        },
        {
            path: 'new',
            component: config.create || create_component_1.FormioResourceCreateComponent
        },
        {
            path: ':id',
            component: config.resource || resource_component_1.FormioResourceComponent,
            children: [
                {
                    path: '',
                    redirectTo: 'view',
                    pathMatch: 'full'
                },
                {
                    path: 'view',
                    component: config.view || view_component_1.FormioResourceViewComponent
                },
                {
                    path: 'edit',
                    component: config.edit || edit_component_1.FormioResourceEditComponent
                },
                {
                    path: 'delete',
                    component: config.delete || delete_component_1.FormioResourceDeleteComponent
                }
            ]
        }
    ];
}

function FormioResourceRoutes ( config ) { config = config || { } ; return [ { path : '' , component : config . index || index_component_1 . FormioResourceIndexComponent } , { path : 'new' , component : config . create || create_component_1 . FormioResourceCreateComponent } , { path : ':id' , component : config . resource || resource_component_1 . FormioResourceComponent , children : [ { path : '' , redirectTo : 'view' , pathMatch : 'full' } , { path : 'view' , component : config . view || view_component_1 . FormioResourceViewComponent } , { path : 'edit' , component : config . edit || edit_component_1 . FormioResourceEditComponent } , { path : 'delete' , component : config . delete || delete_component_1 . FormioResourceDeleteComponent } ] } ] ; }


function BaseProducer (client, options, defaultPartitionerType, customPartitioner) {
  EventEmitter.call(this);
  options = options || {};

  this.ready = false;
  this.client = client;

  this.requireAcks = options.requireAcks === undefined ? DEFAULTS.requireAcks : options.requireAcks;
  this.ackTimeoutMs = options.ackTimeoutMs === undefined ? DEFAULTS.ackTimeoutMs : options.ackTimeoutMs;

  if (customPartitioner !== undefined && options.partitionerType !== PARTITIONER_TYPES.custom) {
    throw new Error('Partitioner Type must be custom if providing a customPartitioner.');
  } else if (customPartitioner === undefined && options.partitionerType === PARTITIONER_TYPES.custom) {
    throw new Error('No customer partitioner defined');
  }

  var partitionerType = PARTITIONER_MAP[options.partitionerType] || PARTITIONER_MAP[defaultPartitionerType];

  // eslint-disable-next-line
  this.partitioner = new partitionerType(customPartitioner);

  this.connect();
}

Provides common functionality for a kafka producer

@param {Client} client A kafka client object to use for the producer
@param {Object} [options] An object containing configuration options
@param {Number} [options.requireAcks=1] Configuration for when to consider a message as acknowledged.

0 = No ack required

1 = Leader ack required

-1 = All in sync replicas ack required

@param {Number} [options.ackTimeoutMs=100] The amount of time in milliseconds to wait for all acks before considered
the message as errored
@param {Number} [defaultPartitionType] The default partitioner type
@param {Object} [customPartitioner] a custom partitinoer to use of the form: function (partitions, key)
@constructor


function Context (options) {
  if (!options) options = { body: '', hostname: '' };

  const body = options.body;
  const href = 'http://' + options.hostname + '/';
  const cache = Object.create(null);
  const keys = [];

  this.atob = function (str) {
    return Buffer.from(str, 'base64').toString('binary');
  };

  // Used for eval during onRedirectChallenge
  this.location = { reload: function () {} };

  this.document = {
    createElement: function () {
      return { firstChild: { href: href } };
    },
    getElementById: function (id) {
      if (keys.indexOf(id) === -1) {
        const re = new RegExp(' id=[\'"]?' + id + '[^>]*>([^<]*)');
        const match = body.match(re);

        keys.push(id);
        cache[id] = match === null ? match : { innerHTML: match[1] };
      }

      return cache[id];
    }
  };
}

Global context used to evaluate standard IUAM JS challenge


function alternative (options, { captcha: { url, siteKey } }) {
  // Here you do some magic with the siteKey provided by cloudscraper
  console.error('The url is "' + url + '"');
  console.error('The site key is "' + siteKey + '"');
  return Promise.reject(new Error('This is a dummy function'));
}

An example handler with destructuring arguments


function performRequest (options, isFirstRequest) {
  // This should be the default export of either request or request-promise.
  const requester = options.requester;

  // Note that request is always an instanceof ReadableStream, EventEmitter
  // If the requester is request-promise, it is also thenable.
  const request = requester(options);

  // We must define the host header ourselves to preserve case and order.
  if (request.getHeader('host') === HOST) {
    request.setHeader('host', request.uri.host);
  }

  // If the requester is not request-promise, ensure we get a callback.
  if (typeof request.callback !== 'function') {
    throw new TypeError('Expected a callback function, got ' +
        typeof (request.callback) + ' instead.');
  }

  // We only need the callback from the first request.
  // The other callbacks can be safely ignored.
  if (isFirstRequest) {
    // This should be a user supplied callback or request-promise's callback.
    // The callback is always wrapped/bound to the request instance.
    options.callback = request.callback;
  }

  request.removeAllListeners('error')
    .once('error', function (error) {
      onRequestResponse(options, error);
    });

  request.removeAllListeners('complete')
    .once('complete', function (response, body) {
      onRequestResponse(options, null, response, body);
    });

  // Indicate that this is a cloudscraper request
  request.cloudscraper = true;
  return request;
}

This function is wrapped to ensure that we get new options on first call. The options object is reused in subsequent calls when calling it directly.

This function is wrapped to ensure that we get new options on first call . The options object is reused in subsequent calls when calling it directly .


function onRequestResponse (options, error, response, body) {
  const callback = options.callback;

  // Encoding is null so body should be a buffer object
  if (error || !body || !body.toString) {
    // Pure request error (bad connection, wrong url, etc)
    return callback(new RequestError(error, options, response));
  }

  response.responseStartTime = Date.now();
  response.isCloudflare = /^cloudflare/i.test('' + response.caseless.get('server'));
  response.isHTML = /text\/html/i.test('' + response.caseless.get('content-type'));

  // If body isn't a buffer, this is a custom response body.
  if (!Buffer.isBuffer(body)) {
    return callback(null, response, body);
  }

  // Decompress brotli compressed responses
  if (/\bbr\b/i.test('' + response.caseless.get('content-encoding'))) {
    if (!brotli.isAvailable) {
      const cause = 'Received a Brotli compressed response. Please install brotli';
      return callback(new RequestError(cause, options, response));
    }

    response.body = body = brotli.decompress(body);
  }

  if (response.isCloudflare && response.isHTML) {
    onCloudflareResponse(options, response, body);
  } else {
    onRequestComplete(options, response, body);
  }
}

The argument convention is options first where possible, options always before response, and body always after response.

The argument convention is options first where possible options always before response and body always after response .


function onCaptcha (options, response, body) {
  const callback = options.callback;
  // UDF that has the responsibility of returning control back to cloudscraper
  const handler = options.onCaptcha;
  // The form data to send back to Cloudflare
  const payload = { /* s, g-re-captcha-response */ };

  let cause;
  let match;

  match = body.match(/<form(?: [^<>]*)? id=["']?challenge-form['"]?(?: [^<>]*)?>([\S\s]*?)<\/form>/);
  if (!match) {
    cause = 'Challenge form extraction failed';
    return callback(new ParserError(cause, options, response));
  }

  // Defining response.challengeForm for debugging purposes
  const form = response.challengeForm = match[1];

  match = form.match(/\/recaptcha\/api\/fallback\?k=([^\s"'<>]*)/);
  if (!match) {
    // The site key wasn't inside the form so search the entire document
    match = body.match(/data-sitekey=["']?([^\s"'<>]*)/);
    if (!match) {
      cause = 'Unable to find the reCAPTCHA site key';
      return callback(new ParserError(cause, options, response));
    }
  }

  // Everything that is needed to solve the reCAPTCHA
  response.captcha = {
    url: response.request.uri.href,
    siteKey: match[1],
    form: payload
  };

  // Adding formData
  match = form.match(/<input(?: [^<>]*)? name=[^<>]+>/g);
  if (!match) {
    cause = 'Challenge form is missing inputs';
    return callback(new ParserError(cause, options, response));
  }

  const inputs = match;
  // Only adding inputs that have both a name and value defined
  for (let name, value, i = 0; i < inputs.length; i++) {
    name = inputs[i].match(/name=["']?([^\s"'<>]*)/);
    if (name) {
      value = inputs[i].match(/value=["']?([^\s"'<>]*)/);
      if (value) {
        payload[name[1]] = value[1];
      }
    }
  }

  // Sanity check
  if (!payload['s']) {
    cause = 'Challenge form is missing secret input';
    return callback(new ParserError(cause, options, response));
  }

  // The callback used to green light form submission
  const submit = function (error) {
    if (error) {
      // Pass an user defined error back to the original request call
      return callback(new CaptchaError(error, options, response));
    }

    onSubmitCaptcha(options, response, body);
  };

  // This seems like an okay-ish API (fewer arguments to the handler)
  response.captcha.submit = submit;

  // We're handing control over to the user now.
  const thenable = handler(options, response, body);
  // Handle the case where the user returns a promise
  if (thenable && typeof thenable.then === 'function') {
    // eslint-disable-next-line promise/catch-or-return
    thenable.then(submit, function (error) {
      if (!error) {
        // The user broke their promise with a falsy error
        submit(new Error('Falsy error'));
      } else {
        submit(error);
      }
    });
  }
}

Parses the reCAPTCHA form and hands control over to the user


function (error) {
    if (error) {
      // Pass an user defined error back to the original request call
      return callback(new CaptchaError(error, options, response));
    }

    onSubmitCaptcha(options, response, body);
  }

The callback used to green light form submission


function assets(userOptions = {}) {
  const options = {
    ...defaults,
    ...userOptions,
  };

  return (files, metalsmith, cb) => {
    const src = metalsmith.path(options.source);
    const dest = options.destination;

    // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js
    readdir(src, (readDirError, arr) => {
      if (readDirError) {
        cb(readDirError);
        return;
      }

      each(arr, read, err => cb(err, files));
    });

    function read(file, done) {
      const name = path.join(dest, path.relative(src, file));
      fs.stat(file, (statError, stats) => {
        if (statError) {
          done(statError);
          return;
        }

        fs.readFile(file, (err, buffer) => {
          if (err) {
            done(err);
            return;
          }

          const newFile = {};

          newFile.contents = buffer;
          newFile.stats = stats;

          newFile.mode = mode(stats).toOctal();
          files[name] = newFile;
          done();
        });
      });
    }
  };
}

Metalsmith plugin to include static assets.

@param {Object} userOptions (optional)
@property {String} source Path to copy static assets from (relative to working directory). Defaults to './public'
@property {String} destination Path to copy static assets to (relative to destination directory). Defaults to '.'
@return {Function} a Metalsmith plugin

Metalsmith plugin to include static assets .


function getStartStopBoundaries(parent, sidebar, topOffset) {
  const bbox = parent.getBoundingClientRect();
  const sidebarBbox = sidebar.getBoundingClientRect();
  const bodyBbox = document.body.getBoundingClientRect();

  const containerAbsoluteTop = bbox.top - bodyBbox.top;
  const sidebarAbsoluteTop = sidebarBbox.top - bodyBbox.top;
  const marginTop = sidebarAbsoluteTop - containerAbsoluteTop;
  const start = containerAbsoluteTop - topOffset;
  const stop = bbox.height + containerAbsoluteTop - sidebarBbox.height - marginTop - topOffset;

  return {
    start,
    stop,
  };
}

function getStartStopBoundaries ( parent , sidebar , topOffset ) { const bbox = parent . getBoundingClientRect ( ) ; const sidebarBbox = sidebar . getBoundingClientRect ( ) ; const bodyBbox = document . body . getBoundingClientRect ( ) ; const containerAbsoluteTop = bbox . top - bodyBbox . top ; const sidebarAbsoluteTop = sidebarBbox . top - bodyBbox . top ; const marginTop = sidebarAbsoluteTop - containerAbsoluteTop ; const start = containerAbsoluteTop - topOffset ; const stop = bbox . height + containerAbsoluteTop - sidebarBbox . height - marginTop - topOffset ; return { start , stop , } ; }

Defines the limits where to start or stop the stickiness
@param {HTMLElement} parent the outer container of the sidebar
@param {HTMLElement} sidebar the sidebar
@param {number} topOffset an optional top offset for sticky menu


function around (obj, method, fn) {
  var old = obj[method]

  obj[method] = function () {
    var args = new Array(arguments.length)
    for (var i = 0; i < args.length; i++) args[i] = arguments[i]
    return fn.call(this, old, args)
  }
}

function around ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { var args = new Array ( arguments . length ) for ( var i = 0 ; i < args . length ; i ++ ) args [ i ] = arguments [ i ] return fn . call ( this , old , args ) } }


function before (obj, method, fn) {
  var old = obj[method]

  obj[method] = function () {
    fn.call(this)
    old.apply(this, arguments)
  }
}

function before ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { fn . call ( this ) old . apply ( this , arguments ) } }


function copyTemplate (from, to) {
  write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))
}

function copyTemplate ( from , to ) { write ( to , fs . readFileSync ( path . join ( TEMPLATE_DIR , from ) , 'utf-8' ) ) }


function copyTemplateMulti (fromDir, toDir, nameGlob) {
  fs.readdirSync(path.join(TEMPLATE_DIR, fromDir))
    .filter(minimatch.filter(nameGlob, { matchBase: true }))
    .forEach(function (name) {
      copyTemplate(path.join(fromDir, name), path.join(toDir, name))
    })
}

function copyTemplateMulti ( fromDir , toDir , nameGlob ) { fs . readdirSync ( path . join ( TEMPLATE_DIR , fromDir ) ) . filter ( minimatch . filter ( nameGlob , { matchBase : true } ) ) . forEach ( function ( name ) { copyTemplate ( path . join ( fromDir , name ) , path . join ( toDir , name ) ) } ) }

Copy multiple files from template directory.

Copy multiple files from template directory .


function createAppName (pathName) {
  return path.basename(pathName)
    .replace(/[^A-Za-z0-9.-]+/g, '-')
    .replace(/^[-_.]+|-+$/g, '')
    .toLowerCase()
}

function createAppName ( pathName ) { return path . basename ( pathName ) . replace ( / [^A-Za-z0-9.-]+ / g , '-' ) . replace ( / ^[-_.]+|-+$ / g , '' ) . toLowerCase ( ) }

Create an app name from a directory path, fitting npm naming requirements.

@param {String} pathName

Create an app name from a directory path fitting npm naming requirements .


function emptyDirectory (dir, fn) {
  fs.readdir(dir, function (err, files) {
    if (err && err.code !== 'ENOENT') throw err
    fn(!files || !files.length)
  })
}

function emptyDirectory ( dir , fn ) { fs . readdir ( dir , function ( err , files ) { if ( err && err . code !== 'ENOENT' ) throw err fn ( ! files || ! files . length ) } ) }

Check if the given directory `dir` is empty.

@param {String} dir
@param {Function} fn

Check if the given directory dir is empty .


function exit (code) {
  // flush output for Node.js Windows pipe bug
  // https://github.com/joyent/node/issues/6247 is just one bug example
  // https://github.com/visionmedia/mocha/issues/333 has a good discussion
  function done () {
    if (!(draining--)) _exit(code)
  }

  var draining = 0
  var streams = [process.stdout, process.stderr]

  exit.exited = true

  streams.forEach(function (stream) {
    // submit empty write request and wait for completion
    draining += 1
    stream.write('', done)
  })

  done()
}


function loadTemplate (name) {
  var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8')
  var locals = Object.create(null)

  function render () {
    return ejs.render(contents, locals, {
      escape: util.inspect
    })
  }

  return {
    locals: locals,
    render: render
  }
}

function loadTemplate ( name ) { var contents = fs . readFileSync ( path . join ( __dirname , '..' , 'templates' , ( name + '.ejs' ) ) , 'utf-8' ) var locals = Object . create ( null ) function render ( ) { return ejs . render ( contents , locals , { escape : util . inspect } ) } return { locals : locals , render : render } }


function main () {
  // Path
  var destinationPath = program.args.shift() || '.'

  // App name
  var appName = createAppName(path.resolve(destinationPath)) || 'hello-world'

  // View engine
  if (program.view === true) {
    if (program.ejs) program.view = 'ejs'
    if (program.hbs) program.view = 'hbs'
    if (program.hogan) program.view = 'hjs'
    if (program.pug) program.view = 'pug'
  }

  // Default view engine
  if (program.view === true) {
    warning('the default view engine will not be jade in future releases\n' +
      "use `--view=jade' or `--help' for additional options")
    program.view = 'jade'
  }

  // Generate application
  emptyDirectory(destinationPath, function (empty) {
    if (empty || program.force) {
      createApplication(appName, destinationPath)
    } else {
      confirm('destination is not empty, continue? [y/N] ', function (ok) {
        if (ok) {
          process.stdin.destroy()
          createApplication(appName, destinationPath)
        } else {
          console.error('aborting')
          exit(1)
        }
      })
    }
  })
}


function mkdir (base, dir) {
  var loc = path.join(base, dir)

  console.log('   \x1b[36mcreate\x1b[0m : ' + loc + path.sep)
  mkdirp.sync(loc, MODE_0755)
}

function
mkdir
(
base
,
dir
)
{
var
loc
=
path
.
join
(
base
,
dir
)
console
.
log
(
'   \x1b[36mcreate\x1b[0m : '
+
loc
+
path
.
sep
)
mkdirp
.
sync
(
loc
,
MODE_0755
)
}

Make the given dir relative to base.

@param {string} base
@param {string} dir


function renamedOption (originalName, newName) {
  return function (val) {
    warning(util.format("option `%s' has been renamed to `%s'", originalName, newName))
    return val
  }
}

function
renamedOption
(
originalName
,
newName
)
{
return
function
(
val
)
{
warning
(
util
.
format
(
"option `%s' has been renamed to `%s'"
,
originalName
,
newName
)
)
return
val
}
}

Generate a callback function for commander to warn about renamed option.

@param {String} originalName
@param {String} newName

Generate a callback function for commander to warn about renamed option .


function warning (message) {
  console.error()
  message.split('\n').forEach(function (line) {
    console.error('  warning: %s', line)
  })
  console.error()
}

function
warning
(
message
)
{
console
.
error
(
)
message
.
split
(
'\n'
)
.
forEach
(
function
(
line
)
{
console
.
error
(
'  warning: %s'
,
line
)
}
)
console
.
error
(
)
}

Display a warning similar to how errors are displayed by commander.

@param {String} message

Display a warning similar to how errors are displayed by commander .


function write (file, str, mode) {
  fs.writeFileSync(file, str, { mode: mode || MODE_0666 })
  console.log('   \x1b[36mcreate\x1b[0m : ' + file)
}

function
write
(
file
,
str
,
mode
)
{
fs
.
writeFileSync
(
file
,
str
,
{
mode
:
mode
||
MODE_0666
}
)
console
.
log
(
'   \x1b[36mcreate\x1b[0m : '
+
file
)
}

echo str > file.

@param {String} file
@param {String} str


function bind_d3(f, context) {
    return function() {
        var args = [this].concat([].slice.call(arguments)) // convert argument to array
        f.apply(context, args)
    }
}

function
bind_d3
(
f
,
context
)
{
return
function
(
)
{
var
args
=
[
this
]
.
concat
(
[
]
.
slice
.
call
(
arguments
)
)
// convert argument to array
f
.
apply
(
context
,
args
)
}
}

similar to _.bind, except it puts this as first argument to f, followed be other arguments, and make context f's this

similar to _ . bind except it puts this as first argument to f followed be other arguments and make context f s this


function adjustOptions(options) {
  const directory = process.cwd();
  const configPath = getWebpackConfigPath(directory, options.config);
  const haulOptions = getHaulConfig(configPath, logger);

  if (haulOptions.platforms) {
    const platformOption =
      command.options && command.options.find(_ => _.name === 'platform');
    if (platformOption) {
      platformOption.choices = [];
      for (const platformName in haulOptions.platforms) {
        if (
          Object.prototype.hasOwnProperty.call(
            haulOptions.platforms,
            platformName
          )
        ) {
          if (platformOption.choices) {
            platformOption.choices.push({
              value: platformName,
              description: `Builds ${haulOptions.platforms[
                platformName
              ]} bundle`,
            });
          }
        }
      }
    }
  }
}

function adjustOptions ( options ) { const directory = process . cwd ( ) ; const configPath = getWebpackConfigPath ( directory , options . config ) ; const haulOptions = getHaulConfig ( configPath , logger ) ; if ( haulOptions . platforms ) { const platformOption = command . options && command . options . find ( _ => _ . name === 'platform' ) ; if ( platformOption ) { platformOption . choices = [ ] ; for ( const platformName in haulOptions . platforms ) { if ( Object . prototype . hasOwnProperty . call ( haulOptions . platforms , platformName ) ) { if ( platformOption . choices ) { platformOption . choices . push ( { value : platformName , description : ` ${ haulOptions . platforms [ platformName ] } ` , } ) ; } } } } } }

Allow config file to override the list of availiable platforms


function devToolsMiddleware(debuggerProxy) {
  return (req, res, next) => {
    switch (req.cleanPath) {
      /**
       * Request for the debugger frontend
       */
      case '/debugger-ui/':
      case '/debugger-ui': {
        const readStream = fs.createReadStream(
          path.join(__dirname, '../assets/debugger.html')
        );
        res.writeHead(200, { 'Content-Type': 'text/html' });
        readStream.pipe(res);
        break;
      }

      /**
       * Request for the debugger worker
       */
      case '/debugger-ui/debuggerWorker.js':
      case '/debuggerWorker.js': {
        const readStream = fs.createReadStream(
          path.join(__dirname, '../assets/debuggerWorker.js')
        );
        res.writeHead(200, { 'Content-Type': 'application/javascript' });
        readStream.pipe(res);
        break;
      }

      /**
       * Request for (maybe) launching devtools
       */
      case '/launch-js-devtools': {
        if (!debuggerProxy.isDebuggerConnected()) {
          launchBrowser(`http://localhost:${req.socket.localPort}/debugger-ui`);
        }
        res.end('OK');
        break;
      }

      default:
        next();
    }
  };
}

Devtools middleware compatible with default React Native implementation


function onLoad(event) {

	// Prepare the render pass.
	event.demo.renderPass.camera = event.demo.camera;

	document.getElementById("viewport").children[0].style.display = "none";

}

function
onLoad
(
event
)
{
// Prepare the render pass.
event
.
demo
.
renderPass
.
camera
=
event
.
demo
.
camera
;
document
.
getElementById
(
"viewport"
)
.
children
[
0
]
.
style
.
display
=
"none"
;
}

Handles demo load events.

@private
@param {Event} event - An event.


function prefixSubstrings(prefix, substrings, strings) {

	let prefixed, regExp;

	for(const substring of substrings) {

		prefixed = "$1" + prefix + substring.charAt(0).toUpperCase() + substring.slice(1);
		regExp = new RegExp("([^\\.])(\\b" + substring + "\\b)", "g");

		for(const entry of strings.entries()) {

			if(entry[1] !== null) {

				strings.set(entry[0], entry[1].replace(regExp, prefixed));

			}

		}

	}

}

function prefixSubstrings ( prefix , substrings , strings ) { let prefixed , regExp ; for ( const substring of substrings ) { prefixed = "$1" + prefix + substring . charAt ( 0 ) . toUpperCase ( ) + substring . slice ( 1 ) ; regExp = new RegExp ( "([^\\.])(\\b" + substring + "\\b)" , "g" ) ; for ( const entry of strings . entries ( ) ) { if ( entry [ 1 ] !== null ) { strings . set ( entry [ 0 ] , entry [ 1 ] . replace ( regExp , prefixed ) ) ; } } } }

Prefixes substrings within the given strings.

@private
@param {String} prefix - A prefix.
@param {String[]} substrings - The substrings.
@param {Map<String, String>} strings - A collection of named strings.

Prefixes substrings within the given strings .


function createCanvas(width, height, data, channels) {

	const canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
	const context = canvas.getContext("2d");

	const imageData = context.createImageData(width, height);
	const target = imageData.data;

	let x, y;
	let i, j;

	for(y = 0; y < height; ++y) {

		for(x = 0; x < width; ++x) {

			i = (y * width + x) * 4;
			j = (y * width + x) * channels;

			target[i] = (channels > 0) ? data[j] : 0;
			target[i + 1] = (channels > 1) ? data[j + 1] : 0;
			target[i + 2] = (channels > 2) ? data[j + 2] : 0;
			target[i + 3] = (channels > 3) ? data[j + 3] : 255;

		}

	}

	canvas.width = width;
	canvas.height = height;

	context.putImageData(imageData, 0, 0);

	return canvas;

}

function createCanvas ( width , height , data , channels ) { const canvas = document . createElementNS ( "http://www.w3.org/1999/xhtml" , "canvas" ) ; const context = canvas . getContext ( "2d" ) ; const imageData = context . createImageData ( width , height ) ; const target = imageData . data ; let x , y ; let i , j ; for ( y = 0 ; y < height ; ++ y ) { for ( x = 0 ; x < width ; ++ x ) { i = ( y * width + x ) * 4 ; j = ( y * width + x ) * channels ; target [ i ] = ( channels > 0 ) ? data [ j ] : 0 ; target [ i + 1 ] = ( channels > 1 ) ? data [ j + 1 ] : 0 ; target [ i + 2 ] = ( channels > 2 ) ? data [ j + 2 ] : 0 ; target [ i + 3 ] = ( channels > 3 ) ? data [ j + 3 ] : 255 ; } } canvas . width = width ; canvas . height = height ; context . putImageData ( imageData , 0 , 0 ) ; return canvas ; }

Creates a new canvas from raw image data.

@private
@param {Number} width - The image width.
@param {Number} height - The image height.
@param {Uint8ClampedArray} data - The image data.
@param {Number} channels - The color channels used for a single pixel.
@return {Canvas} The canvas.

Creates a new canvas from raw image data .


function smoothArea(d, b) {

	const a1 = b.min;
	const a2 = b.max;

	const b1X = Math.sqrt(a1.x * 2.0) * 0.5;
	const b1Y = Math.sqrt(a1.y * 2.0) * 0.5;
	const b2X = Math.sqrt(a2.x * 2.0) * 0.5;
	const b2Y = Math.sqrt(a2.y * 2.0) * 0.5;

	const p = saturate(d / SMOOTH_MAX_DISTANCE);

	a1.set(lerp(b1X, a1.x, p), lerp(b1Y, a1.y, p));
	a2.set(lerp(b2X, a2.x, p), lerp(b2Y, a2.y, p));

	return b;

}

function smoothArea ( d , b ) { const a1 = b . min ; const a2 = b . max ; const b1X = Math . sqrt ( a1 . x * 2.0 ) * 0.5 ; const b1Y = Math . sqrt ( a1 . y * 2.0 ) * 0.5 ; const b2X = Math . sqrt ( a2 . x * 2.0 ) * 0.5 ; const b2Y = Math . sqrt ( a2 . y * 2.0 ) * 0.5 ; const p = saturate ( d / SMOOTH_MAX_DISTANCE ) ; a1 . set ( lerp ( b1X , a1 . x , p ) , lerp ( b1Y , a1 . y , p ) ) ; a2 . set ( lerp ( b2X , a2 . x , p ) , lerp ( b2Y , a2 . y , p ) ) ; return b ; }

A smoothing function for small U-patterns.

@private
@param {Number} d - A smoothing factor.
@param {Box2} b - The area that should be smoothed.
@return {Box2} The smoothed area.

A smoothing function for small U - patterns .


function calculateDiagonalAreaForPixel(p1, p2, pX, pY) {

	let a;
	let x, y;
	let offsetX, offsetY;

	for(a = 0, y = 0; y < DIAGONAL_SAMPLES; ++y) {

		for(x = 0; x < DIAGONAL_SAMPLES; ++x) {

			offsetX = x / (DIAGONAL_SAMPLES - 1.0);
			offsetY = y / (DIAGONAL_SAMPLES - 1.0);

			if(isInsideArea(p1, p2, pX + offsetX, pY + offsetY)) {

				++a;

			}

		}

	}

	return a / (DIAGONAL_SAMPLES * DIAGONAL_SAMPLES);

}

function calculateDiagonalAreaForPixel ( p1 , p2 , pX , pY ) { let a ; let x , y ; let offsetX , offsetY ; for ( a = 0 , y = 0 ; y < DIAGONAL_SAMPLES ; ++ y ) { for ( x = 0 ; x < DIAGONAL_SAMPLES ; ++ x ) { offsetX = x / ( DIAGONAL_SAMPLES - 1.0 ) ; offsetY = y / ( DIAGONAL_SAMPLES - 1.0 ) ; if ( isInsideArea ( p1 , p2 , pX + offsetX , pY + offsetY ) ) { ++ a ; } } } return a / ( DIAGONAL_SAMPLES * DIAGONAL_SAMPLES ) ; }

Calculates the area under the line p1 -> p2 for the pixel p using brute force
sampling.

@private
@param {Vector2} p1 - The lower bounds of the area.
@param {Vector2} p2 - The upper bounds of the area.
@param {Number} pX - The X-coordinates.
@param {Number} pY - The Y-coordinates.
@return {Number} The amount of pixels inside the area relative to the total amount of sampled pixels.

Calculates the area under the line p1 - > p2 for the pixel p using brute force sampling .


function calculateDiagonalArea(pattern, p1, p2, left, offset, result) {

	const e = diagonalEdges[pattern];
	const e1 = e[0];
	const e2 = e[1];

	if(e1 > 0) {

		p1.x += offset[0];
		p1.y += offset[1];

	}

	if(e2 > 0) {

		p2.x += offset[0];
		p2.y += offset[1];

	}

	return result.set(
		1.0 - calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 0.0 + left),
		calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 1.0 + left)
	);

}

function calculateDiagonalArea ( pattern , p1 , p2 , left , offset , result ) { const e = diagonalEdges [ pattern ] ; const e1 = e [ 0 ] ; const e2 = e [ 1 ] ; if ( e1 > 0 ) { p1 . x += offset [ 0 ] ; p1 . y += offset [ 1 ] ; } if ( e2 > 0 ) { p2 . x += offset [ 0 ] ; p2 . y += offset [ 1 ] ; } return result . set ( 1.0 - calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 0.0 + left ) , calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 1.0 + left ) ) ; }

Calculates the area under the line p1 -> p2. This includes the pixel and its
opposite.

@private
@param {Number} pattern - A pattern index.
@param {Vector2} p1 - The lower bounds of the area.
@param {Vector2} p2 - The upper bounds of the area.
@param {Number} left - The left distance.
@param {Float32Array} offset - An offset.
@param {Vector2} result - A target vector to store the area in.
@return {Vector2} The area.

Calculates the area under the line p1 - > p2 . This includes the pixel and its opposite .


function generatePatterns(patterns, offset, orthogonal) {

	const result = new Vector2();

	let i, l;
	let x, y;
	let c;

	let pattern;
	let data, size;

	for(i = 0, l = patterns.length; i < l; ++i) {

		pattern = patterns[i];

		data = pattern.data;
		size = pattern.width;

		for(y = 0; y < size; ++y) {

			for(x = 0; x < size; ++x) {

				if(orthogonal) {

					calculateOrthogonalAreaForPattern(i, x, y, offset, result);

				} else {

					calculateDiagonalAreaForPattern(i, x, y, offset, result);

				}

				c = (y * size + x) * 2;

				data[c] = result.x * 255;
				data[c + 1] = result.y * 255;

			}

		}

	}

}

function generatePatterns ( patterns , offset , orthogonal ) { const result = new Vector2 ( ) ; let i , l ; let x , y ; let c ; let pattern ; let data , size ; for ( i = 0 , l = patterns . length ; i < l ; ++ i ) { pattern = patterns [ i ] ; data = pattern . data ; size = pattern . width ; for ( y = 0 ; y < size ; ++ y ) { for ( x = 0 ; x < size ; ++ x ) { if ( orthogonal ) { calculateOrthogonalAreaForPattern ( i , x , y , offset , result ) ; } else { calculateDiagonalAreaForPattern ( i , x , y , offset , result ) ; } c = ( y * size + x ) * 2 ; data [ c ] = result . x * 255 ; data [ c + 1 ] = result . y * 255 ; } } } }

Calculates orthogonal or diagonal patterns for a given offset.

@param {RawImageData[]} patterns - The patterns to assemble.
@param {Number|Float32Array} offset - A pattern offset. Diagonal offsets are pairs.
@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.

Calculates orthogonal or diagonal patterns for a given offset .


function assemble(base, patterns, edges, size, orthogonal, target) {

	const p = new Vector2();

	const dstData = target.data;
	const dstWidth = target.width;

	let i, l;
	let x, y;
	let c, d;

	let edge;
	let pattern;
	let srcData, srcWidth;

	for(i = 0, l = patterns.length; i < l; ++i) {

		edge = edges[i];
		pattern = patterns[i];

		srcData = pattern.data;
		srcWidth = pattern.width;

		for(y = 0; y < size; ++y) {

			for(x = 0; x < size; ++x) {

				p.fromArray(edge).multiplyScalar(size);
				p.add(base);
				p.x += x;
				p.y += y;

				c = (p.y * dstWidth + p.x) * 2;

				/* The texture coordinates of orthogonal patterns are compressed
				quadratically to reach longer distances for a given texture size. */
				d = orthogonal ? ((y * y * srcWidth + x * x) * 2) :
					((y * srcWidth + x) * 2);

				dstData[c] = srcData[d];
				dstData[c + 1] = srcData[d + 1];

			}

		}

	}

}

Assembles orthogonal or diagonal patterns into the final area image.

@param {Vector2} base - A base position.
@param {RawImageData[]} patterns - The patterns to assemble.
@param {Uint8Array[]} edges - Edge coordinate pairs, used for positioning.
@param {Number} size - The pattern size.
@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.
@param {RawImageData} target - The target image data.

Assembles orthogonal or diagonal patterns into the final area image .


function deltaRight(left, top) {

	let d = 0;

	// If there is an edge, and no crossing edges, continue.
	if(top[3] === 1 && left[1] !== 1 && left[3] !== 1) {

		d += 1;

	}

	/* If an edge was previously found, there is another edge and there are no
	crossing edges, continue. */
	if(d === 1 && top[2] === 1 && left[0] !== 1 && left[2] !== 1) {

		d += 1;

	}

	return d;

}

Computes the delta distance to add in the last step of searches to the right.

@private
@param {Number[]} left - The left edge combination.
@param {Number[]} top - The top edge combination.
@return {Number} The right delta distance.

Computes the delta distance to add in the last step of searches to the right .


Calculates the bilinear fetch for a certain edge combination.

e[0]       e[1]

x <-------- Sample Position: (-0.25, -0.125)
e[2]       e[3] <--- Current Pixel [3]: (0.0, 0.0)

@private
@param {Number[]} e - The edge combination.
@return {Number} The interpolated value.

Calculates the bilinear fetch for a certain edge combination .


function checkForm(that) {
    var newValue = $(that).val()
    var matches = newValue != '' ? newValue.match(timeRegEx) : ''
    var error = $(that)
      .closest('.time-spinner')
      .find('.error_container')
    var $closerTimeSpinner = $(that)
      .closest('.time-spinner')
      .find('.spinner-control')

    if (matches) {
      $(error).html('')
      //$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]);
      //$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]);
      return true
    } else {
      var errMsg = 'Formato data non valido'
      $(error).html(errMsg)
      //$(that).val('Formato data non valido')
      return false
    }
  }


function resetToMove(contextControl) {
    var left = contextControl.find('.source .transfer-group')
    var right = contextControl.find('.target .transfer-group')
    var textLeft = contextControl.find('.source .transfer-header span.num')
    var textRight = contextControl.find('.target .transfer-header span.num')
    var header = contextControl.find('.transfer-header input')

    $(left).html(elemLeft)
    $(right).html(elemRight)

    $(textLeft).text(elemLeftNum)
    $(textRight).text(elemRightNum)

    $(header).prop('disabled', false)
  }

function
resetToMove
(
contextControl
)
{
var
left
=
contextControl
.
find
(
'.source .transfer-group'
)
var
right
=
contextControl
.
find
(
'.target .transfer-group'
)
var
textLeft
=
contextControl
.
find
(
'.source .transfer-header span.num'
)
var
textRight
=
contextControl
.
find
(
'.target .transfer-header span.num'
)
var
header
=
contextControl
.
find
(
'.transfer-header input'
)
$
(
left
)
.
html
(
elemLeft
)
$
(
right
)
.
html
(
elemRight
)
$
(
textLeft
)
.
text
(
elemLeftNum
)
$
(
textRight
)
.
text
(
elemRightNum
)
$
(
header
)
.
prop
(
'disabled'
,
false
)
}


function checkIfActive(
    targetControl,
    targetHeaderControl,
    containerTypeControl,
    addButtonControl
  ) {
    $(targetControl).each(function(el) {
      if ($(this).prop('checked')) {
        if (!$(targetHeaderControl).hasClass('semi-checked')) {
          $(targetHeaderControl).addClass('semi-checked')
          $(targetHeaderControl).prop('checked', false)
          if (containerTypeControl.hasClass('source')) {
            $(addButtonControl).addClass('active')
          }
          if (containerTypeControl.hasClass('target')) {
            $(inverseButton).addClass('active')
          }
        }
        return false
      } else {
        $(targetHeaderControl).removeClass('semi-checked')
        if (containerTypeControl.hasClass('source')) {
          $(addButtonControl).removeClass('active')
        }
        if (containerTypeControl.hasClass('target')) {
          $(inverseButton).removeClass('active')
        }
      }
    })
  }

function checkIfActive ( targetControl , targetHeaderControl , containerTypeControl , addButtonControl ) { $ ( targetControl ) . each ( function ( el ) { if ( $ ( this ) . prop ( 'checked' ) ) { if ( ! $ ( targetHeaderControl ) . hasClass ( 'semi-checked' ) ) { $ ( targetHeaderControl ) . addClass ( 'semi-checked' ) $ ( targetHeaderControl ) . prop ( 'checked' , false ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . addClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . addClass ( 'active' ) } } return false } else { $ ( targetHeaderControl ) . removeClass ( 'semi-checked' ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . removeClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . removeClass ( 'active' ) } } } ) }


function sourceControl(contextControl) {
    var tocheck = contextControl.find('.transfer-scroll').find('input')
    var checknum = tocheck.length
    var targetText = contextControl
      .find('.transfer-header')
      .find('label span.num')
    var header = contextControl.find('.transfer-header input')

    $(header)
      .prop('checked', false)
      .removeClass('semi-checked')

    if (checknum < 1) {
      $(header).prop('disabled', true)
    } else {
      $(header).prop('disabled', false)
    }

    $(targetText).text(checknum)
  }

function
sourceControl
(
contextControl
)
{
var
tocheck
=
contextControl
.
find
(
'.transfer-scroll'
)
.
find
(
'input'
)
var
checknum
=
tocheck
.
length
var
targetText
=
contextControl
.
find
(
'.transfer-header'
)
.
find
(
'label span.num'
)
var
header
=
contextControl
.
find
(
'.transfer-header input'
)
$
(
header
)
.
prop
(
'checked'
,
false
)
.
removeClass
(
'semi-checked'
)
if
(
checknum
<
1
)
{
$
(
header
)
.
prop
(
'disabled'
,
true
)
}
else
{
$
(
header
)
.
prop
(
'disabled'
,
false
)
}
$
(
targetText
)
.
text
(
checknum
)
}


function targetControl(targetControl) {
    var tocheck = targetControl.find('input')
    var checknum = tocheck.length
    var targetText = tocheck
      .closest('.it-transfer-wrapper')
      .find('.transfer-header')
      .find('label span.num')
    var header = $(targetControl).find('.transfer-header input')

    if (checknum < 1) {
      $(header).prop('disabled', true)
    } else {
      $(header).prop('disabled', false)
    }

    $(targetText).text(checknum)
  }

function
targetControl
(
targetControl
)
{
var
tocheck
=
targetControl
.
find
(
'input'
)
var
checknum
=
tocheck
.
length
var
targetText
=
tocheck
.
closest
(
'.it-transfer-wrapper'
)
.
find
(
'.transfer-header'
)
.
find
(
'label span.num'
)
var
header
=
$
(
targetControl
)
.
find
(
'.transfer-header input'
)
if
(
checknum
<
1
)
{
$
(
header
)
.
prop
(
'disabled'
,
true
)
}
else
{
$
(
header
)
.
prop
(
'disabled'
,
false
)
}
$
(
targetText
)
.
text
(
checknum
)
}


function checkToMove(contextControl, targetControl) {
    var elements = contextControl.find('.transfer-group').find('input:checked')
    var sourceTag = $(elements).closest('.form-check')

    $(elements).each(function() {
      $(this).prop('checked', false)
      $(sourceTag)
        .detach()
        .appendTo(targetControl)
        .addClass('added')
    })
  }

function checkToMove ( contextControl , targetControl ) { var elements = contextControl . find ( '.transfer-group' ) . find ( 'input:checked' ) var sourceTag = $ ( elements ) . closest ( '.form-check' ) $ ( elements ) . each ( function ( ) { $ ( this ) . prop ( 'checked' , false ) $ ( sourceTag ) . detach ( ) . appendTo ( targetControl ) . addClass ( 'added' ) } ) }


function updateScrollPos() {
    if (!stickies.length) {
      return
    }

    lastKnownScrollTop =
      document.documentElement.scrollTop || document.body.scrollTop

    // Only trigger a layout change if we’re not already waiting for one
    if (!isAnimationRequested) {
      isAnimationRequested = true

      // Don’t update until next animation frame if we can, otherwise use a
      // timeout - either will help avoid too many repaints
      if (requestAnimationFrame) {
        requestAnimationFrame(setPositions)
      } else {
        if (timeout) {
          clearTimeout(timeout)
        }

        timeout = setTimeout(setPositions, 15)
      }
    }
  }


function scoreText(score) {
      if (score === -1) {
        return options.shortPass
      }

      score = score < 0 ? 0 : score

      if (score < 26) {
        return options.shortPass
      }
      if (score < 51) {
        return options.badPass
      }
      if (score < 76) {
        return options.goodPass
      }

      return options.strongPass
    }

function scoreText ( score ) { if ( score === - 1 ) { return options . shortPass } score = score < 0 ? 0 : score if ( score < 26 ) { return options . shortPass } if ( score < 51 ) { return options . badPass } if ( score < 76 ) { return options . goodPass } return options . strongPass }

Returns strings based on the score given.

@param int score Score base.
@return string

Returns strings based on the score given .


function calculateScore(password) {
      var score = 0

      // password < options.minimumLength
      if (password.length < options.minimumLength) {
        return -1
      }

      // password length
      score += password.length * 4
      score += checkRepetition(1, password).length - password.length
      score += checkRepetition(2, password).length - password.length
      score += checkRepetition(3, password).length - password.length
      score += checkRepetition(4, password).length - password.length

      // password has 3 numbers
      if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
        score += 5
      }

      // password has at least 2 sybols
      var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]'
      symbols = new RegExp('(' + symbols + symbols + ')')
      if (password.match(symbols)) {
        score += 5
      }

      // password has Upper and Lower chars
      if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
        score += 10
      }

      // password has number and chars
      if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
        score += 15
      }

      // password has number and symbol
      if (
        password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
        password.match(/([0-9])/)
      ) {
        score += 15
      }

      // password has char and symbol
      if (
        password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
        password.match(/([a-zA-Z])/)
      ) {
        score += 15
      }

      // password is just numbers or chars
      if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
        score -= 10
      }

      if (score > 100) {
        score = 100
      }

      if (score < 0) {
        score = 0
      }

      return score
    }

function
calculateScore
(
password
)
{
var
score
=
0
// password < options.minimumLength
if
(
password
.
length
<
options
.
minimumLength
)
{
return
1
}
// password length
score
+=
password
.
length
*
4
score
+=
checkRepetition
(
1
,
password
)
.
length
password
.
length
score
+=
checkRepetition
(
2
,
password
)
.
length
password
.
length
score
+=
checkRepetition
(
3
,
password
)
.
length
password
.
length
score
+=
checkRepetition
(
4
,
password
)
.
length
password
.
length
// password has 3 numbers
if
(
password
.
match
(
/
(.*[0-9].*[0-9].*[0-9])
/
)
)
{
score
+=
5
}
// password has at least 2 sybols
var
symbols
=
'.*[!,@,#,$,%,^,&,*,?,_,~]'
symbols
=
new
RegExp
(
'('
+
symbols
+
symbols
+
')'
)
if
(
password
.
match
(
symbols
)
)
{
score
+=
5
}
// password has Upper and Lower chars
if
(
password
.
match
(
/
([a-z].*[A-Z])|([A-Z].*[a-z])
/
)
)
{
score
+=
10
}
// password has number and chars
if
(
password
.
match
(
/
([a-zA-Z])
/
)
&&
password
.
match
(
/
([0-9])
/
)
)
{
score
+=
15
}
// password has number and symbol
if
(
password
.
match
(
/
([!,@,#,$,%,^,&,*,?,_,~])
/
)
&&
password
.
match
(
/
([0-9])
/
)
)
{
score
+=
15
}
// password has char and symbol
if
(
password
.
match
(
/
([!,@,#,$,%,^,&,*,?,_,~])
/
)
&&
password
.
match
(
/
([a-zA-Z])
/
)
)
{
score
+=
15
}
// password is just numbers or chars
if
(
password
.
match
(
/
^\w+$
/
)
||
password
.
match
(
/
^\d+$
/
)
)
{
score
-=
10
}
if
(
score
>
100
)
{
score
=
100
}
if
(
score
<
0
)
{
score
=
0
}
return
score
}

Returns a value between -1 and 100 to score
the user's password.

@param  string password The password to be checked.
@return int

Returns a value between - 1 and 100 to score the user s password .


function checkRepetition(rLen, str) {
      var res = '',
        repeated = false
      for (var i = 0; i < str.length; i++) {
        repeated = true
        for (var j = 0; j < rLen && j + i + rLen < str.length; j++) {
          repeated = repeated && str.charAt(j + i) === str.charAt(j + i + rLen)
        }
        if (j < rLen) {
          repeated = false
        }
        if (repeated) {
          i += rLen - 1
          repeated = false
        } else {
          res += str.charAt(i)
        }
      }
      return res
    }

function checkRepetition ( rLen , str ) { var res = '' , repeated = false for ( var i = 0 ; i < str . length ; i ++ ) { repeated = true for ( var j = 0 ; j < rLen && j + i + rLen < str . length ; j ++ ) { repeated = repeated && str . charAt ( j + i ) === str . charAt ( j + i + rLen ) } if ( j < rLen ) { repeated = false } if ( repeated ) { i += rLen - 1 repeated = false } else { res += str . charAt ( i ) } } return res }

Checks for repetition of characters in
a string

@param int rLen Repetition length.
@param string str The string to be checked.
@return string


function init() {
      var shown = true
      var $text = options.showText

      var $graybar = $('
').addClass(
        'password-meter progress rounded-0 position-absolute'
      )
      $graybar.append(`

`)
      var $colorbar = $('
').attr({
        class: 'progress-bar',
        role: 'progressbar',
        'aria-valuenow': '0',
        'aria-valuemin': '0',
        'aria-valuemax': '100',
      })
      var $insert = $('
').append($graybar.append($colorbar))

      if (options.showText) {
        $text = $('')
          .addClass('form-text text-muted')
          .html(options.enterPass)
        $insert.prepend($text)
      }

      $object.after($insert)

      $object.keyup(function() {
        var score = calculateScore($object.val())
        $object.trigger('password.score', [score])
        var perc = score < 0 ? 0 : score
        $colorbar.removeClass(function(index, className) {
          return (className.match(/(^|\s)bg-\S+/g) || []).join(' ')
        })
        $colorbar.addClass('bg-' + scoreColor(score))
        $colorbar.css({
          width: perc + '%',
        })
        $colorbar.attr('aria-valuenow', perc)

        if (options.showText) {
          var text = scoreText(score)
          if (!$object.val().length && score <= 0) {
            text = options.enterPass
          }

          if (
            $text.html() !==
            $('
')
              .html(text)
              .html()
          ) {
            $text.html(text)
            $text.removeClass(function(index, className) {
              return (className.match(/(^|\s)text-\S+/g) || []).join(' ')
            })
            $text.addClass('text-' + scoreColor(score))
            $object.trigger('password.text', [text, score])
          }
        }
      })

      return this
    }

Initializes the plugin creating and binding the
required layers and events.

@return void

Initializes the plugin creating and binding the required layers and events .


function LevelUpArrayAdapter(name, db, serializer) {
  this.db = Sublevel(db);
  this.db = this.db.sublevel(name);
  this.name = name;
  this.serializer = serializer || {
    encode: function(val, callback) {
      callback(null, val);
    },
    decode: function(val, callback) {
      callback(null, val);
    }
  };
}

function LevelUpArrayAdapter ( name , db , serializer ) { this . db = Sublevel ( db ) ; this . db = this . db . sublevel ( name ) ; this . name = name ; this . serializer = serializer || { encode : function ( val , callback ) { callback ( null , val ) ; } , decode : function ( val , callback ) { callback ( null , val ) ; } } ; }

Level up adapter that looks like an array. Doesn't support inserts.

Level up adapter that looks like an array . Doesn t support inserts .


function fixProps(tx, data) {
  // ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to
  // in order to differentiate between a value that isn't set and a value
  // that is set to 0 in a fake transaction.
  // Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured
  // out we can probably remove this fix/hack.
  // We keep track of the original value and return that value when
  // referenced by its property name. This lets us properly encode a `0` as
  // an empty buffer while still being able to differentiate between a `0`
  // and `null`/`undefined`.
  tx._originals = [];
  const fieldNames = ["nonce", "gasPrice", "gasLimit", "value"];
  fieldNames.forEach((fieldName) => configZeroableField(tx, fieldName, 32));

  // Ethereumjs-tx doesn't set the _chainId value whenever the v value is set,
  // which causes transaction signing to fail on transactions that include a
  // chain id in the v value (like ethers.js does).
  // Whenever the v value changes we need to make sure the chainId is also set.
  const vDescriptors = Object.getOwnPropertyDescriptor(tx, "v");
  // eslint-disable-next-line accessor-pairs
  Object.defineProperty(tx, "v", {
    set: (v) => {
      vDescriptors.set.call(tx, v);
      // calculate chainId from signature
      const sigV = ethUtil.bufferToInt(tx.v);
      let chainId = Math.floor((sigV - 35) / 2);
      if (chainId < 0) {
        chainId = 0;
      }
      tx._chainId = chainId || 0;
    }
  });

  if (tx.isFake()) {
    /**
     * @prop {Buffer} from (read/write) Set from address to bypass transaction
     * signing on fake transactions.
     */
    Object.defineProperty(tx, "from", {
      enumerable: true,
      configurable: true,
      get: tx.getSenderAddress.bind(tx),
      set: (val) => {
        if (val) {
          tx._from = ethUtil.toBuffer(val);
        } else {
          tx._from = null;
        }
      }
    });

    if (data && data.from) {
      tx.from = data.from;
    }

    tx.hash = fakeHash;
  }
}

etheruemjs-tx's Transactions don't behave quite like we need them to, so
we're monkey-patching them to do what we want here.
@param {Transaction} tx The Transaction to fix
@param {Object} [data] The data object

etheruemjs - tx s Transactions don t behave quite like we need them to so we re monkey - patching them to do what we want here .


function initData(tx, data) {
  if (data) {
    if (typeof data === "string") {
      data = to.buffer(data);
    }
    if (Buffer.isBuffer(data)) {
      data = rlp.decode(data);
    }
    const self = tx;
    if (Array.isArray(data)) {
      if (data.length > tx._fields.length) {
        throw new Error("wrong number of fields in data");
      }

      // make sure all the items are buffers
      data.forEach((d, i) => {
        self[self._fields[i]] = ethUtil.toBuffer(d);
      });
    } else if ((typeof data === "undefined" ? "undefined" : typeof data) === "object") {
      const keys = Object.keys(data);
      tx._fields.forEach(function(field) {
        if (keys.indexOf(field) !== -1) {
          self[field] = data[field];
        }
        if (field === "gasLimit") {
          if (keys.indexOf("gas") !== -1) {
            self["gas"] = data["gas"];
          }
        } else if (field === "data") {
          if (keys.indexOf("input") !== -1) {
            self["input"] = data["input"];
          }
        }
      });

      // Set chainId value from the data, if it's there and the data didn't
      // contain a `v` value with chainId in it already. If we do have a
      // data.chainId value let's set the interval v value to it.
      if (!tx._chainId && data && data.chainId != null) {
        tx.raw[self._fields.indexOf("v")] = tx._chainId = data.chainId || 0;
      }
    } else {
      throw new Error("invalid data");
    }
  }
}

Parses the given data object and adds its properties to the given tx.
@param {Transaction} tx
@param {Object} [data]

Parses the given data object and adds its properties to the given tx .


function TXRejectedError(message) {
  // Why not just Error.apply(this, [message])? See
  // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
}

raised when the transaction is rejected prior to running it in the EVM.

raised when the transaction is rejected prior to running it in the EVM .


function RequestFunnel() {
  // We use an object here for O(1) lookups (speed).
  this.methods = {
    eth_call: true,
    eth_getStorageAt: true,
    eth_sendTransaction: true,
    eth_sendRawTransaction: true,

    // Ensure block filter and filter changes are process one at a time
    // as well so filter requests that come in after a transaction get
    // processed once that transaction has finished processing.
    eth_newBlockFilter: true,
    eth_getFilterChanges: true,
    eth_getFilterLogs: true
  };
  this.queue = [];
  this.isWorking = false;
}

See if any payloads for the specified methods are marked as external. If they are external, and match the method list, process them one at a time.

See if any payloads for the specified methods are marked as external . If they are external and match the method list process them one at a time .


function compileSass(_path, ext, data, callback) {
  const compiledCss = sass.renderSync({
    data: data,
    outputStyle: 'expanded',
    importer: function (url, prev, done) {
      if (url.startsWith('~')) {
        const newUrl = path.join(__dirname, 'node_modules', url.substr(1));
        return { file: newUrl };
      } else {
        return { file: url };
      }
    }
  });
  callback(null, compiledCss.css);
}

function compileSass ( _path , ext , data , callback ) { const compiledCss = sass . renderSync ( { data : data , outputStyle : 'expanded' , importer : function ( url , prev , done ) { if ( url . startsWith ( '~' ) ) { const newUrl = path . join ( __dirname , 'node_modules' , url . substr ( 1 ) ) ; return { file : newUrl } ; } else { return { file : url } ; } } } ) ; callback ( null , compiledCss . css ) ; }

Compile SASS to CSS.
@see https://github.com/ludohenin/gulp-inline-ng2-template
@see https://github.com/sass/node-sass


function requireBrocfile(brocfilePath) {
  let brocfile;

  if (brocfilePath.match(/\.ts$/)) {
    try {
      require.resolve('ts-node');
    } catch (e) {
      throw new Error(`Cannot find module 'ts-node', please install`);
    }

    try {
      require.resolve('typescript');
    } catch (e) {
      throw new Error(`Cannot find module 'typescript', please install`);
    }

    // Register ts-node typescript compiler
    require('ts-node').register(); // eslint-disable-line node/no-unpublished-require

    // Load brocfile via ts-node
    brocfile = require(brocfilePath);
  } else {
    // Load brocfile via esm shim
    brocfile = esmRequire(brocfilePath);
  }

  // ESM `export default X` is represented as module.exports = { default: X }
  if (brocfile !== null && typeof brocfile === 'object' && brocfile.hasOwnProperty('default')) {
    brocfile = brocfile.default;
  }

  return brocfile;
}

Require a brocfile via either ESM or TypeScript

@param {String} brocfilePath The path to the brocfile
@returns {*}


function runmath(s) {
    var ans;
    try {// We want to catch parse errors and die appropriately

        // Make a parser and feed the input
        ans = new nearley.Parser(grammar.ParserRules, grammar.ParserStart)
            .feed(s);

        // Check if there are any results
        if (ans.results.length) {
            return ans.results[0].toString();
        } else {
            // This means the input is incomplete.
            var out = "Error: incomplete input, parse failed. :(";
            return out;
        }
    } catch(e) {
        // Panic in style, by graphically pointing out the error location.
        var out = new Array(PROMPT.length + e.offset + 1).join("-") + "^  Error.";
        //                                  --------
        //                                         ^ This comes from nearley!
        return out;
    }
}

//                                         ^ This comes from nearley!


function(arr, isSigned) {
        if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end) arr.push(this.readVarint(isSigned));
        return arr;
    }

function ( arr , isSigned ) { if ( this . type !== Pbf . Bytes ) return arr . push ( this . readVarint ( isSigned ) ) ; var end = readPackedEnd ( this ) ; arr = arr || [ ] ; while ( this . pos < end ) arr . push ( this . readVarint ( isSigned ) ) ; return arr ; }

verbose for performance reasons; doesn't affect gzipped size

verbose for performance reasons ; doesn t affect gzipped size


function handleUnionSelections(
  sqlASTNode,
  children,
  selections,
  gqlType,
  namespace,
  depth,
  options,
  context,
  internalOptions = {}
) {
  for (let selection of selections) {
    // we need to figure out what kind of selection this is
    switch (selection.kind) {
    case 'Field':
      // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it
      const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')
      let newNode = new SQLASTNode(sqlASTNode)
      if (existingNode) {
        newNode = existingNode
      } else {
        children.push(newNode)
      }
      if (internalOptions.defferedFrom) {
        newNode.defferedFrom = internalOptions.defferedFrom
      }
      populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)
      break
    // if its an inline fragment, it has some fields and we gotta recurse thru all them
    case 'InlineFragment':
      {
        const selectionNameOfType = selection.typeCondition.name.value
        // normally, we would scan for the extra join-monster data on the current gqlType.
        // but the gqlType is the Union. The data isn't there, its on each of the types that make up the union
        // lets find that type and handle the selections based on THAT type instead
        const deferredType = this.schema._typeMap[selectionNameOfType]
        const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'
        const handler = deferToObjectType ? handleSelections : handleUnionSelections
        if (deferToObjectType) {
          const typedChildren = sqlASTNode.typedChildren
          children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []
          internalOptions.defferedFrom = gqlType
        }
        handler.call(
          this, sqlASTNode, children,
          selection.selectionSet.selections, deferredType, namespace,
          depth, options, context,
          internalOptions
        )
      }
      break
    // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields
    case 'FragmentSpread':
      {
        const fragmentName = selection.name.value
        const fragment = this.fragments[fragmentName]
        const fragmentNameOfType = fragment.typeCondition.name.value
        const deferredType = this.schema._typeMap[fragmentNameOfType]
        const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'
        const handler = deferToObjectType ? handleSelections : handleUnionSelections
        if (deferToObjectType) {
          const typedChildren = sqlASTNode.typedChildren
          children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []
          internalOptions.defferedFrom = gqlType
        }
        handler.call(
          this, sqlASTNode, children,
          fragment.selectionSet.selections, deferredType, namespace,
          depth, options, context,
          internalOptions
        )
      }
      break
    /* istanbul ignore next */
    default:
      throw new Error('Unknown selection kind: ' + selection.kind)
    }
  }
}

we need to collect all fields from all the fragments requested in the union type and ask for them in SQL


function handleSelections(
  sqlASTNode,
  children,
  selections,
  gqlType,
  namespace,
  depth,
  options,
  context,
  internalOptions = {},
) {
  for (let selection of selections) {
    // we need to figure out what kind of selection this is
    switch (selection.kind) {
    // if its another field, recurse through that
    case 'Field':
      // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it
      const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')
      let newNode = new SQLASTNode(sqlASTNode)
      if (existingNode) {
        newNode = existingNode
      } else {
        children.push(newNode)
      }
      if (internalOptions.defferedFrom) {
        newNode.defferedFrom = internalOptions.defferedFrom
      }
      populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)
      break
    // if its an inline fragment, it has some fields and we gotta recurse thru all them
    case 'InlineFragment':
      {
        // check to make sure the type of this fragment (or one of the interfaces it implements) matches the type being queried
        const selectionNameOfType = selection.typeCondition.name.value
        const sameType = selectionNameOfType === gqlType.name
        const interfaceType = (gqlType._interfaces || []).map(iface => iface.name).includes(selectionNameOfType)
        if (sameType || interfaceType) {
          handleSelections.call(
            this, sqlASTNode, children,
            selection.selectionSet.selections, gqlType, namespace,
            depth, options, context,
            internalOptions
          )
        }
      }
      break
    // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields
    case 'FragmentSpread':
      {
        const fragmentName = selection.name.value
        const fragment = this.fragments[fragmentName]
        // make sure fragment type (or one of the interfaces it implements) matches the type being queried
        const fragmentNameOfType = fragment.typeCondition.name.value
        const sameType = fragmentNameOfType === gqlType.name
        const interfaceType = gqlType._interfaces.map(iface => iface.name).indexOf(fragmentNameOfType) >= 0
        if (sameType || interfaceType) {
          handleSelections.call(
            this, sqlASTNode, children,
            fragment.selectionSet.selections, gqlType, namespace,
            depth, options, context,
            internalOptions
          )
        }
      }
      break
    /* istanbul ignore next */
    default:
      throw new Error('Unknown selection kind: ' + selection.kind)
    }
  }
}

the selections could be several types, recursively handle each type here

the selections could be several types recursively handle each type here


function columnToASTChild(columnName, namespace) {
  return {
    type: 'column',
    name: columnName,
    fieldName: columnName,
    as: namespace.generate('column', columnName)
  }
}

function columnToASTChild ( columnName , namespace ) { return { type : 'column' , name : columnName , fieldName : columnName , as : namespace . generate ( 'column' , columnName ) } }

tell the AST we need a column that perhaps the user didnt ask for, but may be necessary for join monster to ID objects or associate ones across batches

tell the AST we need a column that perhaps the user didnt ask for but may be necessary for join monster to ID objects or associate ones across batches


function keyToASTChild(key, namespace) {
  if (typeof key === 'string') {
    return columnToASTChild(key, namespace)
  }
  if (Array.isArray(key)) {
    const clumsyName = toClumsyName(key)
    return {
      type: 'composite',
      name: key,
      fieldName: clumsyName,
      as: namespace.generate('column', clumsyName)
    }
  }
}

function keyToASTChild ( key , namespace ) { if ( typeof key === 'string' ) { return columnToASTChild ( key , namespace ) } if ( Array . isArray ( key ) ) { const clumsyName = toClumsyName ( key ) return { type : 'composite' , name : key , fieldName : clumsyName , as : namespace . generate ( 'column' , clumsyName ) } } }

keys are necessary for deduplication during the hydration process this will handle singular or composite keys


function stripRelayConnection(gqlType, queryASTNode, fragments) {
  // get the GraphQL Type inside the list of edges inside the Node from the schema definition
  const edgeType = stripNonNullType(gqlType._fields.edges.type)
  const strippedType = stripNonNullType(stripNonNullType(edgeType.ofType)._fields.node.type)
  // let's remember those arguments on the connection
  const args = queryASTNode.arguments
  // and then find the fields being selected on the underlying type, also buried within edges and Node
  const edges = spreadFragments(queryASTNode.selectionSet.selections, fragments, gqlType.name)
    .find(selection => selection.name.value === 'edges')
  if (edges) {
    queryASTNode = spreadFragments(edges.selectionSet.selections, fragments, gqlType.name)
      .find(selection => selection.name.value === 'node') || {}
  } else {
    queryASTNode = {}
  }
  // place the arguments on this inner field, so our SQL AST picks it up later
  queryASTNode.arguments = args
  return { gqlType: strippedType, queryASTNode }
}

if its a connection type, we need to look up the Node type inside their to find the relevant SQL info

if its a connection type we need to look up the Node type inside their to find the relevant SQL info


function spreadFragments(selections, fragments, typeName) {
  return flatMap(selections, selection => {
    switch (selection.kind) {
    case 'FragmentSpread':
      const fragmentName = selection.name.value
      const fragment = fragments[fragmentName]
      return spreadFragments(fragment.selectionSet.selections, fragments, typeName)
    case 'InlineFragment':
      if (selection.typeCondition.name.value === typeName) {
        return spreadFragments(selection.selectionSet.selections, fragments, typeName)
      }
      return []

    default:
      return selection
    }
  })
}

function spreadFragments ( selections , fragments , typeName ) { return flatMap ( selections , selection => { switch ( selection . kind ) { case 'FragmentSpread' : const fragmentName = selection . name . value const fragment = fragments [ fragmentName ] return spreadFragments ( fragment . selectionSet . selections , fragments , typeName ) case 'InlineFragment' : if ( selection . typeCondition . name . value === typeName ) { return spreadFragments ( selection . selectionSet . selections , fragments , typeName ) } return [ ] default : return selection } } ) }

instead of fields, selections can be fragments, which is another group of selections fragments can be arbitrarily nested this function recurses through and gets the relevant fields

instead of fields selections can be fragments which is another group of selections fragments can be arbitrarily nested this function recurses through and gets the relevant fields


async function getNode(typeName, resolveInfo, context, condition, dbCall, options = {}) {
  // get the GraphQL type from the schema using the name
  const type = resolveInfo.schema._typeMap[typeName]
  assert(type, `Type "${typeName}" not found in your schema.`)
  assert(type._typeConfig.sqlTable, `joinMonster can't fetch a ${typeName} as a Node unless it has "sqlTable" tagged.`)

  // we need to determine what the WHERE function should be
  let where = buildWhereFunction(type, condition, options)

  // our getGraphQLType expects every requested field to be in the schema definition. "node" isn't a parent of whatever type we're getting, so we'll just wrap that type in an object that LOOKS that same as a hypothetical Node type
  const fakeParentNode = {
    _fields: {
      node: {
        type,
        name: type.name.toLowerCase(),
        where
      }
    }
  }
  const namespace = new AliasNamespace(options.minify)
  const sqlAST = {}
  const fieldNodes = resolveInfo.fieldNodes || resolveInfo.fieldASTs
  // uses the same underlying function as the main `joinMonster`
  queryAST.populateASTNode.call(resolveInfo, fieldNodes[0], fakeParentNode, sqlAST, namespace, 0, options, context)
  queryAST.pruneDuplicateSqlDeps(sqlAST, namespace)
  const { sql, shapeDefinition } = await compileSqlAST(sqlAST, context, options)
  const data = arrToConnection(await handleUserDbCall(dbCall, sql, sqlAST, shapeDefinition), sqlAST)
  await nextBatch(sqlAST, data, dbCall, context, options)
  if (!data) return data
  data.__type__ = type
  return data
}

A helper for resolving the Node type in Relay.
@param {String} typeName - The Name of the GraphQLObjectType
@param {Object} resolveInfo - Contains the parsed GraphQL query, schema definition, and more. Obtained from the fourth argument to the resolver.
@param {Object} context - An arbitrary object that gets passed to the `where` function. Useful for contextual infomation that influeces the  WHERE condition, e.g. session, logged in user, localization.
@param {where|Number|String|Array} condition - A value to determine the `where` function for searching the node. If it's a function, that function will be used as the `where` function. Otherwise, it is assumed to be the value(s) of the `primaryKey`. An array of values is needed for composite primary keys.
@param {Function} dbCall - A function that is passed the compiled SQL that calls the database and returns (a promise of) the data.
@param {Object} [options] - Same as `joinMonster` function's options.
@returns {Promise.<Object>} The correctly nested data from the database. The GraphQL Type is added to the "\_\_type\_\_" property, which is helpful for the `resolveType` function in the `nodeDefinitions` of **graphql-relay-js**.

A helper for resolving the Node type in Relay .


function arrToConnection(data, sqlAST) {
  // use "post-order" tree traversal
  for (let astChild of sqlAST.children || []) {
    if (Array.isArray(data)) {
      for (let dataItem of data) {
        recurseOnObjInData(dataItem, astChild)
      }
    } else if (data) {
      recurseOnObjInData(data, astChild)
    }
  }
  const pageInfo = {
    hasNextPage: false,
    hasPreviousPage: false
  }
  if (!data) {
    if (sqlAST.paginate) {
      return {
        pageInfo,
        edges: []
      }
    }
    return null
  }
  // is cases where pagination was done, take the data and convert to the connection object
  // if any two fields happen to become a reference to the same object (when their `uniqueKey`s are the same),
  // we must prevent the recursive processing from visting the same object twice, because mutating the object the first
  // time changes it everywhere. we'll set the `_paginated` property to true to prevent this
  if (sqlAST.paginate && !data._paginated) {
    if (sqlAST.sortKey || idx(sqlAST, _ => _.junction.sortKey)) {
      if (idx(sqlAST, _ => _.args.first)) {
        // we fetched an extra one in order to determine if there is a next page, if there is one, pop off that extra
        if (data.length > sqlAST.args.first) {
          pageInfo.hasNextPage = true
          data.pop()
        }
      } else if (sqlAST.args && sqlAST.args.last) {
        // if backward paging, do the same, but also reverse it
        if (data.length > sqlAST.args.last) {
          pageInfo.hasPreviousPage = true
          data.pop()
        }
        data.reverse()
      }
      // convert nodes to edges and compute the cursor for each
      // TODO: only compute all the cursor if asked for them
      const sortKey = sqlAST.sortKey || sqlAST.junction.sortKey
      const edges = data.map(obj => {
        const cursor = {}
        const key = sortKey.key
        for (let column of wrap(key)) {
          cursor[column] = obj[column]
        }
        return { cursor: objToCursor(cursor), node: obj }
      })
      if (data.length) {
        pageInfo.startCursor = edges[0].cursor
        pageInfo.endCursor = last(edges).cursor
      }
      return { edges, pageInfo, _paginated: true }
    }
    if (sqlAST.orderBy || (sqlAST.junction && sqlAST.junction.orderBy)) {
      let offset = 0
      if (idx(sqlAST, _ => _.args.after)) {
        offset = cursorToOffset(sqlAST.args.after) + 1
      }
      // $total was a special column for determining the total number of items
      const arrayLength = data[0] && parseInt(data[0].$total, 10)
      const connection = connectionFromArraySlice(data, sqlAST.args || {}, { sliceStart: offset, arrayLength })
      connection.total = arrayLength || 0
      connection._paginated = true
      return connection
    }
  }
  return data
}

a function for data manipulation AFTER its nested. this is only necessary when using the SQL pagination we have to interpret the slice that comes back and generate the Connection Object type

a function for data manipulation AFTER its nested . this is only necessary when using the SQL pagination we have to interpret the slice that comes back and generate the Connection Object type


function validate(rows) {
  // its supposed to be an array of objects
  if (Array.isArray(rows)) return rows
  // a check for the most common error. a lot of ORMs return an object with the desired data on the `rows` property
  if (rows && rows.rows) return rows.rows

  throw new Error(
    `"dbCall" function must return/resolve an array of objects where each object is a row from the result set.
    Instead got ${util.inspect(rows, { depth: 3 })}`
  )
}


function sortKeyToWhereCondition(keyObj, descending, sortTable, dialect) {
  const { name, quote: q } = dialect
  const sortColumns = []
  const sortValues = []
  for (let key in keyObj) {
    sortColumns.push(`${q(sortTable)}.${q(key)}`)
    sortValues.push(maybeQuote(keyObj[key], name))
  }
  const operator = descending ? '<' : '>'
  return name === 'oracle'
    ? recursiveWhereJoin(sortColumns, sortValues, operator)
    : `(${sortColumns.join(', ')}) ${operator} (${sortValues.join(', ')})`
}

function
sortKeyToWhereCondition
(
keyObj
,
descending
,
sortTable
,
dialect
)
{
const
{
name
,
quote
:
q
}
=
dialect
const
sortColumns
=
[
]
const
sortValues
=
[
]
for
(
let
key
in
keyObj
)
{
sortColumns
.
push
(
`
${
q
(
sortTable
)
}
${
q
(
key
)
}
`
)
sortValues
.
push
(
maybeQuote
(
keyObj
[
key
]
,
name
)
)
}
const
operator
=
descending
'<'
:
'>'
return
name
===
'oracle'
recursiveWhereJoin
(
sortColumns
,
sortValues
,
operator
)
:
`
${
sortColumns
.
join
(
', '
)
}
${
operator
}
${
sortValues
.
join
(
', '
)
}
`
}

take the sort key and translate that for the where clause


function clone(frm, to) {
	if (frm === null || typeof frm !== "object") {
		return frm;
	}
	if (frm.constructor !== Object && frm.constructor !== Array) {
		return frm;
	}
	if (frm.constructor === Date || frm.constructor === RegExp || frm.constructor === Function ||
		frm.constructor === String || frm.constructor === Number || frm.constructor === Boolean) {
		return new frm.constructor(frm);
	}
	to = to || new frm.constructor();
	for (var name in frm) {
		to[name] = typeof to[name] === "undefined" ? clone(frm[name], null) : to[name];
	}
	return to;
}

function clone ( frm , to ) { if ( frm === null || typeof frm !== "object" ) { return frm ; } if ( frm . constructor !== Object && frm . constructor !== Array ) { return frm ; } if ( frm . constructor === Date || frm . constructor === RegExp || frm . constructor === Function || frm . constructor === String || frm . constructor === Number || frm . constructor === Boolean ) { return new frm . constructor ( frm ) ; } to = to || new frm . constructor ( ) ; for ( var name in frm ) { to [ name ] = typeof to [ name ] === "undefined" ? clone ( frm [ name ] , null ) : to [ name ] ; } return to ; }

this is utilized by some of the global state functionality in order to get a clone that will not continue to be modified as the GlobalState mutates


function buildString (length, str) {
  return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')
}

function buildString ( length , str ) { return Array . apply ( null , new Array ( length ) ) . map ( String . prototype . valueOf , str ) . join ( '' ) }

Create an string of given length filled with blank spaces

@param {number} length Length of the array to return
@return {string}


function concatArray (arr, pretty, indentation, indentLevel) {
  var currentIndent = buildString(indentLevel, indentation)
  var closingBraceIndent = buildString(indentLevel - 1, indentation)
  var join = pretty ? ',\n' + currentIndent : ', '

  if (pretty) {
    return '[\n' + currentIndent + arr.join(join) + '\n' + closingBraceIndent + ']'
  } else {
    return '[' + arr.join(join) + ']'
  }
}

function
concatArray
(
arr
,
pretty
,
indentation
,
indentLevel
)
{
var
currentIndent
=
buildString
(
indentLevel
,
indentation
)
var
closingBraceIndent
=
buildString
(
indentLevel
1
,
indentation
)
var
join
=
pretty
',\n'
+
currentIndent
:
', '
if
(
pretty
)
{
return
'[\n'
+
currentIndent
+
arr
.
join
(
join
)
+
'\n'
+
closingBraceIndent
+
']'
}
else
{
return
'['
+
arr
.
join
(
join
)
+
']'
}
}

Create a string corresponding to a Dictionary or Array literal representation with pretty option
and indentation.

Create a string corresponding to a Dictionary or Array literal representation with pretty option and indentation .


function (value, opts, indentLevel) {
    indentLevel = indentLevel === undefined ? 1 : indentLevel + 1

    switch (Object.prototype.toString.call(value)) {
      case '[object Number]':
        return value
      case '[object Array]':
        // Don't prettify arrays nto not take too much space
        var pretty = false
        var valuesRepresentation = value.map(function (v) {
          // Switch to prettify if the value is a dictionary with multiple keys
          if (Object.prototype.toString.call(v) === '[object Object]') {
            pretty = Object.keys(v).length > 1
          }
          return this.literalRepresentation(v, opts, indentLevel)
        }.bind(this))
        return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel)
      case '[object Object]':
        var keyValuePairs = []
        for (var k in value) {
          keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))
        }
        return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)
      case '[object Boolean]':
        return value.toString()
      default:
        if (value === null || value === undefined) {
          return ''
        }
        return '"' + value.toString().replace(/"/g, '\\"') + '"'
    }
  }

Create a valid Swift string of a literal value according to its type.

@param {*} value Any JavaScript literal
@param {Object} opts Target options
@return {string}

Create a valid Swift string of a literal value according to its type .


function(text, placeholders) {
        if (text[text.length - 1] == "]" && text.lastIndexOf(" [") != -1) {
            // Remove translation comments
            text = text.substr(0, text.lastIndexOf(" ["));
        }
        var replaceAll = function(str, substr, replacement) {
            return str.replace(
                new RegExp(
                    substr.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g"),
                replacement);
        }
        var localeReplace = function(text, placeholders) {
            for (var key in placeholders) {
                text = replaceAll(text, "%(" + key + ")s", placeholders[key]);
            }
            return text;
        };
        var reactLocaleReplace = function(text, placeholders) {
            var start;
            var expanded = [text];
            for (var key in placeholders) {
                start = expanded;
                expanded = [];
                for (var i = 0; i < start.length; i++) {
                    if (typeof start[i] == "string") {
                        var keyStr = "%(" + key + ")s";
                        var parts = start[i].split(keyStr);
                        var replaced = [];
                        for (var j = 0; j < parts.length - 1; j++) {
                            replaced.push(parts[j]);
                            replaced.push(placeholders[key]);
                        }
                        replaced.push(parts[parts.length - 1]);
                        replaced = replaced.filter(function (str) {
                            return str != "";
                        });
                        expanded.push.apply(expanded, replaced)
                    } else {
                        expanded.push(start[i]);
                    }
                }
            }
            return expanded;
        }
        if (placeholders) {
            var hasReactElements = false;
            for (var key in placeholders) {
                var val = placeholders[key];
                if (typeof val !== "string" && React.isValidElement(val)) {
                    hasReactElements = true;
                    break;
                }
            }
            return (hasReactElements ?
                reactLocaleReplace(text, placeholders) :
                localeReplace(text, placeholders));
        }
        return text;
    }

function
(
text
,
placeholders
)
{
if
(
text
[
text
.
length
1
]
==
"]"
&&
text
.
lastIndexOf
(
" ["
)
!=
1
)
{
// Remove translation comments
text
=
text
.
substr
(
0
,
text
.
lastIndexOf
(
" ["
)
)
;
}
var
replaceAll
=
function
(
str
,
substr
,
replacement
)
{
return
str
.
replace
(
new
RegExp
(
substr
.
replace
(
/
([.*+?^=!:${}()|\[\]\/\\])
/
g
,
"\\$1"
)
,
"g"
)
,
replacement
)
;
}
var
localeReplace
=
function
(
text
,
placeholders
)
{
for
(
var
key
in
placeholders
)
{
text
=
replaceAll
(
text
,
"%("
+
key
+
")s"
,
placeholders
[
key
]
)
;
}
return
text
;
}
;
var
reactLocaleReplace
=
function
(
text
,
placeholders
)
{
var
start
;
var
expanded
=
[
text
]
;
for
(
var
key
in
placeholders
)
{
start
=
expanded
;
expanded
=
[
]
;
for
(
var
i
=
0
;
i
<
start
.
length
;
i
++
)
{
if
(
typeof
start
[
i
]
==
"string"
)
{
var
keyStr
=
"%("
+
key
+
")s"
;
var
parts
=
start
[
i
]
.
split
(
keyStr
)
;
var
replaced
=
[
]
;
for
(
var
j
=
0
;
j
<
parts
.
length
1
;
j
++
)
{
replaced
.
push
(
parts
[
j
]
)
;
replaced
.
push
(
placeholders
[
key
]
)
;
}
replaced
.
push
(
parts
[
parts
.
length
1
]
)
;
replaced
=
replaced
.
filter
(
function
(
str
)
{
return
str
!=
""
;
}
)
;
expanded
.
push
.
apply
(
expanded
,
replaced
)
}
else
{
expanded
.
push
(
start
[
i
]
)
;
}
}
}
return
expanded
;
}
if
(
placeholders
)
{
var
hasReactElements
=
false
;
for
(
var
key
in
placeholders
)
{
var
val
=
placeholders
[
key
]
;
if
(
typeof
val
!==
"string"
&&
React
.
isValidElement
(
val
)
)
{
hasReactElements
=
true
;
break
;
}
}
return
(
hasReactElements
reactLocaleReplace
(
text
,
placeholders
)
:
localeReplace
(
text
,
placeholders
)
)
;
}
return
text
;
}


function createNode (media) {
    var node = new Audio();

    node.onplay = function () {
        Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STARTING);
    };

    node.onplaying = function () {
        Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
    };

    node.ondurationchange = function (e) {
        Media.onStatus(media.id, Media.MEDIA_DURATION, e.target.duration || -1);
    };

    node.onerror = function (e) {
        // Due to media.spec.15 It should return MediaError for bad filename
        var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?
            { code: MediaError.MEDIA_ERR_ABORTED } :
            e.target.error;

        Media.onStatus(media.id, Media.MEDIA_ERROR, err);
    };

    node.onended = function () {
        Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
    };

    if (media.src) {
        node.src = media.src;
    }

    return node;
}

Creates new Audio node and with necessary event listeners attached
@param  {Media} media Media object
@return {Audio}       Audio element