Don't call initializers in _finish_up anymore

That's handled in _wrap_methods now

    q     = require 'q'
    fs    = require 'fs'
    async = require 'async'
    uuid  = require 'uuid-1345'

    microtime = require 'microtime'

    EventEmitter2 = require('eventemitter2').EventEmitter2
    emitter       = new EventEmitter2 wildcard: true

    available   = { }
    initialized = { }
    listeners   = { }

    code_root = process.env.SEARCH_ROOT || 'dist'

    underscore = (value) -> value.replace /\W+/g, '_'
    strip      = (name)  -> name.toLowerCase().replace /\W+/g, ''

    SEARCH_ROOTS  = { }
    WRAPPED       = { }
    _INITIALIZERS = { }
    HYDRATED      = { }

    HYRDATION_LISTENERS = { }

    INITIALIZERS = (cls, method) ->
      _INITIALIZERS[cls] = [ ] unless _INITIALIZERS[cls]?

      _INITIALIZERS[cls].push fn: method, called: false

    WRAP = (cls, method) ->
      unless WRAPPED[cls]?
        WRAPPED[cls] = [
          'constructor'
          'initialize'
          'details'
        ]

      WRAPPED[cls].indexOf(method) < 0

    class Madul

      details: =>
        name  = @.__proto__.constructor.name
        props = for own key, val of @.__proto__
          if key != 'constructor' &&
             key != 'details'     &&
             key != 'initialize'  && ((
               key[0]            == '_' &&
               @.__proto__[key]? == false
             ) || key[0] != '_')

            if typeof val == 'function'
              value = val.constructor.name
            else if Array.isArray val
              value = for v in val
                if typeof v == 'function'
                  v.constructor.name
                else if typeof v == 'object'
                  v.constructor.name
                else
                  v
              value = value.join ','
            else if typeof val == 'object'
              value = val.constructor.name
            else
              value = val

            "#{key} => #{value}"

        "\n  #{name}\n    #{props.filter((e) -> e?).join '\n    '}"

      @LISTEN: (event, callback) => emitter.on event, callback

      @FIRE: (event, args) => emitter.emit event, args

      @SEARCH_ROOT: (mod, path) =>
        Madul.FIRE '$.Madul.search_root.register', "#{mod}": path

        SEARCH_ROOTS[mod] = path.substring 0, path.lastIndexOf '/'

      listen: (event, callback) ->
        Madul.LISTEN "*.#{@constructor.name}.#{event}", callback

      fire: (event, args) ->
        Madul.FIRE "@.#{@constructor.name}.#{event}", args

      warn: (event, details) ->
        Madul.FIRE "!.#{@constructor.name}.#{event}", details

      _report: (name, method, state, id, args) =>
        Madul.FIRE "@.#{name}.#{method}.#{state}",
          uuid:      id
          args:      args
          timestamp: microtime.now()

      _respond: (proto, method, id, deferred) =>
        (state, data) =>
          process.nextTick =>
            deferred[state] data

            proto._report proto.constructor.name, method, state, id, data

      _prep_invocation: (proto, method, input, def) =>
        id  = uuid.v4fast()
        res = proto._respond proto, method, id, def

        if Array.isArray input
          input.push (out) => res 'resolve', out
          input.push (err) => res 'reject',  err
          input.push (out) => res 'notify',  out
        else if typeof input == 'object'
          input.done   = (out) => res 'resolve', out
          input.fail   = (err) => res 'reject',  err
          input.update = (out) => res 'notify',  out

          input = [ input ]
        else
          msg = "input to #{proto.constructor.name}.#{method} must be an Array of Object"
          @warn 'input.invalid', msg
          throw new Error msg

        proto._report proto.constructor.name, method, 'invoke', id, input

        input

      _do_wrap: (proto, method) =>
        if method != 'fire' && method != 'warn' && method != 'listen'
          Madul.FIRE "$.#{proto.constructor.name}.#{method}.wrap"

          if typeof proto[method] == 'function'
            proto["_#{method}"] = proto[method]

            proto[method] = =>
              def  = q.defer()
              args = if arguments[0]? then Array.prototype.slice.call arguments else [ ]

              proto["_#{method}"].apply @, proto._prep_invocation proto, method, args, def

              def.promise
          else if typeof proto[method] == 'object'

            if Array.isArray proto[method].validate
              args_format = 'ARRAY'
              decs        = for val in proto[method].validate
                @_parse_handle(val).ref

              proto[method].validate = decs
            else if typeof proto[method].validate == 'object'
              args_format = 'OBJECT'
              decs        = for own key, val of proto[method].validate
                { ref } = @_parse_handle val
                proto[method].validate[key] = ref
                ref
            else if typeof proto[method].validate == 'string'
              args_format = 'ARRAY'
              decs        = [ @_parse_handle(proto[method].validate).ref ]
            else if typeof proto[method].validate != 'undefined'
              @warn 'meta.invalid', validate: 'must be a String, Object, or Array'
              return
            else
              args_format = 'ARRAY'
              decs        = [ ]

            decs = decs.concat(proto[method].before.map (b, i) =>
              { ref } = @_parse_handle b
              proto[method].before[i] = ref
              ref
            ) if proto[method].before?

            decs = decs.concat(proto[method].after.map (a, i) =>
              { ref } = @_parse_handle a
              proto[method].after[i] = ref
              ref
            ) if proto[method].after?

            Madul.FIRE '$.Madul.decorators.hydrate', decs

            @_do_hydrate proto, decs, =>
              proto["_#{method}"] = proto[method]

              proto[method] = =>
                def = q.defer()
                me  = proto["_#{method}"]

                if args_format == 'ARRAY'
                  args = Array.prototype.slice.call arguments

                  if me.validate?
                    validators = for val, i in me.validate
                      { ref } = @_parse_handle val
                      Madul.FIRE '$.Madul.validator.execute', "#{ref}": args[i]
                      proto[ref].EXECUTE args[i]
                else if args_format == 'OBJECT'
                  args = arguments[0]

                  if me.validate?
                    validators = for own key, val of me.validate
                      { ref } = @_parse_handle val
                      Madul.FIRE '$.Madul.validator.execute', "#{ref}": args[key]
                      proto[ref].EXECUTE args[key]
                else
                  @warn 'cannot-continue', 'No arg format specified'

                  return def.reject 'No arg format specified'

                me.before = [ ] unless me.before?
                me.after  = [ ] unless me.after?

                q.all validators
                .then =>
                  q.all me.before.map (b) =>
                    Madul.FIRE '$.Madul.before_filter.execute', "#{b}": args
                    proto[b].before args
                .then =>
                  me.behavior.apply @, @_prep_invocation proto, method, args, def
                .then (result) =>
                  if me.after.length > 0
                    q.all me.after.map (b) =>
                      Madul.FIRE '$.Madul.after_filter.execute', "#{b}": result
                      b.after result
                  else
                    d = q.defer()

                    process.nextTick => d.resolve result

                    d.promise
                .then  (out) => def.resolve out
                .catch (err) => def.reject  err

                def.promise
          else
            @warn 'cannot-wrap', method

          WRAPPED[proto.constructor.name].push method

      _wrap_methods: (proto, callback) =>
        name    = proto.constructor.name
        to_wrap = [ ]

        while proto? && Object.keys(proto).length > 0 && WRAPPED[name]? == false
          to_wrap.push { proto, name, methods: [ ] }

          for own prop, body of proto
            if prop[0]                  != '_'         &&
               typeof proto["_#{prop}"] == 'undefined' &&
               WRAP(name, prop)         == true

              continue if proto.deps? && proto.deps.indexOf(prop.replace(/_/g, '-')) > -1

              if typeof body == 'function' || typeof body?.behavior == 'function'
                to_wrap[to_wrap.length - 1].methods.push prop

          proto = proto.__proto__
          name  = proto.constructor.name

        async.each to_wrap.reverse(), (wrap, completed) =>
          async.each wrap.methods, (method, next) =>
            wrap.proto._do_wrap wrap.proto, method

            INITIALIZERS wrap.name, method if method[0] == '$'

            next()
          , => @_call_initializers_for wrap.proto, wrap.name, completed
        , callback

      _make_available: (name, mod) =>
        Madul.FIRE "$.#{name}.available"

        available[strip name] = mod

      _hydrate_deps: (done) =>
        proto  = @.__proto__
        protos = [ proto ]

        if proto.__proto__?
          while proto.__proto__? && Object.keys(proto.__proto__).length > 0
            protos.push proto = proto.__proto__

        async.each protos.reverse(), (p, next) =>
          name = p.constructor.name

          if p.hasOwnProperty 'deps'
            if HYDRATED[name] == undefined
              HYDRATED[name]            = false
              HYRDATION_LISTENERS[name] = [ next ]

              p._do_hydrate p, p.deps, =>
                HYDRATED[name] = true

                for listener in HYRDATION_LISTENERS[name]
                  listener()
            else if HYDRATED[name] == false
              HYRDATION_LISTENERS[name].push next
            else if HYDRATED[name] == true
              next()
          else
            next()
        , done

      _init_if_madul: (path, callback) =>
        mod      = require path
        proto    = mod
        is_madul = false

        while proto
          is_madul = true if proto.name == 'Madul'
          if is_madul                            == false      &&
             proto.constructor.name              != 'Object'   &&
             typeof proto                        == 'function' &&
             typeof proto.__super__?.constructor == 'function'
            proto = proto.__super__.constructor
          else
            proto = undefined

        if is_madul
          new mod()
            .initialize()
            .then callback
        else
          callback mod

      _load: (me, name, path, loaded) =>
        me._init_if_madul path, (mod) =>
          me._make_available name, mod
          loaded mod

      _check: (me, path, dep, ref, finished) =>
        fs.readdir path, (err, files) =>
          if err?
            me.warn 'file-not-found', err

            done type: 'ERROR', info: err
          else
            async.each files, (f, next) =>
              depth = "#{path}/#{f}"

              fs.stat depth, (e, s) =>
                if s.isDirectory() && f[0] != '.'
                  me._check me, depth, dep, ref, next
                else if s.isFile() && f.substring(0, f.length - 3) == dep
                  me._load me, ref, depth, (mod) => me._do_add me, mod, ref, next
                else
                  next()
            , finished

      _do_add: (me, mod, ref, next) =>
        Madul.FIRE "$.#{me.constructor.name}.dependency.register", ref

        me[underscore ref] = mod

        next()

      _add: (me, ref, path, next) =>
        me._init_if_madul path, (mod) =>
          me._make_available ref, mod
          me._do_add me, mod, ref, next

      _parse_handle: (value) =>
        tokens = value.split '='

        if tokens.length == 2
          initer = tokens[1].trim()
          t      = tokens[0].split '->'

          if t[0].indexOf('#') > -1
            r = t[0].split '#'

            root = SEARCH_ROOTS[r[0].trim()]
            t[0] = r[1]

          if t.length == 2
            name  = t[0].trim()
            alias = t[1].trim()
          else if t.length == 1
            name = alias = t[0].trim()
          else
            return next @warn 'alias.invalid', tokens[1]

          toks = initer.split ':'

          if toks.length == 2
            initer = toks[0].trim()
            pres   = toks[1].split(',').map (p) => p.trim()
          else if toks.length == 1
            initer = toks[0].trim()
          else
            return next @warn 'dependency-initializer.invalid', tokens[1]

        else if tokens.length == 1
          t = tokens[0].split '->'

          if t[0].indexOf('#') > -1
            r = t[0].split '#'

            root = SEARCH_ROOTS[r[0].trim()]
            t[0] = r[1]

          if t.length == 2
            name  = t[0].trim()
            alias = t[1].trim()
          else if t.length == 1
            name = alias = t[0].trim()
          else
            return next @warn 'alias.invalid', tokens[1]

        else
          return next @warn 'dependency.invalid', d

        { ref: alias || name, alias, name, root, initer, pres }

      _do_hydrate: (proto, deps, hydration_complete) =>
        initers = [ ]

        async.each deps, (d, next) =>
          { ref, alias, name, root, initer, pres } = @_parse_handle d

          if pres?
            insert_at = for p in pres
              index_for = (sibling) => sibling.alias == p.alias

              initers.find index_for

            insert_at.sort()

            insert_at = if insert_at.length == 0 then 0 else insert_at[insert_at.length - 1]

            initers.splice insert_at, 0, alias: alias, execute: initer

          if proto[underscore ref]? == false
            if available[strip ref]? == true
              proto._do_add proto, available[strip ref], ref, next
            else
              try
                proto._add proto, ref, name, next
              catch e
                if root?
                  Madul.FIRE '$.Madul.search_root.load', { name, alias, root }

                  proto._check proto, root, name, ref, next
                else
                  cwd = process.cwd()
                  pkg = "#{cwd}/node_modules/#{name}/package.json"

                  fs.stat pkg, (err, stat) =>
                    if stat?.isFile()
                      fs.readFile pkg, 'utf8', (err, data) =>
                        json = JSON.parse data
                        main = json.main || json._main || 'index.js'
                        path = "#{cwd}/node_modules/#{name}/#{main}"

                        proto._add proto, ref, path, next
                    else
                      proto._check proto, "#{cwd}/#{code_root}", name, ref, next
          else
            next()
        , =>
          async.eachSeries initers, (initer, next) =>
            @[initer.execute]().then next
          , hydration_complete

      _finish_up: (proto, args) =>
        name = proto.constructor.name

        if listeners[name]?
          async.each listeners[name], (listener, next) =>
            listener @
            next()
          , => @_register_initialized name
        else
          @_register_initialized name

      _register_initialized: (name) =>
        @_make_available name, @

        initialized[name] = true

        Madul.FIRE "$.#{name}.initialized"

      _call_initializers_for: (name, callback) =>
        if _INITIALIZERS[name]?
          async.each _INITIALIZERS[name], (initializer, next) =>
            if initializer.called == false
              @[initializer.fn]()
                .then =>
                  initializer.called = true
                  next()
            else
              next()
          , callback
        else
          callback()

      _invoke_parent_initializers: (callback) =>
        proto = @.__proto__

        if proto.__proto__?
          parents = while proto.__proto__? && Object.keys(proto.__proto__).length > 0
            proto = proto.__proto__

          async.each parents, (parent, next) =>
            @_call_initializers_for parent.constructor.name, next
          , callback
        else
          callback()

      initialize: =>
        deferred = q.defer()
        proto    = @.__proto__
        name     = proto.constructor.name

        Madul.FIRE "$.#{name}.request_instance"

        if initialized[name] == undefined
          Madul.FIRE "$.#{name}.initialize"

          initialized[name] = false
          listeners[name]   = [ deferred.resolve ]

          @_wrap_methods()
          @_hydrate_deps => @_invoke_parent_initializers => @_finish_up proto
        else if initialized[name] == false
          listeners[name].push deferred.resolve
        else if initialized[name] == true
          process.nextTick => deferred.resolve available[strip name]

        deferred.promise

    module.exports = Madul

    q     = require 'q'
    fs    = require 'fs'
    async = require 'async'
    uuid  = require 'uuid-1345'

    microtime = require 'microtime'

    EventEmitter2 = require('eventemitter2').EventEmitter2
    emitter       = new EventEmitter2 wildcard: true

    available   = { }
    initialized = { }
    listeners   = { }

    code_root = process.env.SEARCH_ROOT || 'dist'

    underscore = (value) -> value.replace /\W+/g, '_'
    strip      = (name)  -> name.toLowerCase().replace /\W+/g, ''

    SEARCH_ROOTS  = { }
    WRAPPED       = { }
    _INITIALIZERS = { }
    HYDRATED      = { }

    HYRDATION_LISTENERS = { }

    INITIALIZERS = (cls, method) ->
      _INITIALIZERS[cls] = [ ] unless _INITIALIZERS[cls]?

      _INITIALIZERS[cls].push fn: method, called: false

    WRAP = (cls, method) ->
      unless WRAPPED[cls]?
        WRAPPED[cls] = [
          'constructor'
          'initialize'
          'details'
        ]

      WRAPPED[cls].indexOf(method) < 0

    class Madul

      details: =>
        name  = @.__proto__.constructor.name
        props = for own key, val of @.__proto__
          if key != 'constructor' &&
             key != 'details'     &&
             key != 'initialize'  && ((
               key[0]            == '_' &&
               @.__proto__[key]? == false
             ) || key[0] != '_')

            if typeof val == 'function'
              value = val.constructor.name
            else if Array.isArray val
              value = for v in val
                if typeof v == 'function'
                  v.constructor.name
                else if typeof v == 'object'
                  v.constructor.name
                else
                  v
              value = value.join ','
            else if typeof val == 'object'
              value = val.constructor.name
            else
              value = val

            "#{key} => #{value}"

        "\n  #{name}\n    #{props.filter((e) -> e?).join '\n    '}"

      @LISTEN: (event, callback) => emitter.on event, callback

      @FIRE: (event, args) => emitter.emit event, args

      @SEARCH_ROOT: (mod, path) =>
        Madul.FIRE '$.Madul.search_root.register', "#{mod}": path

        SEARCH_ROOTS[mod] = path.substring 0, path.lastIndexOf '/'

      listen: (event, callback) ->
        Madul.LISTEN "*.#{@constructor.name}.#{event}", callback

      fire: (event, args) ->
        Madul.FIRE "@.#{@constructor.name}.#{event}", args

      warn: (event, details) ->
        Madul.FIRE "!.#{@constructor.name}.#{event}", details

      _report: (name, method, state, id, args) =>
        Madul.FIRE "@.#{name}.#{method}.#{state}",
          uuid:      id
          args:      args
          timestamp: microtime.now()

      _respond: (proto, method, id, deferred) =>
        (state, data) =>
          process.nextTick =>
            deferred[state] data

            proto._report proto.constructor.name, method, state, id, data

      _prep_invocation: (proto, method, input, def) =>
        id  = uuid.v4fast()
        res = proto._respond proto, method, id, def

        if Array.isArray input
          input.push (out) => res 'resolve', out
          input.push (err) => res 'reject',  err
          input.push (out) => res 'notify',  out
        else if typeof input == 'object'
          input.done   = (out) => res 'resolve', out
          input.fail   = (err) => res 'reject',  err
          input.update = (out) => res 'notify',  out

          input = [ input ]
        else
          msg = "input to #{proto.constructor.name}.#{method} must be an Array of Object"
          @warn 'input.invalid', msg
          throw new Error msg

        proto._report proto.constructor.name, method, 'invoke', id, input

        input

      _do_wrap: (proto, method) =>
        if method != 'fire' && method != 'warn' && method != 'listen'
          Madul.FIRE "$.#{proto.constructor.name}.#{method}.wrap"

          if typeof proto[method] == 'function'
            proto["_#{method}"] = proto[method]

            proto[method] = =>
              def  = q.defer()
              args = if arguments[0]? then Array.prototype.slice.call arguments else [ ]

              proto["_#{method}"].apply @, proto._prep_invocation proto, method, args, def

              def.promise
          else if typeof proto[method] == 'object'

            if Array.isArray proto[method].validate
              args_format = 'ARRAY'
              decs        = for val in proto[method].validate
                @_parse_handle(val).ref

              proto[method].validate = decs
            else if typeof proto[method].validate == 'object'
              args_format = 'OBJECT'
              decs        = for own key, val of proto[method].validate
                { ref } = @_parse_handle val
                proto[method].validate[key] = ref
                ref
            else if typeof proto[method].validate == 'string'
              args_format = 'ARRAY'
              decs        = [ @_parse_handle(proto[method].validate).ref ]
            else if typeof proto[method].validate != 'undefined'
              @warn 'meta.invalid', validate: 'must be a String, Object, or Array'
              return
            else
              args_format = 'ARRAY'
              decs        = [ ]

            decs = decs.concat(proto[method].before.map (b, i) =>
              { ref } = @_parse_handle b
              proto[method].before[i] = ref
              ref
            ) if proto[method].before?

            decs = decs.concat(proto[method].after.map (a, i) =>
              { ref } = @_parse_handle a
              proto[method].after[i] = ref
              ref
            ) if proto[method].after?

            Madul.FIRE '$.Madul.decorators.hydrate', decs

            @_do_hydrate proto, decs, =>
              proto["_#{method}"] = proto[method]

              proto[method] = =>
                def = q.defer()
                me  = proto["_#{method}"]

                if args_format == 'ARRAY'
                  args = Array.prototype.slice.call arguments

                  if me.validate?
                    validators = for val, i in me.validate
                      { ref } = @_parse_handle val
                      Madul.FIRE '$.Madul.validator.execute', "#{ref}": args[i]
                      proto[ref].EXECUTE args[i]
                else if args_format == 'OBJECT'
                  args = arguments[0]

                  if me.validate?
                    validators = for own key, val of me.validate
                      { ref } = @_parse_handle val
                      Madul.FIRE '$.Madul.validator.execute', "#{ref}": args[key]
                      proto[ref].EXECUTE args[key]
                else
                  @warn 'cannot-continue', 'No arg format specified'

                  return def.reject 'No arg format specified'

                me.before = [ ] unless me.before?
                me.after  = [ ] unless me.after?

                q.all validators
                .then =>
                  q.all me.before.map (b) =>
                    Madul.FIRE '$.Madul.before_filter.execute', "#{b}": args
                    proto[b].before args
                .then =>
                  me.behavior.apply @, @_prep_invocation proto, method, args, def
                .then (result) =>
                  if me.after.length > 0
                    q.all me.after.map (b) =>
                      Madul.FIRE '$.Madul.after_filter.execute', "#{b}": result
                      b.after result
                  else
                    d = q.defer()

                    process.nextTick => d.resolve result

                    d.promise
                .then  (out) => def.resolve out
                .catch (err) => def.reject  err

                def.promise
          else
            @warn 'cannot-wrap', method

          WRAPPED[proto.constructor.name].push method

      _wrap_methods: (proto, callback) =>
        name    = proto.constructor.name
        to_wrap = [ ]

        while proto? && Object.keys(proto).length > 0 && WRAPPED[name]? == false
          to_wrap.push { proto, name, methods: [ ] }

          for own prop, body of proto
            if prop[0]                  != '_'         &&
               typeof proto["_#{prop}"] == 'undefined' &&
               WRAP(name, prop)         == true

              continue if proto.deps? && proto.deps.indexOf(prop.replace(/_/g, '-')) > -1

              if typeof body == 'function' || typeof body?.behavior == 'function'
                to_wrap[to_wrap.length - 1].methods.push prop

          proto = proto.__proto__
          name  = proto.constructor.name

        async.each to_wrap.reverse(), (wrap, completed) =>
          async.each wrap.methods, (method, next) =>
            wrap.proto._do_wrap wrap.proto, method

            INITIALIZERS wrap.name, method if method[0] == '$'

            next()
          , => @_call_initializers_for wrap.proto, wrap.name, completed
        , callback

      _make_available: (name, mod) =>
        Madul.FIRE "$.#{name}.available"

        available[strip name] = mod

      _hydrate_deps: (done) =>
        proto  = @.__proto__
        protos = [ proto ]

        if proto.__proto__?
          while proto.__proto__? && Object.keys(proto.__proto__).length > 0
            protos.push proto = proto.__proto__

        async.each protos.reverse(), (p, next) =>
          name = p.constructor.name

          if p.hasOwnProperty 'deps'
            if HYDRATED[name] == undefined
              HYDRATED[name]            = false
              HYRDATION_LISTENERS[name] = [ next ]

              p._do_hydrate p, p.deps, =>
                HYDRATED[name] = true

                for listener in HYRDATION_LISTENERS[name]
                  listener()
            else if HYDRATED[name] == false
              HYRDATION_LISTENERS[name].push next
            else if HYDRATED[name] == true
              next()
          else
            next()
        , done

      _init_if_madul: (path, callback) =>
        mod      = require path
        proto    = mod
        is_madul = false

        while proto
          is_madul = true if proto.name == 'Madul'
          if is_madul                            == false      &&
             proto.constructor.name              != 'Object'   &&
             typeof proto                        == 'function' &&
             typeof proto.__super__?.constructor == 'function'
            proto = proto.__super__.constructor
          else
            proto = undefined

        if is_madul
          new mod()
            .initialize()
            .then callback
        else
          callback mod

      _load: (me, name, path, loaded) =>
        me._init_if_madul path, (mod) =>
          me._make_available name, mod
          loaded mod

      _check: (me, path, dep, ref, finished) =>
        fs.readdir path, (err, files) =>
          if err?
            me.warn 'file-not-found', err

            done type: 'ERROR', info: err
          else
            async.each files, (f, next) =>
              depth = "#{path}/#{f}"

              fs.stat depth, (e, s) =>
                if s.isDirectory() && f[0] != '.'
                  me._check me, depth, dep, ref, next
                else if s.isFile() && f.substring(0, f.length - 3) == dep
                  me._load me, ref, depth, (mod) => me._do_add me, mod, ref, next
                else
                  next()
            , finished

      _do_add: (me, mod, ref, next) =>
        Madul.FIRE "$.#{me.constructor.name}.dependency.register", ref

        me[underscore ref] = mod

        next()

      _add: (me, ref, path, next) =>
        me._init_if_madul path, (mod) =>
          me._make_available ref, mod
          me._do_add me, mod, ref, next

      _parse_handle: (value) =>
        tokens = value.split '='

        if tokens.length == 2
          initer = tokens[1].trim()
          t      = tokens[0].split '->'

          if t[0].indexOf('#') > -1
            r = t[0].split '#'

            root = SEARCH_ROOTS[r[0].trim()]
            t[0] = r[1]

          if t.length == 2
            name  = t[0].trim()
            alias = t[1].trim()
          else if t.length == 1
            name = alias = t[0].trim()
          else
            return next @warn 'alias.invalid', tokens[1]

          toks = initer.split ':'

          if toks.length == 2
            initer = toks[0].trim()
            pres   = toks[1].split(',').map (p) => p.trim()
          else if toks.length == 1
            initer = toks[0].trim()
          else
            return next @warn 'dependency-initializer.invalid', tokens[1]

        else if tokens.length == 1
          t = tokens[0].split '->'

          if t[0].indexOf('#') > -1
            r = t[0].split '#'

            root = SEARCH_ROOTS[r[0].trim()]
            t[0] = r[1]

          if t.length == 2
            name  = t[0].trim()
            alias = t[1].trim()
          else if t.length == 1
            name = alias = t[0].trim()
          else
            return next @warn 'alias.invalid', tokens[1]

        else
          return next @warn 'dependency.invalid', d

        { ref: alias || name, alias, name, root, initer, pres }

      _do_hydrate: (proto, deps, hydration_complete) =>
        initers = [ ]

        async.each deps, (d, next) =>
          { ref, alias, name, root, initer, pres } = @_parse_handle d

          if pres?
            insert_at = for p in pres
              index_for = (sibling) => sibling.alias == p.alias

              initers.find index_for

            insert_at.sort()

            insert_at = if insert_at.length == 0 then 0 else insert_at[insert_at.length - 1]

            initers.splice insert_at, 0, alias: alias, execute: initer

          if proto[underscore ref]? == false
            if available[strip ref]? == true
              proto._do_add proto, available[strip ref], ref, next
            else
              try
                proto._add proto, ref, name, next
              catch e
                if root?
                  Madul.FIRE '$.Madul.search_root.load', { name, alias, root }

                  proto._check proto, root, name, ref, next
                else
                  cwd = process.cwd()
                  pkg = "#{cwd}/node_modules/#{name}/package.json"

                  fs.stat pkg, (err, stat) =>
                    if stat?.isFile()
                      fs.readFile pkg, 'utf8', (err, data) =>
                        json = JSON.parse data
                        main = json.main || json._main || 'index.js'
                        path = "#{cwd}/node_modules/#{name}/#{main}"

                        proto._add proto, ref, path, next
                    else
                      proto._check proto, "#{cwd}/#{code_root}", name, ref, next
          else
            next()
        , =>
          async.eachSeries initers, (initer, next) =>
            @[initer.execute]().then next
          , hydration_complete

      _finish_up: (proto, args) =>
        name = proto.constructor.name

        @_call_initializers_for name, =>
          if listeners[name]?
            async.each listeners[name], (listener, next) =>
              listener @
              next()
            , => @_register_initialized name
          else
            @_register_initialized name

      _register_initialized: (name) =>
        @_make_available name, @

        initialized[name] = true

        Madul.FIRE "$.#{name}.initialized"

      _call_initializers_for: (name, callback) =>
        if _INITIALIZERS[name]?
          async.each _INITIALIZERS[name], (initializer, next) =>
            if initializer.called == false
              @[initializer.fn]()
                .then =>
                  initializer.called = true
                  next()
            else
              next()
          , callback
        else
          callback()

      _invoke_parent_initializers: (callback) =>
        proto = @.__proto__

        if proto.__proto__?
          parents = while proto.__proto__? && Object.keys(proto.__proto__).length > 0
            proto = proto.__proto__

          async.each parents, (parent, next) =>
            @_call_initializers_for parent.constructor.name, next
          , callback
        else
          callback()

      initialize: =>
        deferred = q.defer()
        proto    = @.__proto__
        name     = proto.constructor.name

        Madul.FIRE "$.#{name}.request_instance"

        if initialized[name] == undefined
          Madul.FIRE "$.#{name}.initialize"

          initialized[name] = false
          listeners[name]   = [ deferred.resolve ]

          @_wrap_methods()
          @_hydrate_deps => @_invoke_parent_initializers => @_finish_up proto
        else if initialized[name] == false
          listeners[name].push deferred.resolve
        else if initialized[name] == true
          process.nextTick => deferred.resolve available[strip name]

        deferred.promise

    module.exports = Madul


