/**
 * @file setup.js - Functions for setting up a player without
 * user interaction based on the data-setup `attribute` of the video tag.
 *
 * @module setup
 */
import * as Dom from './utils/dom';
import * as Events from './utils/events.js';
import document from 'global/document';
import window from 'global/window';

let _windowLoaded = false;
let videojs;

/**
 * Set up any tags that have a data-setup `attribute` when the player is started.
 */
const autoSetup = function() {

  // Protect against breakage in non-browser environments and check global autoSetup option.
  if (!Dom.isReal() || videojs.options.autoSetup === false) {
    return;
  }

  const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  const mediaEls = vids.concat(audios, divs);

  // Check if any media elements exist
  if (mediaEls && mediaEls.length > 0) {

    for (let i = 0, e = mediaEls.length; i < e; i++) {
      const mediaEl = mediaEls[i];

      // Check if element exists, has getAttribute func.
      if (mediaEl && mediaEl.getAttribute) {

        // Make sure this player hasn't already been set up.
        if (mediaEl.player === undefined) {
          const options = mediaEl.getAttribute('data-setup');

          // Check if data-setup attr exists.
          // We only auto-setup if they've added the data-setup attr.
          if (options !== null) {
            // Create new video.js instance.
            videojs(mediaEl);
          }
        }

      // If getAttribute isn't defined, we need to wait for the DOM.
      } else {
        autoSetupTimeout(1);
        break;
      }
    }

  // No videos were found, so keep looping unless page is finished loading.
  } else if (!_windowLoaded) {
    autoSetupTimeout(1);
  }
};

/**
 * Wait until the page is loaded before running autoSetup. This will be called in
 * autoSetup if `hasLoaded` returns false.
 *
 * @param {number} wait
 *        How long to wait in ms
 *
 * @param {module:videojs} [vjs]
 *        The videojs library function
 */
function autoSetupTimeout(wait, vjs) {
  if (vjs) {
    videojs = vjs;
  }

  window.setTimeout(autoSetup, wait);
}

if (Dom.isReal() && document.readyState === 'complete') {
  _windowLoaded = true;
} else {
  /**
   * Listen for the load event on window, and set _windowLoaded to true.
   *
   * @listens load
   */
  Events.one(window, 'load', function() {
    _windowLoaded = true;
  });
}

/**
 * check if the document has been loaded
 */
const hasLoaded = function() {
  return _windowLoaded;
};

export {autoSetup, autoSetupTimeout, hasLoaded};


# Exclude everything but the contents of the dist directory.
**/*
!dist/**
dist/video-js-*.zip
!es5/**
!src/css/**
!core.js


* An array of collision objects from Tiled. These are defined on the tileset. Each tile

* just gets a references to the objects stored in the tileset, so this is readonly.

* @property {array|null} collisionObjects

* Whether the tile's left edge is interesting for collisions.

keep keep keep replace replace replace replace replace replace replace replace keep keep keep keep keep

var Extend = require('../../../../utils/object/Extend');
var GetValue = require('../../../../utils/object/GetValue');

// Copy properties from tileset to tiles
var AssignTileProperties = function (mapData)
{
    var layerData;
    var tile;
    var sid;
    var set;
    var row;

    // go through each of the map data layers
    for (var i = 0; i < mapData.layers.length; i++)
    {
        layerData = mapData.layers[i];

        set = null;

        // rows of tiles
        for (var j = 0; j < layerData.data.length; j++)
        {
            row = layerData.data[j];

            // individual tiles
            for (var k = 0; k < row.length; k++)
            {
                tile = row[k];

                if (tile === null || tile.index < 0)
                {
                    continue;
                }

                // find the relevant tileset
                sid = mapData.tiles[tile.index][2];
                set = mapData.tilesets[sid];

                // Ensure that a tile's size matches its tileset
                tile.width = set.tileWidth;
                tile.height = set.tileHeight;

                // if that tile type has any properties, add them to the tile object
                if (set.tileProperties && set.tileProperties[tile.index - set.firstgid])
                {
                    tile.properties = Extend(
                        tile.properties, set.tileProperties[tile.index - set.firstgid]
                    );
                }

                // If that tile type has any collision info, add that to the tile object
                if (set.tileData && set.tileData[tile.index - set.firstgid])
                {
                    var tileData = set.tileData[tile.index - set.firstgid];
                    var objects = GetValue(tileData, 'objectgroup.objects', null);
                    if (objects && objects.length > 0)
                    {
                        tile.collisionObjects = objects;
                    }
                }
            }
        }
    }
};

module.exports = AssignTileProperties;


var Circle = require('../../../geom/circle/Circle');
var CircleContains = require('../../../geom/circle/Contains');

var SetHitAreaCircle = function (gameObjects, x, y, radius, callback)
{
    if (callback === undefined) { callback = CircleContains; }

    var shape = new Circle(x, y, radius);

    return this.setHitArea(gameObjects, shape, callback);
};

module.exports = SetHitAreaCircle;


var Shuffle = require('./Shuffle');
var GetValue = require('../object/GetValue');

var BuildChunk = function (a, b, qty)
{
    var out = [];

    for (var aIndex = 0; aIndex < a.length; aIndex++)
    {
        for (var bIndex = 0; bIndex < b.length; bIndex++)
        {
            for (var i = 0; i < qty; i++)
            {
                out.push({ a: a[aIndex], b: b[bIndex] });
            }
        }
    }

    return out;
};

//  options = repeat, random, randomB, yoyo, max, qty

//  Range ([a,b,c], [1,2,3]) =
//  a1, a2, a3, b1, b2, b3, c1, c2, c3

//  Range ([a,b], [1,2,3], qty = 3) =
//  a1, a1, a1, a2, a2, a2, a3, a3, a3, b1, b1, b1, b2, b2, b2, b3, b3, b3

//  Range ([a,b,c], [1,2,3], repeat x1) =
//  a1, a2, a3, b1, b2, b3, c1, c2, c3, a1, a2, a3, b1, b2, b3, c1, c2, c3

//  Range ([a,b], [1,2], repeat -1 = endless, max = 14) =
//  Maybe if max is set then repeat goes to -1 automatically?
//  a1, a2, b1, b2, a1, a2, b1, b2, a1, a2, b1, b2, a1, a2 (capped at 14 elements)

//  Range ([a], [1,2,3,4,5], random = true) =
//  a4, a1, a5, a2, a3

//  Range ([a, b], [1,2,3], random = true) =
//  b3, a2, a1, b1, a3, b2

//  Range ([a, b, c], [1,2,3], randomB = true) =
//  a3, a1, a2, b2, b3, b1, c1, c3, c2

//  Range ([a], [1,2,3,4,5], yoyo = true) =
//  a1, a2, a3, a4, a5, a5, a4, a3, a2, a1

//  Range ([a, b], [1,2,3], yoyo = true) =
//  a1, a2, a3, b1, b2, b3, b3, b2, b1, a3, a2, a1

var Range = function (a, b, options)
{
    var max = GetValue(options, 'max', 0);
    var qty = GetValue(options, 'qty', 1);
    var random = GetValue(options, 'random', false);
    var randomB = GetValue(options, 'randomB', false);
    var repeat = GetValue(options, 'repeat', 0);
    var yoyo = GetValue(options, 'yoyo', false);

    var out = [];

    if (randomB)
    {
        Shuffle(b);
    }

    //  Endless repeat, so limit by max
    if (repeat === -1)
    {
        if (max === 0)
        {
            repeat = 0;
        }
        else
        {
            //  Work out how many repeats we need
            var total = (a.length * b.length) * qty;

            if (yoyo)
            {
                total *= 2;
            }

            repeat = Math.ceil(max / total);
        }
    }

    for (var i = 0; i <= repeat; i++)
    {
        var chunk = BuildChunk(a, b, qty);

        if (random)
        {
            Shuffle(chunk);
        }

        out = out.concat(chunk);

        if (yoyo)
        {
            chunk.reverse();

            out = out.concat(chunk);
        }
    }

    if (max)
    {
        out.splice(max);
    }

    return out;
};

module.exports = Range;


var Vector2 = require('../../../math/Vector2');

var GetWorldPoint = function (screenPoint, output)
{
    var cameraMatrix = this.matrix.matrix;
    var mva = cameraMatrix[0];
    var mvb = cameraMatrix[1];
    var mvc = cameraMatrix[2];
    var mvd = cameraMatrix[3];
    var mve = cameraMatrix[4];
    var mvf = cameraMatrix[5];

    /* First Invert Matrix */
    var determinant = (mva * mvd) - (mvb * mvc);

    if (!determinant)
    {
        return screenPoint;
    }

    determinant = 1 / determinant;

    var ima = mvd * determinant;
    var imb = -mvb * determinant;
    var imc = -mvc * determinant;
    var imd = mva * determinant;
    var ime = (mvc * mvf - mvd * mve) * determinant;
    var imf = (mvb * mve - mva * mvf) * determinant;
    var c = Math.cos(this.rotation);
    var s = Math.sin(this.rotation);
    var zoom = this.zoom;
    var scrollX = this.scrollX;
    var scrollY = this.scrollY;
    var x = screenPoint.x + ((scrollX * c - scrollY * s) * zoom);
    var y = screenPoint.y + ((scrollX * s + scrollY * c) * zoom);

    if (!output)
    {
        output = new Vector2();
    }

    /* Apply transform to point */
    output.x = (x * ima + y * imc + ime);
    output.y = (x * imb + y * imd + imf);

    return output;
};

module.exports = GetWorldPoint;


return this.tileData[tileIndex - this.firstgid];

* Returns true if and only if this Tileset contains the given tile index.

* @param {integer} tileIndex - The unique id of the tile across all tilesets in the map.

* Get a tile's data that is stored in the Tileset. Returns null if tile index is not

return (data && data.objectgroup) ? data.objectgroup : null;

var Class = require('../../utils/Class');
var Components = require('../components');

