<commit_before>/**
 * Unit Tests for maps and map cells.
 *
 */

var chai = require("chai");
var expect = chai.expect;
var RG = require("../roguelike.js");

var Actor = RG.RogueActor;
var Action = RG.RogueAction;
var Level = RG.RogueLevel;
var Element = RG.RogueElement;
var Cell = RG.MapCell;
var Item = RG.RogueItem;
var Container = RG.RogueItemContainer;
var InvAndEquip = RG.RogueInvAndEquip;
var Factory = RG.FACT;

//---------------------------------------------------------------------------
// MAP CELL
//---------------------------------------------------------------------------

describe('Basic properties of map cell', function() {
    it('Holds elements and actors', function() {
        var actor = Factory.createPlayer("Player", 50);
        var cell = new Cell(0, 0, new Element("wall"));
        expect(cell.isFree()).to.equal(false);
        expect(cell.hasPropType("wall")).to.equal(true);
        expect(cell.hasPropType("actors")).to.equal(false);
        expect(cell.lightPasses()).to.equal(false);

        // Setting an element property of the cell
        var floorElem = new Element("floor");
        cell.setProp("elements", floorElem);
        expect(cell.hasPropType("floor")).to.equal(true);
        expect(cell.hasProp("elements")).to.equal(true);

        // Removing a property
        expect(cell.removeProp("elements", floorElem)).to.equal(true);
        expect(cell.hasPropType("floor")).to.equal(false);
        expect(cell.hasProp("elements")).to.equal(false);

        // Retrieving a property
        var propNull = cell.getProp("xxx");
        expect(propNull).to.equal(null);

        // Actors in cell, cell with actor is not free
        var fCell = Factory.createFloorCell(1, 1);
        expect(fCell.isFree()).to.equal(true);
        fCell.setProp("actors", actor);
        expect(fCell.isFree()).to.equal(false);
        expect(fCell.lightPasses()).to.equal(true);
        expect(fCell.hasProp("actors")).to.equal(true);
        expect(fCell.hasProp("items")).to.equal(false);
    });
});

describe('Retrieving styling classes for cells', function() {
    it('description', function() {
        var cell = new Cell(0, 0, new Element("wall"));
        cell.setExplored();
        expect(RG.getStyleClassForCell(cell)).to.equal("cell-element-wall");

        var floorCell = new Cell(0, 0, new Element("floor"));
        var actor = Factory.createPlayer("Player", 50);
        floorCell.setProp("actors", actor);
        floorCell.setExplored();
        expect(RG.getStyleClassForCell(floorCell)).to.equal("cell-actors");
    });
});

//---------------------------------------------------------------------------
// ITEMS AND MAP CELLS
//--------------------------------------------------------------------------

describe('Items in map cells', function() {
    it('Is placed in a cell and needs an owner', function() {
        var cell = new Cell(0, 1, new Element("floor"));
        cell.setExplored();
        var item = new Item("food");
        cell.setProp("items", item);
        expect(cell.hasProp("items")).to.equal(true);

        var items = cell.getProp("items");
        expect(items.length).to.equal(1);

        expect(RG.getStyleClassForCell(cell)).to.equal("cell-items");

        // Item must have its owners x,y
        item.setOwner(cell);
        expect(item.getX()).to.equal(0);
        expect(item.getY()).to.equal(1);

    });

    it('Container can also be placed into the cell', function() {
        var cell = new Cell(1, 2, new Element("floor"));
        cell.setExplored();
        var container = new Container(cell);
        expect(container.getX()).to.equal(1);
        expect(container.getY()).to.equal(2);
        expect(container.isEmpty()).to.equal(true);
        expect(container.first()).to.equal(null);
        expect(container.next()).to.equal(null);

        // Test adding items.
        var food = new Item("food");
        var weapon = new Item("weapon");
        expect(food.getOwner()).to.equal(null);
        container.addItem(food);
        expect(food.getOwner()).to.equal(container);
        expect(container.isEmpty()).to.equal(false);
        expect(container.hasItem(food)).to.equal(true);
        expect(container.hasItem(weapon)).to.equal(false);
        expect(container.first()).to.equal(food);
        expect(container.next()).to.equal(null);

        // Add new weapon, then remove food
        container.addItem(weapon);
        expect(container.first()).to.equal(food);
        expect(container.next()).to.equal(weapon);

        expect(container.removeItem(food)).to.equal(true);
        expect(container.first()).to.equal(weapon);
        expect(container.removeItem(food)).to.equal(false);

        var cont2 = new Container(container);
        container.addItem(cont2);
        expect(cont2.getX()).to.equal(1);
        expect(cont2.getY()).to.equal(2);

    });

    it("Actor inventory has a container and equipped items", function() {
        var food = new Item("food");
        var sword = new Item("weapon");
        var actor = Factory.createPlayer("Player", 50);

        var invEq = new InvAndEquip(actor);
        invEq.addItem(food);
        expect(invEq.getInventory().getItems().length).to.equal(1);
        invEq.addItem(sword);
        expect(invEq.getInventory().getItems().length).to.equal(2);
        expect(invEq.equipItem(sword)).to.equal(true);
        expect(invEq.getInventory().getItems().length).to.equal(1);

        var handsEquipped = invEq.getEquipment().getEquipped("hand");
        expect(handsEquipped[0]).to.equal(sword);
        expect(invEq.unequipItem("hand", 0)).to.equal(true);

    });

    it('Picking up items from floor by actor', function() {
        var level = Factory.createLevel("arena", 20, 20);
        var actor = Factory.createPlayer("Player");
        var inv   = actor.getInvEq().getInventory();
        var weapon = new Item("weapon");
        expect(level.addItem(weapon, 2, 4)).to.equal(true);
        expect(level.addActor(actor, 2, 4)).to.equal(true);

        // After picking up, cell must not have item anymore
        var cell = level.getMap().getCell(2 ,4);
        expect(cell.hasProp("items")).to.equal(true);
        level.pickupItem(actor, 2, 4);
        expect(cell.hasProp("items")).to.equal(false);

        var invItems = inv.getItems();
        expect(invItems[0]).to.equal(weapon);
        expect(actor.getInvEq().equipItem(weapon)).to.equal(true);
        expect(inv.isEmpty()).to.equal(true);

    });

});

//---------------------------------------------------------------------------
// MAP UNIT TESTS
//---------------------------------------------------------------------------

describe('Tests to check that basic operations for map work', function() {
    var actor = new Actor("Player");
    actor.setIsPlayer(true);
    var level1 = Factory.createLevel("arena", 10, 10);
    var level2 = Factory.createLevel("arena", 20, 20);

    it('Is initialized as empty and having floors', function() {
        var map = level1.getMap();
        var map2 = level2.getMap();

        expect(map.hasXY(0,0)).to.equal(true);
        expect(map.hasXY(9,9)).to.equal(true);
        expect(map.hasXY(10,10)).to.equal(false);

        var freeCells = map.getFree();
        expect(freeCells.length).to.equal(8*8);
        for (var i = 0; i < freeCells.length; i++) {
            expect(freeCells[i].isFree()).to.equal(true);
            expect(freeCells[i].lightPasses()).to.equal(true);
        }

        var actorNotInLevel = new Actor("monster");
        actor.getFOVRange = function() {return 1;}; // Override default
        level1.addActor(actor, 4, 4);
        var cells = map.getVisibleCells(actor);
        expect(cells.length).to.equal(9);
        var zeroCells = map.getVisibleCells(actorNotInLevel);
        expect(zeroCells.length).to.equal(0);

        // After setting x,y try again
        actorNotInLevel.setXY(4,4);
        actorNotInLevel.getFOVRange = function() {return 5;}; // Override default
        zeroCells = map.getVisibleCells(actorNotInLevel);
        expect(zeroCells.length).to.equal(0);

        expect(level1.getMap().getCell(4,4).isExplored()).to.equal(false);
        level1.exploreCells(actor);
        expect(level1.getMap().getCell(4,4).isExplored()).to.equal(true);

    });
});

//---------------------------------------------------------------------------
// LEVEL UNIT TESTS
//---------------------------------------------------------------------------

describe('Moving actors around in the game', function() {
    it('Moves but is blocked by walls.', function() {
        var actor = new Actor(true);
        var level = new Level(10, 10);
        var mapgen = new RG.RogueMapGen();
        mapgen.setGen("arena", 10, 10);
        var map = mapgen.getMap();
        level.setMap(map);
        level.addActor(actor, 1, 2);
        expect(actor.getX()).to.equal(1);
        expect(actor.getY()).to.equal(2);

        // Actors x,y changes due to move
        expect(level.moveActorTo(actor, 2, 3)).to.equal(true);
        expect(actor.getX()).to.equal(2);
        expect(actor.getY()).to.equal(3);

        // Create a wall to block the passage
        var wall = new Element("wall");
        level.getMap().setBaseElemXY(4, 4, wall);
        expect(level.moveActorTo(actor, 4, 4)).to.equal(false);
        expect(actor.getX(), "X didn't change due to wall").to.equal(2);
        expect(actor.getY()).to.equal(3);

    });
});

<commit_msg>Added tests for stairs.<commit_after>/**
 * Unit Tests for maps and map cells.
 *
 */

var chai = require("chai");
var expect = chai.expect;
var RG = require("../roguelike.js");

var Actor = RG.RogueActor;
var Action = RG.RogueAction;
var Level = RG.RogueLevel;
var Element = RG.RogueElement;
var Cell = RG.MapCell;
var Item = RG.RogueItem;
var Container = RG.RogueItemContainer;
var InvAndEquip = RG.RogueInvAndEquip;
var Factory = RG.FACT;
var Stairs = RG.RogueStairsElement;