Refactor to use volor instead of carver

Refactor to use volor instead of carver

    Madul = require 'madul'

    class Skyll extends Madul
      deps: [ '~volor', 'async', 'path' ]

      _do_flush: (step, ctx, level_name, exception, next) =>
        if step.flush?
          step.flush ctx, level_name
            .then  next
            .catch (err) =>
              console.log 'flushing', err
              exception err
        else
          next()

      _do_render: (ctx, step, level_name, exception, next) =>
        step.render ctx, level_name
          .then  next
          .catch (err) =>
            console.log 'rendering', err
            exception err

      _decorate: (thing, args, delegates) =>
        for i in [ 'args', 'delegates' ]
          if thing[i]?
            for j in thing[i]
              thing.set j, if i == 'args' then args[j] else delegates[j]

        thing

      craft: (level_name, args, pipeline, delegates, done, exception) ->
        map = @volor()

        @async.eachOfSeries pipeline, (pipe, i, next) =>
          if Array.isArray pipe
            @async.eachSeries pipe, (step, nxt) =>
              decorated = @_decorate step, args, delegates

              @_do_render map, decorated, level_name, exception(nxt), nxt
            , =>
              @_do_flush pipeline[i][0], map, level_name, exception(next), => next()
          else
            decorated = @_decorate pipe, args, delegates

            @_do_render map, decorated, level_name, exception(next), =>
              if i == pipeline.length - 1
                @_do_flush decorated, map, level_name, exception(next), => next()
              else
                next()
        , done

    module.exports = Skyll

    Madul = require 'madul'

    class Skyll extends Madul
      deps: [ 'carver', 'async', 'path' ]

      _do_flush: (step, ctx, level_name, exception, next) =>
        if step.flush?
          step.flush ctx, level_name
            .then  next
            .catch (err) =>
              console.log 'flushing', err
              exception err
        else
          next()

      _do_render: (ctx, step, path, level_name, exception, next) =>
        step.render ctx, path, level_name
          .then  next
          .catch (err) =>
            console.log 'rendering', err
            exception err

      _decorate: (thing, args, delegates) =>
        for i in [ 'args', 'delegates' ]
          if thing[i]?
            for j in thing[i]
              thing.set j, if i == 'args' then args[j] else delegates[j]

        thing

      craft: (level_name, args, pipeline, delegates, done, exception) ->
        ctx = [ ]

        @carver.carve_path delegates.pathfinder, args.rows, args.columns
          .then (path) =>
            console.log 'STARTING RENDER'
            @async.eachOfSeries pipeline, (pipe, i, next) =>
              if Array.isArray pipe
                @async.eachSeries pipe, (step, nxt) =>
                  decorated = @_decorate step, args, delegates

                  @_do_render ctx, decorated, path, level_name, exception(nxt), nxt
                , =>
                  @_do_flush pipeline[i][0], ctx, level_name, exception(next), => next()
              else
                decorated = @_decorate pipe, args, delegates

                @_do_render ctx, decorated, path, level_name, exception(next), =>
                  if i == pipeline.length - 1
                    @_do_flush decorated, ctx, level_name, exception(next), => next()
                  else
                    next()
            , done
          .catch exception

    module.exports = Skyll