var Tile = new Class({

    Mixins: [
        Components.Alpha,
        Components.Flip,
        Components.Visible
    ],

    initialize:

    /**
     * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data
     * representation, so it's position information is stored without factoring in scroll, layer
     * scale or layer position.
     *
     * @class Tile
     * @constructor
     *
     * @param {LayerData} layer - The LayerData object in the Tilemap that this tile belongs to.
     * @param {integer} index - The unique index of this tile within the map.
     * @param {integer} x - The x coordinate of this tile in tile coordinates.
     * @param {integer} y - The y coordinate of this tile in tile coordinates.
     * @param {integer} width - Width of the tile in pixels.
     * @param {integer} height - Height of the tile in pixels.
     * @param {integer} baseWidth - The base width a tile in the map (in pixels). Tiled maps support
     * multiple tileset sizes within one map, but they are still placed at intervals of the base
     * tile width.
     * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). Tiled maps
     * support multiple tileset sizes within one map, but they are still placed at intervals of the
     * base tile height.
     */
    function Tile (layer, index, x, y, width, height, baseWidth, baseHeight)
    {
        /**
         * The LayerData in the Tilemap data that this tile belongs to.
         * @property {LayerData} layer
         */
        this.layer = layer;

        /**
         * The index of this tile within the map data corresponding to the tileset, or -1 if this
         * represents a blank tile.
         * @property {integer} index
         */
        this.index = index;

        /**
         * The x map coordinate of this tile in tile units.
         * @property {integer} x
         */
        this.x = x;

        /**
         * The y map coordinate of this tile in tile units.
         * @property {integer} y
         */
        this.y = y;

        /**
         * The width of the tile in pixels.
         * @property {integer} width
         */
        this.width = width;

        /**
         * The height of the tile in pixels.
         * @property {integer} height
         */
        this.height = height;

        /**
         * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes
         * within one map, but they are still placed at intervals of the base tile size.
         * @property {integer} baseWidth
         */
        this.baseWidth = (baseWidth !== undefined) ? baseWidth : width;

        /**
         * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes
         * within one map, but they are still placed at intervals of the base tile size.
         * @property {integer} baseHeight
         */
        this.baseHeight = (baseHeight !== undefined) ? baseHeight : height;

        /**
         * The x coordinate of the top left of this tile in pixels. This is relative to the top left
         * of the layer this tile is being rendered within. This property does NOT factor in camera
         * scroll, layer scale or layer position.
         * @property {number} pixelX
         */
        this.pixelX = 0;

        /**
         * The y coordinate of the top left of this tile in pixels. This is relative to the top left
         * of the layer this tile is being rendered within. This property does NOT factor in camera
         * scroll, layer scale or layer position.
         * @property {number} pixelY
         */
        this.pixelY = 0;

        this.updatePixelXY();

        /**
         * Tile specific properties. These usually come from Tiled.
         * @property {object} properties
         */
        this.properties = {};

        /**
         * The rotation angle of this tile.
         * @property {number} rotation
         */
        this.rotation = 0;

        /**
         * Whether the tile should collide with any object on the left side.
         * @property {boolean} collideLeft
         */
        this.collideLeft = false;

        /**
         * Whether the tile should collide with any object on the right side.
         * @property {boolean} collideRight
         */
        this.collideRight = false;

        /**
         * Whether the tile should collide with any object on the top side.
         * @property {boolean} collideUp
         */
        this.collideUp = false;

        /**
         * Whether the tile should collide with any object on the bottom side.
         * @property {boolean} collideDown
         */
        this.collideDown = false;

        /**
         * An array of collision objects from Tiled. These are defined on the tileset. Each tile
         * just gets a references to the objects stored in the tileset, so this is readonly.
         * @property {array|null} collisionObjects
         * @readonly
         */
        this.collisionObjects = null;

        /**
         * Whether the tile's left edge is interesting for collisions.
         * @property {boolean} faceLeft
         */
        this.faceLeft = false;

        /**
         * Whether the tile's right edge is interesting for collisions.
         * @property {boolean} faceRight
         */
        this.faceRight = false;

        /**
         * Whether the tile's top edge is interesting for collisions.
         * @property {boolean} faceTop
         */
        this.faceTop = false;

        /**
         * Whether the tile's bottom edge is interesting for collisions.
         * @property {boolean} faceBottom
         */
        this.faceBottom = false;

        /**
         * Tile collision callback.
         * @property {function} collisionCallback
         */
        this.collisionCallback = null;

        /**
         * The context in which the collision callback will be called.
         * @property {object} collisionCallbackContext
         */
        this.collisionCallbackContext = this;

        /**
         * The tint to apply to this tile. Note: tint is currently a single color value instead of
         * the 4 corner tint component on other GameObjects.
         * @property {number} Tint
         * @default
         */
        this.tint = 0xffffff;
    },

    /**
     * Check if the given x and y world coordinates are within this Tile. This does not factor in
     * camera scroll, layer scale or layer position.
     *
     * @param {number} x - The x coordinate to test.
     * @param {number} y - The y coordinate to test.
     * @return {boolean} True if the coordinates are within this Tile, otherwise false.
     */
    containsPoint: function (x, y)
    {
        return !(x < this.pixelX || y < this.pixelY || x > this.right || y > this.bottom);
    },

    /**
     * Copies the tile data & properties from the given tile to this tile. This copies everything
     * except for position and interesting faces.
     *
     * @param {Tile} tile - The tile to copy from.
     * @returns {this}
     */
    copy: function (tile)
    {
        this.index = tile.index;
        this.alpha = tile.alpha;
        this.properties = tile.properties;
        this.visible = tile.visible;
        this.setFlip(tile.flipX, tile.flipY);
        this.tint = tile.tint;
        this.rotation = tile.rotation;
        this.collideUp = tile.collideUp;
        this.collideDown = tile.collideDown;
        this.collideLeft = tile.collideLeft;
        this.collideRight = tile.collideRight;
        this.collisionCallback = tile.collisionCallback;
        this.collisionCallbackContext = tile.collisionCallbackContext;

        return this;
    },

    /**
     * Clean up memory.
     */
    destroy: function ()
    {
        this.collisionCallback = undefined;
        this.collisionCallbackContext = undefined;
        this.properties = undefined;
    },

    /**
     * Check for intersection with this tile. This does not factor in camera scroll, layer scale or
     * layer position.
     *
     * @param {number} x - The x axis in pixels.
     * @param {number} y - The y axis in pixels.
     * @param {number} right - The right point.
     * @param {number} bottom - The bottom point.
     * @return {boolean}
     */
    intersects: function (x, y, right, bottom)
    {
        return !(
            right <= this.pixelX || bottom <= this.pixelY ||
            x >= this.right || y >= this.bottom
        );
    },

    /**
     * Checks if the tile is interesting.
     *
     * @param {boolean} collides - If true, will consider the tile interesting if it collides on any
     * side.
     * @param {boolean} faces - If true, will consider the tile interesting if it has an interesting
     * face.
     * @returns {boolean} True if the Tile is interesting, otherwise false.
     */
    isInteresting: function (collides, faces)
    {
        if (collides && faces) { return (this.canCollide || this.hasInterestingFace); }
        else if (collides) { return this.collides; }
        else if (faces) { return this.hasInterestingFace; }
        return false;
    },

    /**
     * Reset collision status flags.
     *
     * @returns {this}
     */
    resetCollision: function ()
    {
        this.collideLeft = false;
        this.collideRight = false;
        this.collideUp = false;
        this.collideDown = false;

        this.faceTop = false;
        this.faceBottom = false;
        this.faceLeft = false;
        this.faceRight = false;

        return this;
    },

    /**
     * Reset faces.
     *
     * @returns {this}
     */
    resetFaces: function ()
    {
        this.faceTop = false;
        this.faceBottom = false;
        this.faceLeft = false;
        this.faceRight = false;

        return this;
    },

    /**
     * Sets the collision flags for each side of this tile and updates the interesting faces list.
     *
     * @param {boolean} left - Indicating collide with any object on the left.
     * @param {boolean} right - Indicating collide with any object on the right.
     * @param {boolean} up - Indicating collide with any object on the top.
     * @param {boolean} down - Indicating collide with any object on the bottom.
     * @returns {this}
     */
    setCollision: function (left, right, up, down)
    {
        if (right === undefined) { right = left; }
        if (up === undefined) { up = left; }
        if (down === undefined) { down = left; }

        this.collideLeft = left;
        this.collideRight = right;
        this.collideUp = up;
        this.collideDown = down;

        this.faceLeft = left;
        this.faceRight = right;
        this.faceTop = up;
        this.faceBottom = down;

        return this;
    },

    /**
     * Set a callback to be called when this tile is hit by an object. The callback must true for
     * collision processing to take place.
     *
     * @param {function} callback - Callback function.
     * @param {object} context - Callback will be called within this context.
     * @returns {this}
     */
    setCollisionCallback: function (callback, context)
    {
        if (callback === null)
        {
            this.collisionCallback = undefined;
            this.collisionCallbackContext = undefined;
        }
        else
        {
            this.collisionCallback = callback;
            this.collisionCallbackContext = context;
        }

        return this;
    },

    /**
     * Sets the size of the tile and updates its pixelX and pixelY.
     *
     * @param {integer} tileWidth - The width of the tile in pixels.
     * @param {integer} tileHeight - The height of the tile in pixels.
     * @param {integer} baseWidth - The base width a tile in the map (in pixels).
     * @param {integer} baseHeight - The base height of the tile in pixels (in pixels).
     * @returns {this}
     */
    setSize: function (tileWidth, tileHeight, baseWidth, baseHeight)
    {
        if (tileWidth !== undefined) { this.width = tileWidth; }
        if (tileHeight !== undefined) { this.height = tileHeight; }
        if (baseWidth !== undefined) { this.baseWidth = baseWidth; }
        if (baseHeight !== undefined) { this.baseHeight = baseHeight; }

        this.updatePixelXY();

        return this;
    },

    /**
     * Used internally. Updates the tile's world XY position based on the current tile size.
     *
     * @returns {this}
     */
    updatePixelXY: function ()
    {
        // Tiled places tiles on a grid of baseWidth x baseHeight. The origin for a tile is the
        // bottom left, while the Phaser renderer assumes the origin is the top left. The y
        // coordinate needs to be adjusted by the difference.
        this.pixelX = this.x * this.baseWidth;
        this.pixelY = this.y * this.baseHeight - (this.height - this.baseHeight);

        return this;
    },

    /**
     * True if this tile can collide on any of its faces or has a collision callback set.
     * @property {boolean} canCollide
     * @readonly
     */
    canCollide: {
        get: function ()
        {
            return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback);
        }
    },

    /**
     * True if this tile can collide on any of its faces.
     * @property {boolean} canCollide
     * @readonly
     */
    collides: {
        get: function ()
        {
            return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
        }
    },

    /**
     * True if this tile has any interesting faces.
     * @property {boolean} canCollide
     * @readonly
     */
    hasInterestingFace: {
        get: function ()
        {
            return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight);
        }
    },

    /**
     * The world position of the left side of the tile. This does not factor in camera scroll, layer
     * scale or layer position.
     * @property {integer} left
     * @readonly
     */
    left: {
        get: function ()
        {
            return this.pixelX;
        }
    },

    /**
     * The world position of the right side of the tile. This does not factor in camera scroll,
     * layer scale or layer position.
     * @property {integer} right
     * @readonly
     */
    right: {
        get: function ()
        {
            return this.pixelX + this.width;
        }
    },

    /**
     * The world position of the top side of the tile. This does not factor in camera scroll,
     * layer scale or layer position.
     * @property {integer} top
     * @readonly
     */
    top: {
        get: function ()
        {
            return this.pixelY;
        }
    },

    /**
     * The world position of the bottom side of the tile. This does not factor in camera scroll,
     * layer scale or layer position.
     * @property {integer} bottom
     * @readonly
     */
    bottom: {
        get: function ()
        {
            return this.pixelY + this.height;
        }
    },

    /**
     * The x world position of the center of the tile. This does not factor in camera scroll, layer
     * scale or layer position.
     * @property {integer} centerX
     * @readonly
     */
    centerX: {
        get: function ()
        {
            return this.pixelX + this.width / 2;
        }
    },

    /**
     * The y world position of the center of the tile. This does not factor in camera scroll, layer
     * scale or layer position.
     * @property {integer} centerY
     * @readonly
     */
    centerY: {
        get: function ()
        {
            return this.pixelY + this.height / 2;
        }
    }

});