//---------------------------------------------------------------------------
// MAP CELL
//---------------------------------------------------------------------------

describe('Basic properties of map cell', function() {
    it('Holds elements and actors', function() {
        var actor = Factory.createPlayer("Player", 50);
        var cell = new Cell(0, 0, new Element("wall"));
        expect(cell.isFree()).to.equal(false);
        expect(cell.hasPropType("wall")).to.equal(true);
        expect(cell.hasPropType("actors")).to.equal(false);
        expect(cell.lightPasses()).to.equal(false);

        // Setting an element property of the cell
        var floorElem = new Element("floor");
        cell.setProp("elements", floorElem);
        expect(cell.hasPropType("floor")).to.equal(true);
        expect(cell.hasProp("elements")).to.equal(true);

        // Removing a property
        expect(cell.removeProp("elements", floorElem)).to.equal(true);
        expect(cell.hasPropType("floor")).to.equal(false);
        expect(cell.hasProp("elements")).to.equal(false);

        // Retrieving a property
        var propNull = cell.getProp("xxx");
        expect(propNull).to.equal(null);

        // Actors in cell, cell with actor is not free
        var fCell = Factory.createFloorCell(1, 1);
        expect(fCell.isFree()).to.equal(true);
        fCell.setProp("actors", actor);
        expect(fCell.isFree()).to.equal(false);
        expect(fCell.lightPasses()).to.equal(true);
        expect(fCell.hasProp("actors")).to.equal(true);
        expect(fCell.hasProp("items")).to.equal(false);
    });
});

describe('Retrieving styling classes for cells', function() {
    it('description', function() {
        var cell = new Cell(0, 0, new Element("wall"));
        cell.setExplored();
        expect(RG.getStyleClassForCell(cell)).to.equal("cell-element-wall");

        var floorCell = new Cell(0, 0, new Element("floor"));
        var actor = Factory.createPlayer("Player", 50);
        floorCell.setProp("actors", actor);
        floorCell.setExplored();
        expect(RG.getStyleClassForCell(floorCell)).to.equal("cell-actors");
    });
});

//---------------------------------------------------------------------------
// ITEMS AND MAP CELLS
//--------------------------------------------------------------------------

describe('Items in map cells', function() {
    it('Is placed in a cell and needs an owner', function() {
        var cell = new Cell(0, 1, new Element("floor"));
        cell.setExplored();
        var item = new Item("food");
        cell.setProp("items", item);
        expect(cell.hasProp("items")).to.equal(true);

        var items = cell.getProp("items");
        expect(items.length).to.equal(1);

        expect(RG.getStyleClassForCell(cell)).to.equal("cell-items");

        // Item must have its owners x,y
        item.setOwner(cell);
        expect(item.getX()).to.equal(0);
        expect(item.getY()).to.equal(1);

    });

    it('Container can also be placed into the cell', function() {
        var cell = new Cell(1, 2, new Element("floor"));
        cell.setExplored();
        var container = new Container(cell);
        expect(container.getX()).to.equal(1);
        expect(container.getY()).to.equal(2);
        expect(container.isEmpty()).to.equal(true);
        expect(container.first()).to.equal(null);
        expect(container.next()).to.equal(null);

        // Test adding items.
        var food = new Item("food");
        var weapon = new Item("weapon");
        expect(food.getOwner()).to.equal(null);
        container.addItem(food);
        expect(food.getOwner()).to.equal(container);
        expect(container.isEmpty()).to.equal(false);
        expect(container.hasItem(food)).to.equal(true);
        expect(container.hasItem(weapon)).to.equal(false);
        expect(container.first()).to.equal(food);
        expect(container.next()).to.equal(null);

        // Add new weapon, then remove food
        container.addItem(weapon);
        expect(container.first()).to.equal(food);
        expect(container.next()).to.equal(weapon);

        expect(container.removeItem(food)).to.equal(true);
        expect(container.first()).to.equal(weapon);
        expect(container.removeItem(food)).to.equal(false);

        var cont2 = new Container(container);
        container.addItem(cont2);
        expect(cont2.getX()).to.equal(1);
        expect(cont2.getY()).to.equal(2);

    });

    it("Actor inventory has a container and equipped items", function() {
        var food = new Item("food");
        var sword = new Item("weapon");
        var actor = Factory.createPlayer("Player", 50);

        var invEq = new InvAndEquip(actor);
        invEq.addItem(food);
        expect(invEq.getInventory().getItems().length).to.equal(1);
        invEq.addItem(sword);
        expect(invEq.getInventory().getItems().length).to.equal(2);
        expect(invEq.equipItem(sword)).to.equal(true);
        expect(invEq.getInventory().getItems().length).to.equal(1);

        var handsEquipped = invEq.getEquipment().getEquipped("hand");
        expect(handsEquipped[0]).to.equal(sword);
        expect(invEq.unequipItem("hand", 0)).to.equal(true);

    });

    it('Picking up items from floor by actor', function() {
        var level = Factory.createLevel("arena", 20, 20);
        var actor = Factory.createPlayer("Player");
        var inv   = actor.getInvEq().getInventory();
        var weapon = new Item("weapon");
        expect(level.addItem(weapon, 2, 4)).to.equal(true);
        expect(level.addActor(actor, 2, 4)).to.equal(true);

        // After picking up, cell must not have item anymore
        var cell = level.getMap().getCell(2 ,4);
        expect(cell.hasProp("items")).to.equal(true);
        level.pickupItem(actor, 2, 4);
        expect(cell.hasProp("items")).to.equal(false);

        var invItems = inv.getItems();
        expect(invItems[0]).to.equal(weapon);
        expect(actor.getInvEq().equipItem(weapon)).to.equal(true);
        expect(inv.isEmpty()).to.equal(true);

    });

});

//---------------------------------------------------------------------------
// MAP UNIT TESTS
//---------------------------------------------------------------------------

describe('Tests to check that basic operations for map work', function() {
    var actor = new Actor("Player");
    actor.setIsPlayer(true);
    var level1 = Factory.createLevel("arena", 10, 10);
    var level2 = Factory.createLevel("arena", 20, 20);

    it('Is initialized as empty and having floors', function() {
        var map = level1.getMap();
        var map2 = level2.getMap();

        expect(map.hasXY(0,0)).to.equal(true);
        expect(map.hasXY(9,9)).to.equal(true);
        expect(map.hasXY(10,10)).to.equal(false);

        var freeCells = map.getFree();
        expect(freeCells.length).to.equal(8*8);
        for (var i = 0; i < freeCells.length; i++) {
            expect(freeCells[i].isFree()).to.equal(true);
            expect(freeCells[i].lightPasses()).to.equal(true);
        }

        var actorNotInLevel = new Actor("monster");
        actor.getFOVRange = function() {return 1;}; // Override default
        level1.addActor(actor, 4, 4);
        var cells = map.getVisibleCells(actor);
        expect(cells.length).to.equal(9);
        var zeroCells = map.getVisibleCells(actorNotInLevel);
        expect(zeroCells.length).to.equal(0);

        // After setting x,y try again
        actorNotInLevel.setXY(4,4);
        actorNotInLevel.getFOVRange = function() {return 5;}; // Override default
        zeroCells = map.getVisibleCells(actorNotInLevel);
        expect(zeroCells.length).to.equal(0);

        expect(level1.getMap().getCell(4,4).isExplored()).to.equal(false);
        level1.exploreCells(actor);
        expect(level1.getMap().getCell(4,4).isExplored()).to.equal(true);

    });
});

//---------------------------------------------------------------------------
// LEVEL UNIT TESTS
//---------------------------------------------------------------------------

describe('Moving actors around in the game', function() {
    it('Moves but is blocked by walls.', function() {
        var actor = new Actor(true);
        var level = new Level(10, 10);
        var mapgen = new RG.RogueMapGen();
        mapgen.setGen("arena", 10, 10);
        var map = mapgen.getMap();
        level.setMap(map);
        level.addActor(actor, 1, 2);
        expect(actor.getX()).to.equal(1);
        expect(actor.getY()).to.equal(2);

        // Actors x,y changes due to move
        expect(level.moveActorTo(actor, 2, 3)).to.equal(true);
        expect(actor.getX()).to.equal(2);
        expect(actor.getY()).to.equal(3);

        // Create a wall to block the passage
        var wall = new Element("wall");
        level.getMap().setBaseElemXY(4, 4, wall);
        expect(level.moveActorTo(actor, 4, 4)).to.equal(false);
        expect(actor.getX(), "X didn't change due to wall").to.equal(2);
        expect(actor.getY()).to.equal(3);

    });

    it('Moves actors between levels using stairs', function() {
        var level1 = Factory.createLevel("arena", 20, 20);
        var level2 = Factory.createLevel("arena", 20, 20);
        var player = Factory.createPlayer("Player");

        var stairs1 = new Stairs(true, level1, level2);
        var stairs2 = new Stairs(false, level2, level1);
        stairs1.setTargetStairs(stairs2);
        stairs2.setTargetStairs(stairs1);

        level1.addActor(player, 2, 2);
        expect(player.getLevel()).to.equal(level1);
        expect(level1.getMap().getCell(2,2).hasPropType("stairs")).to.equal(false);
        expect(level2.getMap().getCell(10,10).hasPropType("stairs")).to.equal(false);

        // Now add stairs and check they exist in the cells
        level1.addStairs(stairs1, 2, 2);
        level2.addStairs(stairs2, 10, 10);
        expect(level1.getMap().getCell(2,2).hasPropType("stairs")).to.equal(true);
        expect(level2.getMap().getCell(10,10).hasPropType("stairs")).to.equal(true);

        var refStairs1 = level1.getMap().getCell(2,2).getPropType("stairs")[0];
        expect(refStairs1).to.equal(stairs1);

        var refStairs2 = level2.getMap().getCell(10,10).getPropType("stairs")[0];
        expect(refStairs2).to.equal(stairs2);

        expect(player.getX()).to.equal(2);
        expect(player.getY()).to.equal(2);
        level1.useStairs(player);
        expect(player.getLevel()).to.equal(level2);
        expect(player.getX()).to.equal(10);
        expect(player.getY()).to.equal(10);

        // Return to prev level
        level2.useStairs(player);
        expect(player.getLevel()).to.equal(level1);
        expect(player.getX()).to.equal(2);
        expect(player.getY()).to.equal(2);
        level1.useStairs(player);

        // Check level with two stairs to different levels
        var level3 = Factory.createLevel("arena", 30, 30);
        var stairsDown23 = new Stairs(true, level2, level3);
        var stairsUp32 = new Stairs(false, level2, level3);
        level2.addStairs(stairsDown23, 12, 13);
        level3.addStairs(stairsUp32, 6, 7);
        stairsDown23.setTargetStairs(stairsUp32);
        stairsUp32.setTargetStairs(stairsDown23);

        level2.moveActorTo(player, 12, 13);
        level2.useStairs(player);
        expect(player.getLevel()).to.equal(level3);
        expect(player.getX()).to.equal(6);
        expect(player.getY()).to.equal(7);

    });
});