Get rid of undefined variable.

Get rid of undefined variable.

Routing
=======
This file serves as the "glue" between the express router and sanity. Basically, we want a rails-esque routing system with all the routes declared in one location.  One advantage over rails, though, is that we're going to allow some degree of function composition in that we can declare multiple, reusable actions per-route, then let them pass the return value from one to the next.

This is done via unapologetic use of Promises.

##Libraries

    Promise = require 'bluebird'
    fs = Promise.promisifyAll require 'fs'
    _ = require 'lodash'

As a note, the `Promise.promisifyAll` function simply adds `Async` to the end of the methods in `fs` and subsequently allows Promises to be used instead of callbacks.

##Local Modules

    getControllers = require './getControllers'
    policies = require './policies'
    bodyParser = require './bodyParser'

Let's kickstart this router.

    module.exports = (app) ->

-----------

This grabs the controllers and returns back a promise'd object of them. It made more sense to put this in a separate file, since it'sarguably useful in its own right.

        getControllers()

Once we've gotten all the controllers, we'll move on

        .then (controllerObject) ->

Let's load in the routes file

            configuredRoutes = require '../config/routes'

Let's loop through the routes file and do the appropriate mapping.[1]

            _.each configuredRoutes, (totalString, route) ->

Routes are stored like METHOD /route, so we'll split on spaces. To make this a bit more dev-friendly, let's get rid of redundant spaces and newlines.

                [method, endpoint] = route
                             .replace /(?:\r\n|\r|\n)/g, ' '
                             .replace /\s\s+/g, ' '
                             .trim()
                             .split ' '