module.exports = Tile;


<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Phaser Source: src/pixi/renderers/canvas/utils/CanvasMaskManager.js</title>

	<link type="text/css" rel="stylesheet" href="styles/default.css">

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			Phaser API

					Namespaces

							Phaser

							PIXI

					Classes

							Event

							EventTarget

							Animation

							AnimationManager

							AnimationParser

							ArraySet

							ArrayUtils

							AudioSprite

							BitmapData

							BitmapText

							Bullet

							Button

							Cache

							Camera

							Canvas

							Circle

							Color

							Angle

							Animation

							AutoCull

							Bounds

							BringToTop

							Core

							Crop

							Delta

							Destroy

							FixedToCamera

							Health

							InCamera

							InputEnabled

							InWorld

							LifeSpan

							LoadTexture

							Overlap

							PhysicsBody

							Reset

							ScaleMinMax

							Smoothed

							Create

							Creature

							Device

							DeviceButton

							DOM

							Easing

							Back

							Bounce

							Circular

							Cubic

							Elastic

							Exponential

							Linear

							Quadratic

							Quartic

							Quintic

							Sinusoidal

							Ellipse

							Events

							Filter

							FlexGrid

							FlexLayer

							Frame

							FrameData

							Game

							GameObjectCreator

							GameObjectFactory

							Gamepad

							Graphics

							Group

							Hermite

							Image

							ImageCollection

							Input

							InputHandler

							Key

							Keyboard

							KeyCode

							Line

							LinkedList

							Loader

							LoaderParser

							Math

							Matrix

							Mouse

							MSPointer

							Net

							Particle

							Particles

							Arcade

							Emitter

							Path

							PathFollower

							PathPoint

							Physics

							Arcade

							Body

							TilemapCollision

							Ninja

							AABB

							Body

							Circle

							Tile

							P2

							Body

							BodyDebug

							CollisionGroup

							ContactMaterial

							DistanceConstraint

							FixtureList

							GearConstraint

							InversePointProxy

							LockConstraint

							Material

							PointProxy

							PrismaticConstraint

							RevoluteConstraint

							RotationalSpring

							Spring

							Plugin

							PathManager

							PluginManager

							Point

							Pointer

							PointerMode

							Polygon

							QuadTree

							RandomDataGenerator

							Rectangle

							RenderTexture

							RequestAnimationFrame

							RetroFont

							Rope

							RoundedRectangle

							ScaleManager

							Signal

							SignalBinding

							SinglePad

							Sound

							SoundManager

							Sprite

							SpriteBatch

							Stage

							State

							StateManager

							Text

							Tile

							Tilemap

							TilemapLayer

							TilemapParser

							Tileset

							TileSprite

							Time

							Timer

							TimerEvent

							Touch

							Tween

							TweenData

							TweenManager

							Utils

							Debug

							Video

							Weapon

							World

							AbstractFilter

							BaseTexture

							CanvasBuffer

							CanvasGraphics

							CanvasMaskManager

							CanvasPool

							CanvasRenderer

							CanvasTinter

							ComplexPrimitiveShader

							DisplayObjectContainer

							EarCut

							Event

							EventTarget

							FilterTexture

							Graphics

							GraphicsData

							PIXI

							DisplayObject

							PixiFastShader

							PixiShader

							PrimitiveShader

							RenderTexture

							Rope

							Sprite

							SpriteBatch

							Strip

							StripShader

							Texture

							TilingSprite

							WebGLBlendModeManager

							WebGLFastSpriteBatch

							WebGLFilterManager

							WebGLRenderer

					Global

							ANGLE_DOWN

							ANGLE_LEFT

							ANGLE_NORTH_EAST

							ANGLE_NORTH_WEST

							ANGLE_RIGHT

							ANGLE_SOUTH_EAST

							ANGLE_SOUTH_WEST

							ANGLE_UP

							AUTO

							BITMAPDATA

							BITMAPTEXT

							blendModes

							BOTTOM_CENTER

							BOTTOM_LEFT

							BOTTOM_RIGHT

							BUTTON

							CANVAS

							CANVAS_FILTER

							CENTER

							CIRCLE

							CREATURE

							displayList

							DOWN

							ELLIPSE

							emit

							EMITTER

							GAMES

							GRAPHICS

							GROUP

							HEADLESS

							HORIZONTAL

							IMAGE

							LANDSCAPE

							LEFT

							LEFT_BOTTOM

							LEFT_CENTER

							LEFT_TOP

							LINE

							listeners

							MATRIX

							mixin

							NONE

							off

							on

							once

							PENDING_ATLAS

							Phaser.Path#numPoints
return {number} The total number of PathPoints in this Path.

							POINT

							POINTER

							POLYGON

							PORTRAIT

							RECTANGLE

							removeAllListeners

							RENDERTEXTURE

							RETROFONT

							RIGHT

							RIGHT_BOTTOM

							RIGHT_CENTER

							RIGHT_TOP

							ROPE

							ROUNDEDRECTANGLE

							scaleModes

							SPRITE

							SPRITEBATCH

							stopImmediatePropagation

							stopPropagation

							TEXT

							TILEMAP

							TILEMAPLAYER

							TILESPRITE

							TOP_CENTER

							TOP_LEFT

							TOP_RIGHT

							UP

							VERSION

							VERTICAL

							VIDEO

							WEBGL

							WEBGL_FILTER

					Core

Game

Group

World

Loader

Cache

Time

Camera

State Manager

Tween Manager

Sound Manager

Input Manager

Scale Manager

					Game Objects

Factory (game.add)

Creator (game.make)

Sprite

Image

Sound

Video

Particle Emitter

Particle

Text

Tween

BitmapText

Tilemap

BitmapData

RetroFont

Button

Animation

Graphics

RenderTexture

TileSprite

					Geometry

Circle

Ellipse

Line

Matrix

Point

Polygon

Rectangle

Rounded Rectangle

					Physics

Arcade Physics

Body

Weapon

P2 Physics

Body

Spring

CollisionGroup

ContactMaterial

Ninja Physics

Body

					Input

Input Handler

Pointer

Device Button

Mouse

Keyboard

Key

Key Codes

Gamepad

					Community

Phaser Web Site

Phaser Github

Phaser Examples

Phaser Plugins

Forum

Stack Overflow

Tutorials

Newsletter

Twitter

Slack

Donate

Texture Packer

Source: src/pixi/renderers/canvas/utils/CanvasMaskManager.js

/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * A set of functions used to handle masking.
 *
 * @class CanvasMaskManager
 * @constructor
 */
PIXI.CanvasMaskManager = function()
{
};

PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager;

/**
 * This method adds it to the current stack of masks.
 *
 * @method pushMask
 * @param maskData {Object} the maskData that will be pushed
 * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
 */
PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) {

	var context = renderSession.context;

    context.save();

    var cacheAlpha = maskData.alpha;
    var transform = maskData.worldTransform;

    var resolution = renderSession.resolution;

    context.setTransform(transform.a * resolution,
                         transform.b * resolution,
                         transform.c * resolution,
                         transform.d * resolution,
                         transform.tx * resolution,
                         transform.ty * resolution);

    PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);

    context.clip();

    maskData.worldAlpha = cacheAlpha;
};

/**
 * Restores the current drawing context to the state it was before the mask was applied.
 *
 * @method popMask
 * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
 */
PIXI.CanvasMaskManager.prototype.popMask = function(renderSession)
{
    renderSession.context.restore();
};

		Phaser Copyright © 2012-2016 Photon Storm Ltd.

		Documentation generated by JSDoc 3.4.0
		on Fri Aug 26 2016 01:16:09 GMT+0100 (BST) using the DocStrap template.


BasicGame.Game = function (game) {

	//	When a State is added to Phaser it automatically has the following properties set on it, even if they already exist:

    this.game;		//	a reference to the currently running game
    this.add;		//	used to add sprites, text, groups, etc
    this.camera;	//	a reference to the game camera
    this.cache;		//	the game cache
    this.input;		//	the global input manager (you can access this.input.keyboard, this.input.mouse, as well from it)
    this.load;		//	for preloading assets
    this.math;		//	lots of useful common math operations
    this.sound;		//	the sound manager - add a sound, play one, set-up markers, etc
    this.stage;		//	the game stage
    this.time;		//	the clock
    this.tweens;	//	the tween manager
    this.world;		//	the game world
    this.particles;	//	the particle manager
    this.physics;	//	the physics manager
    this.rnd;		//	the repeatable random number generator

    //	You can use any of these from any function within this State.
    //	But do consider them as being 'reserved words', i.e. don't create a property for your own game called "world" or you'll over-write the world reference.

};

BasicGame.Game.prototype = {

	create: function () {

		//	Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out!

	},

	update: function () {

		//	Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out!

	},

	quitGame: function (pointer) {

		//	Here you should destroy anything you no longer need.
		//	Stop music, delete sprites, purge caches, free resources, all that good stuff.

		//	Then let's go back to the main menu.
		this.state.start('MainMenu');

	}

};

v2/resources/Project Templates/Full Screen Mobile/src/Game.js


