<commit_before>'use strict';

// duun prototypical object
var duun = {};

// these registered plugin instances are shared across all duun instances
duun.plugins = {};

// these plugins get a separate instance created for each duun instance
duun.duunedPlugins = [];

// reduce code footprint for proxying plugin methods through duuns
function proxyFn ( pluginName, methodName ) {
  return function () {
    var plugin = this.plugins[ pluginName ] || duun.plugins[ pluginName ];
    return plugin[ methodName ].apply( plugin, arguments );
  };
}

// PRIVATE: map functions to all duuns (or override on a duun instance)
duun._map = function ( pluginName, fns ) {
  var methodName;
  var method;

  if ( 'object' !== typeof fns ) {
    return this;
  }

  for ( var fnKey in fns ) {
    if ( ! fns.hasOwnProperty( fnKey ) ) {
      // skip prototype-inherited properties
      continue;
    }

    // reset vars for each iteration
    methodName = undefined;
    method = undefined;

    if ( fns.constructor === Array ) {
      // fns is an array of methodNames, so fnKey is the array index
      methodName = fns[ fnKey ];
      method = proxyFn( pluginName, fns[ fnKey ] );

    } else if ( 'string' === typeof fnKey && 'string' === typeof fns[ fnKey ] ) {
      // this fns entry maps duun.methodName => plugin.methodName
      methodName = fnKey;
      method = proxyFn( pluginName, fns[ fnKey ] );

    } else if ( 'string' === typeof fnKey && 'function' === typeof fns[ fnKey ] ) {
      // this fns entry maps duun.methodName => function
      methodName = fnKey;
      method = fns[ fnKey ];
    }

    if ( duun[ methodName ] && this === duun ) {
      // do not allow proxy function overriding of global duun plugins
      throw new Error( 'The function "' + methodName + '" has already been registered and cannot be overridden!' );
    }

    this[ methodName ] = method;
  }

  return this;
};

// add a plugin to duun of specified context (e.g., all or this)
duun._register = function ( context, name, plugin, fns ) {
  if ( 'object' === typeof name ) {
    // support ad-hoc sandbox extension (w/o a plugin object)
    context._map( undefined, name );
    return this;
  }

  if ( context.plugins[ name ] && context === duun ) {
    // disallow overwriting of globally-registered plugins
    throw new Error( 'The plugin "' + name + '" has already been registered and cannot be overridden!' );
  }

  if ( plugin ) {
    // register 'plugin' as 'name'
    context.plugins[ name ] = plugin;

    if ( plugin.duuned ) {
      // register 'plugin' as a duuned plugin
      context.duunedPlugins.push( name );
    }
  }

  if ( ! fns ) {
    // get functions to map from duun to plugin
    fns = plugin.duun();
  }

  // map functions from duun to plugin
  context._map( name, fns );

  return this;
};

// add a plugin to all duuns
duun.register = function ( name, plugin, fns ) {
  return this._register( duun, name, plugin, fns );
};

// add a plugin to this duun
duun.extend = function ( name, plugin, fns ) {
  return this._register( this, name, plugin, fns );
};

// duun object factory
duun.create = function ( name ) {
  // create a new duun
  var newDuun = Object.create( duun, {
      name: { value: name },
      plugins: { writable: true, value: {} },
      duunedPlugins: { value: undefined }
    } );

  // create new instances of duuned plugins
  for ( var pluginName in duun.duunedPlugins ) {

    if ( ! duun.duunedPlugins.hasOwnProperty( pluginName ) ) {
      // skip prototype-inherited properties
      continue;
    }

    var plugin = duun.plugins[ pluginName ];

    // build arguments to pass to duuned plugin's create() method
    var pluginArgs = [];
    var duunedProperties = plugin.duuned();
    for ( var pluginArg in duunedProperties ) {

      if ( ! duunedProperties.hasOwnProperty( pluginArg ) ) {
        // skip prototype-inherited properties
        continue;
      }

      // add the value of this property to plugin's create() args
      pluginArgs[ pluginArg ] = newDuun[ pluginArg ];
    }

    // create a new instance of this duuned plugin
    newDuun.plugins[ pluginName ] = plugin.create.apply( plugin, pluginArgs );
  }

  return newDuun;
};

// export prototype duun object
module.exports = duun;
<commit_msg>fixed a very silly bugsies where arrays got iterated like objects<commit_after>'use strict';

// duun prototypical object
var duun = {};

// these registered plugin instances are shared across all duun instances
duun.plugins = {};

// these plugins get a separate instance created for each duun instance
duun.duunedPlugins = [];

// reduce code footprint for proxying plugin methods through duuns
function proxyFn ( pluginName, methodName ) {
  return function () {
    var plugin = this.plugins[ pluginName ] || duun.plugins[ pluginName ];
    return plugin[ methodName ].apply( plugin, arguments );
  };
}

// PRIVATE: map functions to all duuns (or override on a duun instance)
duun._map = function ( pluginName, fns ) {
  var methodName;
  var method;

  if ( 'object' !== typeof fns ) {
    return this;
  }

  for ( var fnKey in fns ) {
    if ( ! fns.hasOwnProperty( fnKey ) ) {
      // skip prototype-inherited properties
      continue;
    }

    // reset vars for each iteration
    methodName = undefined;
    method = undefined;

    if ( fns.constructor === Array ) {
      // fns is an array of methodNames, so fnKey is the array index
      methodName = fns[ fnKey ];
      method = proxyFn( pluginName, fns[ fnKey ] );

    } else if ( 'string' === typeof fnKey && 'string' === typeof fns[ fnKey ] ) {
      // this fns entry maps duun.methodName => plugin.methodName
      methodName = fnKey;
      method = proxyFn( pluginName, fns[ fnKey ] );

    } else if ( 'string' === typeof fnKey && 'function' === typeof fns[ fnKey ] ) {
      // this fns entry maps duun.methodName => function
      methodName = fnKey;
      method = fns[ fnKey ];
    }

    if ( duun[ methodName ] && this === duun ) {
      // do not allow proxy function overriding of global duun plugins
      throw new Error( 'The function "' + methodName + '" has already been registered and cannot be overridden!' );
    }

    this[ methodName ] = method;
  }

  return this;
};

// add a plugin to duun of specified context (e.g., all or this)
duun._register = function ( context, name, plugin, fns ) {
  if ( 'object' === typeof name ) {
    // support ad-hoc sandbox extension (w/o a plugin object)
    context._map( undefined, name );
    return this;
  }

  if ( context.plugins[ name ] && context === duun ) {
    // disallow overwriting of globally-registered plugins
    throw new Error( 'The plugin "' + name + '" has already been registered and cannot be overridden!' );
  }

  if ( plugin ) {
    // register 'plugin' as 'name'
    context.plugins[ name ] = plugin;

    if ( plugin.duuned ) {
      // register 'plugin' as a duuned plugin
      context.duunedPlugins.push( name );
    }
  }

  if ( ! fns ) {
    // get functions to map from duun to plugin
    fns = plugin.duun();
  }

  // map functions from duun to plugin
  context._map( name, fns );

  return this;
};

// add a plugin to all duuns
duun.register = function ( name, plugin, fns ) {
  return this._register( duun, name, plugin, fns );
};

// add a plugin to this duun
duun.extend = function ( name, plugin, fns ) {
  return this._register( this, name, plugin, fns );
};

// duun object factory
duun.create = function ( name ) {
  // create a new duun
  var newDuun = Object.create( duun, {
      name: { value: name },
      plugins: { writable: true, value: {} },
      duunedPlugins: { value: undefined }
    } );

  // create new instances of globally-registered duuned plugins
  duun.duunedPlugins.forEach( function ( pluginName ) {
    var plugin = duun.plugins[ pluginName ];

    // build arguments to pass to duuned plugin's create() method
    var pluginArgs = [];
    plugin.duuned().forEach( function ( pluginArg ) {
      // add the value of this property to plugin's create() args
      pluginArgs.push( newDuun[ pluginArg ] );
    } );

    // create a new instance of this duuned plugin
    newDuun.plugins[ pluginName ] = plugin.create.apply( plugin, pluginArgs );
  } );

  return newDuun;
};

// export prototype duun object
module.exports = duun;
<|endoftext|>


<commit_before>'use strict'

var tap = require('tap')
var testUrl = 'iamok'
process.env.API_URL = testUrl
var config = require('../config')

tap.equal(config.API_URL, testUrl, 'It supports API_URL thorugh env')
<commit_msg>Refactoring<commit_after>'use strict'

const tap = require('tap')
const testUrl = 'iamok'
process.env.API_URL = testUrl
const config = require('../config')

tap.equal(config.API_URL, testUrl, 'It supports API_URL through env')
<|endoftext|>


<commit_before>import { NativeModules, Platform } from 'react-native'

const { RNBranch } = NativeModules

export default async function createBranchUniversalObject(identifier, options = {}) {
  if (typeof identifier !== 'string') throw new Error('react-native-branch: identifier must be a string')

  const branchUniversalObject = {
    contentIndexingMode: 'private',
    canonicalIdentifier: identifier,
    ...options
  }

  const { ident } = await RNBranch.createUniversalObject(branchUniversalObject)

  return {
    ident: ident,
    showShareSheet(shareOptions = {}, linkProperties = {}, controlParams = {}) {
      shareOptions = {
        title: options.title || '',
        text: options.contentDescription || '',
        ...shareOptions,
      }

      linkProperties = {
        feature: 'share',
        channel: 'RNApp',
        ...linkProperties,
      }

      return this.tryFunction(RNBranch.showShareSheet, this.ident, shareOptions, linkProperties, controlParams)
    },
    registerView() {
      return this.tryFunction(RNBranch.registerView, this.ident)
    },
    generateShortUrl(linkProperties = {}, controlParams = {}) {
      return this.tryFunction(RNBranch.generateShortUrl, this.ident, linkProperties, controlParams)
    },
    listOnSpotlight() {
      if (Platform.OS !== 'ios') return Promise.resolve()
      return this.tryFunction(RNBranch.listOnSpotlight, this.ident)
    },
    release() {
      RNBranch.releaseUniversalObject(this.ident)
    },

    tryFunction(func, ident, ...args) {
      return func(ident, ...args).catch((error) => {
        if (error.code != "RNBranch::Error::BUONotFound") {
          throw error
        }

        return RNBranch.createUniversalObject(branchUniversalObject)
      })
      .then((response) => {
        this.ident = response.ident
        return func(response.ident, ...args)
      })
    }
  }
}
<commit_msg>No need to pass this.ident each time<commit_after>import { NativeModules, Platform } from 'react-native'