<|endoftext|>


<commit_before>var _ = require('lodash');
var assert = require("chai").assert;
var ObsRouter = require('../../../lib');
describe('browser window state binding', function(){
	//var router;
	before(function(){
		router = new ObsRouter({
			routes: {
				home: '/',
				a: '/a',
				b: '/b(/:x)',
				c: '/c/:x/c',
				notfound: '*path'
			},
			bindToWindow: true
		});
	});
	it('url should always match the current browser location', function(cb){
		var assertUrl = function(url){
			assert.strictEqual(url, router.url);
			assert.strictEqual(url, document.location.pathname+document.location.search);
		};
		assertUrl(router.url);
		console.log('router.url', router.url);
		var urls = ['/', '/a/sf', '/a', '/b/asf', '/c/c/c', '/c/c/c/c', '/?asd=asd'];
		_.forEach(urls, function(url){
			router.pushUrl(url);
			assertUrl(url);
		});
		var i = urls.length-1;
		var loop = function(){
			assertUrl(urls[i]);
			if (i-- == 0) {
				return cb()
			}
			window.history.go(-1);
			assertUrl(router.url); //not updated yet but make sure router.url is consistent with document location
			//allow 250 ms for this to register
			setTimeout(loop, 250);
		};
		loop();
	})
});<commit_msg>tweak<commit_after>var _ = require('lodash');
var assert = require("chai").assert;
var ObsRouter = require('../../../lib');
describe('browser window state binding', function(){
	//var router;
	before(function(){
		router = new ObsRouter({
			routes: {
				home: '/',
				a: '/a',
				b: '/b(/:x)',
				c: '/c/:x/c',
				notfound: '*path'
			},
			bindToWindow: true
		});
	});
	it('url should always match the current browser location', function(cb){
		var assertUrl = function(url){
			assert.strictEqual(url, router.url);
			assert.strictEqual(url, document.location.pathname+document.location.search);
		};
		assertUrl(router.url);
		var urls = ['/', '/a/sf', '/a', '/b/asf', '/c/c/c', '/c/c/c/c', '/?asd=asd'];
		_.forEach(urls, function(url){
			router.pushUrl(url);
			assertUrl(url);
		});
		var i = urls.length-1;
		var loop = function(){
			assertUrl(urls[i]);
			if (i-- == 0) {
				return cb()
			}
			window.history.go(-1);
			assertUrl(router.url); //not updated yet but make sure router.url is consistent with document location
			//allow 250 ms for this to register
			setTimeout(loop, 250);
		};
		loop();
	})
});<|endoftext|>


<commit_before>/**
 * The Core module provides the Editable singleton that defines the Editable.JS
 * API and is the main entry point for Editable.JS.
 * It also provides the cursor module for cross-browser cursors, and the dom
 * submodule.
 *
 * @module core
 */