-----------

This bigass thing here is for dev-friendliness.  I don't want to punish people for separating controller calls to multiple lines if they want, and I don't want punish them for adding multiple spaces.  Subsequently, I replace newlines with a  space, then replace extra spaces down to one space, trim it, and split on the @ sign so I can make the dichotomy between application logic and error-handling logic. Utilizing Coffee's "multi-return" thing, I can set the values pretty cleanly, but not before I make sure the values are trimmed.

                [actionString, catchString] = totalString
                                  .replace /(?:\r\n|\r|\n)/g, ' '
                                  .replace /\s\s+/g, ' '
                                  .trim()
                                  .split '@'
                                  .map (i) -> do i.trim
-----------

Again, just make it cleaner, we'll utilize the "multi-return" thing coffeescript does. Since I don't want a hard requirement for a catch to exist, I will put a conditional to see if the catch is defined.

                [catchController,catchFunction] = catchString.split '.' if catchString?

If we have a catch defined, awesome, else we'll just feed in an empty function.

                catcher = controllerObject[catchController]?[catchFunction] || ->

Split the routes on a space so as to separate individual action handlers.

                allRoutes = actionString.split ' '

-------

Loop through all the actions that are provided for that route, look them up, return back the handles on the function. So as to save a "push" command we'll use a map

                actionHandles = _.map allRoutes, (a) ->