const { RNBranch } = NativeModules

export default async function createBranchUniversalObject(identifier, options = {}) {
  if (typeof identifier !== 'string') throw new Error('react-native-branch: identifier must be a string')

  const branchUniversalObject = {
    contentIndexingMode: 'private',
    canonicalIdentifier: identifier,
    ...options
  }

  const { ident } = await RNBranch.createUniversalObject(branchUniversalObject)

  return {
    ident: ident,
    showShareSheet(shareOptions = {}, linkProperties = {}, controlParams = {}) {
      shareOptions = {
        title: options.title || '',
        text: options.contentDescription || '',
        ...shareOptions,
      }

      linkProperties = {
        feature: 'share',
        channel: 'RNApp',
        ...linkProperties,
      }

      return this.tryFunction(RNBranch.showShareSheet, shareOptions, linkProperties, controlParams)
    },
    registerView() {
      return this.tryFunction(RNBranch.registerView)
    },
    generateShortUrl(linkProperties = {}, controlParams = {}) {
      return this.tryFunction(RNBranch.generateShortUrl, linkProperties, controlParams)
    },
    listOnSpotlight() {
      if (Platform.OS !== 'ios') return Promise.resolve()
      return this.tryFunction(RNBranch.listOnSpotlight)
    },
    release() {
      RNBranch.releaseUniversalObject(this.ident)
    },

    tryFunction(func, ...args) {
      return func(this.ident, ...args).catch((error) => {
        if (error.code != "RNBranch::Error::BUONotFound") {
          throw error
        }

        return RNBranch.createUniversalObject(branchUniversalObject)
      })
      .then((response) => {
        this.ident = response.ident
        return func(response.ident, ...args)
      })
    }
  }
}
<|endoftext|>


<commit_before>/**
 * UX action types
 */

 // redirect url action types
export const SET_REDIRECT_URL = 'SET_REDIRECT_URL'
export const NAVIGATE_TO_REDIRECT_URL = 'NAVIGATE_TO_REDIRECT_URL'

/**
 * API action types
 */

// authentication
export const LOGIN = 'LOGIN'
export const LOGOUT = 'LOGOUT'

<commit_msg>changed action types SET_REDIRECT_TO to NAVIGATE_TO_LOGIN NAVIGATE_TO_REDIRECT_URL to NAVIGATE_TO_PANEL<commit_after>/**
 * UX action types
 */

 // redirect url action types
export const NAVIGATE_TO_LOGIN = 'NAVIGATE_TO_LOGIN'
export const NAVIGATE_TO_PANEL = 'NAVIGATE_TO_PANEL'

/**
 * API action types
 */

// authentication
export const LOGIN = 'LOGIN'
export const LOGOUT = 'LOGOUT'

<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Mickael Jeanroy
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

describe('$vdom', function() {

  var fixtures;

  beforeEach(function() {
    fixtures = document.createElement('div');
    fixtures.setAttribute('id', 'fixtures');

    var node1 = document.createElement('span');
    node1.setAttribute('id', 'span1');
    fixtures.appendChild(node1);

    var node2 = document.createElement('span');
    node2.setAttribute('id', 'span2');
    fixtures.appendChild(node2);

    document.body.appendChild(fixtures);
  });

  afterEach(function() {
    fixtures.parentNode.removeChild(fixtures);
  });

  it('should update node attribute', function() {
    var node1 = document.createElement('div');
    node1.setAttribute('data-foo', 'bar');
    node1.setAttribute('data-idx', 1);

    var node2 = document.createElement('div');
    node2.setAttribute('data-foo', 'foo');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBe('foo');
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node attribute and add new ones', function() {
    var node1 = document.createElement('div');
    node1.setAttribute('data-idx', 1);

    var node2 = document.createElement('div');
    node2.setAttribute('data-foo', 'foo');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBe('foo');
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node attribute and remove old ones', function() {
    var node1 = document.createElement('div');
    node1.setAttribute('data-foo', 'foo');
    node1.setAttribute('data-idx', 1);

    var node2 = document.createElement('div');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBeNull();
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node inline styles', function() {
    var node1 = document.createElement('div');
    node1.style.width = '100px';
    node1.style.height = '200px';

    var node2 = document.createElement('div');
    node2.style.width = '110px';
    node2.style.height = '210px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBe('210px');
  });

  it('should update node inline styles and add new ones', function() {
    var node1 = document.createElement('div');
    node1.style.width = '100px';

    var node2 = document.createElement('div');
    node2.style.width = '110px';
    node2.style.height = '210px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBe('210px');
  });

  it('should update node inline styles and remove old ones', function() {
    var node1 = document.createElement('div');
    node1.style.width = '100px';
    node1.style.height = '200px';

    var node2 = document.createElement('div');
    node2.style.width = '110px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBeEmpty();
  });

  it('should update node classes', function() {
    var node1 = document.createElement('div');
    node1.className = 'foo bar';

    var node2 = document.createElement('div');
    node2.className = 'foo';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.className).toBe('foo');
  });

  it('should merge two nodes', function() {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    var node1 = document.createElement('div');
    var node2 = document.createElement('div');

    var span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    var span2 = document.createElement('span');
    span2.className = 'foo-2';
    span2.setAttribute('foo', 'foo2');
    span2.style.width = '200px';
    span2.innerHTML = 'foo #2';

    node1.appendChild(span1);
    node2.appendChild(span2);

    var rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    var result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).toHaveBeenCalledWith(span1, span2);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(1);
    expect(node1.childNodes[0].className).toBe('foo-2');
    expect(node1.childNodes[0].getAttribute('foo')).toBe('foo2');
    expect(node1.childNodes[0].innerHTML).toBe('foo #2');
  });

  it('should update content of nodes', function() {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    var node1 = document.createElement('div');
    var node2 = document.createElement('div');

    var span = document.createElement('span');
    span.className = 'foo-1';
    span.setAttribute('foo', 'foo1');
    span.style.width = '100px';
    span.innerHTML = 'foo #1';

    var input = document.createElement('input');
    input.setAttribute('type', 'text');

    node1.appendChild(span);
    node2.appendChild(input);

    var rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    var result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span, input);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(1);
    expect(node1.childNodes[0]).toBe(input);
  });

  it('should update content of nodes if nodes do not have same child length', function() {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    var node1 = document.createElement('div');
    var node2 = document.createElement('div');

    var span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    var span2 = document.createElement('span');
    span2.className = 'foo-1';
    span2.setAttribute('foo', 'foo1');
    span2.style.width = '100px';
    span2.innerHTML = 'foo #1';

    var input = document.createElement('input');
    input.setAttribute('type', 'text');

    node1.appendChild(span1);
    node2.appendChild(span2);
    node2.appendChild(input);

    var rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    var result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span1, span2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span1, input);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(2);
    expect(node1.childNodes[0]).toBe(span2);
    expect(node1.childNodes[1]).toBe(input);
  });

  it('should replace node if types are different', function() {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    var node1 = document.createElement('div');
    var node2 = document.createElement('p');

    var span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    var span2 = document.createElement('span');
    span2.className = 'foo-1';
    span2.setAttribute('foo', 'foo1');
    span2.style.width = '100px';
    span2.innerHTML = 'foo #1';

    node1.appendChild(span1);
    node2.appendChild(span2);

    var rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    var result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).not.toHaveBeenCalled();

    expect(result).toBe(node2);
    expect(result.childNodes.length).toBe(1);
    expect(result.childNodes[0]).toBe(span2);
  });
});
<commit_msg>refactor(test): migrate vdom-spec to es6<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Mickael Jeanroy
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