<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Phaser Source: src/core/SignalBinding.js</title>

	<link type="text/css" rel="stylesheet" href="styles/default.css">

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			Phaser API

					Namespaces

							Phaser

							PIXI

					Classes

							Event

							EventTarget

							Animation

							AnimationManager

							AnimationParser

							ArraySet

							ArrayUtils

							AudioSprite

							BitmapData

							BitmapText

							Bullet

							Button

							Cache

							Camera

							Canvas

							Circle

							Color

							Angle

							Animation

							AutoCull

							Bounds

							BringToTop

							Core

							Crop

							Delta

							Destroy

							FixedToCamera

							Health

							InCamera

							InputEnabled

							InWorld

							LifeSpan

							LoadTexture

							Overlap

							PhysicsBody

							Reset

							ScaleMinMax

							Smoothed

							Create

							Creature

							Device

							DeviceButton

							DOM

							Easing

							Back

							Bounce

							Circular

							Cubic

							Elastic

							Exponential

							Linear

							Quadratic

							Quartic

							Quintic

							Sinusoidal

							Ellipse

							Events

							Filter

							FlexGrid

							FlexLayer

							Frame

							FrameData

							Game

							GameObjectCreator

							GameObjectFactory

							Gamepad

							Graphics

							Group

							Hermite

							Image

							ImageCollection

							Input

							InputHandler

							Key

							Keyboard

							KeyCode

							Line

							LinkedList

							Loader

							LoaderParser

							Math

							Matrix

							Mouse

							MSPointer

							Net

							Particle

							Particles

							Arcade

							Emitter

							Path

							PathFollower

							PathPoint

							Physics

							Arcade

							Body

							TilemapCollision

							Ninja

							AABB

							Body

							Circle

							Tile

							P2

							Body

							BodyDebug

							CollisionGroup

							ContactMaterial

							DistanceConstraint

							FixtureList

							GearConstraint

							InversePointProxy

							LockConstraint

							Material

							PointProxy

							PrismaticConstraint

							RevoluteConstraint

							RotationalSpring

							Spring

							Plugin

							PathManager

							PluginManager

							Point

							Pointer

							PointerMode

							Polygon

							QuadTree

							RandomDataGenerator

							Rectangle

							RenderTexture

							RequestAnimationFrame

							RetroFont

							Rope

							RoundedRectangle

							ScaleManager

							Signal

							SignalBinding

							SinglePad

							Sound

							SoundManager

							Sprite

							SpriteBatch

							Stage

							State

							StateManager

							Text

							Tile

							Tilemap

							TilemapLayer

							TilemapParser

							Tileset

							TileSprite

							Time

							Timer

							TimerEvent

							Touch

							Tween

							TweenData

							TweenManager

							Utils

							Debug

							Video

							Weapon

							World

							AbstractFilter

							BaseTexture

							CanvasBuffer

							CanvasGraphics

							CanvasMaskManager

							CanvasPool

							CanvasRenderer

							CanvasTinter

							ComplexPrimitiveShader

							DisplayObjectContainer

							EarCut

							Event

							EventTarget

							FilterTexture

							Graphics

							GraphicsData

							PIXI

							DisplayObject

							PixiFastShader

							PixiShader

							PrimitiveShader

							RenderTexture

							Rope

							Sprite

							SpriteBatch

							Strip

							StripShader

							Texture

							TilingSprite

							WebGLBlendModeManager

							WebGLFastSpriteBatch

							WebGLFilterManager

							WebGLRenderer

					Global

							ANGLE_DOWN

							ANGLE_LEFT

							ANGLE_NORTH_EAST

							ANGLE_NORTH_WEST

							ANGLE_RIGHT

							ANGLE_SOUTH_EAST

							ANGLE_SOUTH_WEST

							ANGLE_UP

							AUTO

							BITMAPDATA

							BITMAPTEXT

							blendModes

							BOTTOM_CENTER

							BOTTOM_LEFT

							BOTTOM_RIGHT

							BUTTON

							CANVAS

							CANVAS_FILTER

							CENTER

							CIRCLE

							CREATURE

							displayList

							DOWN

							ELLIPSE

							emit

							EMITTER

							GAMES

							GRAPHICS

							GROUP

							HEADLESS

							HORIZONTAL

							IMAGE

							LANDSCAPE

							LEFT

							LEFT_BOTTOM

							LEFT_CENTER

							LEFT_TOP

							LINE

							listeners

							MATRIX

							mixin

							NONE

							off

							on

							once

							PENDING_ATLAS

							Phaser.Path#numPoints
return {number} The total number of PathPoints in this Path.

							POINT

							POINTER

							POLYGON

							PORTRAIT

							RECTANGLE

							removeAllListeners

							RENDERTEXTURE

							RETROFONT

							RIGHT

							RIGHT_BOTTOM

							RIGHT_CENTER

							RIGHT_TOP

							ROPE

							ROUNDEDRECTANGLE

							scaleModes

							SPRITE

							SPRITEBATCH

							stopImmediatePropagation

							stopPropagation

							TEXT

							TILEMAP

							TILEMAPLAYER

							TILESPRITE

							TOP_CENTER

							TOP_LEFT

							TOP_RIGHT

							UP

							VERSION

							VERTICAL

							VIDEO

							WEBGL

							WEBGL_FILTER

					Core

Game

Group

World

Loader

Cache

Time

Camera

State Manager

Tween Manager

Sound Manager

Input Manager

Scale Manager

					Game Objects

Factory (game.add)

Creator (game.make)

Sprite

Image

Sound

Video

Particle Emitter

Particle

Text

Tween

BitmapText

Tilemap

BitmapData

RetroFont

Button

Animation

Graphics

RenderTexture

TileSprite

					Geometry

Circle

Ellipse

Line

Matrix

Point

Polygon

Rectangle

Rounded Rectangle

					Physics

Arcade Physics

Body

Weapon

P2 Physics

Body

Spring

CollisionGroup

ContactMaterial

Ninja Physics

Body

					Input

Input Handler

Pointer

Device Button

Mouse

Keyboard

Key

Key Codes

Gamepad

					Community

Phaser Web Site

Phaser Github

Phaser Examples

Phaser Plugins

Forum

Stack Overflow

Tutorials

Newsletter

Twitter

Slack

Donate

Texture Packer

Source: src/core/SignalBinding.js

/**
* @author       Miller Medeiros http://millermedeiros.github.com/js-signals/
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* Object that represents a binding between a Signal and a listener function.
* This is an internal constructor and shouldn't be created directly.
* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
*
* @class Phaser.SignalBinding
* @constructor
* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
* @param {function} listener - Handler function bound to the signal.
* @param {boolean} isOnce - If binding should be executed just once.
* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {number} [priority] - The priority level of the event listener. (default = 0).
* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
*/
Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) {

    /**
    * @property {Phaser.Game} _listener - Handler function bound to the signal.
    * @private
    */
    this._listener = listener;

    if (isOnce)
    {
        this._isOnce = true;
    }

    if (listenerContext != null) /* not null/undefined */
    {
        this.context = listenerContext;
    }

    /**
    * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
    * @private
    */
    this._signal = signal;

    if (priority)
    {
        this._priority = priority;
    }

    if (args && args.length)
    {
        this._args = args;
    }

};

Phaser.SignalBinding.prototype = {

    /**
    * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
    */
    context: null,

    /**
    * @property {boolean} _isOnce - If binding should be executed just once.
    * @private
    */
    _isOnce: false,

    /**
    * @property {number} _priority - Listener priority.
    * @private
    */
    _priority: 0,

    /**
    * @property {array} _args - Listener arguments.
    * @private
    */
    _args: null,

    /**
    * @property {number} callCount - The number of times the handler function has been called.
    */
    callCount: 0,

    /**
    * If binding is active and should be executed.
    * @property {boolean} active
    * @default
    */
    active: true,

    /**
    * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
    * @property {array|null} params
    * @default
    */
    params: null,

    /**
    * Call listener passing arbitrary parameters.
    * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
    * @method Phaser.SignalBinding#execute
    * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener.
    * @return {any} Value returned by the listener.
    */
    execute: function(paramsArr) {

        var handlerReturn, params;

        if (this.active && !!this._listener)
        {
            params = this.params ? this.params.concat(paramsArr) : paramsArr;

            if (this._args)
            {
                params = params.concat(this._args);
            }

            handlerReturn = this._listener.apply(this.context, params);

            this.callCount++;

            if (this._isOnce)
            {
                this.detach();
            }
        }

        return handlerReturn;

    },

    /**
    * Detach binding from signal.
    * alias to: @see mySignal.remove(myBinding.getListener());
    * @method Phaser.SignalBinding#detach
    * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
    */
    detach: function () {
        return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
    },

    /**
    * @method Phaser.SignalBinding#isBound
    * @return {boolean} True if binding is still bound to the signal and has a listener.
    */
    isBound: function () {
        return (!!this._signal && !!this._listener);
    },

    /**
    * @method Phaser.SignalBinding#isOnce
    * @return {boolean} If SignalBinding will only be executed once.
    */
    isOnce: function () {
        return this._isOnce;
    },

    /**
    * @method Phaser.SignalBinding#getListener
    * @return {function} Handler function bound to the signal.
    */
    getListener: function () {
        return this._listener;
    },

    /**
    * @method Phaser.SignalBinding#getSignal
    * @return {Phaser.Signal} Signal that listener is currently bound to.
    */
    getSignal: function () {
        return this._signal;
    },

    /**
    * Delete instance properties
    * @method Phaser.SignalBinding#_destroy
    * @private
    */
    _destroy: function () {
        delete this._signal;
        delete this._listener;
        delete this.context;
    },

    /**
    * @method Phaser.SignalBinding#toString
    * @return {string} String representation of the object.
    */
    toString: function () {
        return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
    }

};

Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;

		Phaser Copyright © 2012-2016 Photon Storm Ltd.

		Documentation generated by JSDoc 3.4.0
		on Fri Aug 26 2016 01:16:09 GMT+0100 (BST) using the DocStrap template.


tile.properties, set.tileProperties[tile.index - set.firstgid]

// If that tile type has any collision info, add that to the tile object

if (set.tileData && set.tileData[tile.index - set.firstgid])

var tileData = set.tileData[tile.index - set.firstgid];

var objects = GetValue(tileData, 'objectgroup.objects', null);

keep keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace keep keep keep


Phaser.Cache

game

A reference to the currently running game.

A game only has one instance of a Cache and it is used to store all externally loaded assets such as images, sounds\nand data files as a result of Loader calls. Cached items use string based keys for look-up.

addBinary

binaryData

The binary object to be addded to the cache.

addBitmapData

The BitmapData object to be addded to the cache.

Add a BitmapData object in to the cache.

frameData

Optional FrameData set associated with the given BitmapData.

addBitmapFont

key

The unique key by which you will reference this object.

xSpacing

If you'd like to add additional horizontal spacing between the characters then set the pixel value here.

ySpacing

If you'd like to add additional vertical spacing between the lines then set the pixel value here.

addCanvas

Add a new canvas object in to the cache.