First we need to separate out the error handling stuff from the actual program, so let's split that out, and utilize the multi-return value feature of coffeescript.

                    [actionStuff, errorStuff] = a.split '!'

Since I don't want to make a hard requirement to provide an error-handler, let's put a put quick "if" at the end of this to make sure we have errorstuff to assign.

                    [errorController, errorAction] = errorStuff.split '.' if errorStuff?

Let's parse out the controller and action.

                    [myController, myAction] = actionStuff.split '.'

Now let's grab the appropriate stuff out of the controllers.

                    finalAction =  controllerObject[myController][myAction]
                    finalError = controllerObject[errorController]?[errorAction]

Since everything is parsed out, let's just wrap this in an object so as to easily pipe into the promises.

                    finalObject =
                        action: finalAction
                        error: finalError
                        controllerName: myController
                        actionName: myAction

Once everything is done, let's just return out of the map and move on.

                    return finalObject

The `wrapper` function.
-----------------------

This here is the glue that does the joining of the actual functions.  In a nutshell, when the request it made, it should run `wrapper`, which will loop through the functions that were returned by the previous map, and run them sequentially as part of the promise chain.  I would like to eventually add a mechanism in which to do this in parallel (instead of just sequentially) eventually.

                wrapper = (req, res) ->

We need to make sure the user is allowed to use everything that this route has to offer.  Due to the beauty of Bluebird, if this this trips up, it'll just kill the promise chain and make it so that we don't go any farther than we're allowed to.

                        bodyParser req
                        .then (updatedReq) ->
                            policies actionHandles, updatedReq, res