describe('$vdom', () => {

  let fixtures;

  beforeEach(() => {
    fixtures = document.createElement('div');
    fixtures.setAttribute('id', 'fixtures');

    const node1 = document.createElement('span');
    node1.setAttribute('id', 'span1');
    fixtures.appendChild(node1);

    const node2 = document.createElement('span');
    node2.setAttribute('id', 'span2');
    fixtures.appendChild(node2);

    document.body.appendChild(fixtures);
  });

  afterEach(() => fixtures.parentNode.removeChild(fixtures));

  it('should update node attribute', () => {
    const node1 = document.createElement('div');
    node1.setAttribute('data-foo', 'bar');
    node1.setAttribute('data-idx', 1);

    const node2 = document.createElement('div');
    node2.setAttribute('data-foo', 'foo');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBe('foo');
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node attribute and add new ones', () => {
    const node1 = document.createElement('div');
    node1.setAttribute('data-idx', 1);

    const node2 = document.createElement('div');
    node2.setAttribute('data-foo', 'foo');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBe('foo');
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node attribute and remove old ones', () => {
    const node1 = document.createElement('div');
    node1.setAttribute('data-foo', 'foo');
    node1.setAttribute('data-idx', 1);

    const node2 = document.createElement('div');
    node2.setAttribute('data-idx', 2);

    $vdom.mergeAttributes(node1, node2);

    expect(node1.getAttribute('data-foo')).toBeNull();
    expect(node1.getAttribute('data-idx')).toBe('2');
  });

  it('should update node inline styles', () => {
    const node1 = document.createElement('div');
    node1.style.width = '100px';
    node1.style.height = '200px';

    const node2 = document.createElement('div');
    node2.style.width = '110px';
    node2.style.height = '210px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBe('210px');
  });

  it('should update node inline styles and add new ones', () => {
    const node1 = document.createElement('div');
    node1.style.width = '100px';

    const node2 = document.createElement('div');
    node2.style.width = '110px';
    node2.style.height = '210px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBe('210px');
  });

  it('should update node inline styles and remove old ones', () => {
    const node1 = document.createElement('div');
    node1.style.width = '100px';
    node1.style.height = '200px';

    const node2 = document.createElement('div');
    node2.style.width = '110px';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.style.width).toBe('110px');
    expect(node1.style.height).toBeEmpty();
  });

  it('should update node classes', () => {
    const node1 = document.createElement('div');
    node1.className = 'foo bar';

    const node2 = document.createElement('div');
    node2.className = 'foo';

    $vdom.mergeAttributes(node1, node2);

    expect(node1.className).toBe('foo');
  });

  it('should merge two nodes', () => {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    const node1 = document.createElement('div');
    const node2 = document.createElement('div');

    const span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    const span2 = document.createElement('span');
    span2.className = 'foo-2';
    span2.setAttribute('foo', 'foo2');
    span2.style.width = '200px';
    span2.innerHTML = 'foo #2';

    node1.appendChild(span1);
    node2.appendChild(span2);

    const rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    const result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).toHaveBeenCalledWith(span1, span2);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(1);
    expect(node1.childNodes[0].className).toBe('foo-2');
    expect(node1.childNodes[0].getAttribute('foo')).toBe('foo2');
    expect(node1.childNodes[0].innerHTML).toBe('foo #2');
  });

  it('should update content of nodes', () => {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    const node1 = document.createElement('div');
    const node2 = document.createElement('div');

    const span = document.createElement('span');
    span.className = 'foo-1';
    span.setAttribute('foo', 'foo1');
    span.style.width = '100px';
    span.innerHTML = 'foo #1';

    const input = document.createElement('input');
    input.setAttribute('type', 'text');

    node1.appendChild(span);
    node2.appendChild(input);

    const rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    const result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span, input);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(1);
    expect(node1.childNodes[0]).toBe(input);
  });

  it('should update content of nodes if nodes do not have same child length', () => {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    const node1 = document.createElement('div');
    const node2 = document.createElement('div');

    const span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    const span2 = document.createElement('span');
    span2.className = 'foo-1';
    span2.setAttribute('foo', 'foo1');
    span2.style.width = '100px';
    span2.innerHTML = 'foo #1';

    const input = document.createElement('input');
    input.setAttribute('type', 'text');

    node1.appendChild(span1);
    node2.appendChild(span2);
    node2.appendChild(input);

    const rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    const result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).toHaveBeenCalledWith(node1, node2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span1, span2);
    expect($vdom.mergeAttributes).not.toHaveBeenCalledWith(span1, input);

    expect(result).toBe(node1);
    expect(node1.childNodes.length).toBe(2);
    expect(node1.childNodes[0]).toBe(span2);
    expect(node1.childNodes[1]).toBe(input);
  });

  it('should replace node if types are different', () => {
    spyOn($vdom, 'mergeAttributes').and.callThrough();

    const node1 = document.createElement('div');
    const node2 = document.createElement('p');

    const span1 = document.createElement('span');
    span1.className = 'foo-1';
    span1.setAttribute('foo', 'foo1');
    span1.style.width = '100px';
    span1.innerHTML = 'foo #1';

    const span2 = document.createElement('span');
    span2.className = 'foo-1';
    span2.setAttribute('foo', 'foo1');
    span2.style.width = '100px';
    span2.innerHTML = 'foo #1';

    node1.appendChild(span1);
    node2.appendChild(span2);

    const rootNode = document.createElement('div');
    rootNode.appendChild(node1);
    rootNode.appendChild(node2);

    const result = $vdom.mergeNodes(rootNode, node1, node2);

    expect($vdom.mergeAttributes).not.toHaveBeenCalled();

    expect(result).toBe(node2);
    expect(result.childNodes.length).toBe(1);
    expect(result.childNodes[0]).toBe(span2);
  });
});
<|endoftext|>


<commit_before>
$(function()
{
  $('.sf_admin_form input:text:visible:first').focus();

  $('#sympal_content_type_menu h3').click(function() {
    $('#sympal_content_type_menu ul').slideToggle('fast');
  });

  $('#sympal_content_type_menu a').click(function() {
    $('#sympal_content_type_menu ul').slideToggle('fast');
  });

  $('.sf_admin_form fieldset h2').click(function() {

    var name = $('.sf_admin_form').parent('div').attr('id');
    var current = $.cookie($('.sf_admin_form').parent('div').attr('id'));
    var clicked = $(this).parent('fieldset').attr('id');
    var h2 = $(this);

    if (current && current !== clicked && $('#' + current).length)
    {
      $('#' + current + ' h2').css('background-image', $('#' + current + ' h2').css('background-image').replace('collapse', 'expand'));
      $('#' + current + ' .sf_admin_form_row').slideUp('fast');
    }

    if (h2.css('background-image').indexOf('expand') > -1)
    {
      h2.css('background-image', h2.css('background-image').replace('expand', 'collapse'));
    } else {
      h2.css('background-image', h2.css('background-image').replace('collapse', 'expand'));
    }

    h2.parent('fieldset').find('.sf_admin_form_row').slideToggle('fast');

    if (current == clicked)
    {
      $.cookie(name, null);
    } else {
      $.cookie(name, clicked);
    }
  });

  if ($('.sf_admin_form fieldset h2').length)
  {
    $('.sf_admin_form_row').hide();

    var current = $.cookie($('.sf_admin_form').parent('div').attr('id'));
    if (!current)
    {
      current = $('.sf_admin_form fieldset h2:first-child').parent('fieldset').attr('id');
      $.cookie($('.sf_admin_form').parent('div').attr('id'), current);
    }

    if (current && $('#' + current).length)
    {
      $('#' + current + ' h2').css('background-image', $('#' + current + ' h2').css('background-image').replace('expand', 'collapse'));
      $('#' + current + ' .sf_admin_form_row').show();
    }
  }

  if ($('.sf_admin_filter').html())
  {
    $('.sf_admin_filter').hide();

    var append = '' + $('#sf_admin_container h1').html() + '

';
    $('#sf_admin_container h1').html(append);

    $('#sympal_filters_button').click(function() {
      $('.sf_admin_filter').slideToggle();

      var pos = $('.sf_admin_list').offset();
      var width = $('.sf_admin_list').width();
      $("#sf_admin_bar").css( { "position": "absolute", "left": (pos.right + width) + "px", "top":pos.top + 1 + "px" } );
    });
  }

  var current = $.cookie('sympal_admin_menu');
  if (!current)
  {
    current = $('#sympal_admin_menu ul li .clickable:first-child').parents('li').attr('id');
  }
  $('#sympal_admin_menu ul li .clickable').click(function() {
    $(this).parents('li').find('ul li').slideToggle();
    $('#' + current + ' li').hide();
    current = $(this).parents('li').attr('id');
    $.cookie('sympal_admin_menu', current);

    sympalMenuItem = false;
  });

  $('#sympal_admin_menu ul li ul li').hide();
  $('#' + current + ' li').show();
});<commit_msg>[1.4][sfSympalPlugin][1.0] Removing old orphaned js code that was causing issues with admin menu when in the admin backend<commit_after>
$(function()
{
  $('.sf_admin_form input:text:visible:first').focus();

  $('#sympal_content_type_menu h3').click(function() {
    $('#sympal_content_type_menu ul').slideToggle('fast');
  });

  $('#sympal_content_type_menu a').click(function() {
    $('#sympal_content_type_menu ul').slideToggle('fast');
  });

  $('.sf_admin_form fieldset h2').click(function() {

    var name = $('.sf_admin_form').parent('div').attr('id');
    var current = $.cookie($('.sf_admin_form').parent('div').attr('id'));
    var clicked = $(this).parent('fieldset').attr('id');
    var h2 = $(this);

    if (current && current !== clicked && $('#' + current).length)
    {
      $('#' + current + ' h2').css('background-image', $('#' + current + ' h2').css('background-image').replace('collapse', 'expand'));
      $('#' + current + ' .sf_admin_form_row').slideUp('fast');
    }

    if (h2.css('background-image').indexOf('expand') > -1)
    {
      h2.css('background-image', h2.css('background-image').replace('expand', 'collapse'));
    } else {
      h2.css('background-image', h2.css('background-image').replace('collapse', 'expand'));
    }

    h2.parent('fieldset').find('.sf_admin_form_row').slideToggle('fast');

    if (current == clicked)
    {
      $.cookie(name, null);
    } else {
      $.cookie(name, clicked);
    }
  });

  if ($('.sf_admin_form fieldset h2').length)
  {
    $('.sf_admin_form_row').hide();

    var current = $.cookie($('.sf_admin_form').parent('div').attr('id'));
    if (!current)
    {
      current = $('.sf_admin_form fieldset h2:first-child').parent('fieldset').attr('id');
      $.cookie($('.sf_admin_form').parent('div').attr('id'), current);
    }

    if (current && $('#' + current).length)
    {
      $('#' + current + ' h2').css('background-image', $('#' + current + ' h2').css('background-image').replace('expand', 'collapse'));
      $('#' + current + ' .sf_admin_form_row').show();
    }
  }

  if ($('.sf_admin_filter').html())
  {
    $('.sf_admin_filter').hide();

    var append = '' + $('#sf_admin_container h1').html() + '

';
    $('#sf_admin_container h1').html(append);

    $('#sympal_filters_button').click(function() {
      $('.sf_admin_filter').slideToggle();

      var pos = $('.sf_admin_list').offset();
      var width = $('.sf_admin_list').width();
      $("#sf_admin_bar").css( { "position": "absolute", "left": (pos.right + width) + "px", "top":pos.top + 1 + "px" } );
    });
  }
});<|endoftext|>


<commit_before>var Feed = require('feed');

module.exports = createFeed;

function createFeed (items) {
  var feed = new Feed({
    title: items[0].type + 's' + ' - ' + geddy.config.eventName,
    link: 'http://example.com/',
    image: geddy.config.domain + '/img/logo-200.png',
    author: {
      name: geddy.config.eventName
    }
  });

  var itemtype = (items[0].type + '').toLowerCase();
  var author = items[0].contributor ? 'contributor' : 'prospect';
  for (var key in items) {
    feed.item({
      title: items[key].title,
      link: geddy.viewHelpers[itemtype + 'Path'](items[key].id),
      description: items[key].description,
      author: [{name: items[key][author]}],
      date: items[key].updatedAt
    });
  }

  return feed;
}
<commit_msg>fix feed for not updated entries<commit_after>var Feed = require('feed');