addImage

Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader.

addRenderTexture

Add a new Phaser.RenderTexture in to the cache.

texture

The texture to use as the base of the RenderTexture.

addSound

Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader.

audioTag

True if the file is using legacy HTML audio.

addSpriteSheet

frameMax

How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.

margin

If the frames have been drawn with a margin, specify the amount here.

spacing

If the frames have been drawn with spacing between them, specify the amount here.

addTilemap

Add a new physics data object to the Cache.

checkBinaryKey

True if the key exists, otherwise false.

Checks if the given key exists in the Binary Cache.

key

Asset key of the binary file to check is in the Cache.

checkBitmapDataKey

Checks if the given key exists in the BitmapData Cache.

key

Asset key of the BitmapData to check is in the Cache.

checkBitmapFontKey

Checks if the given key exists in the BitmapFont Cache.

key

Asset key of the BitmapFont to check is in the Cache.

checkCanvasKey

Checks if the given key exists in the Canvas Cache.

key

Asset key of the canvas to check is in the Cache.

checkImageKey

Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts.

key

Asset key of the image to check is in the Cache.

checkJSONKey

Checks if the given key exists in the JSON Cache.

key

Asset key of the JSON file to check is in the Cache.

checkKey

Checks if a key for the given cache object type exists.

type

The Cache type to check against. I.e. Phaser.Cache.CANVAS, Phaser.Cache.IMAGE, Phaser.Cache.JSON, etc.

checkPhysicsKey

Checks if the given key exists in the Physics Cache.

key

Asset key of the physics data file to check is in the Cache.

checkSoundKey

True if the key exists, otherwise false.

Checks if the given key exists in the Sound Cache.

key

Asset key of the sound file to check is in the Cache.

checkTextKey

Checks if the given key exists in the Text Cache.

key

Asset key of the text file to check is in the Cache.

checkTextureKey

Checks if the given key exists in the Texture Cache.

checkTilemapKey

Checks if the given key exists in the Tilemap Cache.

key

Asset key of the Tilemap to check is in the Cache.

checkUrl

True if the url exists, otherwise false.

Checks if the given URL has been loaded into the Cache.

checkXMLKey

Checks if the given key exists in the XML Cache.

key

Asset key of the XML file to check is in the Cache.

destroy

Clears the cache. Removes every local cache object reference.

getBinary

key

Asset key of the binary data object to retrieve from the Cache.

getBitmapData

The requested BitmapData object if found, or null if not.

Get a BitmapData object from the cache by its key.

key

Asset key of the BitmapData object to retrieve from the Cache.

getBitmapFont

The requested BitmapFont object if found, or null if not.

Get a BitmapFont object from the cache by its key.

key

Asset key of the BitmapFont object to retrieve from the Cache.

getCanvas

Get a canvas object from the cache by its key.

key

Asset key of the canvas to retrieve from the Cache.

getFrame

Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.

key

Asset key of the frame data to retrieve from the Cache.

getFrameByIndex

Get a single frame out of a frameData set by key.

getFrameCount

Then number of frames. 0 if the image is not found.

getFrameData

map

The asset map to get the frameData from, for example `Phaser.Cache.IMAGE`.

getImage

The image data if found in the Cache, otherwise `null`.

key

Asset key of the image to retrieve from the Cache.

getJSON

Get a JSON object by key from the cache.

key

Asset key of the json object to retrieve from the Cache.

getKeys

Gets all keys used by the Cache for the given data type.

type

The type of Cache keys you wish to get. Can be Cache.CANVAS, Cache.IMAGE, Cache.SOUND, etc.

getPhysicsData

The requested physics object data if found.

Get a physics data object from the cache by its key. You can get either the entire data set, a single object or a single fixture of an object from it.

key

Asset key of the physics data object to retrieve from the Cache.

object

If specified it will return just the physics object that is part of the given key, if null it will return them all.

fixtureKey

Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter.

getSound

key

Asset key of the sound to retrieve from the Cache.

getText

key

Asset key of the text data to retrieve from the Cache.

getTexture

key

Asset key of the RenderTexture to retrieve from the Cache.

getTextureFrame

Get a single texture frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.

key

Asset key of the frame to retrieve from the Cache.

getTilemapData

The raw tilemap data in CSV or JSON format.

key

Asset key of the tilemap data to retrieve from the Cache.

getUrl

url

The url for the object loaded to get from the cache.

getXML

key

Asset key of the XML object to retrieve from the Cache.

isSoundDecoded

Check if the given sound has finished decoding.

isSoundReady

True if the sound is decoded and the device is not touch locked.

Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked.

reloadSoundComplete

Fires the onSoundUnlock event when the sound has completed reloading.

removeImage

Removes an image from the cache and optionally from the Pixi.BaseTextureCache as well.

removeFromPixi

Should this image also be removed from the Pixi BaseTextureCache?

removePhysics

Removes a physics data file from the cache.

updateFrameData

Replaces a set of frameData with a new Phaser.FrameData object.

addDefaultImage

Adds a default image to be used in special cases such as WebGL Filters. Is mapped to the key __default.

addMissingImage

Adds an image to be used when a key is wrong / missing. Is mapped to the key __missing.

onSoundUnlock

This event is dispatched when the sound system is unlocked via a touch event on cellular devices.

Used to resolve URLs to the absolute path.

Temporary variable to hold a resolved url.


var OS = require('./OS');

var Browser = {

    //  @property {boolean} arora - Set to true if running in Arora.
    arora: false,

    //  @property {boolean} chrome - Set to true if running in Chrome.
    chrome: false,

    //  @property {number} chromeVersion - If running in Chrome this will contain the major version number.
    chromeVersion: 0,

    //  @property {boolean} epiphany - Set to true if running in Epiphany.
    epiphany: false,

    //  @property {boolean} firefox - Set to true if running in Firefox.
    firefox: false,

    //  @property {number} firefoxVersion - If running in Firefox this will contain the major version number.
    firefoxVersion: 0,

    //  @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
    mobileSafari: false,

    //  @property {boolean} ie - Set to true if running in Internet Explorer.
    ie: false,

    //  @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion.
    ieVersion: 0,

    //  @property {boolean} midori - Set to true if running in Midori.
    midori: false,

    //  @property {boolean} opera - Set to true if running in Opera.
    opera: false,

    //  @property {boolean} safari - Set to true if running in Safari.
    safari: false,

    //  @property {number} safariVersion - If running in Safari this will contain the major version number.
    safariVersion: 0,

    //  @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
    trident: false,

    //  @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx}
    tridentVersion: 0,

    //  @property {boolean} edge - Set to true if running in Microsoft Edge browser.
    edge: false,

    //  @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
    silk: false

};

function init ()
{
    var ua = navigator.userAgent;

    if ((/Arora/).test(ua))
    {
        Browser.arora = true;
    }
    else if (/Edge\/\d+/.test(ua))
    {
        Browser.edge = true;
    }
    else if ((/Chrome\/(\d+)/).test(ua) && !OS.windowsPhone)
    {
        Browser.chrome = true;
        Browser.chromeVersion = parseInt(RegExp.$1, 10);
    }
    else if ((/Epiphany/).test(ua))
    {
        Browser.epiphany = true;
    }
    else if ((/Firefox\D+(\d+)/).test(ua))
    {
        Browser.firefox = true;
        Browser.firefoxVersion = parseInt(RegExp.$1, 10);
    }
    else if ((/AppleWebKit/).test(ua) && OS.iOS)
    {
        Browser.mobileSafari = true;
    }
    else if ((/MSIE (\d+\.\d+);/).test(ua))
    {
        Browser.ie = true;
        Browser.ieVersion = parseInt(RegExp.$1, 10);
    }
    else if ((/Midori/).test(ua))
    {
        Browser.midori = true;
    }
    else if ((/Opera/).test(ua))
    {
        Browser.opera = true;
    }
    else if ((/Safari/).test(ua) && !OS.windowsPhone)
    {
        Browser.safari = true;
    }
    else if ((/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/).test(ua))
    {
        Browser.ie = true;
        Browser.trident = true;
        Browser.tridentVersion = parseInt(RegExp.$1, 10);
        Browser.ieVersion = parseInt(RegExp.$3, 10);
    }

    //  Silk gets its own if clause because its ua also contains 'Safari'
    if ((/Silk/).test(ua))
    {
        Browser.silk = true;
    }

    return Browser;
}

module.exports = init();


/**
* Get the angle of the curves entry point.
*
* @param {Phaser.Point|Object} point - The Phaser.Point object, or an Object with public `x` and `y` properties, in which the tangent vector values will be stored.
* @return {Phaser.Point} A Point object containing the tangent vector of this Hermite curve.
*/
var GetEntryTangent = function (curve, point)
{
    point.x = curve._v1x;
    point.y = curve._v1y;

    return point;
};

module.exports = GetEntryTangent;


keep keep keep keep add keep keep keep keep

const path = require('path')
const { isWindows } = require('@vue/cli-shared-utils')

function genTranspileDepRegex (transpileDependencies) {
  const deps = transpileDependencies.map(dep => {
    if (typeof dep === 'string') {
      const depPath = path.join('node_modules', dep, '/')
      return isWindows
        ? depPath.replace(/\\/g, '\\\\') // double escape for windows style path
        : depPath
    } else if (dep instanceof RegExp) {
      return dep.source
    }
  })
  return deps.length ? new RegExp(deps.join('|')) : null
}

module.exports = (api, options) => {
  const useThreads = process.env.NODE_ENV === 'production' && options.parallel
  const cliServicePath = require('path').dirname(require.resolve('@vue/cli-service'))
  const transpileDepRegex = genTranspileDepRegex(options.transpileDependencies)

  api.chainWebpack(webpackConfig => {
    webpackConfig.resolveLoader.modules.prepend(path.join(__dirname, 'node_modules'))

    const jsRule = webpackConfig.module
      .rule('js')
        .test(/\.jsx?$/)
        .exclude
          .add(filepath => {
            // always transpile js in vue files
            if (/\.vue\.jsx?$/.test(filepath)) {
              return false
            }
            // exclude dynamic entries from cli-service
            if (filepath.startsWith(cliServicePath)) {
              return true
            }
            // check if this is something the user explicitly wants to transpile
            if (transpileDepRegex && transpileDepRegex.test(filepath)) {
              return false
            }
            // Don't transpile node_modules
            return /node_modules/.test(filepath)
          })
          .end()
        .use('cache-loader')
          .loader('cache-loader')
          .options(api.genCacheConfig('babel-loader', {
            '@babel/core': require('@babel/core/package.json').version,
            '@vue/babel-preset-app': require('@vue/babel-preset-app/package.json').version,
            'babel-loader': require('babel-loader/package.json').version,
            browserslist: api.service.pkg.browserslist
          }, [
            'babel.config.js',
            '.browserslistrc'
          ]))
          .end()

    if (useThreads) {
      jsRule
        .use('thread-loader')
          .loader('thread-loader')
    }

    jsRule
      .use('babel-loader')
        .loader('babel-loader')
  })
}