Once we've gotten all the handles on the functions we need to call, we can concat it to all previous promises. Afterwards we want these to run sequentially, so we use the reduce function to run them, then converge into a single, final promise.

                            finalPromise =
                                _.chain [authPromise]
                                .flatten()
                                .concat actionHandles
                                .reduce (cur, next) ->
                                    cur.then next.action, next.error
                                .value()

Everything should be done.  We can finally render a template or return back JSON depending on what they did on that last function

                            finalPromise.then (endData) ->

What happens now is pretty simple.  A requirement for frameworkey is that you return an object with your data and the `renderType` property. From there it's pretty straightforward.

                                if endData.renderType.toLowerCase() == 'html'
                                    # We used "toLowerCase" to make it more dev-friendly.
                                    res.render endData.page
                                else if endData.renderType.toLowerCase() == 'json'
                                    res.send endData.data

We'll use the global catch defined at the end of the actions to handle residual errors.  If there's an issue, we go here. We can default to an empty function if there's an issue.

                            finalPromise.catch catcher

As stated above, wrapper will return a new function based on what we send in for "allRoutes".  We're adding the "toLowerCase()" to make this a bit more dev-friendly.

                app[do method.toLowerCase] endpoint, wrapper

[1]: I *really* hate how the value comes before the key in Lodash

Routing
=======
This file serves as the "glue" between the express router and sanity. Basically, we want a rails-esque routing system with all the routes declared in one location.  One advantage over rails, though, is that we're going to allow some degree of function composition in that we can declare multiple, reusable actions per-route, then let them pass the return value from one to the next.