module.exports = createFeed;

function createFeed (items) {
  var feed = new Feed({
    title: items[0].type + 's' + ' - ' + geddy.config.eventName,
    link: 'http://example.com/',
    image: geddy.config.domain + '/img/logo-200.png',
    author: {
      name: geddy.config.eventName
    }
  });

  var itemtype = (items[0].type + '').toLowerCase();
  var author = items[0].contributor ? 'contributor' : 'prospect';
  for (var key in items) {
    feed.item({
      title: items[key].title,
      link: geddy.viewHelpers[itemtype + 'Path'](items[key].id),
      description: items[key].description,
      author: [{name: items[key][author]}],
      date: items[key].updatedAt || items[key].createdAt
    });
  }

  return feed;
}
<|endoftext|>


<commit_before>/* eslint-env jasmine */
var nock = require('nock')
var VoucherifyClient = require('./client-loader')
var fixtures = require('./fixtures')
var reqWithBody = fixtures.reqWithBody
var reqWithoutBody = fixtures.reqWithoutBody

nock.disableNetConnect()

describe('Distributions API', function () {
  var client = new VoucherifyClient({
    applicationId: 'node-sdk-test-id',
    clientSecretKey: 'node-sdk-test-secret'
  })

  describe('publish voucher', function () {
    it('should publish by camaign name', function (done) {
      var server = nock('https://api.voucherify.io', reqWithBody)
        .post('/v1/vouchers/publish', {
          campaign: 'test-campaign'
        })
        .reply(200, {})

      client.distributions.publish('test-campaign')
      .then(function () {
        server.done()
        done()
      })
    })

    it('should publish by voucher', function (done) {
      var server = nock('https://api.voucherify.io', reqWithBody)
        .post('/v1/vouchers/publish', {
          campaign: 'test-campaign',
          voucher: 'test-voucher'
        })
        .reply(200, {})

      client.distributions.publish({
        campaign: 'test-campaign',
        voucher: 'test-voucher'
      })
      .then(function () {
        server.done()
        done()
      })
    })
  })

  describe('list publications', function () {
    it('should list all publications', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .reply(200, [])

      client.distributions.publications.list()
      .then(function () {
        server.done()
        done()
      })
    })

    it('should list all publications (callback)', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .reply(200, [])

      client.distributions.publications.list(function (err) {
        expect(err).toBeNull()
        server.done()
        done()
      })
    })

    it('should list publications by query', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .query({campaign: 'test-campaign'})
      .reply(200, [])

      client.distributions.publications.list({campaign: 'test-campaign'})
      .then(function () {
        server.done()
        done()
      })
    })
  })

  describe('exports', function () {
    it('should create export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithBody)
      .post('/v1/exports', {
        exported_object: 'voucher',
        parameters: {}
      })
      .reply(200, {})

      client.distributions.exports.create({
        exported_object: 'voucher',
        parameters: {}
      })
      .then(function () {
        server.done()
        done()
      })
    })

    it('should get export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/exports/exp_test-id')
      .reply(200, {})

      client.distributions.exports.get('exp_test-id')
      .then(function () {
        server.done()
        done()
      })
    })

    it('should delete export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .delete('/v1/exports/exp_test-id')
      .reply(200, {})

      client.distributions.exports.delete('exp_test-id')
      .then(function () {
        server.done()
        done()
      })
    })
  })
})
<commit_msg>update tests for distributions.publish interface<commit_after>/* eslint-env jasmine */
var nock = require('nock')
var VoucherifyClient = require('./client-loader')
var fixtures = require('./fixtures')
var reqWithBody = fixtures.reqWithBody
var reqWithoutBody = fixtures.reqWithoutBody

nock.disableNetConnect()

describe('Distributions API', function () {
  var client = new VoucherifyClient({
    applicationId: 'node-sdk-test-id',
    clientSecretKey: 'node-sdk-test-secret'
  })

  describe('publish voucher', function () {
    it('should publish by voucher', function (done) {
      var server = nock('https://api.voucherify.io', reqWithBody)
        .post('/v1/vouchers/publish', {
          campaign: 'test-campaign',
          voucher: 'test-voucher',
          customer: 'test@custom.er'
        })
        .reply(200, {})

      client.distributions.publish({
        campaign: 'test-campaign',
        voucher: 'test-voucher',
        customer: 'test@custom.er'
      })
      .then(function () {
        server.done()
        done()
      })
    })
  })

  describe('list publications', function () {
    it('should list all publications', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .reply(200, [])

      client.distributions.publications.list()
      .then(function () {
        server.done()
        done()
      })
    })

    it('should list all publications (callback)', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .reply(200, [])

      client.distributions.publications.list(function (err) {
        expect(err).toBeNull()
        server.done()
        done()
      })
    })

    it('should list publications by query', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/publications')
      .query({campaign: 'test-campaign'})
      .reply(200, [])

      client.distributions.publications.list({campaign: 'test-campaign'})
      .then(function () {
        server.done()
        done()
      })
    })
  })

  describe('exports', function () {
    it('should create export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithBody)
      .post('/v1/exports', {
        exported_object: 'voucher',
        parameters: {}
      })
      .reply(200, {})

      client.distributions.exports.create({
        exported_object: 'voucher',
        parameters: {}
      })
      .then(function () {
        server.done()
        done()
      })
    })

    it('should get export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .get('/v1/exports/exp_test-id')
      .reply(200, {})

      client.distributions.exports.get('exp_test-id')
      .then(function () {
        server.done()
        done()
      })
    })

    it('should delete export', function (done) {
      var server = nock('https://api.voucherify.io', reqWithoutBody)
      .delete('/v1/exports/exp_test-id')
      .reply(200, {})

      client.distributions.exports.delete('exp_test-id')
      .then(function () {
        server.done()
        done()
      })
    })
  })
})
<|endoftext|>


<commit_before>/*

 Library to work with files and directories

 */

/* global Java */

var File = Java.type('java.io.File'),
    FileReader = Java.type('java.io.FileReader');

(function() {

    var realFiles = [];

    // returns the content as an array of lines
    function _getContent(file) {

        return function() {

            var fr = new FileReader(file);

            //carriage returns
            var crs = [10, 13];

            var char = fr.read();

            var content = [];

            var lineContent = '';
            var lines = 0;

            while (char !== -1) {

                if (crs.indexOf(char) > -1) {
                    content.push(lineContent);
                    lineContent = '';
                } else {
                    lineContent = lineContent + String.fromCharCode(char);
                }

                char = fr.read();
            }
            fr.close();
            return content;
        }

    };

    // returns a file as an object
    function _realFile(file) {

        return {
            path: file,
            name: '',
            getContent: _getContent(file)
        };

    };

    function getDir(dir) {
        return new File(dir);
    };

    // list all directories in a directory
    function listDirs(dir) {

        var currDir = getDir(dir),
            fileList = Java.from(currDir.listFiles()),
            dirs = [];

        // Get directories
        fileList.forEach(function(file) {
            currFile = new File(file);
            print(currFile.isDirectory())
            if (currFile.isDirectory()) {
                dirs.push[currFile.getName()];
            };
        });

        return dirs;

    };

    function filesInDir(options) {

        // default settings
        var settings = {
            dir: "",
            subDirectories: false
        };

        // extend settings with options
        for (obj in settings) {
            if (options.hasOwnProperty(obj)) {
                settings[obj] = options[obj];
            }
        }

        // We want all real files from dir and subdirs
        var dir = getDir(options.dir),
            fileList = Java.from(dir.listFiles()),
            currFile;

        // Get files
        fileList.forEach(function(file) {
            currFile = new File(file);
            // Get files in subdirectories
            if (currFile.isDirectory() && options.subDirectories) {
                var filesInSubDir = filesInDir(currFile.getAbsolutePath());
            } else if (currFile.isFile()) {
                realFiles.push(_realFile(file));
            };
        });

        return realFiles;

    };

    return {
        getDir: getDir,
        listDirs: listDirs,
        filesInDir: filesInDir
    };

})();
<commit_msg>no message<commit_after>/*

 Library to work with files and directories

 */

/* global Java */

var File = Java.type('java.io.File'),
    FileReader = Java.type('java.io.FileReader');

(function() {

    var realFiles = [];

    // returns the content as an array of lines
    function _getContent(file) {

        return function() {

            var fr = new FileReader(file);

            //carriage returns
            var crs = [10, 13];

            var char = fr.read();

            var content = [];

            var lineContent = '';
            var lines = 0;

            while (char !== -1) {

                if (crs.indexOf(char) > -1) {
                    content.push(lineContent);
                    lineContent = '';
                } else {
                    lineContent = lineContent + String.fromCharCode(char);
                }

                char = fr.read();
            }
            fr.close();
            return content;
        }

    };

    // returns a file as an object
    function _realFile(file) {

        return {
            path: file,
            name: '',
            getContent: _getContent(file)
        };

    };

    function getDir(dir) {
        return new File(dir);
    };

    // list all directories in a directory
    function listDirs(dir) {

        var currDir = getDir(dir),
            fileList = currDir.listFiles(),
            dirs = [];

            print(fileList)

        // Get directories
        fileList.forEach(function(file) {
            currFile = new File(file);
            print(currFile.isDirectory())
            if (currFile.isDirectory()) {
                dirs.push[currFile.getName()];
            };
        });

        return dirs;

    };

    function filesInDir(options) {

        // default settings
        var settings = {
            dir: "",
            subDirectories: false
        };

        // extend settings with options
        for (obj in settings) {
            if (options.hasOwnProperty(obj)) {
                settings[obj] = options[obj];
            }
        }

        // We want all real files from dir and subdirs
        var dir = getDir(options.dir),
            fileList = Java.from(dir.listFiles()),
            currFile;

        // Get files
        fileList.forEach(function(file) {
            currFile = new File(file);
            // Get files in subdirectories
            if (currFile.isDirectory() && options.subDirectories) {
                var filesInSubDir = filesInDir(currFile.getAbsolutePath());
            } else if (currFile.isFile()) {
                realFiles.push(_realFile(file));
            };
        });

        return realFiles;

    };

    return {
        getDir: getDir,
        listDirs: listDirs,
        filesInDir: filesInDir
    };

})();
<|endoftext|>