query currentProjectId {
  currentProjectId @client
}


const prefixRE = /^VUE_APP_/

module.exports = function resolveClientEnv (options, raw) {
  const env = {}
  Object.keys(process.env).forEach(key => {
    if (prefixRE.test(key) || key === 'NODE_ENV') {
      env[key] = process.env[key]
    }
  })
  env.BASE_URL = options.publicPath

  if (raw) {
    return env
  }

  for (const key in env) {
    env[key] = JSON.stringify(env[key])
  }
  return {
    'process.env': env
  }
}


module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    '@vue/standard'
  ],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  },
  parserOptions: {
    parser: 'babel-eslint'
  },
  globals: {
    ClientAddonApi: false,
    mapSharedData: false,
    Vue: false
  }
}


const path = require('path')
const hash = require('hash-sum')
const { matchesPluginId } = require('@vue/cli-shared-utils')

// Note: if a plugin-registered command needs to run in a specific default mode,
// the plugin needs to expose it via `module.exports.defaultModes` in the form
// of { [commandName]: mode }. This is because the command mode needs to be
// known and applied before loading user options / applying plugins.

class PluginAPI {
  /**
   * @param {string} id - Id of the plugin.
   * @param {Service} service - A vue-cli-service instance.
   */
  constructor (id, service) {
    this.id = id
    this.service = service
  }

  /**
   * Current working directory.
   */
  getCwd () {
    return this.service.context
  }

  /**
   * Resolve path for a project.
   *
   * @param {string} _path - Relative path from project root
   * @return {string} The resolved absolute path.
   */
  resolve (_path) {
    return path.resolve(this.service.context, _path)
  }

  /**
   * Check if the project has a given plugin.
   *
   * @param {string} id - Plugin id, can omit the (@vue/|vue-|@scope/vue)-cli-plugin- prefix
   * @return {boolean}
   */
  hasPlugin (id) {
    if (id === 'router') id = 'vue-router'
    if (['vue-router', 'vuex'].includes(id)) {
      const pkg = this.service.pkg
      return ((pkg.dependencies && pkg.dependencies[id]) || (pkg.devDependencies && pkg.devDependencies[id]))
    }
    return this.service.plugins.some(p => matchesPluginId(id, p.id))
  }

  /**
   * Register a command that will become available as `vue-cli-service [name]`.
   *
   * @param {string} name
   * @param {object} [opts]
   *   {
   *     description: string,
   *     usage: string,
   *     options: { [string]: string }
   *   }
   * @param {function} fn
   *   (args: { [string]: string }, rawArgs: string[]) => ?Promise
   */
  registerCommand (name, opts, fn) {
    if (typeof opts === 'function') {
      fn = opts
      opts = null
    }
    this.service.commands[name] = { fn, opts: opts || {}}
  }

  /**
   * Register a function that will receive a chainable webpack config
   * the function is lazy and won't be called until `resolveWebpackConfig` is
   * called
   *
   * @param {function} fn
   */
  chainWebpack (fn) {
    this.service.webpackChainFns.push(fn)
  }

  /**
   * Register
   * - a webpack configuration object that will be merged into the config
   * OR
   * - a function that will receive the raw webpack config.
   *   the function can either mutate the config directly or return an object
   *   that will be merged into the config.
   *
   * @param {object | function} fn
   */
  configureWebpack (fn) {
    this.service.webpackRawConfigFns.push(fn)
  }

  /**
   * Register a dev serve config function. It will receive the express `app`
   * instance of the dev server.
   *
   * @param {function} fn
   */
  configureDevServer (fn) {
    this.service.devServerConfigFns.push(fn)
  }

  /**
   * Resolve the final raw webpack config, that will be passed to webpack.
   *
   * @param {ChainableWebpackConfig} [chainableConfig]
   * @return {object} Raw webpack config.
   */
  resolveWebpackConfig (chainableConfig) {
    return this.service.resolveWebpackConfig(chainableConfig)
  }

  /**
   * Resolve an intermediate chainable webpack config instance, which can be
   * further tweaked before generating the final raw webpack config.
   * You can call this multiple times to generate different branches of the
   * base webpack config.
   * See https://github.com/mozilla-neutrino/webpack-chain
   *
   * @return {ChainableWebpackConfig}
   */
  resolveChainableWebpackConfig () {
    return this.service.resolveChainableWebpackConfig()
  }

  /**
   * Generate a cache identifier from a number of variables
   */
  genCacheConfig (id, partialIdentifier, configFiles) {
    const fs = require('fs')
    const cacheDirectory = this.resolve(`node_modules/.cache/${id}`)

    // replace \r\n to \n generate consistent hash
    const fmtFunc = conf => {
      if (typeof conf === 'function') {
        return conf.toString().replace(/\r\n?/g, '\n')
      }
      return conf
    }

    const variables = {
      partialIdentifier,
      'cli-service': require('../package.json').version,
      'cache-loader': require('cache-loader/package.json').version,
      env: process.env,
      config: [
        fmtFunc(this.service.projectOptions.chainWebpack),
        fmtFunc(this.service.projectOptions.configureWebpack)
      ]
    }

    if (configFiles) {
      const readConfig = file => {
        const absolutePath = this.resolve(file)
        if (fs.existsSync(absolutePath)) {
          return fs.readFileSync(absolutePath, 'utf-8')
        }
      }
      if (!Array.isArray(configFiles)) {
        configFiles = [configFiles]
      }
      for (const file of configFiles) {
        const content = readConfig(file)
        if (content) {
          variables.configFiles = content.replace(/\r\n?/g, '\n')
          break
        }
      }
    }

    const cacheIdentifier = hash(variables)
    return { cacheDirectory, cacheIdentifier }
  }
}

module.exports = PluginAPI


#!/usr/bin/env node

const semver = require('semver')
const { error } = require('@vue/cli-shared-utils')
const requiredVersion = require('../package.json').engines.node

if (!semver.satisfies(process.version, requiredVersion)) {
  error(
    `You are using Node ${process.version}, but vue-cli-service ` +
    `requires Node ${requiredVersion}.\nPlease upgrade your Node version.`
  )
  process.exit(1)
}

const Service = require('../lib/Service')
const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())

const rawArgv = process.argv.slice(2)
const args = require('minimist')(rawArgv, {
  boolean: [
    // build
    'modern',
    'report',
    'report-json',
    'watch',
    // serve
    'open',
    'copy',
    'https',
    // inspect
    'verbose'
  ]
})
const command = args._[0]

service.run(command, args, rawArgv).catch(err => {
  error(err)
  process.exit(1)
})


const path = require('path')
const fs = require('fs-extra')
const LRU = require('lru-cache')
const chalk = require('chalk')
// Context
const getContext = require('../context')
// Subs
const channels = require('../channels')
// Connectors
const cwd = require('./cwd')
const folders = require('./folders')
const prompts = require('./prompts')
const progress = require('./progress')
const logs = require('./logs')
const clientAddons = require('./client-addons')
const views = require('./views')
const locales = require('./locales')
const sharedData = require('./shared-data')
const suggestions = require('./suggestions')
const dependencies = require('./dependencies')
// Api
const PluginApi = require('../api/PluginApi')
// Utils
const {
  isPlugin,
  isOfficialPlugin,
  getPluginLink,
  resolveModule,
  loadModule,
  clearModule
} = require('@vue/cli-shared-utils')
const {
  progress: installProgress,
  installPackage,
  uninstallPackage,
  updatePackage
} = require('@vue/cli/lib/util/installDeps')
const invoke = require('@vue/cli/lib/invoke')
const { getCommand } = require('../util/command')
const ipc = require('../util/ipc')
const { log } = require('../util/logger')
const { notify } = require('../util/notification')

const PROGRESS_ID = 'plugin-installation'
const CLI_SERVICE = '@vue/cli-service'

// Caches
const logoCache = new LRU({
  max: 50
})

// Local
let currentPluginId
let eventsInstalled = false
let installationStep
let pluginsStore = new Map()
let pluginApiInstances = new Map()
let pkgStore = new Map()

async function list (file, context, { resetApi = true, lightApi = false, autoLoadApi = true } = {}) {
  let pkg = folders.readPackage(file, context)
  let pkgContext = cwd.get()
  // Custom package.json location
  if (pkg.vuePlugins && pkg.vuePlugins.resolveFrom) {
    pkgContext = path.resolve(cwd.get(), pkg.vuePlugins.resolveFrom)
    pkg = folders.readPackage(pkgContext, context)
  }
  pkgStore.set(file, { pkgContext, pkg })

  let plugins = []
  plugins = plugins.concat(findPlugins(pkg.devDependencies || {}, file))
  plugins = plugins.concat(findPlugins(pkg.dependencies || {}, file))

  // Put cli service at the top
  const index = plugins.findIndex(p => p.id === CLI_SERVICE)
  if (index !== -1) {
    const service = plugins[index]
    plugins.splice(index, 1)
    plugins.unshift(service)
  }

  pluginsStore.set(file, plugins)

  log('Plugins found:', plugins.length, chalk.grey(file))

  if (resetApi || (autoLoadApi && !pluginApiInstances.has(file))) {
    await resetPluginApi({ file, lightApi }, context)
  }
  return plugins
}

function findOne ({ id, file }, context) {
  const plugins = getPlugins(file)
  const plugin = plugins.find(
    p => p.id === id
  )
  if (!plugin) log('Plugin Not found', id, chalk.grey(file))
  return plugin
}

function findPlugins (deps, file) {
  return Object.keys(deps).filter(
    id => isPlugin(id) || id === CLI_SERVICE
  ).map(
    id => ({
      id,
      versionRange: deps[id],
      official: isOfficialPlugin(id) || id === CLI_SERVICE,
      installed: fs.existsSync(dependencies.getPath({ id, file })),
      website: getLink(id),
      baseDir: file
    })
  )
}

function getLink (id) {
  if (id === CLI_SERVICE) return 'https://cli.vuejs.org/'
  return getPluginLink(id)
}

function getPlugins (file) {
  const plugins = pluginsStore.get(file)
  if (!plugins) return []
  return plugins
}