This is done via unapologetic use of Promises.

##Libraries

    Promise = require 'bluebird'
    fs = Promise.promisifyAll require 'fs'
    _ = require 'lodash'

As a note, the `Promise.promisifyAll` function simply adds `Async` to the end of the methods in `fs` and subsequently allows Promises to be used instead of callbacks.

##Local Modules

    getControllers = require './getControllers'
    policies = require './policies'
    bodyParser = require './bodyParser'

Let's kickstart this router.

    module.exports = (app) ->

-----------

This grabs the controllers and returns back a promise'd object of them. It made more sense to put this in a separate file, since it'sarguably useful in its own right.

        getControllers()

Once we've gotten all the controllers, we'll move on

        .then (controllerObject) ->

Let's load in the routes file

            configuredRoutes = require '../config/routes'

Let's loop through the routes file and do the appropriate mapping.[1]

            _.each configuredRoutes, (totalString, route) ->

Routes are stored like METHOD /route, so we'll split on spaces. To make this a bit more dev-friendly, let's get rid of redundant spaces and newlines.

                [method, endpoint] = route
                             .replace /(?:\r\n|\r|\n)/g, ' '
                             .replace /\s\s+/g, ' '
                             .trim()
                             .split ' '

-----------

This bigass thing here is for dev-friendliness.  I don't want to punish people for separating controller calls to multiple lines if they want, and I don't want punish them for adding multiple spaces.  Subsequently, I replace newlines with a  space, then replace extra spaces down to one space, trim it, and split on the @ sign so I can make the dichotomy between application logic and error-handling logic. Utilizing Coffee's "multi-return" thing, I can set the values pretty cleanly, but not before I make sure the values are trimmed.

                [actionString, catchString] = totalString
                                  .replace /(?:\r\n|\r|\n)/g, ' '
                                  .replace /\s\s+/g, ' '
                                  .trim()
                                  .split '@'
                                  .map (i) -> do i.trim
-----------

Again, just make it cleaner, we'll utilize the "multi-return" thing coffeescript does. Since I don't want a hard requirement for a catch to exist, I will put a conditional to see if the catch is defined.

                [catchController,catchFunction] = catchString.split '.' if catchString?

If we have a catch defined, awesome, else we'll just feed in an empty function.

                catcher = controllerObject[catchController]?[catchFunction] || ->

Split the routes on a space so as to separate individual action handlers.

                allRoutes = actionString.split ' '

-------

Loop through all the actions that are provided for that route, look them up, return back the handles on the function. So as to save a "push" command we'll use a map

                actionHandles = _.map allRoutes, (a) ->

First we need to separate out the error handling stuff from the actual program, so let's split that out, and utilize the multi-return value feature of coffeescript.

                    [actionStuff, errorStuff] = a.split '!'

Since I don't want to make a hard requirement to provide an error-handler, let's put a put quick "if" at the end of this to make sure we have errorstuff to assign.

                    [errorController, errorAction] = errorStuff.split '.' if errorStuff?

Let's parse out the controller and action.

                    [myController, myAction] = actionStuff.split '.'

Now let's grab the appropriate stuff out of the controllers.

                    finalAction =  controllerObject[myController][myAction]
                    finalError = controllerObject[errorController]?[errorAction]

Since everything is parsed out, let's just wrap this in an object so as to easily pipe into the promises.

                    finalObject =
                        action: finalAction
                        error: finalError
                        controllerName: myController
                        actionName: myAction

Once everything is done, let's just return out of the map and move on.

                    return finalObject

The `wrapper` function.
-----------------------

This here is the glue that does the joining of the actual functions.  In a nutshell, when the request it made, it should run `wrapper`, which will loop through the functions that were returned by the previous map, and run them sequentially as part of the promise chain.  I would like to eventually add a mechanism in which to do this in parallel (instead of just sequentially) eventually.

                wrapper = (req, res) ->

We need to make sure the user is allowed to use everything that this route has to offer.  Due to the beauty of Bluebird, if this this trips up, it'll just kill the promise chain and make it so that we don't go any farther than we're allowed to.

                        bodyParser req
                        .then (updatedReq) ->
                            policies actionHandles, updatedReq, res

Once we've gotten all the handles on the functions we need to call, we can concat it to all previous promises. Afterwards we want these to run sequentially, so we use the reduce function to run them, then converge into a single, final promise.

                            finalPromise =
                                _.chain [authPromise, bodyParsePromise]
                                .flatten()
                                .concat actionHandles
                                .reduce (cur, next) ->
                                    cur.then next.action, next.error
                                .value()

Everything should be done.  We can finally render a template or return back JSON depending on what they did on that last function

                            finalPromise.then (endData) ->

What happens now is pretty simple.  A requirement for frameworkey is that you return an object with your data and the `renderType` property. From there it's pretty straightforward.

                                if endData.renderType.toLowerCase() == 'html'
                                    # We used "toLowerCase" to make it more dev-friendly.
                                    res.render endData.page
                                else if endData.renderType.toLowerCase() == 'json'
                                    res.send endData.data

We'll use the global catch defined at the end of the actions to handle residual errors.  If there's an issue, we go here. We can default to an empty function if there's an issue.

                            finalPromise.catch catcher

As stated above, wrapper will return a new function based on what we send in for "allRoutes".  We're adding the "toLowerCase()" to make this a bit more dev-friendly.

                app[do method.toLowerCase] endpoint, wrapper

[1]: I *really* hate how the value comes before the key in Lodash


Path issue

Path issue

# Strapped

*Shrub's default skin.*

    path = require 'path'

    shrubSkin = require 'shrub-skin'

    exports.pkgmanRegister = (registrar) ->

#### Implements hook `shrubNodemailerHtml`.

      registrar.registerHook 'shrubNodemailerHtml', ($body, html, $) ->

        $('.container > .main', $body).html html

        $body.find('.navbar-toggle, .navbar-collapse').remove()
        $body.find('[data-shrub-ui-messages]').remove()

        $body.find('script').remove()

        $('noscript', $body).remove()

#### Implements hook `skinAssets`.

      registrar.registerHook 'skinAssets', (assets) ->

Add our future-compiled LESS style sheets.

        assets.styleSheets.default.push '/css/style.css'
        assets.styleSheets.production.push '/css/style.css'