(function() {
  var isInitialized = false;

  var initialize = function() {
    if (!isInitialized) {
      // TODO check config file integrity

      // make sure rangy is initialized. e.g Rangy doesn't initialize
      // when loaded after the document is ready.
      if (!rangy.initialized) {
        rangy.init();
      }

      isInitialized = true;
      dispatcher.setup();
    }
  };

  /**
   * Singleton for the Editable.JS API that is externally visible.
   * Note that the Editable literal is defined
   * first in editable.prefix in order for it to be the only externally visible
   * variable.
   *
   * @class Editable
   * @static
   */
  Editable = {
    /**
     * Initialzed Editable with a custom configuration
     */
    init: function(userConfiguration) {
      if (isInitialized) {
        error('Editable is already initialized');
        return;
      }

      $.extend(true, config, userConfiguration);
      initialize();
    },

    /**
     * Adds the Editable.JS API to the given target elements.
     * Opposite of {{#crossLink "Editable/remove"}}{{/crossLink}}.
     * Calls dispatcher.setup to setup all event listeners.
     *
     * @method add
     * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
     *    array of HTMLElement or a query selector representing the target where
     *    the API should be added on.
     * @param {Object} [elementConfiguration={}] Configuration options override.
     * @static
     * @chainable
     */
    add: function(target, elementConfiguration) {
      initialize();
      var elemConfig = $.extend(true, {}, config, elementConfiguration);
      // todo: store element configuration

      if (!this.isDisabled) {
        this.enable( $(target) )
      } else {
        this.disable( $(target) )
      }

      // todo: check css whitespace settings
      return this;
    },

    /**
     * Removes the Editable.JS API from the given target elements.
     * Opposite of {{#crossLink "Editable/add"}}{{/crossLink}}.
     *
     * @method remove
     * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
     *    array of HTMLElement or a query selector representing the target where
     *    the API should be removed from.
     * @static
     * @chainable
     */
    remove: function(target) {
      $target = $(target)
      this.disable($target)
      $target.removeClass(config.editableDisabledClass);
      return this;
    },

    isDisabled: false,

    disable: function($elem) {
      this.isDisabled = true;
      $elem = $elem || $('.' + config.editableClass)
      $elem
        .removeAttr('contenteditable')
        .removeClass(config.editableClass)
        .addClass(config.editableDisabledClass);
    },

    enable: function($elem) {
      this.isDisabled = false;
      $elem = $elem || $('.' + config.editableDisabledClass)
      $elem
        .attr('contenteditable', true)
        .removeClass(config.editableDisabledClass)
        .addClass(config.editableClass);
    },

    /**
     * Subscribe a callback function to a custom event fired by the API.
     * Opposite of {{#crossLink "Editable/off"}}{{/crossLink}}.
     *
     * @method on
     * @param {String} event The name of the event.
     * @param {Function} handler The callback to execute in response to the
     *     event.
     * @static
     * @chainable
     */
    on: function(event, handler) {
      initialize();
      // TODO throw error if event is not one of EVENTS
      // TODO throw error if handler is not a function
      dispatcher.addListener(event, handler);
      return this;
    },

    /**
     * Unsubscribe a callback function from a custom event fired by the API.
     * Opposite of {{#crossLink "Editable/on"}}{{/crossLink}}.
     *
     * @method off
     * @param {String} event The name of the event.
     * @param {Function|Boolean} handler The callback to remove from the
     *     event or the special value false to remove all callbacks.
     * @static
     * @chainable
     */
    off: function(event, handler) {
      // TODO throw error if event is not one of EVENTS
      // TODO if handler is flase remove all callbacks
      dispatcher.removeListener(event, handler);
      return this;
    },

    /**
     * Subscribe to the {{#crossLink "Editable/focus:event"}}{{/crossLink}}
     * event.
     *
     * @method focus
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    focus: function(handler) {
      return this.on('focus', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/blur:event"}}{{/crossLink}}
     * event.
     *
     * @method blur
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    blur: function(handler) {
      return this.on('blur', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/flow:event"}}{{/crossLink}}
     * event.
     *
     * @method flow
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    flow: function(handler) {
      return this.on('flow', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/selection:event"}}{{/crossLink}}
     * event.
     *
     * @method selection
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    selection: function(handler) {
      return this.on('selection', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/cursor:event"}}{{/crossLink}}
     * event.
     *
     * @method cursor
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    cursor: function(handler) {
      return this.on('cursor', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/newline:event"}}{{/crossLink}}
     * event.
     *
     * @method newline
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    newline: function(handler) {
      return this.on('newline', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/insert:event"}}{{/crossLink}}
     * event.
     *
     * @method insert
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    insert: function(handler) {
      return this.on('insert', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/split:event"}}{{/crossLink}}
     * event.
     *
     * @method split
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    split: function(handler) {
      return this.on('split', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/merge:event"}}{{/crossLink}}
     * event.
     *
     * @method merge
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    merge: function(handler) {
      return this.on('merge', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/empty:event"}}{{/crossLink}}
     * event.
     *
     * @method empty
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    empty: function(handler) {
      return this.on('empty', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/switch:event"}}{{/crossLink}}
     * event.
     *
     * @method switch
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    'switch': function(handler) {
      return this.on('switch', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/move:event"}}{{/crossLink}}
     * event.
     *
     * @method move
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    move: function(handler) {
      return this.on('move', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/clipboard:event"}}{{/crossLink}}
     * event.
     *
     * @method clipboard
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    clipboard: function(handler) {
      return this.on('clipboard', handler);
    }
  };
})();
<commit_msg>Remove Editable.isDisabled<commit_after>/**
 * The Core module provides the Editable singleton that defines the Editable.JS
 * API and is the main entry point for Editable.JS.
 * It also provides the cursor module for cross-browser cursors, and the dom
 * submodule.
 *
 * @module core
 */

(function() {
  var isInitialized = false;

  var initialize = function() {
    if (!isInitialized) {
      // TODO check config file integrity

      // make sure rangy is initialized. e.g Rangy doesn't initialize
      // when loaded after the document is ready.
      if (!rangy.initialized) {
        rangy.init();
      }

      isInitialized = true;
      dispatcher.setup();
    }
  };

  /**
   * Singleton for the Editable.JS API that is externally visible.
   * Note that the Editable literal is defined
   * first in editable.prefix in order for it to be the only externally visible
   * variable.
   *
   * @class Editable
   * @static
   */
  Editable = {
    /**
     * Initialzed Editable with a custom configuration
     */
    init: function(userConfiguration) {
      if (isInitialized) {
        error('Editable is already initialized');
        return;
      }

      $.extend(true, config, userConfiguration);
      initialize();
    },

    /**
     * Adds the Editable.JS API to the given target elements.
     * Opposite of {{#crossLink "Editable/remove"}}{{/crossLink}}.
     * Calls dispatcher.setup to setup all event listeners.
     *
     * @method add
     * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
     *    array of HTMLElement or a query selector representing the target where
     *    the API should be added on.
     * @param {Object} [elementConfiguration={}] Configuration options override.
     * @static
     * @chainable
     */
    add: function(target, elementConfiguration) {
      initialize();
      var elemConfig = $.extend(true, {}, config, elementConfiguration);
      // todo: store element configuration
      this.enable( $(target) )

      // todo: check css whitespace settings
      return this;
    },

    /**
     * Removes the Editable.JS API from the given target elements.
     * Opposite of {{#crossLink "Editable/add"}}{{/crossLink}}.
     *
     * @method remove
     * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
     *    array of HTMLElement or a query selector representing the target where
     *    the API should be removed from.
     * @static
     * @chainable
     */
    remove: function(target) {
      $target = $(target)
      this.disable($target)
      $target.removeClass(config.editableDisabledClass);
      return this;
    },

    disable: function($elem) {
      $elem = $elem || $('.' + config.editableClass)
      $elem
        .removeAttr('contenteditable')
        .removeClass(config.editableClass)
        .addClass(config.editableDisabledClass);
    },

    enable: function($elem) {
      $elem = $elem || $('.' + config.editableDisabledClass)
      $elem
        .attr('contenteditable', true)
        .removeClass(config.editableDisabledClass)
        .addClass(config.editableClass);
    },

    /**
     * Subscribe a callback function to a custom event fired by the API.
     * Opposite of {{#crossLink "Editable/off"}}{{/crossLink}}.
     *
     * @method on
     * @param {String} event The name of the event.
     * @param {Function} handler The callback to execute in response to the
     *     event.
     * @static
     * @chainable
     */
    on: function(event, handler) {
      initialize();
      // TODO throw error if event is not one of EVENTS
      // TODO throw error if handler is not a function
      dispatcher.addListener(event, handler);
      return this;
    },

    /**
     * Unsubscribe a callback function from a custom event fired by the API.
     * Opposite of {{#crossLink "Editable/on"}}{{/crossLink}}.
     *
     * @method off
     * @param {String} event The name of the event.
     * @param {Function|Boolean} handler The callback to remove from the
     *     event or the special value false to remove all callbacks.
     * @static
     * @chainable
     */
    off: function(event, handler) {
      // TODO throw error if event is not one of EVENTS
      // TODO if handler is flase remove all callbacks
      dispatcher.removeListener(event, handler);
      return this;
    },

    /**
     * Subscribe to the {{#crossLink "Editable/focus:event"}}{{/crossLink}}
     * event.
     *
     * @method focus
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    focus: function(handler) {
      return this.on('focus', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/blur:event"}}{{/crossLink}}
     * event.
     *
     * @method blur
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    blur: function(handler) {
      return this.on('blur', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/flow:event"}}{{/crossLink}}
     * event.
     *
     * @method flow
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    flow: function(handler) {
      return this.on('flow', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/selection:event"}}{{/crossLink}}
     * event.
     *
     * @method selection
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    selection: function(handler) {
      return this.on('selection', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/cursor:event"}}{{/crossLink}}
     * event.
     *
     * @method cursor
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    cursor: function(handler) {
      return this.on('cursor', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/newline:event"}}{{/crossLink}}
     * event.
     *
     * @method newline
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    newline: function(handler) {
      return this.on('newline', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/insert:event"}}{{/crossLink}}
     * event.
     *
     * @method insert
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    insert: function(handler) {
      return this.on('insert', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/split:event"}}{{/crossLink}}
     * event.
     *
     * @method split
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    split: function(handler) {
      return this.on('split', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/merge:event"}}{{/crossLink}}
     * event.
     *
     * @method merge
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    merge: function(handler) {
      return this.on('merge', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/empty:event"}}{{/crossLink}}
     * event.
     *
     * @method empty
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    empty: function(handler) {
      return this.on('empty', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/switch:event"}}{{/crossLink}}
     * event.
     *
     * @method switch
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    'switch': function(handler) {
      return this.on('switch', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/move:event"}}{{/crossLink}}
     * event.
     *
     * @method move
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    move: function(handler) {
      return this.on('move', handler);
    },

    /**
     * Subscribe to the {{#crossLink "Editable/clipboard:event"}}{{/crossLink}}
     * event.
     *
     * @method clipboard
     * @param {Function} handler The callback to execute in response to the
     *   event.
     * @static
     * @chainable
     */
    clipboard: function(handler) {
      return this.on('clipboard', handler);
    }
  };
})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const packageJson = require('../package.json');
const tools = require('../lib/tools');
const colors = require('colors');
const Applesign = require('../');
const conf = require('minimist')(process.argv.slice(2), {
  string: [
    'i', 'identity',
    'O', 'osversion'
  ],
  boolean: [
    '7', 'use-7zip',
    'a', 'all',
    'A', 'all-dirs',
    'B', 'bundleid-access-group',
    'c', 'clone-entitlements',
    'E', 'entry-entitlement',
    'f', 'force-family',
    'f', 'force-family',
    'H', 'allow-http',
    'L', 'identities',
    'M', 'massage-entitlements',
    'n', 'noclean',
    'p', 'parallel',
    'A', 'parallel',
    'r', 'replace',
    'S', 'self-signed-provision',
    's', 'single',
    't', 'without-get-task-allow',
    'u', 'unfair',
    'u', 'unsigned-provision',
    'V', 'dont-verify',
    'v', 'verify-twice',
    'w', 'without-watchapp',
    'z', 'ignore-zip-errors'
  ]
});

const options = {
  all: conf.a || conf.all || false,
  allDirs: conf['all-dirs'] || conf.A,
  allowHttp: conf['allow-http'] || conf.H,
  bundleIdKeychainGroup: conf.B || conf['bundleid-access-group'],
  bundleid: conf.bundleid || conf.b,
  cloneEntitlements: conf.c || conf['clone-entitlements'],
  customKeychainGroup: conf.K || conf['add-access-group'],
  dontVerify: conf['dont-verify'] || conf.V,
  entitlement: conf.entitlement || conf.e,
  entry: conf['entry-entitlement'] || conf.E,
  file: conf._[0] || 'undefined',
  forceFamily: conf['force-family'] || conf.f,
  withGetTaskAllow: !(conf['without-get-task-allow'] || conf.t),
  identity: conf.identity || conf.i,
  ignoreZipErrors: conf.z || conf['ignore-zip-errors'],
  insertLibrary: conf.I || conf.insert,
  keychain: conf.keychain || conf.k,
  lipoArch: conf.lipo || conf.l,
  massageEntitlements: conf['massage-entitlements'] || conf.M,
  mobileprovision: conf.mobileprovision || conf.m,
  noclean: conf.n || conf.noclean,
  osversion: conf.osversion || conf.O,
  outfile: conf.output || conf.o,
  parallel: conf.parallel || conf.p,
  replaceipa: conf.replace || conf.r,
  selfSignedProvision: conf.S || conf['self-signed-provision'],
  single: conf.single || conf.s,
  unfairPlay: conf.unfair || conf.u,
  use7zip: conf['7'] || conf['use-7zip'],
  useOpenSSL: conf['use-openssl'],
  verifyTwice: conf.verifyTwice || !!conf.v,
  withoutWatchapp: !!conf['without-watchapp'] || !!conf.w
};

colors.setTheme({
  error: 'red',
  msg: 'yellow',
  warning: 'green'
});

new Applesign(options, (err, instance) => {
  if (conf.identities || conf.L) {
    instance.getIdentities((err, ids) => {
      if (err) {
        console.error(colors.error(err));
      } else {
        ids.forEach((id) => {
          console.log(id.hash, id.name);
        });
      }
    });
  } else if (conf.version) {
    console.log(packageJson.version);
  } else if (conf.h || conf.help || conf._.length === 0) {
    console.error(usageMessage);
  } else {
    if (options.insertLibrary !== undefined) {
      if (err && err.toString().indexOf('dylib_insert') !== -1) {
        console.error(err);
      }
    }
    const target = getTargetMethod(options.file, (conf.s || conf.single));
    if (target === undefined) {
      console.error('Cannot open file');
      process.exitCode = 1;
    } else {
      const session = instance[target](options.file, (error, data) => {
        if (error) {
          console.error(error, data);
          process.exitCode = 1;
        } else {
          console.log('Target is now signed:', session.config.outfile || options.file);
        }
      }).on('message', (msg) => {
        console.log(colors.msg(msg));
      }).on('warning', (msg) => {
        console.error(colors.warning('warning'), msg);
      }).on('error', (msg) => {
        console.error(colors.msg(msg));
      });
    }
  }
});

function getTargetMethod (file, single) {
  try {
    if (tools.isDirectory(file)) {
      return 'signDirectory';
    }
    return (single) ? 'signFile' : 'signIPA';
  } catch (e) {
    return undefined;
  }
}

const usageMessage = `Usage:

  applesign [--options ...] [input-ipafile]

  -7, --use-7zip                Use 7zip instead of unzip
      --use-openssl             Use OpenSSL cms instead of Apple's security tool
  -a, --all                     Resign all binaries, even it unrelated to the app
  -A, --all-dirs                Archive all directories, not just Payload/
  -b, --bundleid [BUNDLEID]     Change the bundleid when repackaging
  -B, --bundleid-access-group   Add $(TeamIdentifier).bundleid to keychain-access-groups
  -c, --clone-entitlements      Clone the entitlements from the provisioning to the bin
  -e, --entitlements [ENTITL]   Specify entitlements file (EXPERIMENTAL)
  -E, --entry-entitlement       Use generic entitlement (EXPERIMENTAL)
  -f, --force-family            Force UIDeviceFamily in Info.plist to be iPhone
  -h, --help                    Show this help message
  -H, --allow-http              Add NSAppTransportSecurity.NSAllowsArbitraryLoads in plist
  -i, --identity [1C4D1A..]     Specify hash-id of the identity to use
  -I, --insert [frida.dylib]    Insert a dynamic library to the main executable
  -k, --keychain [KEYCHAIN]     Specify alternative keychain file
  -K, --add-access-group [NAME] Add $(TeamIdentifier).NAME to keychain-access-groups
  -l, --lipo [arm64|armv7]      Lipo -thin all bins inside the IPA for the given architecture
  -L, --identities              List local codesign identities
  -m, --mobileprovision [FILE]  Specify the mobileprovision file to use
  -M, --massage-entitlements    Massage entitlements to remove privileged ones
  -n, --noclean                 keep temporary files when signing error happens
  -o, --output [APP.IPA]        Path to the output IPA filename
  -O, --osversion 9.0           Force specific OSVersion if any in Info.plist
  -p, --parallel                Run layered signing dependencies in parallel
  -r, --replace                 Replace the input IPA file with the resigned one
  -s, --single                  Sign a single file instead of an IPA
  -S, --self-sign-provision     Self-sign mobile provisioning (EXPERIMENTAL)
  -t, --without-get-task-allow  Do not set the get-task-allow entitlement (EXPERIMENTAL)
  -u, --unfair                  Resign encrypted applications
  -v, --verify-twice            Verify after signing every file and at the end
  -V, --dont-verify             Do not perform any codesign verification
  -w, --without-watchapp        Remove the WatchApp from the IPA before resigning
      --version                 Show applesign version
  -z, --ignore-zip-errors       Ignore unzip/7z uncompressing errors
  [input-ipafile]               Path to the IPA file to resign

Examples:

  applesign -L # enumerate codesign identities, grab one and use it with -i
  applesign -m embedded.mobileprovision test-app.ipa
  applesign -i AD71EB42BC289A2B9FD3C2D5C9F02D923495A23C test-app.ipa
  applesign -i AD71EB4... -c --lipo arm64 -w -V test-app.ipa
`;
<commit_msg>Change the default behaviour of -v and -V, do not verify by default.<commit_after>#!/usr/bin/env node
'use strict';

const packageJson = require('../package.json');
const tools = require('../lib/tools');
const colors = require('colors');
const Applesign = require('../');
const conf = require('minimist')(process.argv.slice(2), {
  string: [
    'i', 'identity',
    'O', 'osversion'
  ],
  boolean: [
    '7', 'use-7zip',
    'a', 'all',
    'A', 'all-dirs',
    'B', 'bundleid-access-group',
    'c', 'clone-entitlements',
    'E', 'entry-entitlement',
    'f', 'force-family',
    'f', 'force-family',
    'H', 'allow-http',
    'L', 'identities',
    'M', 'massage-entitlements',
    'n', 'noclean',
    'p', 'parallel',
    'A', 'parallel',
    'r', 'replace',
    'S', 'self-signed-provision',
    's', 'single',
    't', 'without-get-task-allow',
    'u', 'unfair',
    'u', 'unsigned-provision',
    'v', 'verify',
    'V', 'verify-twice',
    'w', 'without-watchapp',
    'z', 'ignore-zip-errors'
  ]
});

const options = {
  all: conf.a || conf.all || false,
  allDirs: conf['all-dirs'] || conf.A,
  allowHttp: conf['allow-http'] || conf.H,
  bundleIdKeychainGroup: conf.B || conf['bundleid-access-group'],
  bundleid: conf.bundleid || conf.b,
  cloneEntitlements: conf.c || conf['clone-entitlements'],
  customKeychainGroup: conf.K || conf['add-access-group'],
  dontVerify: !conf.v && !conf.V && !conf.verify && !conf['verify-twice'],
  entitlement: conf.entitlement || conf.e,
  entry: conf['entry-entitlement'] || conf.E,
  file: conf._[0] || 'undefined',
  forceFamily: conf['force-family'] || conf.f,
  withGetTaskAllow: !(conf['without-get-task-allow'] || conf.t),
  identity: conf.identity || conf.i,
  ignoreZipErrors: conf.z || conf['ignore-zip-errors'],
  insertLibrary: conf.I || conf.insert,
  keychain: conf.keychain || conf.k,
  lipoArch: conf.lipo || conf.l,
  massageEntitlements: conf['massage-entitlements'] || conf.M,
  mobileprovision: conf.mobileprovision || conf.m,
  noclean: conf.n || conf.noclean,
  osversion: conf.osversion || conf.O,
  outfile: conf.output || conf.o,
  parallel: conf.parallel || conf.p,
  replaceipa: conf.replace || conf.r,
  selfSignedProvision: conf.S || conf['self-signed-provision'],
  single: conf.single || conf.s,
  unfairPlay: conf.unfair || conf.u,
  use7zip: conf['7'] || conf['use-7zip'],
  useOpenSSL: conf['use-openssl'],
  verifyTwice: conf.V || conf['verify-twice'],
  withoutWatchapp: !!conf['without-watchapp'] || !!conf.w
};

colors.setTheme({
  error: 'red',
  msg: 'yellow',
  warning: 'green'
});

new Applesign(options, (err, instance) => {
  if (conf.identities || conf.L) {
    instance.getIdentities((err, ids) => {
      if (err) {
        console.error(colors.error(err));
      } else {
        ids.forEach((id) => {
          console.log(id.hash, id.name);
        });
      }
    });
  } else if (conf.version) {
    console.log(packageJson.version);
  } else if (conf.h || conf.help || conf._.length === 0) {
    console.error(usageMessage);
  } else {
    if (options.insertLibrary !== undefined) {
      if (err && err.toString().indexOf('dylib_insert') !== -1) {
        console.error(err);
      }
    }
    const target = getTargetMethod(options.file, (conf.s || conf.single));
    if (target === undefined) {
      console.error('Cannot open file');
      process.exitCode = 1;
    } else {
      const session = instance[target](options.file, (error, data) => {
        if (error) {
          console.error(error, data);
          process.exitCode = 1;
        } else {
          console.log('Target is now signed:', session.config.outfile || options.file);
        }
      }).on('message', (msg) => {
        console.log(colors.msg(msg));
      }).on('warning', (msg) => {
        console.error(colors.warning('warning'), msg);
      }).on('error', (msg) => {
        console.error(colors.msg(msg));
      });
    }
  }
});

function getTargetMethod (file, single) {
  try {
    if (tools.isDirectory(file)) {
      return 'signDirectory';
    }
    return (single) ? 'signFile' : 'signIPA';
  } catch (e) {
    return undefined;
  }
}

const usageMessage = `Usage:

  applesign [--options ...] [input-ipafile]

  -7, --use-7zip                Use 7zip instead of unzip
      --use-openssl             Use OpenSSL cms instead of Apple's security tool
  -a, --all                     Resign all binaries, even it unrelated to the app
  -A, --all-dirs                Archive all directories, not just Payload/
  -b, --bundleid [BUNDLEID]     Change the bundleid when repackaging
  -B, --bundleid-access-group   Add $(TeamIdentifier).bundleid to keychain-access-groups
  -c, --clone-entitlements      Clone the entitlements from the provisioning to the bin
  -e, --entitlements [ENTITL]   Specify entitlements file (EXPERIMENTAL)
  -E, --entry-entitlement       Use generic entitlement (EXPERIMENTAL)
  -f, --force-family            Force UIDeviceFamily in Info.plist to be iPhone
  -h, --help                    Show this help message
  -H, --allow-http              Add NSAppTransportSecurity.NSAllowsArbitraryLoads in plist
  -i, --identity [1C4D1A..]     Specify hash-id of the identity to use
  -I, --insert [frida.dylib]    Insert a dynamic library to the main executable
  -k, --keychain [KEYCHAIN]     Specify alternative keychain file
  -K, --add-access-group [NAME] Add $(TeamIdentifier).NAME to keychain-access-groups
  -l, --lipo [arm64|armv7]      Lipo -thin all bins inside the IPA for the given architecture
  -L, --identities              List local codesign identities
  -m, --mobileprovision [FILE]  Specify the mobileprovision file to use
  -M, --massage-entitlements    Massage entitlements to remove privileged ones
  -n, --noclean                 keep temporary files when signing error happens
  -o, --output [APP.IPA]        Path to the output IPA filename
  -O, --osversion 9.0           Force specific OSVersion if any in Info.plist
  -p, --parallel                Run layered signing dependencies in parallel
  -r, --replace                 Replace the input IPA file with the resigned one
  -s, --single                  Sign a single file instead of an IPA
  -S, --self-sign-provision     Self-sign mobile provisioning (EXPERIMENTAL)
  -t, --without-get-task-allow  Do not set the get-task-allow entitlement (EXPERIMENTAL)
  -u, --unfair                  Resign encrypted applications
  -v, --verify                  Verify all the signed files at the end
  -V, --verify-twice            Verify after signing every file and at the end
  -w, --without-watchapp        Remove the WatchApp from the IPA before resigning
      --version                 Show applesign version
  -z, --ignore-zip-errors       Ignore unzip/7z uncompressing errors
  [input-ipafile]               Path to the IPA file to resign

Examples:

  applesign -L # enumerate codesign identities, grab one and use it with -i
  applesign -m embedded.mobileprovision test-app.ipa
  applesign -i AD71EB42BC289A2B9FD3C2D5C9F02D923495A23C test-app.ipa
  applesign -i AD71EB4... -c --lipo arm64 -w -V test-app.ipa
`;
<|endoftext|>


<commit_before>exports.excelFileParser = function(fileName, tabName, metadataFields){
    var assert = require('assert');
    console.log(metadataFields);
    if(typeof require !== 'undefined') XLSX = require('xlsx');

    var mongodb = require('mongodb');
    var _ = require('underscore');

    var fs = require('fs');

    var Converter=require("csvtojson").core.Converter;

    var  distinctDataFields;

    var collectionFields = [];

    var MongoClient = mongodb.MongoClient;

    var url = 'mongodb://localhost:27017/datamanager-03-test';

    var workbook = XLSX.readFile('./uploads/' + fileName);

    var worksheet = workbook.Sheets[tabName];

    var metaFields = metadataFields;

    var json_conversion = XLSX.utils.sheet_to_json(worksheet);

    var csv_conversion = XLSX.utils.sheet_to_csv(worksheet);

    var csv_lines = csv_conversion.split('\n');

    var dirtyHeaderLine = csv_lines[0];

    var cleanHeaderLine = dirtyHeaderLine.replace(/\./g,"")
        .replace(/ /g,"")
        .replace(/"'"/g,"")
        .replace(/","/g,"")
        .replace(/"\/"/g,"")
        .replace(/"#"/g,"")
        .replace(/\(/g,"")
        .replace(/\)/g,"");

    cleanHeaderLine = cleanHeaderLine.replace(/,+$/, "");

    console.log(cleanHeaderLine);

    csv_lines[0] = cleanHeaderLine;

    var newCsvLines = [];

    csv_lines.forEach(function(line){
        if (line.charAt(0) == ',') { line = line.slice(1); }
        var currentIndex = csv_lines.indexOf(line);
        if(currentIndex === 0){
            newCsvLines.push(line);
        }
        else {
            newCsvLines.push("\n" + line);
        }
    });

    var csvFileName = './uploads/' + fileName + '_clean.csv';

    fs.writeFileSync(csvFileName, newCsvLines);

    var fileStream=fs.createReadStream(csvFileName);
//new converter instance
    var csvConverter=new Converter({constructResult:true});

    //end_parsed will be emitted once parsing finished
    csvConverter.on("end_parsed",function(jsonObj){
        //console.log(jsonObj); //here is your result json object
        var p = 0;
        makeRecords(jsonObj);

    });

    //read from file
    fileStream.pipe(csvConverter);

    function makeRecords(result){
        console.log(result.length);

        MongoClient.connect(url, function (err, db) {
            if (err) {
                console.log('Unable to connect to the mongoDB server. Error:', err);
            } else {
                console.log('Connection established to', url);

                var categoryName = metaFields.subjectCategory;

                var collectionName = categoryName.replace(/ /g,"_");

                db.open(function(err, client){
                    if(err){
                        console.log(err);
                    }
                    try {
                        client.createCollection(collectionName, function (err, col) {
                        });

                        var collection = db.collection(collectionName);

                        if(metaFields.subjectCategory === 'SalesforceData'){
                            //Here we will use the upsert logic to either insert new, or update existing records

                            for (var i = 0; i < result.length; i++) {
                                //console.log(result[i]);

                                var inserted = 0;

                                for (var i = 0; i < result.length; i++) {
                                    var dataRecord = result[i];

                                    dataRecord.OriginalDocumentName = fileName;
                                    dataRecord.DocumentAuthor = metaFields.documentAuthor;
                                    dataRecord.TabName = tabName;
                                    dataRecord.SubjectCategory = metaFields.subjectCategory;
                                    dataRecord.Subject = metaFields.subject;
                                    dataRecord.DateDocumentProduced = metaFields.dateDocumentProduced;
                                    dataRecord.DateDocumentReceived = metaFields.dateDocumentReceived;
                                    dataRecord.DocumentSubmitter = metaFields.documentSubmitter;
                                    dataRecord.DocumentReviewer = metaFields.documentReviewer;
                                    dataRecord.OriginalSource = metadataFields.originalSource,
                                        dataRecord.DataVersion = metadataFields.dataVersion,
                                        dataRecord.DataFields = newCsvLines[0];

                                    collection.update(
                                    {
                                        CSCOpportunityId: dataRecord.CSCOpportunityID
                                    },
                                        {
                                            $set: {

                                                OriginalDocumentName:   dataRecord.OriginalDocumentName,
                                                DocumentAuthor: dataRecord.DocumentAuthor,
                                                TabName:    dataRecord.TabName,
                                                SubjectCategory:    dataRecord.SubjectCategory,
                                                Subject:    dataRecord.Subject,
                                                DateDocumentProduced:   dataRecord.DateDocumentProduced,
                                                DateDocumentReceived:   dataRecord.DateDocumentReceived,
                                                DocumentSubmitter:  dataRecord.DocumentSubmitter,
                                                DocumentReviewer:   dataRecord.DocumentReviewer,
                                                OriginalSource: dataRecord.OriginalSource,
                                                DataVersion:    dataRecord.DataVersion,
                                                DataFields: dataRecord.DataFields,

                                                CSCOpportunityID : dataRecord.CSCOpportunityID,
                                                OpportunityName: dataRecord.OpportunityName ,
                                                AccountName : dataRecord.AccountName,
                                                OpportunityOwner : dataRecord.OpportunityOwner,
                                                Stage : dataRecord.Stage,
                                                Industry : dataRecord.Industry,
                                                ACV : dataRecord.ACV,
                                                RevenueStartDate : dataRecord.RevenueStartDate,
                                                RevenueTerm : dataRecord.RevenueTerm,
                                                ProbabilityPct : dataRecord.ProbabilityPct,
                                                DealRegion : dataRecord.DealRegion
                                            }
                                        },
                                        {upsert: true}

                                        //if (++inserted == result.length) {
                                        //    console.log("finished");
                                        //    //db.close();
                                        //}
                                    );
                                }
                            }
                        }
                        else {
                            for (var i = 0; i < result.length; i++) {
                                //console.log(result[i]);

                                var inserted = 0;

                                for (var i = 0; i < result.length; i++) {
                                    var dataRecord = result[i];

                                    dataRecord.OriginalDocumentName = fileName;
                                    dataRecord.DocumentAuthor = metaFields.documentAuthor;
                                    dataRecord.TabName = tabName;
                                    dataRecord.SubjectCategory = metaFields.subjectCategory;
                                    dataRecord.Subject = metaFields.subject;
                                    dataRecord.DateDocumentProduced = metaFields.dateDocumentProduced;
                                    dataRecord.DateDocumentReceived = metaFields.dateDocumentReceived;
                                    dataRecord.DocumentSubmitter = metaFields.documentSubmitter;
                                    dataRecord.DocumentReviewer = metaFields.documentReviewer;
                                    dataRecord.OriginalSource = metadataFields.originalSource,
                                        dataRecord.DataVersion = metadataFields.dataVersion,
                                        dataRecord.DataFields = newCsvLines[0];

                                    collection.insert(dataRecord, function (err) {
                                        if (++inserted == result.length) {
                                            console.log("finished");
                                            //db.close();
                                        }
                                    });
                                }
                            }

                        }
                    }
                    catch (err) {'excel parser - main record making Error:  ' +  err}
                });

                db.open(function(err, client) {
                    var dataFields = [];
                    var dataVersions = [];

                        client.collection(collectionName).distinct("DataFields", (function (err, docs) {
                            if(err){
                                console.log(err);
                            }
                            try {
                                console.log('DataFields:  ' + docs);
                                var commaIndex = docs[0].indexOf(",");
                                if (commaIndex !== -1) {
                                    dataFields = docs[0].split(',')
                                }
                                else {
                                    dataFields.push(docs);
                                }

                                client.collection('collections_metadata').update(
                                    {
                                        collectionName: collectionName
                                    },
                                    {
                                        $set: {
                                            dataFields: dataFields

                                        }
                                    }
                                    ,
                                    {upsert: true}
                                )
                            }
                            catch (err) {console.log('excel parser - DataFields assignment Error:  ' +  err)}
                        }));

                        client.collection(collectionName).distinct("DataVersion", (function (err, docs) {
                            if(err){
                                console.log(err);
                            }
                            try {
                                console.log('DataVersion:  ' + docs);
                                var commaIndex = docs.indexOf(",");
                                if (commaIndex !== -1) {
                                    dataVersions = docs.split(',')
                                }
                                else {
                                    dataVersions = docs;
                                }
                                client.collection('collections_metadata').update(
                                    {
                                        collectionName: collectionName
                                    },
                                    {
                                        $set: {
                                            dataVersions: dataVersions
                                        }
                                    }
                                    ,
                                    {upsert: true}
                                )
                            }
                            catch (err) {'excel parser - DataVersion asignment Error:  ' +  err}
                        }));
                });
            }
        });
    }
};
<commit_msg>we can now update existing salesforce records as well as insert new ones<commit_after>exports.excelFileParser = function(fileName, tabName, metadataFields){
    var assert = require('assert');
    console.log(metadataFields);
    if(typeof require !== 'undefined') XLSX = require('xlsx');

    var mongodb = require('mongodb');
    var _ = require('underscore');

    var fs = require('fs');

    var Converter=require("csvtojson").core.Converter;

    var  distinctDataFields;

    var collectionFields = [];

    var MongoClient = mongodb.MongoClient;

    var url = 'mongodb://localhost:27017/datamanager-03-test';

    var workbook = XLSX.readFile('./uploads/' + fileName);

    var worksheet = workbook.Sheets[tabName];

    var metaFields = metadataFields;

    var json_conversion = XLSX.utils.sheet_to_json(worksheet);

    var csv_conversion = XLSX.utils.sheet_to_csv(worksheet);

    var csv_lines = csv_conversion.split('\n');

    var dirtyHeaderLine = csv_lines[0];

    var cleanHeaderLine = dirtyHeaderLine.replace(/\./g,"")
        .replace(/ /g,"")
        .replace(/"'"/g,"")
        .replace(/","/g,"")
        .replace(/"\/"/g,"")
        .replace(/"#"/g,"")
        .replace(/\(/g,"")
        .replace(/\)/g,"");

    cleanHeaderLine = cleanHeaderLine.replace(/,+$/, "");

    console.log(cleanHeaderLine);

    csv_lines[0] = cleanHeaderLine;

    var newCsvLines = [];

    csv_lines.forEach(function(line){
        if (line.charAt(0) == ',') { line = line.slice(1); }
        var currentIndex = csv_lines.indexOf(line);
        if(currentIndex === 0){
            newCsvLines.push(line);
        }
        else {
            newCsvLines.push("\n" + line);
        }
    });

    var csvFileName = './uploads/' + fileName + '_clean.csv';

    fs.writeFileSync(csvFileName, newCsvLines);

    var fileStream=fs.createReadStream(csvFileName);
//new converter instance
    var csvConverter=new Converter({constructResult:true});

    //end_parsed will be emitted once parsing finished
    csvConverter.on("end_parsed",function(jsonObj){
        //console.log(jsonObj); //here is your result json object
        var p = 0;
        makeRecords(jsonObj);

    });

    //read from file
    fileStream.pipe(csvConverter);

    function makeRecords(result){
        console.log(result.length);

        MongoClient.connect(url, function (err, db) {
            if (err) {
                console.log('Unable to connect to the mongoDB server. Error:', err);
            } else {
                console.log('Connection established to', url);

                var categoryName = metaFields.subjectCategory;

                var collectionName = categoryName.replace(/ /g,"_");

                db.open(function(err, client){
                    if(err){
                        console.log(err);
                    }
                    try {
                        client.createCollection(collectionName, function (err, col) {
                        });

                        var collection = db.collection(collectionName);

                        if(metaFields.subjectCategory === 'SalesforceData'){
                            //Here we will use the upsert logic to either insert new, or update existing records

                            for (var i = 0; i < result.length; i++) {
                                //console.log(result[i]);

                                var inserted = 0;

                                for (var i = 0; i < result.length; i++) {
                                    var dataRecord = result[i];

                                    dataRecord.OriginalDocumentName = fileName;
                                    dataRecord.DocumentAuthor = metaFields.documentAuthor;
                                    dataRecord.TabName = tabName;
                                    dataRecord.SubjectCategory = metaFields.subjectCategory;
                                    dataRecord.Subject = metaFields.subject;
                                    dataRecord.DateDocumentProduced = metaFields.dateDocumentProduced;
                                    dataRecord.DateDocumentReceived = metaFields.dateDocumentReceived;
                                    dataRecord.DocumentSubmitter = metaFields.documentSubmitter;
                                    dataRecord.DocumentReviewer = metaFields.documentReviewer;
                                    dataRecord.OriginalSource = metadataFields.originalSource,
                                        dataRecord.DataVersion = metadataFields.dataVersion,
                                        dataRecord.DataFields = newCsvLines[0];

                                    collection.update(
                                    {
                                        CSCOpportunityId: dataRecord.CSCOpportunityID
                                    },
                                        {
                                            $set: {
                                                CSCOpportunityId: dataRecord.CSCOpportunityID,
                                                OriginalDocumentName:   dataRecord.OriginalDocumentName,
                                                DocumentAuthor: dataRecord.DocumentAuthor,
                                                TabName:    dataRecord.TabName,
                                                SubjectCategory:    dataRecord.SubjectCategory,
                                                Subject:    dataRecord.Subject,
                                                DateDocumentProduced:   dataRecord.DateDocumentProduced,
                                                DateDocumentReceived:   dataRecord.DateDocumentReceived,
                                                DocumentSubmitter:  dataRecord.DocumentSubmitter,
                                                DocumentReviewer:   dataRecord.DocumentReviewer,
                                                OriginalSource: dataRecord.OriginalSource,
                                                DataVersion:    dataRecord.DataVersion,
                                                DataFields: dataRecord.DataFields,

                                                CSCOpportunityID : dataRecord.CSCOpportunityID,
                                                OpportunityName: dataRecord.OpportunityName ,
                                                AccountName : dataRecord.AccountName,
                                                OpportunityOwner : dataRecord.OpportunityOwner,
                                                Stage : dataRecord.Stage,
                                                Industry : dataRecord.Industry,
                                                ACV : dataRecord.ACV,
                                                RevenueStartDate : dataRecord.RevenueStartDate,
                                                RevenueTerm : dataRecord.RevenueTerm,
                                                ProbabilityPct : dataRecord.ProbabilityPct,
                                                DealRegion : dataRecord.DealRegion
                                            }
                                        },
                                        {
                                            upsert: true,
                                            multi:true
                                        }

                                        //if (++inserted == result.length) {
                                        //    console.log("finished");
                                        //    //db.close();
                                        //}
                                    );
                                }
                            }
                        }
                        else {
                            for (var i = 0; i < result.length; i++) {
                                //console.log(result[i]);

                                var inserted = 0;

                                for (var i = 0; i < result.length; i++) {
                                    var dataRecord = result[i];

                                    dataRecord.OriginalDocumentName = fileName;
                                    dataRecord.DocumentAuthor = metaFields.documentAuthor;
                                    dataRecord.TabName = tabName;
                                    dataRecord.SubjectCategory = metaFields.subjectCategory;
                                    dataRecord.Subject = metaFields.subject;
                                    dataRecord.DateDocumentProduced = metaFields.dateDocumentProduced;
                                    dataRecord.DateDocumentReceived = metaFields.dateDocumentReceived;
                                    dataRecord.DocumentSubmitter = metaFields.documentSubmitter;
                                    dataRecord.DocumentReviewer = metaFields.documentReviewer;
                                    dataRecord.OriginalSource = metadataFields.originalSource,
                                        dataRecord.DataVersion = metadataFields.dataVersion,
                                        dataRecord.DataFields = newCsvLines[0];

                                    collection.insert(dataRecord, function (err) {
                                        if (++inserted == result.length) {
                                            console.log("finished");
                                            //db.close();
                                        }
                                    });
                                }
                            }

                        }
                    }
                    catch (err) {'excel parser - main record making Error:  ' +  err}
                });

                db.open(function(err, client) {
                    var dataFields = [];
                    var dataVersions = [];

                        client.collection(collectionName).distinct("DataFields", (function (err, docs) {
                            if(err){
                                console.log(err);
                            }
                            try {
                                console.log('DataFields:  ' + docs);
                                var commaIndex = docs[0].indexOf(",");
                                if (commaIndex !== -1) {
                                    dataFields = docs[0].split(',')
                                }
                                else {
                                    dataFields.push(docs);
                                }

                                client.collection('collections_metadata').update(
                                    {
                                        collectionName: collectionName
                                    },
                                    {
                                        $set: {
                                            dataFields: dataFields

                                        }
                                    }
                                    ,
                                    {upsert: true}
                                )
                            }
                            catch (err) {console.log('excel parser - DataFields assignment Error:  ' +  err)}
                        }));

                        client.collection(collectionName).distinct("DataVersion", (function (err, docs) {
                            if(err){
                                console.log(err);
                            }
                            try {
                                console.log('DataVersion:  ' + docs);
                                var commaIndex = docs.indexOf(",");
                                if (commaIndex !== -1) {
                                    dataVersions = docs.split(',')
                                }
                                else {
                                    dataVersions = docs;
                                }
                                client.collection('collections_metadata').update(
                                    {
                                        collectionName: collectionName
                                    },
                                    {
                                        $set: {
                                            dataVersions: dataVersions
                                        }
                                    }
                                    ,
                                    {upsert: true}
                                )
                            }
                            catch (err) {'excel parser - DataVersion asignment Error:  ' +  err}
                        }));
                });
            }
        });
    }
};
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import * as c from '../colors'
import NativeSearchBar from 'react-native-searchbar'
import Icon from 'react-native-vector-icons/Ionicons'

const iconStyles = StyleSheet.create({
	icon: {
		color: c.gray,
	},
})

const searchIcon = <Icon name="md-search" size={28} style={iconStyles.icon} />
const backIcon = <Icon name="md-arrow-back" size={28} style={iconStyles.icon} />
const closeIcon = <Icon name="md-close" size={28} style={iconStyles.icon} />

const styles = StyleSheet.create({
	searchbar: {
		backgroundColor: c.white,
		height: 44,
	},
})

type Props = {
	getRef?: any,
	style?: any,
	placeholder?: string,
	onChangeText: string => any,
	onCancel: () => any,
	onFocus: () => any,
	onSearchButtonPress: string => any,
	searchActive: boolean,
}

type State = {
	input: string,
}

export class SearchBar extends React.PureComponent<Props, State> {
	state = {
		input: '',
	}

	updateText = input => {
		this.setState({input: input})
	}

	onSearch = () => {
		this.props.onSearchButtonPress(this.state.input)
	}

	render() {
		const backButton = this.props.searchActive ? backIcon : searchIcon
		return (
			<NativeSearchBar
				ref={this.props.getRef}
				backButton={backButton}
				closeButton={this.props.searchActive ? closeIcon : null}
				focusOnLayout={false}
				handleChangeText={this.updateText}
				hideX={!this.props.searchActive}
				onBack={this.props.onCancel}
				onFocus={this.props.onFocus}
				onSubmitEditing={this.onSearch}
				placeholder={this.props.placeholder || 'Search'}
				showOnLoad={true}
				style={[styles.searchbar, this.props.style]}
			/>
		)
	}
}
<commit_msg>fix a setState in Searchbar/android<commit_after>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import * as c from '../colors'
import NativeSearchBar from 'react-native-searchbar'
import Icon from 'react-native-vector-icons/Ionicons'

const iconStyles = StyleSheet.create({
	icon: {
		color: c.gray,
	},
})

const searchIcon = <Icon name="md-search" size={28} style={iconStyles.icon} />
const backIcon = <Icon name="md-arrow-back" size={28} style={iconStyles.icon} />
const closeIcon = <Icon name="md-close" size={28} style={iconStyles.icon} />

const styles = StyleSheet.create({
	searchbar: {
		backgroundColor: c.white,
		height: 44,
	},
})

type Props = {
	getRef?: any,
	style?: any,
	placeholder?: string,
	onChangeText: string => any,
	onCancel: () => any,
	onFocus: () => any,
	onSearchButtonPress: string => any,
	searchActive: boolean,
}

type State = {
	input: string,
}

export class SearchBar extends React.PureComponent<Props, State> {
	state = {
		input: '',
	}

	updateText = input => {
		this.setState(() => ({input: input}))
	}

	onSearch = () => {
		this.props.onSearchButtonPress(this.state.input)
	}

	render() {
		const backButton = this.props.searchActive ? backIcon : searchIcon
		return (
			<NativeSearchBar
				ref={this.props.getRef}
				backButton={backButton}
				closeButton={this.props.searchActive ? closeIcon : null}
				focusOnLayout={false}
				handleChangeText={this.updateText}
				hideX={!this.props.searchActive}
				onBack={this.props.onCancel}
				onFocus={this.props.onFocus}
				onSubmitEditing={this.onSearch}
				placeholder={this.props.placeholder || 'Search'}
				showOnLoad={true}
				style={[styles.searchbar, this.props.style]}
			/>
		)
	}
}
<|endoftext|>


<commit_before>const path = require('path');
const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default;

const isDev = process.env.NODE_ENV === 'development';

module.exports = {
  port: 8001,
  source: {
    components: './components',
    docs: './docs',
    changelog: [
      'CHANGELOG.zh-CN.md',
      'CHANGELOG.en-US.md',
    ],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig: {
    categoryOrder: {
      设计原则: 2,
      Principles: 2,
    },
    typeOrder: {
      General: 0,
      Layout: 1,
      Navigation: 2,
      'Data Entry': 3,
      'Data Display': 4,
      Feedback: 5,
      Localization: 6,
      Other: 7,
    },
    docVersions: {
      '0.9.x': 'http://09x.ant.design',
      '0.10.x': 'http://010x.ant.design',
      '0.11.x': 'http://011x.ant.design',
      '0.12.x': 'http://012x.ant.design',
      '1.x': 'http://1x.ant.design',
    },
  },
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
    plugins: ['dora-plugin-upload'],
  },
  webpackConfig(config) {
    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      react: 'React',
      'react-dom': 'ReactDOM',
      'react-router-dom': 'ReactRouterDOM',
    };

    config.babel.plugins.push([
      require.resolve('babel-plugin-transform-runtime'),
      {
        polyfill: false,
        regenerator: true,
      },
    ]);

    config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 }));

    return config;
  },
  htmlTemplateExtraData: {
    isDev,
  },
};
<commit_msg>site: fix config, ref: a73d0504<commit_after>const path = require('path');
const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default;

