fix #94, skip 'source' property of Element from being categorized as sub-elements

# Element - cascading element tree

## Class Element

    debug = require('debug')('yang:element')
    delegate = require 'delegates'
    Emitter = require('events').EventEmitter
    Emitter.defaultMaxListeners = 100

    class Element
      @property: (prop, desc) ->
        Object.defineProperty @prototype, prop, desc
      @use: ->
        res = [].concat(arguments...)
          .filter (x) -> x?
          .map (elem) =>
            exists = Element::match.call this, elem.kind, elem.tag
            if exists?
              debug "use: using previously loaded '#{elem.kind}:#{elem.tag}'"
              return exists
            try Element::merge.call this, elem
            catch e
              throw @error "use: unable to merge '#{elem.kind}:#{elem.tag}'", e
        return switch
          when res.length > 1  then res
          when res.length is 1 then res[0]
          else undefined
      @debug: -> debug @uri, arguments...
      @error: (err, ctx=this) ->
        unless err instanceof Error
          err = new Error err
        err.uri = @uri
        err.src = this
        err.ctx = ctx
        return err

      constructor: (@kind, @tag, source={}) ->
        unless @kind?
          throw @error "must supply 'kind' to create a new Element"
        unless source instanceof Object
          throw @error "must supply 'source' as an object"
        Object.defineProperties this,
          parent: value: null, writable: true
          origin: value: null, writable: true
          source: value: source, writable: true
          index:  value: 0, writable: true
          state:  value: {}, writable: true
          emitter: value: new Emitter

      error: @error
      debug: @debug

      delegate @prototype, 'emitter'
        .method 'emit'
        .method 'once'
        .method 'on'

      delegate @prototype, 'source'
        .getter 'scope'
        .getter 'construct'

      delegate @prototype, 'cache'
        .getter 'elements'
        .getter 'nodes'
        .getter 'attrs'

### Computed Properties

      @property 'datakey',
        get: -> @tag ? @kind

      @property 'uri',
        get: ->
          mark = @kind
          mark += "(#{@tag})" if @tag? and @source.argument not in [ 'value', 'text' ]
          return mark unless @parent instanceof Element
          return "#{@parent.uri}/#{mark}"

      @property 'root',
        get: -> switch
          when @parent instanceof Element then @parent.root
          when @origin instanceof Element then @origin.root
          else this

      @property 'node',
        get: -> @construct instanceof Function

      @property 'cache',
        get: ->
          unless this._cache?
            elements = (v for own k, v of this when k not in [ 'parent', 'origin', 'tag', '_cache', 'source' ])
              .reduce ((a,b) -> switch
                when b instanceof Element then a.concat b
                when b instanceof Array
                  a.concat b.filter (x) -> x instanceof Element
                else a
              ), []
            elements = elements.sort (a,b) -> a.index - b.index
            this._cache =
              elements: elements
              nodes: elements.filter (x) -> x.node is true
              attrs: elements.filter (x) -> x.node is false
          return this._cache

      @property '*',     get: -> @nodes
      @property '..',    get: -> @parent

## Instance-level methods

### clone

      clone: (relative=false) ->
        @debug "cloning #{@kind}:#{@tag} with #{@elements.length} elements"
        copy = (new @constructor @kind, @tag, @source).extends @elements.map (x) =>
          c = x.clone(relative)
          c.parent = x.parent unless x.parent is this
          return c
        copy.state = Object.create(@state)
        copy.state.relative = relative
        copy.origin = @origin ? this
        return copy

### extends (elements...)

This is the primary mechanism for defining sub-elements to become part
of the element tree

      extends: ->
        elems = ([].concat arguments...).filter (x) -> x? and !!x
        return this unless elems.length > 0
        elems.forEach (expr) => @merge expr
        @emit 'change', elems...
        return this

### merge (element)

This helper method merges a specific Element into current Element
while performing `@scope` validations.

      merge: (elem, opts={}) ->
        unless elem instanceof Element
          throw @error "cannot merge invalid element into Element", elem
        elem.index = @elements.length if @elements?
        elem.parent = this
        this._cache = null

        _merge = (item) ->
          if not item.node or opts.append or item.datakey not in (@keys ? [])
            @push item
            true
          else if opts.replace is true
            for x, i in this when x.datakey is item.datakey
              @splice i, 1, item
              break
            true
          else false

        unless @scope?
          unless @hasOwnProperty elem.kind
            @[elem.kind] = elem
            return elem

          unless Array.isArray @[elem.kind]
            exists = @[elem.kind]
            @[elem.kind] = [ exists ]
            Object.defineProperty @[elem.kind], 'keys',
              get: (-> @map (x) -> x.datakey ).bind @[elem.kind]

          unless _merge.call @[elem.kind], elem
            throw @error "constraint violation for '#{elem.kind} #{elem.datakey}' - cannot define more than once"

          return elem

        unless elem.kind of @scope
          if elem.scope?
            @debug @scope
            throw @error "scope violation - invalid '#{elem.kind}' extension found"
          else
            @scope[elem.kind] = '*' # this is hackish...

        switch @scope[elem.kind]
          when '0..n', '1..n', '*'
            unless @hasOwnProperty elem.kind
              @[elem.kind] = []
              Object.defineProperty @[elem.kind], 'keys',
                get: (-> @map (x) -> x.datakey ).bind @[elem.kind]
            unless _merge.call @[elem.kind], elem
              throw @error "constraint violation for '#{elem.kind} #{elem.datakey}' - already defined"
          when '0..1', '1'
            unless @hasOwnProperty elem.kind
              @[elem.kind] = elem
            else if opts.replace is true
              @debug "replacing pre-existing #{elem.kind}"
              @[elem.kind] = elem
            else
              throw @error "constraint violation for '#{elem.kind}' - cannot define more than once"
          else
            throw @error "unrecognized scope constraint defined for '#{elem.kind}' with #{@scope[elem.kind]}"

        return elem

      removes: ->
        elems = ([].concat arguments...).filter (x) -> x? and !!x
        return this unless elems.length > 0
        elems.forEach (expr) => @remove expr
        @emit 'change', elems...
        return this

      remove: (elem) ->
        unless elem instanceof Element
          throw @error "cannot remove a non-Element from an Element", elem

        exists = Element::match.call this, elem.kind, elem.datakey
        return this unless exists?

        if Array.isArray @[elem.kind]
          @[elem.kind] = @[elem.kind].filter (x) -> x.datakey isnt elem.datakey
          delete @[elem.kind] unless @[elem.kind].length
        else
          delete @[elem.kind]

        this._cache = null
        return this

### update (element)