<commit_before>/** @license MIT License (c) copyright 2010-2013 original author or authors */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @author Brian Cavalier
 * @author John Hann
 */

(function(define) { 'use strict';
define(function() {

	return function flow(Promise) {

		var reject = Promise.reject;
		var origCatch = Promise.prototype['catch'];

		/**
		 * Handle the ultimate fulfillment value or rejection reason, and assume
		 * responsibility for all errors.  If an error propagates out of handleResult
		 * or handleFatalError, it will be rethrown to the host, resulting in a
		 * loud stack track on most platforms and a crash on some.
		 * @param {function?} handleResult
		 * @param {function?} handleError
		 * @returns {undefined}
		 */
		Promise.prototype.done = function(handleResult, handleError) {
			this.then(handleResult, handleError)['catch'](this._fatal);
		};

		/**
		 * Add Error-type and predicate matching to catch.  Examples:
		 * promise.catch(TypeError, handleTypeError)
		 *   .catch(predicate, handleMatchedErrors)
		 *   .catch(handleRemainingErrors)
		 * @param onRejected
		 * @returns {*}
		 */
		Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
			if (arguments.length === 1) {
				return origCatch.call(this, onRejected);
			} else {
				if(typeof onRejected !== 'function') {
					return origCatch.call(this, rejectInvalidPredicate);
				}

				return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
			}
		};

		/**
		 * Wraps the provided catch handler, so that it will only be called
		 * if the predicate evaluates truthy
		 * @param {?function} handler
		 * @param {function} predicate
		 * @returns {function} conditional catch handler
		 */
		function createCatchFilter(handler, predicate) {
			return function(e) {
				return evaluatePredicate(e, predicate)
					? handler.call(this, e)
					: reject(e);
			};
		}

		/**
		 * Ensures that onFulfilledOrRejected will be called regardless of whether
		 * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
		 * receive the promises' value or reason.  Any returned value will be disregarded.
		 * onFulfilledOrRejected may throw or return a rejected promise to signal
		 * an additional error.
		 * @param {function} onFulfilledOrRejected handler to be called regardless of
		 *  fulfillment or rejection
		 * @returns {Promise}
		 */
		Promise.prototype['finally'] = Promise.prototype.ensure = function(onFulfilledOrRejected) {
			return typeof onFulfilledOrRejected === 'function'
				? this.then(injectHandler, injectHandler)['yield'](this)
				: this;

			function injectHandler() {
				// prevent argument passing to finally handler
				return onFulfilledOrRejected();
			}
		};

		/**
		 * Recover from a failure by returning a defaultValue.  If defaultValue
		 * is a promise, it's fulfillment value will be used.  If defaultValue is
		 * a promise that rejects, the returned promise will reject with the
		 * same reason.
		 * @param {*} defaultValue
		 * @returns {Promise} new promise
		 */
		Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
			return this.then(void 0, function() {
				return defaultValue;
			});
		};

		/**
		 * Shortcut for .then(function() { return value; })
		 * @param  {*} value
		 * @return {Promise} a promise that:
		 *  - is fulfilled if value is not a promise, or
		 *  - if value is a promise, will fulfill with its value, or reject
		 *    with its reason.
		 */
		Promise.prototype['yield'] = function(value) {
			return this.then(function() {
				return value;
			});
		};

		/**
		 * Runs a side effect when this promise fulfills, without changing the
		 * fulfillment value.
		 * @param {function} onFulfilledSideEffect
		 * @returns {Promise}
		 */
		Promise.prototype.tap = function(onFulfilledSideEffect) {
			return this.then(onFulfilledSideEffect)['yield'](this);
		};

		return Promise;
	};

	function rejectInvalidPredicate() {
		throw new TypeError('catch predicate must be a function');
	}

	function evaluatePredicate(e, predicate) {
		return isError(predicate) ? e instanceof predicate : predicate(e);
	}

	function isError(predicate) {
		return predicate === Error
			|| (predicate != null && predicate.prototype instanceof Error);
	}

});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
<commit_msg>Simplify finally<commit_after>/** @license MIT License (c) copyright 2010-2013 original author or authors */

/**
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @author Brian Cavalier
 * @author John Hann
 */

(function(define) { 'use strict';
define(function() {

	return function flow(Promise) {

		var reject = Promise.reject;
		var origCatch = Promise.prototype['catch'];

		/**
		 * Handle the ultimate fulfillment value or rejection reason, and assume
		 * responsibility for all errors.  If an error propagates out of handleResult
		 * or handleFatalError, it will be rethrown to the host, resulting in a
		 * loud stack track on most platforms and a crash on some.
		 * @param {function?} handleResult
		 * @param {function?} handleError
		 * @returns {undefined}
		 */
		Promise.prototype.done = function(handleResult, handleError) {
			this.then(handleResult, handleError)['catch'](this._fatal);
		};

		/**
		 * Add Error-type and predicate matching to catch.  Examples:
		 * promise.catch(TypeError, handleTypeError)
		 *   .catch(predicate, handleMatchedErrors)
		 *   .catch(handleRemainingErrors)
		 * @param onRejected
		 * @returns {*}
		 */
		Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
			if (arguments.length === 1) {
				return origCatch.call(this, onRejected);
			} else {
				if(typeof onRejected !== 'function') {
					return origCatch.call(this, rejectInvalidPredicate);
				}

				return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
			}
		};

		/**
		 * Wraps the provided catch handler, so that it will only be called
		 * if the predicate evaluates truthy
		 * @param {?function} handler
		 * @param {function} predicate
		 * @returns {function} conditional catch handler
		 */
		function createCatchFilter(handler, predicate) {
			return function(e) {
				return evaluatePredicate(e, predicate)
					? handler.call(this, e)
					: reject(e);
			};
		}

		/**
		 * Ensures that onFulfilledOrRejected will be called regardless of whether
		 * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
		 * receive the promises' value or reason.  Any returned value will be disregarded.
		 * onFulfilledOrRejected may throw or return a rejected promise to signal
		 * an additional error.
		 * @param {function} handler handler to be called regardless of
		 *  fulfillment or rejection
		 * @returns {Promise}
		 */
		Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
			if(typeof handler !== 'function') {
				// Optimization: result will not change, return same promise
				return this;
			}

			handler = isolate(handler, this);
			return this.then(handler, handler);
		};

		/**
		 * Recover from a failure by returning a defaultValue.  If defaultValue
		 * is a promise, it's fulfillment value will be used.  If defaultValue is
		 * a promise that rejects, the returned promise will reject with the
		 * same reason.
		 * @param {*} defaultValue
		 * @returns {Promise} new promise
		 */
		Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
			return this.then(void 0, function() {
				return defaultValue;
			});
		};

		/**
		 * Shortcut for .then(function() { return value; })
		 * @param  {*} value
		 * @return {Promise} a promise that:
		 *  - is fulfilled if value is not a promise, or
		 *  - if value is a promise, will fulfill with its value, or reject
		 *    with its reason.
		 */
		Promise.prototype['yield'] = function(value) {
			return this.then(function() {
				return value;
			});
		};

		/**
		 * Runs a side effect when this promise fulfills, without changing the
		 * fulfillment value.
		 * @param {function} onFulfilledSideEffect
		 * @returns {Promise}
		 */
		Promise.prototype.tap = function(onFulfilledSideEffect) {
			return this.then(onFulfilledSideEffect)['yield'](this);
		};

		return Promise;
	};

	function rejectInvalidPredicate() {
		throw new TypeError('catch predicate must be a function');
	}

	function evaluatePredicate(e, predicate) {
		return isError(predicate) ? e instanceof predicate : predicate(e);
	}

	function isError(predicate) {
		return predicate === Error
			|| (predicate != null && predicate.prototype instanceof Error);
	}

	// prevent argument passing to f and ignore return value
	function isolate(f, x) {
		return function() {
			f.call(this);
			return x;
		};
	}

//	function noop() {}

});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var bundler = require('../client/bundler');
var program = require('commander');
var fs = require('fs');
var pkg = require('../package');
var join = require('path').join;
var beautify = require('js-beautify').js_beautify;

var CONFIG = JSON.parse(fs.readFileSync('./yai.config.json', 'utf-8'));
var DEFAULT_ADDRESS = CONFIG.address || CONFIG.defaultAddress;
var DEFAULT_KEYSET = CONFIG.keyset || CONFIG.defaultKeyset;
var DEFAULT_LANG = CONFIG.lang || CONFIG.defaultLang;
var DEFAULT_TYPE = CONFIG.type || CONFIG.defaultType;
var DEFAULT_ADDER = CONFIG.adder || CONFIG.defaultAdder;
var DEFAULT_REMOVER = CONFIG.remover || CONFIG.defaultRemover;

function lastOf(v) {
    return Array.isArray(v) ? v.pop() : v;
}

program
    .version(pkg.kit.version)
    .option('-l, --lang [lang]', 'Choose language', DEFAULT_LANG)
    .option('-k, --keyset [set]', 'Choose keyset', DEFAULT_KEYSET)
    .option('-a, --add <key> <value>', 'Add key to keyset')
    .option('-r, --remove [key]', 'Remove key from')
    .option('-s, --setup [address]', 'Setup address for keysets', DEFAULT_ADDRESS)
    .option('-A, --use-adder [adder]', 'Use custom adder function', DEFAULT_ADDER)
    .option('-R, --use-remover [remover]', 'Use custom remover function', DEFAULT_REMOVER)
    .option('-i, --info', 'Show info')
    .option('-e, --storage-type', 'Storage type')
    .option('-c, --compile', 'Build i18n bundle')
    .option('--setup-adder [adder]', 'Setup adder')
    .option('--setup-remover [remover]', 'Setup remover\n')
    .option('config', 'Shows configuration file')
    .parse(process.argv);