#### Implements hook `shrubGruntConfig`.

      registrar.registerHook 'shrubGruntConfig', (gruntConfig) ->

        gruntConfig.less ?= {}

        shrubSkin.gruntSkin gruntConfig, 'shrub-skin-strapped'

        gruntConfig.configureTask 'less', 'shrub-skin-strapped', files: [
          src: [
            "#{__dirname}/app/less/style.less"
          ]
          dest: 'app/skin/shrub-skin-strapped/css/style.css'
        ]

        gruntConfig.configureTask(
          'watch', 'shrub-skin-strappedLess'

          files: [
            "#{__dirname}/app/less/style.less"
          ]
          tasks: [
            'newer:less:shrub-skin-strapped'
          ]
        )

        gruntConfig.registerTask 'build:shrub-skin-strapped', [
          'clean:shrub-skin-strapped'
          'newer:copy:shrub-skin-strapped'
          'less:shrub-skin-strapped'
        ]

        gruntConfig.registerTask 'build', ['build:shrub-skin-strapped']

        gruntConfig.loadNpmTasks ['grunt-contrib-less']

# Strapped

*Shrub's default skin.*

    path = require 'path'

    shrubSkin = require 'shrub-skin'

    exports.pkgmanRegister = (registrar) ->

#### Implements hook `shrubNodemailerHtml`.

      registrar.registerHook 'shrubNodemailerHtml', ($body, html, $) ->

        $('.container > .main', $body).html html

        $body.find('.navbar-toggle, .navbar-collapse').remove()
        $body.find('[data-shrub-ui-messages]').remove()

        $body.find('script').remove()

        $('noscript', $body).remove()

#### Implements hook `skinAssets`.

      registrar.registerHook 'skinAssets', (assets) ->

Add our future-compiled LESS style sheets.

        assets.styleSheets.default.push 'css/style.css'
        assets.styleSheets.production.push 'css/style.css'

#### Implements hook `shrubGruntConfig`.

      registrar.registerHook 'shrubGruntConfig', (gruntConfig) ->

        gruntConfig.less ?= {}

        shrubSkin.gruntSkin gruntConfig, 'shrub-skin-strapped'

        gruntConfig.configureTask 'less', 'shrub-skin-strapped', files: [
          src: [
            "#{__dirname}/app/less/style.less"
          ]
          dest: 'app/skin/shrub-skin-strapped/css/style.css'
        ]

        gruntConfig.configureTask(
          'watch', 'shrub-skin-strappedLess'

          files: [
            "#{__dirname}/app/less/style.less"
          ]
          tasks: [
            'newer:less:shrub-skin-strapped'
          ]
        )

        gruntConfig.registerTask 'build:shrub-skin-strapped', [
          'clean:shrub-skin-strapped'
          'newer:copy:shrub-skin-strapped'
          'less:shrub-skin-strapped'
        ]

        gruntConfig.registerTask 'build', ['build:shrub-skin-strapped']

        gruntConfig.loadNpmTasks ['grunt-contrib-less']


add environment info to README

add environment info to README

# loopback-with-domain

run loopback server with "domain"

domain is in this context business logic, the same as Domain-Driven Design (DDD).

connection with [base-domain](https://github.com/CureApp/base-domain)

# install

```
npm install loopback-with-domain
```

# run

before running, you can prepare a directory which contains custom config information.

```text
(config-dir) # any name is acceptable
|-- common
|   |-- server.coffee
|   `-- admin.coffee
|-- development
|   `-- datasources.coffee
|-- production
|   `-- datasources.coffee
```

    lbWithDomain = require 'loopback-with-domain'

    configDir = '/path/to/config-dir'

    domain = require('base-domain').createInstance(dirname: 'domain')

    lbWithDomain.runWithDomain(domain, configDir).then ->
        # loopback started

# configs

these are the config names.

- admin
- datasources
- middleware
- model-config
- server
- push-credentials

see JSON files in "default-configs" directory.
you can set the same properties as these JSONs.

## admin

 config key  | meaning
-------------|-----------------------
 accessToken | accessToken for admin

## datasources

 config key  | meaning
-------------|-----------------------
 memory      | on memory datasource
 db          | datasource for domain entities

## server

 config key  | meaning       | default
-------------|---------------|----------------
 restApiRoot | REST api root | /api
 port        | port number   | 3000

## push-credentials

 config key      | meaning
-----------------|-------------------------------------------
 gcmServerApiKey | api key for Google Cloud Messaging (GCM)
 apnsCertData    | certificate pem contents for APNs
 apnsKeyData     | key pem contents for APNs

# switching environment

running script with environment variable "NODE\_ENV" like

```bash
$ NODE_ENV=production node app.js
```

"development" is selected by default.

when your config dir is

```text
(config-dir) # any name is acceptable
|-- common
|   |-- server.coffee
|   `-- admin.coffee
|-- development
|   `-- datasources.coffee
|-- local
|   `-- datasources.coffee
|-- production
|   `-- datasources.coffee
```

and launching script like

```bash
$ NODE_ENV=local node app.js
```
then, loopback-with-domain selects configs in "local" directory.

## passing custom environment with argument

    env = 'production'

    lbWithDomain.runWithDomain(domain, configDir, env)

env is prior to NODE\_ENV settings.

# loopback-with-domain

run loopback server with "domain"

domain is in this context business logic, the same as Domain-Driven Design (DDD).

connection with [base-domain](https://github.com/CureApp/base-domain)

# install

```
npm install loopback-with-domain
```

# run

before running, you can prepare a directory which contains custom config information.

```
(config-dir) # any name is acceptable
|-- common
|   |-- server.coffee
|   `-- admin.coffee
|-- development
|   `-- datasources.coffee
|-- production
|   `-- datasources.coffee
```

    lbWithDomain = require 'loopback-with-domain'

    configDir = '/path/to/config-dir'

    domain = require('base-domain').createInstance(dirname: 'domain')

    lbWithDomain.runWithDomain(domain, configDir).then ->
        # loopback started

# configs

these are the config names.

- admin
- datasources
- middleware
- model-config
- server
- push-credentials

see JSON files in "default-configs" directory.
you can set the same properties as these JSONs.

## admin

 config key  | meaning
-------------|-----------------------
 accessToken | accessToken for admin

## datasources

 config key  | meaning
-------------|-----------------------
 memory      | on memory datasource
 db          | datasource for domain entities

## server

 config key  | meaning       | default
-------------|---------------|----------------
 restApiRoot | REST api root | /api
 port        | port number   | 3000

## push-credentials

 config key      | meaning
-----------------|-------------------------------------------
 gcmServerApiKey | api key for Google Cloud Messaging (GCM)
 apnsCertData    | certificate pem contents for APNs
 apnsKeyData     | key pem contents for APNs