function resetPluginApi ({ file, lightApi }, context) {
  return new Promise((resolve, reject) => {
    log('Plugin API reloading...', chalk.grey(file))

    const widgets = require('./widgets')

    let pluginApi = pluginApiInstances.get(file)
    let projectId

    // Clean up
    if (pluginApi) {
      projectId = pluginApi.project.id
      pluginApi.views.forEach(r => views.remove(r.id, context))
      pluginApi.ipcHandlers.forEach(fn => ipc.off(fn))
    }
    if (!lightApi) {
      if (projectId) sharedData.unWatchAll({ projectId }, context)
      clientAddons.clear(context)
      suggestions.clear(context)
      widgets.reset(context)
    }

    // Cyclic dependency with projects connector
    setTimeout(async () => {
      const projects = require('./projects')
      const project = projects.findByPath(file, context)

      if (!project) {
        resolve(false)
        return
      }

      const plugins = getPlugins(file)

      if (project && projects.getType(project, context) !== 'vue') {
        resolve(false)
        return
      }

      pluginApi = new PluginApi({
        plugins,
        file,
        project,
        lightMode: lightApi
      }, context)
      pluginApiInstances.set(file, pluginApi)

      // Run Plugin API
      runPluginApi(path.resolve(__dirname, '../../'), pluginApi, context, 'ui-defaults')
      plugins.forEach(plugin => runPluginApi(plugin.id, pluginApi, context))
      // Local plugins
      const { pkg, pkgContext } = pkgStore.get(file)
      if (pkg.vuePlugins && pkg.vuePlugins.ui) {
        const files = pkg.vuePlugins.ui
        if (Array.isArray(files)) {
          for (const file of files) {
            runPluginApi(pkgContext, pluginApi, context, file)
          }
        }
      }
      // Add client addons
      pluginApi.clientAddons.forEach(options => {
        clientAddons.add(options, context)
      })
      // Add views
      for (const view of pluginApi.views) {
        await views.add({ view, project }, context)
      }
      // Register widgets
      for (const definition of pluginApi.widgetDefs) {
        await widgets.registerDefinition({ definition, project }, context)
      }

      if (lightApi) {
        resolve(true)
        return
      }

      if (projectId !== project.id) {
        callHook({
          id: 'projectOpen',
          args: [project, projects.getLast(context)],
          file
        }, context)
      } else {
        callHook({
          id: 'pluginReload',
          args: [project],
          file
        }, context)

        // View open hook
        const currentView = views.getCurrent()
        if (currentView) views.open(currentView.id)
      }

      // Load widgets for current project
      widgets.load(context)

      resolve(true)
    })
  })
}

function runPluginApi (id, pluginApi, context, filename = 'ui') {
  const name = filename !== 'ui' ? `${id}/${filename}` : id

  let module
  try {
    module = loadModule(`${id}/${filename}`, pluginApi.cwd, true)
  } catch (e) {
    if (process.env.VUE_CLI_DEBUG) {
      console.error(e)
    }
  }
  if (module) {
    if (typeof module !== 'function') {
      log(`${chalk.red('ERROR')} while loading plugin API: no function exported, for`, name, chalk.grey(pluginApi.cwd))
      logs.add({
        type: 'error',
        message: `An error occured while loading ${name}: no function exported`
      })
    } else {
      pluginApi.pluginId = id
      try {
        module(pluginApi)
        log('Plugin API loaded for', name, chalk.grey(pluginApi.cwd))
      } catch (e) {
        log(`${chalk.red('ERROR')} while loading plugin API for ${name}:`, e)
        logs.add({
          type: 'error',
          message: `An error occured while loading ${name}: ${e.message}`
        })
      }
      pluginApi.pluginId = null
    }
  }

  // Locales
  try {
    const folder = fs.existsSync(id) ? id : dependencies.getPath({ id, file: pluginApi.cwd })
    locales.loadFolder(folder, context)
  } catch (e) {}
}

function getApi (folder) {
  const pluginApi = pluginApiInstances.get(folder)
  return pluginApi
}

function callHook ({ id, args, file }, context) {
  const pluginApi = getApi(file)
  if (!pluginApi) return
  const fns = pluginApi.hooks[id]
  log(`Hook ${id}`, fns.length, 'handlers')
  fns.forEach(fn => fn(...args))
}

async function getLogo (plugin, context) {
  const { id, baseDir } = plugin
  const cached = logoCache.get(id)
  if (cached) {
    return cached
  }
  const folder = dependencies.getPath({ id, file: baseDir })
  const file = path.join(folder, 'logo.png')
  if (fs.existsSync(file)) {
    const data = `/_plugin-logo/${encodeURIComponent(id)}`
    logoCache.set(id, data)
    return data
  }
  return null
}

function getInstallation (context) {
  if (!eventsInstalled) {
    eventsInstalled = true

    // Package installation progress events
    installProgress.on('progress', value => {
      if (progress.get(PROGRESS_ID)) {
        progress.set({ id: PROGRESS_ID, progress: value }, context)
      }
    })
    installProgress.on('log', message => {
      if (progress.get(PROGRESS_ID)) {
        progress.set({ id: PROGRESS_ID, info: message }, context)
      }
    })
  }

  return {
    id: 'plugin-install',
    pluginId: currentPluginId,
    step: installationStep,
    prompts: prompts.list()
  }
}

function install (id, context) {
  return progress.wrap(PROGRESS_ID, context, async setProgress => {
    setProgress({
      status: 'plugin-install',
      args: [id]
    })
    currentPluginId = id
    installationStep = 'install'
    if (process.env.VUE_CLI_DEBUG && isOfficialPlugin(id)) {
      mockInstall(id, context)
    } else {
      await installPackage(cwd.get(), getCommand(cwd.get()), null, id)
    }
    await initPrompts(id, context)
    installationStep = 'config'

    notify({
      title: `Plugin installed`,
      message: `Plugin ${id} installed, next step is configuration`,
      icon: 'done'
    })

    return getInstallation(context)
  })
}

function mockInstall (id, context) {
  const pkg = folders.readPackage(cwd.get(), context, true)
  pkg.devDependencies[id] = '*'
  folders.writePackage({ file: cwd.get(), data: pkg }, context)
  return true
}

function installLocal (context) {
  const projects = require('./projects')
  const folder = cwd.get()
  cwd.set(projects.getCurrent(context).path, context)
  return progress.wrap(PROGRESS_ID, context, async setProgress => {
    const pkg = loadModule(path.resolve(folder, 'package.json'), cwd.get(), true)

    const id = pkg.name

    setProgress({
      status: 'plugin-install',
      args: [id]
    })
    currentPluginId = id
    installationStep = 'install'

    // Update package.json
    {
      const pkgFile = path.resolve(cwd.get(), 'package.json')
      const pkg = await fs.readJson(pkgFile)
      if (!pkg.devDependencies) pkg.devDependencies = {}
      pkg.devDependencies[id] = `file:${folder}`
      await fs.writeJson(pkgFile, pkg, {
        spaces: 2
      })
    }

    const from = path.resolve(cwd.get(), folder)
    const to = path.resolve(cwd.get(), 'node_modules', ...id.split('/'))
    console.log('copying from', from, 'to', to)
    await fs.copy(from, to)

    await initPrompts(id, context)
    installationStep = 'config'

    notify({
      title: `Plugin installed`,
      message: `Plugin ${id} installed, next step is configuration`,
      icon: 'done'
    })

    return getInstallation(context)
  })
}

function uninstall (id, context) {
  return progress.wrap(PROGRESS_ID, context, async setProgress => {
    setProgress({
      status: 'plugin-uninstall',
      args: [id]
    })
    installationStep = 'uninstall'
    currentPluginId = id
    if (process.env.VUE_CLI_DEBUG && isOfficialPlugin(id)) {
      mockUninstall(id, context)
    } else {
      await uninstallPackage(cwd.get(), getCommand(cwd.get()), null, id)
    }
    currentPluginId = null
    installationStep = null

    notify({
      title: `Plugin uninstalled`,
      message: `Plugin ${id} uninstalled`,
      icon: 'done'
    })

    return getInstallation(context)
  })
}

function mockUninstall (id, context) {
  const pkg = folders.readPackage(cwd.get(), context, true)
  delete pkg.devDependencies[id]
  folders.writePackage({ file: cwd.get(), data: pkg }, context)
  return true
}

function runInvoke (id, context) {
  return progress.wrap(PROGRESS_ID, context, async setProgress => {
    setProgress({
      status: 'plugin-invoke',
      args: [id]
    })

    clearModule('@vue/cli-service/webpack.config.js', cwd.get())

    currentPluginId = id
    // Allow plugins that don't have a generator
    if (resolveModule(`${id}/generator`, cwd.get())) {
      await invoke(id, prompts.getAnswers(), cwd.get())
    }
    // Run plugin api
    runPluginApi(id, getApi(cwd.get()), context)
    installationStep = 'diff'

    notify({
      title: `Plugin invoked successfully`,
      message: `Plugin ${id} invoked successfully`,
      icon: 'done'
    })

    return getInstallation(context)
  })
}

function finishInstall (context) {
  installationStep = null
  currentPluginId = null
  return getInstallation(context)
}

async function initPrompts (id, context) {
  await prompts.reset()
  try {
    let data = require(path.join(dependencies.getPath({ id, file: cwd.get() }), 'prompts'))
    if (typeof data === 'function') {
      data = await data()
    }
    data.forEach(prompts.add)
  } catch (e) {
    console.warn(`No prompts found for ${id}`)
  }
  await prompts.start()
}

function update ({ id, full }, context) {
  return progress.wrap('plugin-update', context, async setProgress => {
    setProgress({
      status: 'plugin-update',
      args: [id]
    })
    currentPluginId = id
    const plugin = findOne({ id, file: cwd.get() }, context)
    const { current, wanted, localPath } = await dependencies.getVersion(plugin, context)

    if (localPath) {
      await updateLocalPackage({ cwd: cwd.get(), id, localPath, full }, context)
    } else {
      await updatePackage(cwd.get(), getCommand(cwd.get()), null, id)
    }

    logs.add({
      message: `Plugin ${id} updated from ${current} to ${wanted}`,
      type: 'info'
    }, context)

    notify({
      title: `Plugin updated`,
      message: `Plugin ${id} was successfully updated`,
      icon: 'done'
    })

    await resetPluginApi({ file: cwd.get() }, context)
    dependencies.invalidatePackage({ id }, context)

    currentPluginId = null
    return findOne({ id, file: cwd.get() }, context)
  })
}

async function updateLocalPackage ({ id, cwd, localPath, full = true }, context) {
  const from = path.resolve(cwd, localPath)
  const to = path.resolve(cwd, 'node_modules', ...id.split('/'))
  let filterRegEx
  if (full) {
    await fs.remove(to)
    filterRegEx = /\.git/
  } else {
    filterRegEx = /(\.git|node_modules)/
  }
  await fs.copy(from, to, {
    filter: (file) => !file.match(filterRegEx)
  })
}