var remover = require(program.useRemover);
var adder = require(program.useAdder);
var address = program.setup;
var lang = program.lang;
var keyset = program.keyset;

run(program);

function run(program) {
    if (!validate(program)) {
        return;
    }

    if (program.config) {
        var last = program.rawArgs.slice().pop();
        if (last === 'default') {
            setConfigDefault();
        } else {
            console.log(CONFIG);
        }
        return;
    }

    if (program.info) {
        return info();
    }

    if (program.compile) {
        return build(program.rawArgs.slice());
    }

    if (program.setupAdder) {
        save('adder', program.setupAdder);
        adder = program.setupAdder;
    }

    if (program.setupRemover) {
        save('remover', program.setupRemover);
        remover = program.setupRemover;
    }

    if (program.setup !== DEFAULT_ADDRESS) {
        save('address', lastOf(address));
    }

    if (program.keyset !== DEFAULT_KEYSET) {
        save('keyset', lastOf(keyset));
    }

    if (program.lang !== DEFAULT_LANG) {
        save('lang', lastOf(lang));
    }

    if (program.add && typeof program.add === 'string') {
        let key = program.add;
        let value = program.args.pop();

        adder(address, lang, keyset, key, value);
    }

    if (program.remove && typeof program.remove === 'string') {
        let key = program.remove;

        remover(address, lang, keyset, key);
    }

}

function save(prop, value) {
    if (value) {
        CONFIG[prop] = value;
    } else {
        delete CONFIG[prop];
    }

    var json = beautify(JSON.stringify(CONFIG), {
        indent_size: 4
    });

    fs.writeFileSync('./config.json', json, 'utf-8');

    if (value) {
        console.log(`Property: ${prop} successfuly saved as: ${value}`);
    } else {
        console.log(`Property: ${prop} was deleted`);
    }
}

function info() {
    console.log('Yai info\n');
    console.log('------------------------------------------------------------------------------');
    console.log('Storage address:          ' + join(__dirname, program.setup));
    console.log('Storage type:             ' + (program.storageType || DEFAULT_TYPE));
    console.log('Adder address:            ' + join(__dirname, program.useAdder));
    console.log('Remover address:          ' + join(__dirname, program.useRemover));
    console.log('\n----------------------------------------------------------------------------');
    console.log('Lang:                     ' + (program.lang || DEFAULT_LANG));
    console.log('Keyset:                   ' + (program.keyset || DEFAULT_KEYSET));
}

function build(args) {
    var name = '__yai__';

    if (args.length === 6) {
        name = args.pop();
    }

    if (args.length < 4) {
        throw 'Specify bundle for reading';
    }

    var dist = args.length === 5 ? args.pop() : undefined;
    var from = args.pop();

    dist = dist ? dist + '.' + lang + '.js' : undefined;
    bundler.create(address, [lang], name, from, dist);
    return;
}

function setConfigDefault() {
    save('address');
    save('keyset');
    save('lang');
    save('type');
    save('adder');
    save('remover');
}

function validate() {
    return true;
}

<commit_msg>Fixed config saving<commit_after>#!/usr/bin/env node

'use strict';

var bundler = require('../client/bundler');
var program = require('commander');
var fs = require('fs');
var pkg = require('../package');
var join = require('path').join;
var beautify = require('js-beautify').js_beautify;

var CONFIG = JSON.parse(fs.readFileSync('./yai.config.json', 'utf-8'));
var DEFAULT_ADDRESS = CONFIG.address || CONFIG.defaultAddress;
var DEFAULT_KEYSET = CONFIG.keyset || CONFIG.defaultKeyset;
var DEFAULT_LANG = CONFIG.lang || CONFIG.defaultLang;
var DEFAULT_TYPE = CONFIG.type || CONFIG.defaultType;
var DEFAULT_ADDER = CONFIG.adder || CONFIG.defaultAdder;
var DEFAULT_REMOVER = CONFIG.remover || CONFIG.defaultRemover;

function lastOf(v) {
    return Array.isArray(v) ? v.pop() : v;
}

program
    .version(pkg.kit.version)
    .option('-l, --lang [lang]', 'Choose language', DEFAULT_LANG)
    .option('-k, --keyset [set]', 'Choose keyset', DEFAULT_KEYSET)
    .option('-a, --add <key> <value>', 'Add key to keyset')
    .option('-r, --remove [key]', 'Remove key from')
    .option('-s, --setup [address]', 'Setup address for keysets', DEFAULT_ADDRESS)
    .option('-A, --use-adder [adder]', 'Use custom adder function', DEFAULT_ADDER)
    .option('-R, --use-remover [remover]', 'Use custom remover function', DEFAULT_REMOVER)
    .option('-i, --info', 'Show info')
    .option('-e, --storage-type', 'Storage type')
    .option('-c, --compile', 'Build i18n bundle')
    .option('--setup-adder [adder]', 'Setup adder')
    .option('--setup-remover [remover]', 'Setup remover\n')
    .option('config', 'Shows configuration file')
    .parse(process.argv);

var remover = require(program.useRemover);
var adder = require(program.useAdder);
var address = program.setup;
var lang = program.lang;
var keyset = program.keyset;

run(program);

function run(program) {
    if (!validate(program)) {
        return;
    }

    if (program.config) {
        var last = program.rawArgs.slice().pop();
        if (last === 'default') {
            setConfigDefault();
        } else {
            console.log(CONFIG);
        }
        return;
    }

    if (program.info) {
        return info();
    }

    if (program.compile) {
        return build(program.rawArgs.slice());
    }

    if (program.setupAdder) {
        save('adder', program.setupAdder);
        adder = program.setupAdder;
    }

    if (program.setupRemover) {
        save('remover', program.setupRemover);
        remover = program.setupRemover;
    }

    if (program.setup !== DEFAULT_ADDRESS) {
        save('address', lastOf(address));
    }

    if (program.keyset !== DEFAULT_KEYSET) {
        save('keyset', lastOf(keyset));
    }

    if (program.lang !== DEFAULT_LANG) {
        save('lang', lastOf(lang));
    }

    if (program.add && typeof program.add === 'string') {
        let key = program.add;
        let value = program.args.pop();

        adder(address, lang, keyset, key, value);
    }

    if (program.remove && typeof program.remove === 'string') {
        let key = program.remove;

        remover(address, lang, keyset, key);
    }

}

function save(prop, value) {
    if (value) {
        CONFIG[prop] = value;
    } else {
        delete CONFIG[prop];
    }

    var json = beautify(JSON.stringify(CONFIG), {
        indent_size: 4
    });

    fs.writeFileSync('./yai.config.json', json, 'utf-8');

    if (value) {
        console.log(`Property: ${prop} successfuly saved as: ${value}`);
    } else {
        console.log(`Property: ${prop} was deleted`);
    }
}

function info() {
    console.log('Yai info\n');
    console.log('------------------------------------------------------------------------------');
    console.log('Storage address:          ' + join(__dirname, program.setup));
    console.log('Storage type:             ' + (program.storageType || DEFAULT_TYPE));
    console.log('Adder address:            ' + join(__dirname, program.useAdder));
    console.log('Remover address:          ' + join(__dirname, program.useRemover));
    console.log('\n----------------------------------------------------------------------------');
    console.log('Lang:                     ' + (program.lang || DEFAULT_LANG));
    console.log('Keyset:                   ' + (program.keyset || DEFAULT_KEYSET));
}

function build(args) {
    var name = '__yai__';

    if (args.length === 6) {
        name = args.pop();
    }

    if (args.length < 4) {
        throw 'Specify bundle for reading';
    }

    var dist = args.length === 5 ? args.pop() : undefined;
    var from = args.pop();

    dist = dist ? dist + '.' + lang + '.js' : undefined;
    bundler.create(address, [lang], name, from, dist);
    return;
}

function setConfigDefault() {
    save('address');
    save('keyset');
    save('lang');
    save('type');
    save('adder');
    save('remover');
}

function validate() {
    return true;
}

<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import { StyleSheet, Modal, KeyboardAvoidingView, TextInput, View, } from 'react-native';

import IconButton from 'Acornote_React_Native/js/components/iconButton'

export default class EditFolderScreen extends Component {

  state = {
    text: ''
  }

  _onSure = ()=>{

  }
  _onEditLink = ()=>{

  }
  _onEditMark = ()=>{

  }
  _onEditFlip = ()=>{

  }
  _onEditAudio = ()=>{

  }

  render() {
    return (
      <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.props.modalVisible}
          >
          <KeyboardAvoidingView behavior='height' style={styles.view}>

            <View style={styles.buttons}>
              <IconButton
                onPress={this.props.onCancel}
                source={require('Acornote_React_Native/img/ic_cancel@3x.png')} />

              <IconButton
                onPress={this._onSure}
                source={require('Acornote_React_Native/img/ic_ok@3x.png')} />
            </View>

            <TextInput
              ref='title'
              style={styles.textInput}
              placeholder="Folder name"
              autoFocus={true}
              onChangeText={(text) => this.setState({text})}
            />

            <View style={styles.buttons}>
              <IconButton
                onPress={this._onEditLink}
                source={require('Acornote_React_Native/img/ic_link_off@3x.png')} />

              <IconButton
                onPress={this._onEditMark}
                source={require('Acornote_React_Native/img/ic_mark_off@3x.png')} />

              <IconButton
                onPress={this._onEditFlip}
                source={require('Acornote_React_Native/img/ic_flip_off@3x.png')} />

              <IconButton
                onPress={this._onEditAudio}
                source={require('Acornote_React_Native/img/ic_audio_off@3x.png')} />
            </View>

         </KeyboardAvoidingView>
        </Modal>
    );
  }
}

const styles = StyleSheet.create({
  view: {
    flex: 1,
    backgroundColor: 'red',
    justifyContent: 'space-between',
    alignItems: 'stretch',
  },
  textInput: {
    color: 'white',
    textAlign: 'center',
    fontSize: 50,
    marginRight: 10,
    marginLeft: 10,
  },
  buttons: {
    margin: 10,
    height: 44,
    flexDirection: 'row',
    justifyContent: 'space-between',
  }
})<commit_msg>fix the height bug of textinput in edit folder<commit_after>'use strict';