const isDev = process.env.NODE_ENV === 'development';

module.exports = {
  port: 8001,
  source: {
    components: './components',
    docs: './docs',
    changelog: [
      'CHANGELOG.zh-CN.md',
      'CHANGELOG.en-US.md',
    ],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig: {
    categoryOrder: {
      设计原则: 2,
      Principles: 2,
    },
    typeOrder: {
      General: 0,
      Layout: 1,
      Navigation: 2,
      'Data Entry': 3,
      'Data Display': 4,
      Feedback: 5,
      Localization: 6,
      Other: 7,
    },
    docVersions: {
      '0.9.x': 'http://09x.ant.design',
      '0.10.x': 'http://010x.ant.design',
      '0.11.x': 'http://011x.ant.design',
      '0.12.x': 'http://012x.ant.design',
      '1.x': 'http://1x.ant.design',
    },
  },
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
    plugins: ['dora-plugin-upload'],
  },
  webpackConfig(config) {
    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      'react-router-dom': 'ReactRouterDOM',
    };
    if (isDev) {
      Object.assign(config.externals, {
        react: 'React',
        'react-dom': 'ReactDOM',
      });
    }

    config.babel.plugins.push([
      require.resolve('babel-plugin-transform-runtime'),
      {
        polyfill: false,
        regenerator: true,
      },
    ]);

    config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 }));

    return config;
  },
  htmlTemplateExtraData: {
    isDev,
  },
};
<|endoftext|>