async function updateAll (context) {
  return progress.wrap('plugins-update', context, async setProgress => {
    const plugins = await list(cwd.get(), context, { resetApi: false })
    let updatedPlugins = []
    for (const plugin of plugins) {
      const version = await dependencies.getVersion(plugin, context)
      if (version.current !== version.wanted) {
        updatedPlugins.push(plugin)
        dependencies.invalidatePackage({ id: plugin.id }, context)
      }
    }

    if (!updatedPlugins.length) {
      notify({
        title: `No updates available`,
        message: `No plugin to update in the version ranges declared in package.json`,
        icon: 'done'
      })
      return []
    }

    setProgress({
      status: 'plugins-update',
      args: [updatedPlugins.length]
    })

    await updatePackage(cwd.get(), getCommand(cwd.get()), null, updatedPlugins.map(
      p => p.id
    ).join(' '))

    notify({
      title: `Plugins updated`,
      message: `${updatedPlugins.length} plugin(s) were successfully updated`,
      icon: 'done'
    })

    await resetPluginApi({ file: cwd.get() }, context)

    return updatedPlugins
  })
}

async function callAction ({ id, params, file = cwd.get() }, context) {
  const pluginApi = getApi(file)

  context.pubsub.publish(channels.PLUGIN_ACTION_CALLED, {
    pluginActionCalled: { id, params }
  })
  log('PluginAction called', id, params)
  const results = []
  const errors = []
  const list = pluginApi.actions.get(id)
  if (list) {
    for (const cb of list) {
      let result = null
      let error = null
      try {
        result = await cb(params)
      } catch (e) {
        error = e
      }
      results.push(result)
      errors.push(error)
    }
  }
  context.pubsub.publish(channels.PLUGIN_ACTION_RESOLVED, {
    pluginActionResolved: { id, params, results, errors }
  })
  log('PluginAction resolved', id, params, 'results:', results, 'errors:', errors)
  return { id, params, results, errors }
}

function serveFile ({ pluginId, projectId = null, file }, res) {
  let baseFile = cwd.get()
  if (projectId) {
    const projects = require('./projects')
    const project = projects.findOne(projectId, getContext())
    if (project) {
      baseFile = project.path
    }
  }

  if (pluginId) {
    const basePath = pluginId === '.' ? baseFile : dependencies.getPath({ id: decodeURIComponent(pluginId), file: baseFile })
    if (basePath) {
      res.sendFile(path.join(basePath, file))
      return
    }
  } else {
    console.log('serve issue', 'pluginId:', pluginId, 'projectId:', projectId, 'file:', file)
  }

  res.status(404)
  res.send(`Addon ${pluginId} not found in loaded addons. Try opening a vue-cli project first?`)
}

function serve (req, res) {
  const { id: pluginId, 0: file } = req.params
  serveFile({ pluginId, file: path.join('ui-public', file) }, res)
}

function serveLogo (req, res) {
  const { id: pluginId } = req.params
  const { project: projectId } = req.query
  serveFile({ pluginId, projectId, file: 'logo.png' }, res)
}

module.exports = {
  list,
  findOne,
  getLogo,
  getInstallation,
  install,
  installLocal,
  uninstall,
  update,
  updateAll,
  runInvoke,
  resetPluginApi,
  getApi,
  finishInstall,
  callAction,
  callHook,
  serve,
  serveLogo
}


jest.setTimeout(15000)

const path = require('path')
const portfinder = require('portfinder')
const { createServer } = require('http-server')
const { defaultPreset } = require('@vue/cli/lib/options')
const create = require('@vue/cli-test-utils/createTestProject')
const launchPuppeteer = require('@vue/cli-test-utils/launchPuppeteer')

let server, browser, page
test('build as wc in async mode', async () => {
  const project = await create('build-wc-async', defaultPreset)

  const { stdout } = await project.run(`vue-cli-service build --target wc-async **/*.vue`)
  expect(stdout).toMatch('Build complete.')

  expect(project.has('dist/demo.html')).toBe(true)
  expect(project.has('dist/build-wc-async.js')).toBe(true)
  expect(project.has('dist/build-wc-async.min.js')).toBe(true)

  // code-split chunks
  expect(project.has('dist/build-wc-async.1.js')).toBe(true)
  expect(project.has('dist/build-wc-async.1.min.js')).toBe(true)
  expect(project.has('dist/build-wc-async.2.js')).toBe(true)
  expect(project.has('dist/build-wc-async.2.min.js')).toBe(true)

  const port = await portfinder.getPortPromise()
  server = createServer({ root: path.join(project.dir, 'dist') })

  await new Promise((resolve, reject) => {
    server.listen(port, err => {
      if (err) return reject(err)
      resolve()
    })
  })

  const launched = await launchPuppeteer(`http://localhost:${port}/demo.html`)
  browser = launched.browser
  page = launched.page

  const styleCount = await page.evaluate(() => {
    return document.querySelector('build-wc-async-app').shadowRoot.querySelectorAll('style').length
  })
  expect(styleCount).toBe(2) // should contain styles from both app and child

  const h1Text = await page.evaluate(() => {
    return document.querySelector('build-wc-async-app').shadowRoot.querySelector('h1').textContent
  })
  expect(h1Text).toMatch('Welcome to Your Vue.js App')

  const childStyleCount = await page.evaluate(() => {
    return document.querySelector('build-wc-async-hello-world').shadowRoot.querySelectorAll('style').length
  })
  expect(childStyleCount).toBe(1)

  const h3Text = await page.evaluate(() => {
    return document.querySelector('build-wc-async-hello-world').shadowRoot.querySelector('h3').textContent
  })
  expect(h3Text).toMatch('Installed CLI Plugins')
})

afterAll(async () => {
  if (browser) {
    await browser.close()
  }
  if (server) {
    server.close()
  }
})


#import "./viewFragment.gql"

subscription viewRemoved {
  viewRemoved {
    ...view
  }
}


@vue/eslint-config-prettier

eslint-config-prettier for vue-cli


keep keep keep keep keep replace keep keep keep keep

// should evaluate config scripts to reflect environment variable changes


module.exports = function injectImportsAndOptions (source, imports, injections) {
  imports = imports instanceof Set ? Array.from(imports) : imports
  injections = injections instanceof Set ? Array.from(injections) : injections

  const hasImports = imports && imports.length > 0
  const hasInjections = injections && injections.length > 0

  if (!hasImports && !hasInjections) {
    return source
  }

  const recast = require('recast')
  const ast = recast.parse(source)

  if (hasImports) {
    const toImport = i => recast.parse(`${i}\n`).program.body[0]
    const importDeclarations = []
    let lastImportIndex = -1

    recast.types.visit(ast, {
      visitImportDeclaration ({ node }) {
        lastImportIndex = ast.program.body.findIndex(n => n === node)
        importDeclarations.push(node)
        return false
      }
    })
    // avoid blank line after the previous import
    if (lastImportIndex !== -1) {
      delete ast.program.body[lastImportIndex].loc
    }

    const nonDuplicates = i => {
      return !importDeclarations.some(node => {
        const result = node.source.raw === i.source.raw && node.specifiers.length === i.specifiers.length

        return result && node.specifiers.every((item, index) => {
          return i.specifiers[index].local.name === item.local.name
        })
      })
    }

    const newImports = imports.map(toImport).filter(nonDuplicates)
    ast.program.body.splice(lastImportIndex + 1, 0, ...newImports)
  }

  if (hasInjections) {
    const toProperty = i => {
      return recast.parse(`({${i}})`).program.body[0].expression.properties
    }
    recast.types.visit(ast, {
      visitNewExpression ({ node }) {
        if (node.callee.name === 'Vue') {
          const options = node.arguments[0]
          if (options && options.type === 'ObjectExpression') {
            const nonDuplicates = i => {
              return !options.properties.slice(0, -1).some(p => {
                return p.key.name === i[0].key.name &&
                  recast.print(p.value).code === recast.print(i[0].value).code
              })
            }
            // inject at index length - 1 as it's usually the render fn
            options.properties = [
              ...options.properties.slice(0, -1),
              ...([].concat(...injections.map(toProperty).filter(nonDuplicates))),
              ...options.properties.slice(-1)
            ]
          }
        }
        return false
      }
    })
  }

  return recast.print(ast).code
}


const chalk = require('chalk')
const invoke = require('./invoke')
const { loadOptions } = require('./options')
const { installPackage } = require('./util/installDeps')
const {
  log,
  error,
  hasProjectYarn,
  resolvePluginId,
  resolveModule,
  loadModule
} = require('@vue/cli-shared-utils')

async function add (pluginName, options = {}, context = process.cwd()) {
  // special internal "plugins"
  if (/^(@vue\/)?router$/.test(pluginName)) {
    return addRouter(context)
  }
  if (/^(@vue\/)?vuex$/.test(pluginName)) {
    return addVuex(context)
  }

  const packageName = resolvePluginId(pluginName)

  log()
  log(`📦  Installing ${chalk.cyan(packageName)}...`)
  log()

  const packageManager = loadOptions().packageManager || (hasProjectYarn(context) ? 'yarn' : 'npm')
  await installPackage(context, packageManager, options.registry, packageName)

  log(`${chalk.green('✔')}  Successfully installed plugin: ${chalk.cyan(packageName)}`)
  log()

  const generatorPath = resolveModule(`${packageName}/generator`, context)
  if (generatorPath) {
    invoke(pluginName, options, context)
  } else {
    log(`Plugin ${packageName} does not have a generator to invoke`)
  }
}

async function addRouter (context) {
  const inquirer = require('inquirer')
  const options = await inquirer.prompt([{
    name: 'routerHistoryMode',
    type: 'confirm',
    message: `Use history mode for router? ${chalk.yellow(`(Requires proper server setup for index fallback in production)`)}`
  }])
  invoke.runGenerator(context, {
    id: 'core:router',
    apply: loadModule('@vue/cli-service/generator/router', context),
    options
  })
}

async function addVuex (context) {
  invoke.runGenerator(context, {
    id: 'core:vuex',
    apply: loadModule('@vue/cli-service/generator/vuex', context)
  })
}

module.exports = (...args) => {
  return add(...args).catch(err => {
    error(err)
    if (!process.env.VUE_CLI_TEST) {
      process.exit(1)
    }
  })
}


#import "./projectFragment.gql"

mutation projectCreate ($input: ProjectCreateInput!) {
  projectCreate(input: $input) {
    ...project
  }
}