import React, { Component } from 'react';
import { StyleSheet, Modal, KeyboardAvoidingView, TextInput, View, StatusBar, } from 'react-native';

import IconButton from 'Acornote_React_Native/js/components/iconButton'

export default class EditFolderScreen extends Component {

  state = {
    text: ''
  }

  _onSure = ()=>{

  }
  _onEditLink = ()=>{

  }
  _onEditMark = ()=>{

  }
  _onEditFlip = ()=>{

  }
  _onEditAudio = ()=>{

  }

  render() {
    return (
      <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.props.modalVisible}
          onRequestClose={()=>{}}
          >
          <StatusBar
            hidden={true}
            animated={true}
            showHideTransition="slide"
          />
          <KeyboardAvoidingView behavior='height' style={styles.view} >

            <View style={styles.canselSureBtns}>
              <IconButton
                onPress={this.props.onCancel}
                source={require('Acornote_React_Native/img/ic_cancel@3x.png')} />

              <IconButton
                onPress={this._onSure}
                source={require('Acornote_React_Native/img/ic_ok@3x.png')} />
            </View>

            <TextInput
              ref='title'
              style={styles.textInput}
              placeholder="Folder name"
              autoFocus={true}
              autoCorrect={true}
              onChangeText={(text) => this.setState({text})}
              clearButtonMode="while-editing"
              returnKeyType="done"
              enablesReturnKeyAutomatically={true}
              underlineColorAndroid="transparent"
            />

            <View style={styles.bottomBtns}>
              <IconButton
                onPress={this._onEditLink}
                source={require('Acornote_React_Native/img/ic_link_off@3x.png')} />

              <IconButton
                onPress={this._onEditMark}
                source={require('Acornote_React_Native/img/ic_mark_off@3x.png')} />

              <IconButton
                onPress={this._onEditFlip}
                source={require('Acornote_React_Native/img/ic_flip_off@3x.png')} />

              <IconButton
                onPress={this._onEditAudio}
                source={require('Acornote_React_Native/img/ic_audio_off@3x.png')} />
            </View>

         </KeyboardAvoidingView>
        </Modal>
    );
  }
}