This alternative form of [merge](#merge-element) performs conditional
merge based on existence check. It is considered *safer* alternative
to direct [merge](#merge-element) call.

      # performs conditional merge based on existence
      update: (elem) ->
        unless elem instanceof Element
          throw @error "cannot update a non-Element into an Element", elem

        #@debug "update with #{elem.kind}/#{elem.tag}"
        exists = switch
          when elem.tag? then Element::match.call this, elem.kind, elem.datakey
          else Element::match.call this, elem.kind
        return @merge elem unless exists?

        #@debug "update #{exists.kind} in-place for #{elem.elements.length} elements"
        exists.update target for target in elem.elements
        return exists

      # Looks for matching Elements using kind and tag
      # Direction: up the hierarchy (towards root)
      lookup: (kind, tag) ->
        res = switch
          when this not instanceof Object then undefined
          when this instanceof Element then @match kind, tag
          else Element::match.call this, kind, tag
        res ?= switch
          when @origin? then Element::lookup.apply @origin, arguments
          when @parent? then Element::lookup.apply @parent, arguments
          else Element::match.call @constructor, kind, tag
        return res

      # Looks for matching Elements using YPATH notation
      # Direction: down the hierarchy (away from root)
      at: -> @locate arguments...
      locate: (ypath) ->
        return unless ypath?
        if typeof ypath is 'string'
          @debug "locate: #{ypath}"
          ypath = ypath.replace /\s/g, ''
          if (/^\//.test ypath) and this isnt @root
            return @root.locate ypath
          [ key, rest... ] = ypath.split('/').filter (e) -> !!e
        else
          @debug "locate: #{ypath.join('/')}"
          [ key, rest... ] = ypath
        return this unless key?

        match = switch
          when key is '..' then @match key
          else @match '*', key

        return switch
          when rest.length is 0 then match
          else match?.locate rest

      # Looks for a matching Element(s) in immediate sub-elements
      match: (kind, tag) ->
        return unless kind? and @[kind]?
        return @[kind] unless tag?

        match = @[kind]
        match = [ match ] unless match instanceof Array
        return match if tag is '*'

        for elem in match when elem instanceof Element
          return elem if tag is elem.datakey or tag is elem.tag
        return undefined

### toJSON

Converts the Element into a JS object

      toJSON: (opts={ tag: true, extended: false }) ->
        #@debug "converting #{@kind} toJSON with #{@elements.length}"
        sub =
          @elements
            .filter (x) => opts.extended or x.parent is this
            .reduce ((a,b) ->
              for k, v of b.toJSON()
                if a[k] instanceof Object
                  a[k][kk] = vv for kk, vv of v if v instanceof Object
                else
                  a[k] = v
              return a
            ), {}
        if opts.tag
          "#{@kind}": switch
            when Object.keys(sub).length > 0
              if @tag? then "#{@tag}": sub else sub
            when @tag instanceof Object then "#{@tag}"
            else @tag
        else sub

## Export Element Class

    module.exports = Element

# Element - cascading element tree

## Class Element

    debug = require('debug')('yang:element')
    delegate = require 'delegates'
    Emitter = require('events').EventEmitter
    Emitter.defaultMaxListeners = 100

    class Element
      @property: (prop, desc) ->
        Object.defineProperty @prototype, prop, desc
      @use: ->
        res = [].concat(arguments...)
          .filter (x) -> x?
          .map (elem) =>
            exists = Element::match.call this, elem.kind, elem.tag
            if exists?
              debug "use: using previously loaded '#{elem.kind}:#{elem.tag}'"
              return exists
            try Element::merge.call this, elem
            catch e
              throw @error "use: unable to merge '#{elem.kind}:#{elem.tag}'", e
        return switch
          when res.length > 1  then res
          when res.length is 1 then res[0]
          else undefined
      @debug: -> debug @uri, arguments...
      @error: (err, ctx=this) ->
        unless err instanceof Error
          err = new Error err
        err.uri = @uri
        err.src = this
        err.ctx = ctx
        return err

      constructor: (@kind, @tag, source={}) ->
        unless @kind?
          throw @error "must supply 'kind' to create a new Element"
        unless source instanceof Object
          throw @error "must supply 'source' as an object"
        Object.defineProperties this,
          parent: value: null, writable: true
          origin: value: null, writable: true
          source: value: source, writable: true
          index:  value: 0, writable: true
          state:  value: {}, writable: true
          emitter: value: new Emitter

      error: @error
      debug: @debug

      delegate @prototype, 'emitter'
        .method 'emit'
        .method 'once'
        .method 'on'

      delegate @prototype, 'source'
        .getter 'scope'
        .getter 'construct'

      delegate @prototype, 'cache'
        .getter 'elements'
        .getter 'nodes'
        .getter 'attrs'

### Computed Properties

      @property 'datakey',
        get: -> @tag ? @kind

      @property 'uri',
        get: ->
          mark = @kind
          mark += "(#{@tag})" if @tag? and @source.argument not in [ 'value', 'text' ]
          return mark unless @parent instanceof Element
          return "#{@parent.uri}/#{mark}"

      @property 'root',
        get: -> switch
          when @parent instanceof Element then @parent.root
          when @origin instanceof Element then @origin.root
          else this

      @property 'node',
        get: -> @construct instanceof Function

      @property 'cache',
        get: ->
          unless this._cache?
            elements = (v for own k, v of this when k not in [ 'parent', 'origin', 'tag', '_cache' ])
              .reduce ((a,b) -> switch
                when b instanceof Element then a.concat b
                when b instanceof Array
                  a.concat b.filter (x) -> x instanceof Element
                else a
              ), []
            elements = elements.sort (a,b) -> a.index - b.index
            this._cache =
              elements: elements
              nodes: elements.filter (x) -> x.node is true
              attrs: elements.filter (x) -> x.node is false
          return this._cache

      @property '*',     get: -> @nodes
      @property '..',    get: -> @parent

## Instance-level methods

### clone

      clone: (relative=false) ->
        @debug "cloning #{@kind}:#{@tag} with #{@elements.length} elements"
        copy = (new @constructor @kind, @tag, @source).extends @elements.map (x) =>
          c = x.clone(relative)
          c.parent = x.parent unless x.parent is this
          return c
        copy.state = Object.create(@state)
        copy.state.relative = relative
        copy.origin = @origin ? this
        return copy

### extends (elements...)

This is the primary mechanism for defining sub-elements to become part
of the element tree

      extends: ->
        elems = ([].concat arguments...).filter (x) -> x? and !!x
        return this unless elems.length > 0
        elems.forEach (expr) => @merge expr
        @emit 'change', elems...
        return this

### merge (element)

This helper method merges a specific Element into current Element
while performing `@scope` validations.

      merge: (elem, opts={}) ->
        unless elem instanceof Element
          throw @error "cannot merge invalid element into Element", elem
        elem.index = @elements.length if @elements?
        elem.parent = this
        this._cache = null

        _merge = (item) ->
          if not item.node or opts.append or item.datakey not in (@keys ? [])
            @push item
            true
          else if opts.replace is true
            for x, i in this when x.datakey is item.datakey
              @splice i, 1, item
              break
            true
          else false

        unless @scope?
          unless @hasOwnProperty elem.kind
            @[elem.kind] = elem
            return elem

          unless Array.isArray @[elem.kind]
            exists = @[elem.kind]
            @[elem.kind] = [ exists ]
            Object.defineProperty @[elem.kind], 'keys',
              get: (-> @map (x) -> x.datakey ).bind @[elem.kind]

          unless _merge.call @[elem.kind], elem
            throw @error "constraint violation for '#{elem.kind} #{elem.datakey}' - cannot define more than once"

          return elem

        unless elem.kind of @scope
          if elem.scope?
            @debug @scope
            throw @error "scope violation - invalid '#{elem.kind}' extension found"
          else
            @scope[elem.kind] = '*' # this is hackish...

        switch @scope[elem.kind]
          when '0..n', '1..n', '*'
            unless @hasOwnProperty elem.kind
              @[elem.kind] = []
              Object.defineProperty @[elem.kind], 'keys',
                get: (-> @map (x) -> x.datakey ).bind @[elem.kind]
            unless _merge.call @[elem.kind], elem
              throw @error "constraint violation for '#{elem.kind} #{elem.datakey}' - already defined"
          when '0..1', '1'
            unless @hasOwnProperty elem.kind
              @[elem.kind] = elem
            else if opts.replace is true
              @debug "replacing pre-existing #{elem.kind}"
              @[elem.kind] = elem
            else
              throw @error "constraint violation for '#{elem.kind}' - cannot define more than once"
          else
            throw @error "unrecognized scope constraint defined for '#{elem.kind}' with #{@scope[elem.kind]}"

        return elem

      removes: ->
        elems = ([].concat arguments...).filter (x) -> x? and !!x
        return this unless elems.length > 0
        elems.forEach (expr) => @remove expr
        @emit 'change', elems...
        return this

      remove: (elem) ->
        unless elem instanceof Element
          throw @error "cannot remove a non-Element from an Element", elem

        exists = Element::match.call this, elem.kind, elem.datakey
        return this unless exists?

        if Array.isArray @[elem.kind]
          @[elem.kind] = @[elem.kind].filter (x) -> x.datakey isnt elem.datakey
          delete @[elem.kind] unless @[elem.kind].length
        else
          delete @[elem.kind]

        this._cache = null
        return this

### update (element)

This alternative form of [merge](#merge-element) performs conditional
merge based on existence check. It is considered *safer* alternative
to direct [merge](#merge-element) call.

      # performs conditional merge based on existence
      update: (elem) ->
        unless elem instanceof Element
          throw @error "cannot update a non-Element into an Element", elem

        #@debug "update with #{elem.kind}/#{elem.tag}"
        exists = switch
          when elem.tag? then Element::match.call this, elem.kind, elem.datakey
          else Element::match.call this, elem.kind
        return @merge elem unless exists?

        #@debug "update #{exists.kind} in-place for #{elem.elements.length} elements"
        exists.update target for target in elem.elements
        return exists

      # Looks for matching Elements using kind and tag
      # Direction: up the hierarchy (towards root)
      lookup: (kind, tag) ->
        res = switch
          when this not instanceof Object then undefined
          when this instanceof Element then @match kind, tag
          else Element::match.call this, kind, tag
        res ?= switch
          when @origin? then Element::lookup.apply @origin, arguments
          when @parent? then Element::lookup.apply @parent, arguments
          else Element::match.call @constructor, kind, tag
        return res

      # Looks for matching Elements using YPATH notation
      # Direction: down the hierarchy (away from root)
      at: -> @locate arguments...
      locate: (ypath) ->
        return unless ypath?
        if typeof ypath is 'string'
          @debug "locate: #{ypath}"
          ypath = ypath.replace /\s/g, ''
          if (/^\//.test ypath) and this isnt @root
            return @root.locate ypath
          [ key, rest... ] = ypath.split('/').filter (e) -> !!e
        else
          @debug "locate: #{ypath.join('/')}"
          [ key, rest... ] = ypath
        return this unless key?

        match = switch
          when key is '..' then @match key
          else @match '*', key

        return switch
          when rest.length is 0 then match
          else match?.locate rest

      # Looks for a matching Element(s) in immediate sub-elements
      match: (kind, tag) ->
        return unless kind? and @[kind]?
        return @[kind] unless tag?

        match = @[kind]
        match = [ match ] unless match instanceof Array
        return match if tag is '*'

        for elem in match when elem instanceof Element
          return elem if tag is elem.datakey or tag is elem.tag
        return undefined

### toJSON

Converts the Element into a JS object

      toJSON: (opts={ tag: true, extended: false }) ->
        #@debug "converting #{@kind} toJSON with #{@elements.length}"
        sub =
          @elements
            .filter (x) => opts.extended or x.parent is this
            .reduce ((a,b) ->
              for k, v of b.toJSON()
                if a[k] instanceof Object
                  a[k][kk] = vv for kk, vv of v if v instanceof Object
                else
                  a[k] = v
              return a
            ), {}
        if opts.tag
          "#{@kind}": switch
            when Object.keys(sub).length > 0
              if @tag? then "#{@tag}": sub else sub
            when @tag instanceof Object then "#{@tag}"
            else @tag
        else sub

## Export Element Class

    module.exports = Element


add `state.bind` and `state.fix`

add `state.bind` and `state.fix`

Portends deprecation of `state.method`.

## [state()](#state-function)

> [`state()`](/api/#state-function)
> [The `state` function](/docs/#getting-started--the-state-function)

The `state` module is exported as a function. Invoking this function is the
primary point of entry into the module. It is used either to:

1. generate a formal `StateExpression`; or

2. bestow an arbitrary `owner` object with a state implementation, based on the
   application of the provided `expression` to a new `RootState` — and then
   return the owner’s initial `State`.

All arguments are optional. If only one `object`-typed argument is provided,
it is assigned to the `expression` parameter. If no `owner` is present,
`state()` returns a `StateExpression` based on the contents of `expression`
(and `attributes`). If both an `owner` and `expression` are present, `state`
acts in the second capacity, causing `owner` to become stateful.

The `attributes` argument may include any of the words defined in
`STATE_ATTRIBUTE_MODIFIERS`, which are encoded into the provided `expression`.

> See also:
> [`State`][],
> [`STATE_ATTRIBUTES`][],
> [`StateExpression`][]

    state = ( owner, attributes, expression, options ) ->
      if arguments.length < 2
        if typeof owner is 'string'
        then attributes = owner
        else expression = owner
        owner = undefined
      else
        if typeof owner is 'string'
          options = expression
          expression = attributes
          attributes = owner
          owner = undefined
        if typeof attributes isnt 'string'
          options = expression
          expression = attributes
          attributes = undefined

Formalize the provided `expression` (even if `expression` is already a formal
`StateExpression`), incorporating any provided `attributes`.

      expression = new StateExpression attributes, expression

With an `owner` present, the inferred intent is to *implement* `expression`
into `owner`; otherwise the inference is only to *formalize* the `expression`
as a `StateExpression`.

      if owner
      then ( new RootState owner, expression, options )._current
      else expression

### Accessory properties

#### Metadata

Mix the project’s `meta` properties into the exported `state` function.

    O.assign state, meta

### Utility functions

#### [state.bind](#state-function--bind)

Used inside a state expression, a function `fn` wrapped with `state.bind` will
bind the context of `fn` either to any `State` created from that expression, or
when invoked for an object that inherits from the `owner` of the bound `State`,
to the corresponding **epistate** of that `State`.

Thusly bound methods, event listeners, etc., whose context would have normally
been the `owner`, still retain a reference thereto via `this.owner`.

* `fn` : ( any… ) → any

    state.bind = ( fn ) -> { type: 'state-bound-function', fn }

#### [state.fix](#state-function--fix)

Used inside a state expression, a combinator `fn` wrapped with `state.fix` will
be partially applied with a reference to `autostate`, the precise `State` to
which the combinator’s returned function will belong, and a reference to
`protostate`, the immediate **protostate** of `autostate`.

A method, event listener, etc. that is `fix`ed thusly has access to, and full
lexical awareness of, the particular `State` environment in which it exists.

* `fn` : ( autostate, protostate ) → ( any… ) → any

    state.fix = ( fn ) -> { type: 'state-fixed-function', fn }

#### [state.method](#state-function--method)

> Deprecate me

Returns a `factory`, nominally for internal use, which will flatten the scope
of the provided `fn`, reclose it both over any provided `bindings` and over a
set of `lexicals` based on `autostate`, which is provided to `factory` as the
`State` instance that will contain the **lexical state methods** that `factory`
produces.

Wrapping method functions with `state.method` inside a state expression is
useful particularly for exposing to the method body a correct reference to the
**protostate**, while also ensuring that the method is fully heritable by both
**substates** and **epistates** (inheritors of a protostate).

> [Lexical binding in state methods][]

> [`state.method`](/api/#state-function--method)

    state.method = do ->
      lexicals = ['__State__', 'autostate', 'protostate']

      pattern = ///^
        ( function
            \s*
          (?:[$_A-Za-z][$\w]*)?
            \s*
          \((?:[\s\S]*?)\)
            \s*
          \{
        )
        (\s\S]*)
      ///

      template = """
        return $1
          var superstate, owner;
          if ( this instanceof __State__ ) {
            superstate = this.superstate;
            owner = this.owner;
          }
        $2;
      """

      createMethod = ( factory, autostate, bindings, fn ) ->

Gather all the identifiers that the transformed `fn` will be closed over, and
arrange them into an array of named `params`.

        identifiers = if bindings? and ( typeof bindings is 'object' or
          typeof bindings is 'function' ) then O.keys bindings else []
        values = ( bindings[ id ] for id in identifiers )
        params = identifiers.concat lexicals

Gather all the values that will be mapped to the `params`.

        args = [ State, autostate, autostate.protostate() ]
        args = values.concat args if values.length

Write the body of the function that wraps `fn`, and inject `fn` with references
to the superstate and owner of the context `State`.

        body = Function::toString.call( fn ).replace pattern, template

Generate the wrapper function defined by `params` and `body`, and immediately
apply it with all of the closed binding values to produce the `method`.

        method = Function.apply( null, params.concat body ).apply( null, args )

Save the `factory` from which the method was created, so that the method can be
cloned or exported, e.g. by calling `express`, to a separate `State`, where the
method will need to be re-transformed with bindings to the environment of the
new state.

        method.factory = factory

        method.isLexicalStateMethod = true
        method

      return ( bindings, fn ) ->

        factory = ( autostate ) ->

Invocation from outside the module is forbidden, as this could expose
`bindings`, which must remain private.

          throw ReferenceError unless this is __MODULE__

With proper `bindings` and `fn` arguments, forward the invocation to
`createMethod`.

          if typeof bindings is 'object' and typeof fn is 'function'
            createMethod factory, autostate, bindings, fn

If passed `bindings` only, return a partially applied function that accepts
`fn` later.

          else if typeof bindings is 'object' and fn is undefined
            ( fn ) -> createMethod factory, autostate, bindings, fn

If passed only `fn` as the first argument, assume no `bindings`.

          else if typeof bindings is 'function' and fn is undefined
            createMethod factory, autostate, null, bindings

        factory.isLexicalStateMethodFactory = true
        factory

### Exports

The `state` module is exported via CommonJS on the server, and globally in the
browser.

    if O.env.server then module.exports = exports = state
    if O.env.client then global['state'] = state

## [state()](#state-function)

> [`state()`](/api/#state-function)
> [The `state` function](/docs/#getting-started--the-state-function)

The `state` module is exported as a function. Invoking this function is the
primary point of entry into the module. It is used either to:

1. generate a formal `StateExpression`; or

2. bestow an arbitrary `owner` object with a state implementation, based on the
   application of the provided `expression` to a new `RootState` — and then
   return the owner’s initial `State`.

All arguments are optional. If only one `object`-typed argument is provided,
it is assigned to the `expression` parameter. If no `owner` is present,
`state()` returns a `StateExpression` based on the contents of `expression`
(and `attributes`). If both an `owner` and `expression` are present, `state`
acts in the second capacity, causing `owner` to become stateful.

The `attributes` argument may include any of the words defined in
`STATE_ATTRIBUTE_MODIFIERS`, which are encoded into the provided `expression`.

> See also:
> [`State`][],
> [`STATE_ATTRIBUTES`][],
> [`StateExpression`][]

    state = ( owner, attributes, expression, options ) ->
      if arguments.length < 2
        if typeof owner is 'string'
        then attributes = owner
        else expression = owner
        owner = undefined
      else
        if typeof owner is 'string'
          options = expression
          expression = attributes
          attributes = owner
          owner = undefined
        if typeof attributes isnt 'string'
          options = expression
          expression = attributes
          attributes = undefined

Formalize the provided `expression` (even if `expression` is already a formal
`StateExpression`), incorporating any provided `attributes`.

      expression = new StateExpression attributes, expression

With an `owner` present, the inferred intent is to *implement* `expression`
into `owner`; otherwise the inference is only to *formalize* the `expression`
as a `StateExpression`.

      if owner
      then ( new RootState owner, expression, options )._current
      else expression

### Accessory properties

#### Metadata

Mix the project’s `meta` properties into the exported `state` function.

    O.assign state, meta

#### [state.method](#state-function--method)

Returns a `factory`, nominally for internal use, which will flatten the scope
of the provided `fn`, reclose it both over any provided `bindings` and over a
set of `lexicals` based on `autostate`, which is provided to `factory` as the
`State` instance that will contain the **lexical state methods** that `factory`
produces.

Wrapping method functions with `state.method` inside a state expression is
useful particularly for exposing to the method body a correct reference to the
**protostate**, while also ensuring that the method is fully heritable by both
**substates** and **epistates** (inheritors of a protostate).

> [Lexical binding in state methods][]

> [`state.method`](/api/#state-function--method)

    state.method = do ->
      lexicals = ['__State__', 'autostate', 'protostate']

      pattern = ///^
        ( function
            \s*
          (?:[$_A-Za-z][$\w]*)?
            \s*
          \((?:[\s\S]*?)\)
            \s*
          \{
        )
        (\s\S]*)
      ///

      template = """
        return $1
          var superstate, owner;
          if ( this instanceof __State__ ) {
            superstate = this.superstate;
            owner = this.owner;
          }
        $2;
      """

      createMethod = ( factory, autostate, bindings, fn ) ->

Gather all the identifiers that the transformed `fn` will be closed over, and
arrange them into an array of named `params`.

        identifiers = if bindings? and ( typeof bindings is 'object' or
          typeof bindings is 'function' ) then O.keys bindings else []
        values = ( bindings[ id ] for id in identifiers )
        params = identifiers.concat lexicals

Gather all the values that will be mapped to the `params`.

        args = [ State, autostate, autostate.protostate() ]
        args = values.concat args if values.length

Write the body of the function that wraps `fn`, and inject `fn` with references
to the superstate and owner of the context `State`.

        body = Function::toString.call( fn ).replace pattern, template

Generate the wrapper function defined by `params` and `body`, and immediately
apply it with all of the closed binding values to produce the `method`.

        method = Function.apply( null, params.concat body ).apply( null, args )

Save the `factory` from which the method was created, so that the method can be
cloned or exported, e.g. by calling `express`, to a separate `State`, where the
method will need to be re-transformed with bindings to the environment of the
new state.

        method.factory = factory

        method.isLexicalStateMethod = true
        method

      return ( bindings, fn ) ->

        factory = ( autostate ) ->

Invocation from outside the module is forbidden, as this could expose
`bindings`, which must remain private.

          throw ReferenceError unless this is __MODULE__

With proper `bindings` and `fn` arguments, forward the invocation to
`createMethod`.

          if typeof bindings is 'object' and typeof fn is 'function'
            createMethod factory, autostate, bindings, fn

If passed `bindings` only, return a partially applied function that accepts
`fn` later.

          else if typeof bindings is 'object' and fn is undefined
            ( fn ) -> createMethod factory, autostate, bindings, fn

If passed only `fn` as the first argument, assume no `bindings`.

          else if typeof bindings is 'function' and fn is undefined
            createMethod factory, autostate, null, bindings

        factory.isLexicalStateMethodFactory = true
        factory

### Exports

The `state` module is exported via CommonJS on the server, and globally in the
browser.

    if O.env.server then module.exports = exports = state
    if O.env.client then global['state'] = state


Clean up /upload routes

Clean up /upload routes

    express      = require 'express'
    errorHandler = require 'errorhandler'
    morgan       = require 'morgan'

    multer       = require 'multer'
    async        = require 'async'

    raven        = require 'raven'
    sentry       = require './sentry'

    app = express()
    app.use morgan 'combined'

    Upload = require 's3-uploader'
    s3 = new Upload process.env.AWS_BUCKET_NAME,
      awsBucketUrl: "https://s3-eu-west-1.amazonaws.com/#{process.env.AWS_BUCKET_NAME}/"
      awsBucketPath: process.env.AWS_BUCKET_PATH
      awsBucketAcl: 'public-read'
      awsHttpTimeout: 60000

      versions: [{
        original: true
        awsImageAcl: 'private'
      },{
        suffix: '-large'
        quality: 80
        maxHeight: 1040
        maxWidth: 1040
      },{
        suffix: '-medium'
        maxHeight: 780
        maxWidth: 780
      },{
        suffix: '-small'
        maxHeight: 320
        maxWidth: 320
      }]

    app.all '/upload', (req, res, next) ->
      res.once 'close', -> sentry.captureResClose res

      return next() if not req.get 'Origin'

      res.set 'Access-Control-Allow-Origin', '*'
      res.set 'Access-Control-Allow-Methods', 'POST'
      res.set 'Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'
      res.set 'Access-Control-Allow-Max-Age', 0

      return res.send 200 if req.method is 'OPTIONS'
      return next()

    app.post '/upload', multer(dest: require('os').tmpdir()), (req, res, next) ->
      console.log "Recieved #{Object.keys(req.files).length} files"

      async.mapSeries Object.keys(req.files), (key, cb) ->
        # @TODO check if file is valid image
        s3.upload req.files[key].path, {}, (err, images, meta) ->
          return cb err if err
          return cb null, images.splice(1)
      , (err, files) ->
        return next err if err
        sentry.captureHeaderSent req, files if res._headerSent
        return res.status(201).json files

    app.use raven.middleware.express sentry
    app.use errorHandler dumpExceptions: true, showStack: true

    if not module.parent
      app.listen process.env.PORT_WWW
      console.log "Server listening on port #{process.env.PORT_WWW}"
    else
      module.exports = app

    express      = require 'express'
    errorHandler = require 'errorhandler'
    morgan       = require 'morgan'

    multer       = require 'multer'
    async        = require 'async'

    raven        = require 'raven'
    sentry       = require './sentry'

    app = express()
    app.use morgan 'combined'

    Upload = require 's3-uploader'
    s3 = new Upload process.env.AWS_BUCKET_NAME,
      awsBucketUrl: "https://s3-eu-west-1.amazonaws.com/#{process.env.AWS_BUCKET_NAME}/"
      awsBucketPath: process.env.AWS_BUCKET_PATH
      awsBucketAcl: 'public-read'
      awsHttpTimeout: 60000

      versions: [{
        original: true
        awsImageAcl: 'private'
      },{
        suffix: '-large'
        quality: 80
        maxHeight: 1040
        maxWidth: 1040
      },{
        suffix: '-medium'
        maxHeight: 780
        maxWidth: 780
      },{
        suffix: '-small'
        maxHeight: 320
        maxWidth: 320
      }]

    app.all '/upload', (req, res, next) ->
      res.once 'close', -> sentry.captureResClose res

      return next() if not req.get 'Origin'

      res.set 'Access-Control-Allow-Origin', '*'
      res.set 'Access-Control-Allow-Methods', 'POST'
      res.set 'Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'
      res.set 'Access-Control-Allow-Max-Age', 0

      return res.send 200 if req.method is 'OPTIONS'
      return next()

    app.use '/upload', multer dest: require('os').tmpdir()

    app.options '/upload', (req, res, next) ->
      res.set 'access-control-allow-methods', 'OPTIONS, POST'
      res.set 'access-control-allow-headers', 'Content-Type'
      res.end()

    app.post '/upload', (req, res, next) ->
      console.log "Recieved #{Object.keys(req.files).length} files"

      async.mapSeries Object.keys(req.files), (key, cb) ->
        # @TODO check if file is valid image
        s3.upload req.files[key].path, {}, (err, images, meta) ->
          return cb err if err
          return cb null, images.splice(1)
      , (err, files) ->
        return next err if err
        sentry.captureHeaderSent req, files if res._headerSent
        return res.status(201).json files

    app.use raven.middleware.express sentry
    app.use errorHandler dumpExceptions: true, showStack: true

    if not module.parent
      app.listen process.env.PORT_WWW
      console.log "Server listening on port #{process.env.PORT_WWW}"
    else
      module.exports = app


Fixed the X axis of analogue touch controls being inverted.

On calling, this sets up touch bindings for any "touchpad" elements.

    gamepad = require "./gamepad.litcoffee"

    touchpads = undefined

    module.exports =
        load: ->
            touchpads = for element in document.getElementsByTagName "touchpad"
                element: element
                button: element.getAttribute "button"
                type: element.getAttribute "type"
                up: element.getAttribute "up"
                down: element.getAttribute "down"
                left: element.getAttribute "left"
                right: element.getAttribute "right"
                touchIdentifier: null

            addEventListener "touchstart", (event) ->
                for touch in event.changedTouches
                    for touchpad in touchpads
                        if touchpad.element isnt touch.target then continue
                        touchpad.touchIdentifier = touch.identifier
                        touchpad.latestX = touchpad.startedX = touchpad.lastX = touch.clientX
                        touchpad.latestY = touchpad.startedY = touchpad.lastY = touch.clientY
                        if touchpad.button then gamepad[touchpad.button] = 1
                return

            addEventListener "touchmove", (event) ->
                scale = Math.min window.innerWidth, window.innerHeight
                for touch in event.touches
                    for touchpad in touchpads
                        if touchpad.touchIdentifier isnt touch.identifier then continue
                        touchpad.latestX = touch.clientX
                        touchpad.latestY = touch.clientY
                        switch touchpad.type
                            when "mouse"
                                if touchpad.left then gamepad[touchpad.left] = -15 * Math.min 0, (touchpad.latestX - touchpad.lastX) / scale
                                if touchpad.right then gamepad[touchpad.right] = 15 * Math.max 0, (touchpad.latestX - touchpad.lastX) / scale
                                if touchpad.up then gamepad[touchpad.up] = -15 * Math.max 0, (touchpad.latestY - touchpad.lastY) / scale
                                if touchpad.down then gamepad[touchpad.down] = 15 * Math.min 0, (touchpad.latestY - touchpad.lastY) / scale
                            when "joystick"
                                if touchpad.left then gamepad[touchpad.left] = -3 * Math.max 0, (touchpad.latestX - touchpad.startedX) / scale
                                if touchpad.right then gamepad[touchpad.right] = 3 * Math.min 0, (touchpad.latestX - touchpad.startedX) / scale
                                if touchpad.up then gamepad[touchpad.up] = -3 * Math.max 0, (touchpad.latestY - touchpad.startedY) / scale
                                if touchpad.down then gamepad[touchpad.down] = 3 * Math.min 0, (touchpad.latestY - touchpad.startedY) / scale
                return

            addEventListener "touchend", (event) ->
                for touch in event.changedTouches
                    for touchpad in touchpads
                        if touchpad.touchIdentifier isnt touch.identifier then continue
                        if touchpad.left then gamepad[touchpad.left] = 0
                        if touchpad.right then gamepad[touchpad.right] = 0
                        if touchpad.up then gamepad[touchpad.up] = 0
                        if touchpad.down then gamepad[touchpad.down] = 0
                        if touchpad.button then gamepad[touchpad.button] = 0
                        touchpad.touchIdentifier = null
                return
            return

        tick: ->
            for touchpad in touchpads
                touchpad.lastX = touchpad.latestX
                touchpad.lastY = touchpad.latestY
                if touchpad.type is "mouse" and touchpad.touchIdentifier isnt null
                    if touchpad.left then gamepad[touchpad.left] = 0
                    if touchpad.right then gamepad[touchpad.right] = 0
                    if touchpad.up then gamepad[touchpad.up] = 0
                    if touchpad.down then gamepad[touchpad.down] = 0
            return

# touch

Handles "touch zones".

Each touch zone is a "touchzone" DOM element.

If a "button" attribute is defined, its value is set to 1 on touching the zone,
and 0 on releasing it.

If the "type" attribute defines how analogue input should be handled:

- "joystick": Continuous motion from the point of first touch.
- "mouse": Motion is only generated by moving the touch point.

The following attributes, if defined, map motion in that direction to the named
gamepad axis.

- "up"
- "down"
- "left"
- "right"

    gamepad = require "./gamepad.litcoffee"

    touchpads = undefined

    module.exports =

## load

Called at startup to discover elements and bind events.

        load: ->
            touchpads = for element in document.getElementsByTagName "touchpad"
                element: element
                button: element.getAttribute "button"
                type: element.getAttribute "type"
                up: element.getAttribute "up"
                down: element.getAttribute "down"
                left: element.getAttribute "left"
                right: element.getAttribute "right"
                touchIdentifier: null

            addEventListener "touchstart", (event) ->
                for touch in event.changedTouches
                    for touchpad in touchpads
                        if touchpad.element isnt touch.target then continue
                        touchpad.touchIdentifier = touch.identifier
                        touchpad.latestX = touchpad.startedX = touchpad.lastX = touch.clientX
                        touchpad.latestY = touchpad.startedY = touchpad.lastY = touch.clientY
                        if touchpad.button then gamepad[touchpad.button] = 1
                return

            addEventListener "touchmove", (event) ->
                scale = Math.min window.innerWidth, window.innerHeight
                for touch in event.touches
                    for touchpad in touchpads
                        if touchpad.touchIdentifier isnt touch.identifier then continue
                        touchpad.latestX = touch.clientX
                        touchpad.latestY = touch.clientY
                        switch touchpad.type
                            when "mouse"
                                if touchpad.left then gamepad[touchpad.left] = 15 * Math.min 0, (touchpad.latestX - touchpad.lastX) / scale
                                if touchpad.right then gamepad[touchpad.right] = -15 * Math.max 0, (touchpad.latestX - touchpad.lastX) / scale
                                if touchpad.up then gamepad[touchpad.up] = -15 * Math.max 0, (touchpad.latestY - touchpad.lastY) / scale
                                if touchpad.down then gamepad[touchpad.down] = 15 * Math.min 0, (touchpad.latestY - touchpad.lastY) / scale
                            when "joystick"
                                if touchpad.left then gamepad[touchpad.left] = 3 * Math.min 0, (touchpad.latestX - touchpad.startedX) / scale
                                if touchpad.right then gamepad[touchpad.right] = -3 * Math.max 0, (touchpad.latestX - touchpad.startedX) / scale
                                if touchpad.up then gamepad[touchpad.up] = -3 * Math.max 0, (touchpad.latestY - touchpad.startedY) / scale
                                if touchpad.down then gamepad[touchpad.down] = 3 * Math.min 0, (touchpad.latestY - touchpad.startedY) / scale
                return

            addEventListener "touchend", (event) ->
                for touch in event.changedTouches
                    for touchpad in touchpads
                        if touchpad.touchIdentifier isnt touch.identifier then continue
                        if touchpad.left then gamepad[touchpad.left] = 0
                        if touchpad.right then gamepad[touchpad.right] = 0
                        if touchpad.up then gamepad[touchpad.up] = 0
                        if touchpad.down then gamepad[touchpad.down] = 0
                        if touchpad.button then gamepad[touchpad.button] = 0
                        touchpad.touchIdentifier = null
                return
            return

## tick

Called after game logic is ticked to prepare for future touch events.

        tick: ->
            for touchpad in touchpads
                touchpad.lastX = touchpad.latestX
                touchpad.lastY = touchpad.latestY
                if touchpad.type is "mouse" and touchpad.touchIdentifier isnt null
                    if touchpad.left then gamepad[touchpad.left] = 0
                    if touchpad.right then gamepad[touchpad.right] = 0
                    if touchpad.up then gamepad[touchpad.up] = 0
                    if touchpad.down then gamepad[touchpad.down] = 0
            return


Take literate programming a bit more serious in server.litcoffee

nodePush Pushserver
===================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

First we import the required packages and make them available in a global variable.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Next we try to load the configuration file "config.js".

	try
		config = require '../config.js'
	catch e
		config = { }

In case not every configuration property is set we initialize it with a default property.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= __dirname + "/../outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= __dirname + "/../inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

We continue with creating some helper functions.

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

`app` will become an instance of `express`.

		app: null

`server` willbecome an instance of `http`.

		server: null

`io` will become an instance of `socket.io`.

		io: null

`stats` is an object with the different statistics recorded. Statistics will be shown on the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**
The constructor is executed when the class is initialized. It prints some helpful information,
such as the PID and the used sockets and continues with initializing everything.

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

First we display the used inbound and outbound sockets.

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

Afterwards we initialize the inbound and outbound connection.

			@initInbound()
			@initOutbound()

In order to do a proper cleanup on shutdown we bind the `shutdown` method to the needed events and signals.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

At the end we set a nice title for `ps`.

			process.title = 'nodePush'

**initOutbound()**
`initOutbound` initializes the connection to the browser. That includes starting the HTTP server and preparing
socket.io.

		initOutbound: ->
			log 'Initializing outbound socket'

First we start the express based HTTP server.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

Afterwards we set socket.io configuration for the default environment. Files will be minified and logging reduced to a minimum.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

In case `env` is set to development we show some more debug output.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Next we listen on the socket.io `connection` event to record statistics.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++
				@stats.outbound.current++

				socket.on 'disconnect', =>
					@stats.outbound.current--

We continue with creating a callback for the `listen` call.

			listenCallback = =>

In case we are running as root we try to shed root privilegies. If this is not possible we exit, as a service
running as root is dangerous.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

After the the HTTP server is listening and we are no longer running as root we start some intervals for the builtin tick events.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

Start listening on the configured outbound socket.

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

				@stats.status++
				reply = """
				Up since: #{@stats.bootTime}
				Status page: #{thousandsSeparator @stats.status} Requests
				Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
				Inbound: #{thousandsSeparator @stats.inbound}
				Messages:
				"""
				for message, amount of @stats.messages
					reply += "\n	#{message}: #{thousandsSeparator amount}"

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			@stats.messages[name] ?= 0
			@stats.messages[name]++
			@io.sockets.send name

**initInbound()**
`initInbound` initializes the PHP side socket.

		initBound: ->
			log 'Initializing inbound socket'

We start by creating a server.

			socket = net.createServer (c) =>
				@stats.inbound++

In case data is written to the server we pass it to the connected browsers and close the connection afterwards.

				c.on 'data', (data) =>
					setTimeout =>
						@sendMessage data.toString().trim()
					, 20
					c.end()

				c.on 'end', ->
					c.end()

In case nothing happens within 5 seconds we close the connection in order to save resources.

				c.setTimeout 5e3, ->
					c.end()

After all callbacks are bound we start listening.

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
`shutdown` performs a clean shutdown of nodePush. It cleans up the unix socket files.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

In the end we finally initialize the class with starts all the services.

	new be.bastelstu.wcf.nodePush()

nodePush Pushserver
===================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

Load required namespaces.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Load config

	try
		config = require '../config.js'
	catch e
		config = { }

Initialize sane values.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= __dirname + "/../outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= __dirname + "/../inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

Prepare environment

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

Instance of express.

		app: null

Instance of http

		server: null

Instance of socket.io

		io: null

Statistics for the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

			@initUnixSocket()
			@initServer()

Bind shutdown function to needed events.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

Set nice title for PS.

			process.title = 'nodePush'

**initServer()**
Initialize socket server.

		initServer: ->
			log 'Initializing outbound socket'

Start HTTP service.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

			listenCallback = =>

Shed root privilegies.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

Initialize intervals for tick events. The ticks are sent every 15 / 30 / 60 / 90 / 120 seconds.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Initialize production environment.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

Development configuration.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Record statistics for Websocket connections.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++
				@stats.outbound.current++

				socket.on 'disconnect', =>
					@stats.outbound.current--

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

				@stats.status++
				reply = """
				Up since: #{@stats.bootTime}
				Status page: #{thousandsSeparator @stats.status} Requests
				Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
				Inbound: #{thousandsSeparator @stats.inbound}
				Messages:
				"""
				for message, amount of @stats.messages
					reply += "\n	#{message}: #{thousandsSeparator amount}"

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			@stats.messages[name] ?= 0
			@stats.messages[name]++
			@io.sockets.send name

**initUnixSocket()**
Initialize PHP side unix socket.

		initUnixSocket: ->
			log 'Initializing inbound socket'
			socket = net.createServer (c) =>
				@stats.inbound++

Pass data to the browsers and close connection.

				c.on 'data', (data) =>
					setTimeout =>
						@sendMessage data.toString().trim()
					, 20
					c.end()

				c.on 'end', ->
					c.end()

Kill connection after 5 seconds.

				c.setTimeout 5e3, ->
					c.end()

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
Performs a clean shutdown of nodePush.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

And finally start the service.

	new be.bastelstu.wcf.nodePush()


Add reference to thousandsSeparator function

nodePush Pushserver
===================

	### Copyright Information
	# @author	Tim Düsterhus
	# @copyright	2012-2013 Tim Düsterhus
	# @license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>
	# @package	be.bastelstu.wcf.nodePush
	###

Setup
-----

First we import the required packages and make them available in a global variable.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Next we try to load the configuration file "config.js".

	try
		filename = "#{__dirname}/../config.js"
		if process.argv[2]
			if process.argv[2].substring(0, 1) is '/'
				filename = process.argv[2]
			else
				filename = "#{__dirname}/../#{process.argv[2]}"

		filename = fs.realpathSync filename

		console.log "Using config '#{filename}'"
		config = require filename
	catch e
		console.warn e.message
		config = { }

In case not every configuration property is set we initialize it with a default property.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= "#{__dirname}/../tmp/outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= "#{__dirname}/../tmp/inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

We continue with creating some helper functions.

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	# http://stackoverflow.com/a/6502556/782822
	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

`app` will become an instance of `express`.

		app: null

`server` willbecome an instance of `http`.

		server: null

`io` will become an instance of `socket.io`.

		io: null

`stats` is an object with the different statistics recorded. Statistics will be shown on the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**
The constructor is executed when the class is initialized. It prints some helpful information,
such as the PID and the used sockets and continues with initializing everything.

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

First we display the used inbound and outbound sockets.

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

Afterwards we initialize the inbound and outbound connection.

			@initInbound()
			@initOutbound()

In order to do a proper cleanup on shutdown we bind the `shutdown` method to the needed events and signals.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

At the end we set a nice title for `ps`.

			process.title = 'nodePush'

**initOutbound()**
`initOutbound` initializes the connection to the browser. That includes starting the HTTP server and preparing
socket.io.

		initOutbound: ->
			log 'Initializing outbound socket'

First we start the express based HTTP server.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

Afterwards we set socket.io configuration for the default environment. Files will be minified and logging reduced to a minimum.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

In case `env` is set to development we show some more debug output.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Next we listen on the socket.io `connection` event to record statistics.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++ if @app.get('env') is 'development'
				@stats.outbound.current++

				socket.on 'userID', (userID) =>
					socket.get 'userID', (_, currentUserID) =>

In case a client misbehaves, by sending the `userID` twice, we `disconnect` it.

						if currentUserID?
							socket.disconnect()
							return

Mark user as *authenticated* by joining **user**. If a client does not send a `userID` it will not receive any messages.

						socket.set 'userID', userID
						socket.join 'authenticated'
						socket.join "user#{userID}"
						socket.emit 'authenticated'

				socket.on 'disconnect', =>
					@stats.outbound.current--

We continue with creating a callback for the `listen` call.

			listenCallback = =>

In case we are running as root we try to shed root privilegies. If this is not possible we exit, as a service
running as root is dangerous.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

After the the HTTP server is listening and we are no longer running as root we start some intervals for the builtin tick events.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

Start listening on the configured outbound socket.

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

Show detailed information when environment is `development`.

				if @app.get('env') is 'development'
					@stats.status++
					reply = """
					Up since: #{@stats.bootTime}
					Status page: #{thousandsSeparator @stats.status} Requests
					Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
					Inbound: #{thousandsSeparator @stats.inbound}
					Messages:
					"""
					for message, amount of @stats.messages
						reply += "\n	#{message}: #{thousandsSeparator amount}"
				else
					reply = """
					Up since: #{@stats.bootTime}
					Outbound: #{thousandsSeparator @stats.outbound.current} now
					"""

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name, userIDs = [ ]) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			if name is 'be.bastelstu.wcf.nodePush._restart'
				process.kill process.pid, 'SIGHUP'

			if @app.get('env') is 'development'
				@stats.messages[name] ?= 0
				@stats.messages[name]++

			if userIDs.length
				@io.sockets.in("user#{userID}").send name for userID in userIDs
			else
				@io.sockets.in('authenticated').send name

**initInbound()**
`initInbound` initializes the PHP side socket.

		initInbound: ->
			log 'Initializing inbound socket'

We start by creating a server.

			socket = net.createServer (c) =>
				@stats.inbound++ if @app.get('env') is 'development'

In case data is written to the server we pass it to the connected browsers and close the connection afterwards.

				c.on 'data', (data) =>
					[ message, userIDs ] = data.toString().trim().split /:/
					if userIDs? and userIDs.length
						userIDs = userIDs.split /,/
						userIDs = (parseInt userID for userID in userIDs when not isNaN parseInt userID)
					else
						userIDs = [ ]

					setTimeout =>
						@sendMessage message, userIDs
					, 20
					c.end()

				c.on 'end', ->
					c.end()

In case nothing happens within 5 seconds we close the connection in order to save resources.

				c.setTimeout 5e3, ->
					c.end()

After all callbacks are bound we start listening.

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
`shutdown` performs a clean shutdown of nodePush. It cleans up the unix socket files.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

In the end we finally initialize the class with starts all the services.

	new be.bastelstu.wcf.nodePush()

nodePush Pushserver
===================

	### Copyright Information
	# @author	Tim Düsterhus
	# @copyright	2012-2013 Tim Düsterhus
	# @license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>
	# @package	be.bastelstu.wcf.nodePush
	###

Setup
-----

First we import the required packages and make them available in a global variable.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Next we try to load the configuration file "config.js".

	try
		filename = "#{__dirname}/../config.js"
		if process.argv[2]
			if process.argv[2].substring(0, 1) is '/'
				filename = process.argv[2]
			else
				filename = "#{__dirname}/../#{process.argv[2]}"

		filename = fs.realpathSync filename

		console.log "Using config '#{filename}'"
		config = require filename
	catch e
		console.warn e.message
		config = { }

In case not every configuration property is set we initialize it with a default property.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= "#{__dirname}/../tmp/outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= "#{__dirname}/../tmp/inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

We continue with creating some helper functions.

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

`app` will become an instance of `express`.

		app: null

`server` willbecome an instance of `http`.

		server: null

`io` will become an instance of `socket.io`.

		io: null

`stats` is an object with the different statistics recorded. Statistics will be shown on the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**
The constructor is executed when the class is initialized. It prints some helpful information,
such as the PID and the used sockets and continues with initializing everything.

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

First we display the used inbound and outbound sockets.

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

Afterwards we initialize the inbound and outbound connection.

			@initInbound()
			@initOutbound()

In order to do a proper cleanup on shutdown we bind the `shutdown` method to the needed events and signals.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

At the end we set a nice title for `ps`.

			process.title = 'nodePush'

**initOutbound()**
`initOutbound` initializes the connection to the browser. That includes starting the HTTP server and preparing
socket.io.

		initOutbound: ->
			log 'Initializing outbound socket'

First we start the express based HTTP server.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

Afterwards we set socket.io configuration for the default environment. Files will be minified and logging reduced to a minimum.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

In case `env` is set to development we show some more debug output.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Next we listen on the socket.io `connection` event to record statistics.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++ if @app.get('env') is 'development'
				@stats.outbound.current++

				socket.on 'userID', (userID) =>
					socket.get 'userID', (_, currentUserID) =>

In case a client misbehaves, by sending the `userID` twice, we `disconnect` it.

						if currentUserID?
							socket.disconnect()
							return

Mark user as *authenticated* by joining **user**. If a client does not send a `userID` it will not receive any messages.

						socket.set 'userID', userID
						socket.join 'authenticated'
						socket.join "user#{userID}"
						socket.emit 'authenticated'

				socket.on 'disconnect', =>
					@stats.outbound.current--

We continue with creating a callback for the `listen` call.

			listenCallback = =>

In case we are running as root we try to shed root privilegies. If this is not possible we exit, as a service
running as root is dangerous.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

After the the HTTP server is listening and we are no longer running as root we start some intervals for the builtin tick events.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

Start listening on the configured outbound socket.

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

Show detailed information when environment is `development`.

				if @app.get('env') is 'development'
					@stats.status++
					reply = """
					Up since: #{@stats.bootTime}
					Status page: #{thousandsSeparator @stats.status} Requests
					Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
					Inbound: #{thousandsSeparator @stats.inbound}
					Messages:
					"""
					for message, amount of @stats.messages
						reply += "\n	#{message}: #{thousandsSeparator amount}"
				else
					reply = """
					Up since: #{@stats.bootTime}
					Outbound: #{thousandsSeparator @stats.outbound.current} now
					"""

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name, userIDs = [ ]) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			if name is 'be.bastelstu.wcf.nodePush._restart'
				process.kill process.pid, 'SIGHUP'

			if @app.get('env') is 'development'
				@stats.messages[name] ?= 0
				@stats.messages[name]++

			if userIDs.length
				@io.sockets.in("user#{userID}").send name for userID in userIDs
			else
				@io.sockets.in('authenticated').send name

**initInbound()**
`initInbound` initializes the PHP side socket.

		initInbound: ->
			log 'Initializing inbound socket'

We start by creating a server.

			socket = net.createServer (c) =>
				@stats.inbound++ if @app.get('env') is 'development'

In case data is written to the server we pass it to the connected browsers and close the connection afterwards.

				c.on 'data', (data) =>
					[ message, userIDs ] = data.toString().trim().split /:/
					if userIDs? and userIDs.length
						userIDs = userIDs.split /,/
						userIDs = (parseInt userID for userID in userIDs when not isNaN parseInt userID)
					else
						userIDs = [ ]

					setTimeout =>
						@sendMessage message, userIDs
					, 20
					c.end()

				c.on 'end', ->
					c.end()

In case nothing happens within 5 seconds we close the connection in order to save resources.

				c.setTimeout 5e3, ->
					c.end()

After all callbacks are bound we start listening.

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
`shutdown` performs a clean shutdown of nodePush. It cleans up the unix socket files.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

In the end we finally initialize the class with starts all the services.

	new be.bastelstu.wcf.nodePush()


Fix naming in docs

Fix naming in docs

# /api/Data Structures/Batman.Object/Batman.Proxy

`Batman.Proxy` extends `Batman.Object` but implements the default accessor to `get`, `set`, and `unset` on its `target`.

Any accessors without explicit definitions will be delegated to `target`:

    test "a Batman.Proxy delegates to its target", ->
      class CustomProxy extends Batman.Proxy
        @accessor 'customValue', -> "Custom Value!"

      targetObject = new Batman.Object({name: "Batman", favoriteColor: "#000"})
      proxy = new CustomProxy(targetObject)

      equal proxy.get('favoriteColor'), '#000', "Default accessor delegates to target"
      equal proxy.get('customValue'), "Custom Value!", "Custom accessors override delegated ones"

## ::constructor(target : Batman.Object) : Proxy

Returns a new `Batman.Proxy` delegating to `target`.

## ::.isProxy[=true] : Boolean

Returns `true`. Shows that the object is a proxy.

## ::%target : Object

Returns the object which the `Proxy` is delegating to.

## @delegatesToTarget(functionNames...)

Defines a whitelist of functions which the `Proxy` will delegate to its target object. Unlike accessors, functions are not automatically passed to the target. For example:

    class Batman.AssociationProxy
      ...
      @delegatesToTarget('save', 'validate', 'destroy')
      ...

passes calls to `save`, `validate`, and `destroy` made on an `AssociationProxy` to the target `Batman.Model` where those functions are defined.

# /api/Data Structures/Batman.Object/Batman.Proxy

`Batman.Proxy` extends `Batman.Object` but implements the default accessor to `get`, `set`, and `unset` on its `target`.

Any accessors without explicit definitions will be delegated to `target`:

    test "a Batman.Proxy delegates to its target", ->
      class CustomProxy extends Batman.Proxy
        @accessor 'customValue', -> "Custom Value!"

      targetObject = new Batman.Object({name: "Batman", favoriteColor: "#000"})
      proxy = new CustomProxy(targetObject)

      equal proxy.get('favoriteColor'), '#000', "Default accessor delegates to target"
      equal proxy.get('customValue'), "Custom Value!", "Custom accessors override delegated ones"

## ::constructor(target : Batman.Object) : Proxy

Returns a new `Batman.Proxy` delegating to `target`.

## ::.isProxy[=true] : Boolean

Returns `true`. Shows that the object is a proxy.

## ::%target : Object

Returns the object which the `Proxy` is delegating to.

## @delegatesFunctionsToTarget(names...)

Defines a whitelist of functions which the `Proxy` will delegate to its target object. Unlike accessors, functions are not automatically passed to the target. For example:

    class Batman.AssociationProxy
      ...
      @delegatesFunctionsToTarget('save', 'validate', 'destroy')
      ...

passes calls to `save`, `validate`, and `destroy` made on an `AssociationProxy` to the target `Batman.Model` where those functions are defined.