<commit_before>const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const babelConfig = require('./.babelrc');

module.exports = (storybookBaseConfig, configType, defaultConfig) => {
  return ({
  ...defaultConfig,
  module: {
    ...defaultConfig.module,
    rules: [
      {
        test: /\.(styl|css)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'stylus-loader',
        ].filter(Boolean),
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'babel-loader',
            options: babelConfig,
          },
          {
            loader: 'vue-template-loader',
            options: {
              transformAssetUrls: {
                // The key should be an element name
                // The value should be an attribute name or an array of attribute names
                img: 'src',
              },
            },
          },
        ],
      },
      ...defaultConfig.module.rules.map(x => {
        if (x.test.source === /\.(mjs|jsx?)$/.source) {
          x.use[0].options.plugins.push('@babel/plugin-proposal-optional-chaining')
          return x
        }
        return x
      }),
    ],
  },
  plugins: [
    ...defaultConfig.plugins,
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  resolve: {
    ...defaultConfig.resolve,
    alias: {
      ...defaultConfig.alias,
      vue$: 'vue/dist/vue.esm.js',
    },
  },
})};<commit_msg>add commented line to turn on mangle for storybook build<commit_after>const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const babelConfig = require('./.babelrc');

module.exports = (storybookBaseConfig, configType, defaultConfig) => {
  const mergedConfig = {
    ...defaultConfig,
    module: {
      ...defaultConfig.module,
      rules: [
        {
          test: /\.(styl|css)$/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'stylus-loader',
          ].filter(Boolean),
        },
        {
          test: /\.html$/,
          use: [
            {
              loader: 'babel-loader',
              options: babelConfig,
            },
            {
              loader: 'vue-template-loader',
              options: {
                transformAssetUrls: {
                  // The key should be an element name
                  // The value should be an attribute name or an array of attribute names
                  img: 'src',
                },
              },
            },
          ],
        },
        ...defaultConfig.module.rules.map((x) => {
          if (x.test.source === /\.(mjs|jsx?)$/.source) {
            x.use[0].options.plugins.push(
              '@babel/plugin-proposal-optional-chaining',
            );
            return x;
          }
          return x;
        }),
      ],
    },
    plugins: [
      ...defaultConfig.plugins,
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        filename: '[name].css',
        chunkFilename: '[id].css',
      }),
    ],
    resolve: {
      ...defaultConfig.resolve,
      alias: {
        ...defaultConfig.alias,
        vue$: 'vue/dist/vue.esm.js',
      },
    },
  };

  // uncommenting this will cause the log graph to bork (points that should be at 0 go to max(y))
  // mergedConfig.optimization.minimizer[0].options.terserOptions.mangle = true;

  return mergedConfig;
};
<|endoftext|>