const styles = StyleSheet.create({
  view: {
    flex: 1,
    flexDirection:'column',
    backgroundColor: '#19D2B9',
    justifyContent: 'space-between',
    alignItems: 'stretch',
  },
  textInput: {
    flex: 1,
    color: 'white',
    textAlign: 'center',
    fontSize: 50,
    marginRight: 10,
    marginLeft: 10,
  },
  canselSureBtns: {
    margin: 10,
    height: 44,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  bottomBtns: {
    margin: 10,
    height: 44,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
})<|endoftext|>


<commit_before>/*!
 * flow.js v0.0.13
 * https://github.com/minodisk/flow-js
 * Author: Daisuke MINO
 * Licensed under the MIT license.
 * https://github.com/minodisk/flow-js/raw/master/LICENSE
 */
(function () {
  function Flow(type, actors) {
    switch (type) {
      case 'serial':
        this._serial(actors);
        break;
      case 'parallel':
        this._parallel(actors);
        break;
      case 'repeat':
        this._repeat(actors[0], actors[1]);
        break;
      default:
        throw new Error(type + 'is not implemented.');
        break;
    }
  }

  Flow.serial = function (/*...actors*/) {
    return Flow.serialActors(Array.prototype.slice.call(arguments));
  };

  Flow.serialActors = function (actors) {
    return new Flow('serial', actors);
  };

  Flow.parallel = function (/*...actors*/) {
    return Flow.parallelActors(Array.prototype.slice.call(arguments));
  };

  Flow.parallelActors = function (actors) {
    return new Flow('parallel', actors);
  };

  Flow.repeat = function (actor, repeatCount) {
    return new Flow('repeat', [actor, repeatCount]);
  };

  Flow.wait = function (delay) {
    return function (flow) {
      setTimeout(flow.next, delay);
    };
  };

  Flow.prototype = {};

  /*Flow.prototype.running;
   Flow.prototype.currentPhase;
   Flow.prototype.totalPhase;
   Flow.prototype.userData;
   Flow.prototype._actors;*/

  Flow.prototype._serial = function (actors) {
    var that = this;
    this._actors = actors;
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = actors.length;
    this.userData = {};
    this.start = function () {
      that._serialStart.apply(that, arguments);
    };
    this.next = function () {
      that._serialNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  Flow.prototype._parallel = function (actors) {
    var that = this;
    this._actors = actors;
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = actors.length;
    this.userData = {};
    this.start = function () {
      that._parallelStart.apply(that, arguments);
    };
    this.next = function () {
      that._parallelNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  Flow.prototype._repeat = function (actor, repeatCount) {
    var that = this;
    this._actors = [];
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = repeatCount;
    this.userData = {};
    while (repeatCount--) {
      this._actors.push(actor);
    }
    this.start = function () {
      that._serialStart.apply(that, arguments);
    };
    this.next = function () {
      if (actor instanceof Flow) {
        actor.reset();
      }
      that._serialNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  /*Flow.prototype.start;
   Flow.prototype.next;
   Flow.prototype.stop;
   Flow.prototype.reset;
   Flow.prototype.onComplete;
   Flow.prototype.onError;*/

  Flow.prototype._serialStart = function () {
    if (!this.running && this.currentPhase < this.totalPhase) {
      this.running = true;
      var actor = this._actors[this.currentPhase];
      if (actor instanceof Flow) {
        if (this.onError) {
          actor.onError = this.onError;
        }
        actor.onComplete = this.next;
        actor.start();
      } else {
        var args = Array.prototype.slice.call(arguments);
        args[0] = this;
        actor.apply(null, args);
      }
    }
  };

  Flow.prototype._serialNext = function () {
    if (this.running) {
      if (++this.currentPhase < this.totalPhase) {
        var actor = this._actors[this.currentPhase];
        if (actor instanceof Flow) {
          if (this.onError) {
            actor.onError = this.onError;
          }
          actor.onComplete = this.next;
          actor.start();
        } else {
          var args = Array.prototype.slice.call(arguments);
          if (args[0] === null || args[0] === undefined ||
            args[0] instanceof Error) {
            var err = args.shift();
            if (err && this.onError) {
              this.onError(err);
              return;
            }
          }
          args.unshift(this);
          actor.apply(null, args);
        }
      } else {
        this.stop();
        if (this.onComplete) {
          this.onComplete();
        }
      }
    }
  };

  Flow.prototype._parallelStart = function () {
    if (!this.running && this.currentPhase < this.totalPhase) {
      this.running = true;
      var actor;
      for (var i = 0, len = this._actors.length; i < len; i++) {
        actor = this._actors[i];
        if (actor instanceof Flow) {
          if (this.onError) {
            actor.onError = this.onError;
          }
          actor.onComplete = this.next;
          actor.start();
        } else {
          actor.apply(null, [this]);
        }
      }
    }
  };

  Flow.prototype._parallelNext = function (err) {
    var that = this;
    setTimeout(function () {
      if (err) {
        if (that.onError) {
          that.onError(err);
          return;
        }
        return;
      }
      if (that.running) {
        if (++that.currentPhase >= that.totalPhase) {
          that.stop();
          if (that.onComplete) {
            that.onComplete();
          }
        }
      }
    }, 0);
  };

  Flow.prototype._stop = function () {
    this.running = false;
    var i = this._actors.length;
    while (i--) {
      if (this._actors[i] instanceof Flow) {
        this._actors[i].stop();
      }
    }
  };

  Flow.prototype._reset = function () {
    this.running = false;
    this.currentPhase = 0;
    var i = this._actors.length;
    while (i--) {
      if (this._actors[i] instanceof Flow) {
        this._actors[i].reset();
      }
    }
  };

  if (typeof exports !== 'undefined') {
    // Node.js
    exports.Flow = Flow;
  } else if (typeof define !== 'undefined') {
    // RequireJS
    define('net.minodisk.core.Flow', [], Flow);
  } else if (typeof window !== 'undefined') {
    // browser
    window.Flow = Flow;
  }
})();<commit_msg>* bug fix - repeat() factory * bug fix - stop() of deep nested flow * bug fix - reset() of deep nested flow<commit_after>/*!
 * flow.js v0.0.14
 * https://github.com/minodisk/flow-js
 * Author: Daisuke MINO
 * Licensed under the MIT license.
 * https://github.com/minodisk/flow-js/raw/master/LICENSE
 */
(function () {
  function Flow(type, actors) {
    switch (type) {
      case 'serial':
        this._serial(actors);
        break;
      case 'parallel':
        this._parallel(actors);
        break;
      case 'repeat':
        this._repeat(actors[0], actors[1]);
        break;
      default:
        throw new Error(type + 'is not implemented.');
        break;
    }
  }

  Flow.serial = function (/*...actors*/) {
    return Flow.serialActors(Array.prototype.slice.call(arguments));
  };

  Flow.serialActors = function (actors) {
    return new Flow('serial', actors);
  };

  Flow.parallel = function (/*...actors*/) {
    return Flow.parallelActors(Array.prototype.slice.call(arguments));
  };

  Flow.parallelActors = function (actors) {
    return new Flow('parallel', actors);
  };

  Flow.repeat = function (actor, repeatCount) {
    return new Flow('repeat', [actor, repeatCount]);
  };

  Flow.wait = function (delay) {
    return function (flow) {
      setTimeout(flow.next, delay);
    };
  };

  Flow.prototype = {};

  /*Flow.prototype.running;
   Flow.prototype.currentPhase;
   Flow.prototype.totalPhase;
   Flow.prototype.userData;
   Flow.prototype._actors;*/

  Flow.prototype._serial = function (actors) {
    var that = this;
    this._actors = actors;
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = actors.length;
    this.userData = {};
    this.start = function () {
      that._serialStart.apply(that, arguments);
    };
    this.next = function () {
      that._serialNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  Flow.prototype._parallel = function (actors) {
    var that = this;
    this._actors = actors;
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = actors.length;
    this.userData = {};
    this.start = function () {
      that._parallelStart.apply(that, arguments);
    };
    this.next = function () {
      that._parallelNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  Flow.prototype._repeat = function (actor, repeatCount) {
    var that = this;
    this._actors = [];
    this.running = false;
    this.currentPhase = 0;
    this.totalPhase = repeatCount;
    this.userData = {};
    while (repeatCount--) {
      this._actors.push(actor);
    }
    this.start = function () {
      that._serialStart.apply(that, arguments);
    };
    this.next = function () {
      if (actor instanceof Flow) {
        actor.reset();
      }
      that._serialNext.apply(that, arguments);
    };
    this.stop = function () {
      that._stop.apply(that, arguments);
    };
    this.reset = function () {
      that._reset.apply(that, arguments);
    };
  };

  /*Flow.prototype.start;
   Flow.prototype.next;
   Flow.prototype.stop;
   Flow.prototype.reset;
   Flow.prototype.onComplete;
   Flow.prototype.onError;*/

  Flow.prototype._serialStart = function () {
    if (!this.running && this.currentPhase < this.totalPhase) {
      this.running = true;
      var actor = this._actors[this.currentPhase];
      if (actor instanceof Flow) {
        if (this.onError) {
          actor.onError = this.onError;
        }
        actor.onComplete = this.next;
        actor.start();
      } else {
        var args = Array.prototype.slice.call(arguments);
        args[0] = this;
        actor.apply(null, args);
      }
    }
  };

  Flow.prototype._serialNext = function () {
    if (this.running) {
      if (++this.currentPhase < this.totalPhase) {
        var actor = this._actors[this.currentPhase];
        if (actor instanceof Flow) {
          if (this.onError) {
            actor.onError = this.onError;
          }
          actor.onComplete = this.next;
          actor.start();
        } else {
          var args = Array.prototype.slice.call(arguments);
          if (args[0] === null || args[0] === undefined ||
            args[0] instanceof Error) {
            var err = args.shift();
            if (err && this.onError) {
              this.onError(err);
              return;
            }
          }
          args.unshift(this);
          actor.apply(null, args);
        }
      } else {
        this.stop();
        if (this.onComplete) {
          this.onComplete();
        }
      }
    }
  };

  Flow.prototype._parallelStart = function () {
    if (!this.running && this.currentPhase < this.totalPhase) {
      this.running = true;
      var actor;
      for (var i = 0, len = this._actors.length; i < len; i++) {
        actor = this._actors[i];
        if (actor instanceof Flow) {
          if (this.onError) {
            actor.onError = this.onError;
          }
          actor.onComplete = this.next;
          actor.start();
        } else {
          actor.apply(null, [this]);
        }
      }
    }
  };

  Flow.prototype._parallelNext = function (err) {
    var that = this;
    setTimeout(function () {
      if (err) {
        if (that.onError) {
          that.onError(err);
          return;
        }
        return;
      }
      if (that.running) {
        if (++that.currentPhase >= that.totalPhase) {
          that.stop();
          if (that.onComplete) {
            that.onComplete();
          }
        }
      }
    }, 0);
  };

  Flow.prototype._stop = function () {
    this.running = false;
    var i = this._actors.length;
    while (i--) {
      if (this._actors[i] instanceof Flow) {
        this._actors[i].stop();
      }
    }
  };

  Flow.prototype._reset = function () {
    this.running = false;
    this.currentPhase = 0;
    var i = this._actors.length;
    while (i--) {
      if (this._actors[i] instanceof Flow) {
        this._actors[i].reset();
      }
    }
  };

  if (typeof exports !== 'undefined') {
    // Node.js
    exports.Flow = Flow;
  } else if (typeof define !== 'undefined') {
    // RequireJS
    define('net.minodisk.core.Flow', [], Flow);
  } else if (typeof window !== 'undefined') {
    // browser
    window.Flow = Flow;
  }
})();<|endoftext|>


<commit_before>'use strict';
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const Emittery = require('emittery');

if (fs.realpathSync(__filename) !== __filename) {
	console.warn('WARNING: `npm link ava` and the `--preserve-symlink` flag are incompatible. We have detected that AVA is linked via `npm link`, and that you are using either an early version of Node 6, or the `--preserve-symlink` flag. This breaks AVA. You should upgrade to Node 6.2.0+, avoid the `--preserve-symlink` flag, or avoid using `npm link ava`.');
}

// In case the test file imports a different AVA install,
// the presence of this variable allows it to require this one instead
const AVA_PATH = path.resolve(__dirname, '..');

const workerPath = require.resolve('./worker/subprocess');

module.exports = (file, options, execArgv = process.execArgv) => {
	let finished = false;

	const emitter = new Emittery();
	const emitStateChange = evt => {
		if (!finished) {
			emitter.emit('stateChange', Object.assign(evt, {testFile: file}));
		}
	};

	options = {
		file,
		baseDir: process.cwd(),
		...options
	};

	const subprocess = childProcess.fork(workerPath, options.workerArgv, {
		cwd: options.projectDir,
		silent: true,
		env: {NODE_ENV: 'test', ...process.env, ...options.environmentVariables, AVA_PATH},
		execArgv
	});

	subprocess.stdout.on('data', chunk => {
		emitStateChange({type: 'worker-stdout', chunk});
	});

	subprocess.stderr.on('data', chunk => {
		emitStateChange({type: 'worker-stderr', chunk});
	});

	let forcedExit = false;
	const send = evt => {
		if (subprocess.connected && !finished && !forcedExit) {
			subprocess.send({ava: evt}, () => {
				// Disregard errors.
			});
		}
	};

	const promise = new Promise(resolve => {
		const finish = () => {
			finished = true;
			resolve();
		};

		subprocess.on('message', message => {
			if (!message.ava) {
				return;
			}

			if (message.ava.type === 'ready-for-options') {
				send({type: 'options', options});
				return;
			}

			if (message.ava.type === 'ping') {
				send({type: 'pong'});
			} else {
				emitStateChange(message.ava);
			}
		});

		subprocess.on('error', err => {
			emitStateChange({type: 'worker-failed', err});
			finish();
		});

		subprocess.on('exit', (code, signal) => {
			if (forcedExit) {
				emitStateChange({type: 'worker-finished', forcedExit});
			} else if (code > 0) {
				emitStateChange({type: 'worker-failed', nonZeroExitCode: code});
			} else if (code === null && signal) {
				emitStateChange({type: 'worker-failed', signal});
			} else {
				emitStateChange({type: 'worker-finished', forcedExit});
			}

			finish();
		});
	});

	return {
		exit() {
			forcedExit = true;
			subprocess.kill();
		},

		notifyOfPeerFailure() {
			send({type: 'peer-failed'});
		},

		onStateChange(listener) {
			return emitter.on('stateChange', listener);
		},

		file,
		promise
	};
};
<commit_msg>Use advanced serialization (when available) for test worker communication<commit_after>'use strict';
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const Emittery = require('emittery');

if (fs.realpathSync(__filename) !== __filename) {
	console.warn('WARNING: `npm link ava` and the `--preserve-symlink` flag are incompatible. We have detected that AVA is linked via `npm link`, and that you are using either an early version of Node 6, or the `--preserve-symlink` flag. This breaks AVA. You should upgrade to Node 6.2.0+, avoid the `--preserve-symlink` flag, or avoid using `npm link ava`.');
}

// In case the test file imports a different AVA install,
// the presence of this variable allows it to require this one instead
const AVA_PATH = path.resolve(__dirname, '..');

const workerPath = require.resolve('./worker/subprocess');

const useAdvanced = process.versions.node >= '12.16.0';
// FIXME: Fix this in api.js or cli.js.
const serializeOptions = useAdvanced ?
	options => JSON.parse(JSON.stringify(options)) : // Use JSON serialization to remove non-clonable values.
	options => options;

module.exports = (file, options, execArgv = process.execArgv) => {
	let finished = false;

	const emitter = new Emittery();
	const emitStateChange = evt => {
		if (!finished) {
			emitter.emit('stateChange', Object.assign(evt, {testFile: file}));
		}
	};

	options = {
		file,
		baseDir: process.cwd(),
		...options
	};

	const subprocess = childProcess.fork(workerPath, options.workerArgv, {
		cwd: options.projectDir,
		silent: true,
		env: {NODE_ENV: 'test', ...process.env, ...options.environmentVariables, AVA_PATH},
		execArgv,
		serialization: useAdvanced ? 'advanced' : 'json'
	});

	subprocess.stdout.on('data', chunk => {
		emitStateChange({type: 'worker-stdout', chunk});
	});

	subprocess.stderr.on('data', chunk => {
		emitStateChange({type: 'worker-stderr', chunk});
	});

	let forcedExit = false;
	const send = evt => {
		if (subprocess.connected && !finished && !forcedExit) {
			subprocess.send({ava: evt}, () => {
				// Disregard errors.
			});
		}
	};

	const promise = new Promise(resolve => {
		const finish = () => {
			finished = true;
			resolve();
		};

		subprocess.on('message', message => {
			if (!message.ava) {
				return;
			}

			if (message.ava.type === 'ready-for-options') {
				send({type: 'options', options: serializeOptions(options)});
				return;
			}

			if (message.ava.type === 'ping') {
				send({type: 'pong'});
			} else {
				emitStateChange(message.ava);
			}
		});

		subprocess.on('error', err => {
			emitStateChange({type: 'worker-failed', err});
			finish();
		});

		subprocess.on('exit', (code, signal) => {
			if (forcedExit) {
				emitStateChange({type: 'worker-finished', forcedExit});
			} else if (code > 0) {
				emitStateChange({type: 'worker-failed', nonZeroExitCode: code});
			} else if (code === null && signal) {
				emitStateChange({type: 'worker-failed', signal});
			} else {
				emitStateChange({type: 'worker-finished', forcedExit});
			}

			finish();
		});
	});

	return {
		exit() {
			forcedExit = true;
			subprocess.kill();
		},

		notifyOfPeerFailure() {
			send({type: 'peer-failed'});
		},

		onStateChange(listener) {
			return emitter.on('stateChange', listener);
		},

		file,
		promise
	};
};
<|endoftext|>