index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. var setupWatchify = require('./lib/bundlers/watchify.js')
  2. , createHandler = require('./lib/create-handler.js')
  3. , makeIO = require('./lib/make-io.js')
  4. , path = require('path')
  5. var parseArgs = require('./lib/args-to-options.js')
  6. module.exports = beefy
  7. function beefy(opts, ready) {
  8. var io = makeIO(process, process.stdout, process.stderr)
  9. opts =
  10. typeof opts === 'string' ? {entries: [opts]} :
  11. Array.isArray(opts) ? {entries: opts} :
  12. opts
  13. opts.cwd = opts.cwd || path.dirname(module.parent)
  14. opts.entries = opts.entries || []
  15. opts.bundlerFlags = opts.bundlerFlags || []
  16. opts.bundler = opts.bundler || null
  17. opts.quiet = opts.quiet === undefined ? true : opts.quiet
  18. opts.live = !!opts.live
  19. opts.watchify = opts.watchify === undefined ? true : opts.watchify
  20. var args = ['9999']
  21. , innerHandler
  22. if(opts.cwd) {
  23. args.push('--cwd', opts.cwd)
  24. }
  25. if(opts.live) {
  26. args.push('--live')
  27. }
  28. if(typeof opts.bundler === 'string') {
  29. args.push('--bundler', opts.bundler)
  30. }
  31. if(opts.index) {
  32. args.push('--index', opts.index)
  33. }
  34. if('watchify' in opts && !opts.watchify) {
  35. args.push('--no-watchify')
  36. }
  37. args.push('--')
  38. args = args.concat(opts.bundlerFlags)
  39. parseArgs(args, opts.cwd, function(err, genOpts) {
  40. if(err) {
  41. if(ready) {
  42. return ready(err)
  43. }
  44. throw err
  45. }
  46. switch(opts.bundler && typeof opts.bundler) {
  47. case 'function':
  48. genOpts.handler.bundler.command = opts.bundler
  49. break
  50. case 'object':
  51. genOpts.handler.bundler = opts.bundler
  52. break
  53. }
  54. genOpts.handler.entries = fixupEntries(opts.entries)
  55. genOpts.handler.log = opts.quiet ? false : genOpts.handler.log
  56. innerHandler = createHandler(genOpts.handler, io, opts.unhandled)
  57. })
  58. return handler
  59. function handler(req, resp) {
  60. if(!innerHandler) {
  61. return setTimeout(handler, 0, req, resp)
  62. }
  63. innerHandler(req, resp)
  64. }
  65. function fixupEntries(entries) {
  66. return Array.isArray(entries) ? entries.reduce(toObject, {}) : entries
  67. function toObject(obj, entry) {
  68. entry = path.resolve(opts.cwd, entry)
  69. obj[entry
  70. .replace(opts.cwd, '/')
  71. .replace('\\', '/')
  72. .replace(/\/+/g, '/')] = entry
  73. return obj
  74. }
  75. }
  76. }