<commit_before>function prop (map) {
  if('string' == typeof map) {
    var key = map
    return function (data) { return data[key] }
  }
  return map
}

function id (item) {
  return item
}

var k = 0
var map = exports.map =
function (read, map) {
  var _k = k++
  map = prop(map) || id
  return function (end, cb) {
    read(end, function (end, data) {
      var data = !end ? map(data) : null
      cb(end, data)
    })
  }
}

var asyncMap = exports.asyncMap =
function (read, map) {
  if(!map) return read
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    read(null, function (end, data) {
      if(end) return cb(end, data)
      map(data, cb)
    })
  }
}

var filter = exports.filter =
function (read, test) {
  //regexp
  if('object' === typeof test
    && 'function' === typeof test.test)
    test = test.test.bind(test)
  test = prop(test) || id
  return function next (end, cb) {
    read(end, function (end, data) {
      if(!end && !test(data))
        return next(end, cb)
      cb(end, data)
    })
  }
}

var through = exports.through =
function (read, op, onEnd) {
  var a = false
  function once (abort) {
    if(a || !onEnd) return
    a = true
    onEnd(abort === true ? null : abort)
  }

  return function (end, cb) {
    return read(end, function (end, data) {
      if(!end) op && op(data)
      else once(end)
      cb(end, data)
    })
  }
}

var take = exports.take =
function (read, test) {
  var ended = false
  if('number' === typeof test) {
    var n = test; test = function () {
      return n --> 0
    }
  }
  return function (end, cb) {
    if(ended = ended || end)
      return read(ended, cb)

    read(null, function (end, data) {
      if(ended = ended || end) return cb(ended)
      //TODO, CHECK THAT END LOGIC IS CORRECT WITH TAKE!!!
      if(!test(data)) {
        ended = true
        read(true, cb)
      }
      else
        cb(null, data)
    })
  }
}

var unique = exports.unique = function (read, field, invert) {
  field = prop(field) || id
  var seen = {}
  return filter(read, function (data) {
    var key = field(data)
    if(seen[key]) return !!invert //false, by default
    else seen[key] = true
    return !invert //true by default
  })
}

var nonUnique = exports.nonUnique = function (read, field) {
  return unique(read, field, true)
}

var group = exports.group =
function (read, size) {
  var ended; size = size || 5
  var queue = []

  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)
    //this means that we read an end before.
    if(ended) return cb(ended)

    read(null, function next(end, data) {
      if(ended = ended || end) {
        if(!queue.length)
          return cb(ended)

        var _queue = queue; queue = []
        return cb(null, _queue)
      }
      queue.push(data)
      if(queue.length < size)
        return read(null, next)

      var _queue = queue; queue = []
      cb(null, _queue)
    })
  }
}

var flatten = exports.flatten = function (read) {
  var chunk
  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)

    if(chunk && chunk.length)
      return cb(null, chunk.shift())

    read(null, function (err, data) {
      if(err) return cb(err)
      chunk = data

      if(chunk && chunk.length)
        return cb(null, chunk.shift())
    })
  }
}

var nextTick = process.nextTick

var highWaterMark = exports.highWaterMark =
function (read, highWaterMark) {
  var buffer = [], waiting = [], ended, reading = false
  highWaterMark = highWaterMark || 10

  function readAhead () {
    while(waiting.length && (buffer.length || ended))
      waiting.shift()(ended, ended ? null : buffer.shift())
  }

  function next () {
    if(ended || reading || buffer.length >= highWaterMark)
      return
    reading = true
    return read(ended, function (end, data) {
      reading = false
      ended = ended || end
      if(data != null) buffer.push(data)

      next(); readAhead()
    })
  }

  nextTick(next)

  return function (end, cb) {
    ended = ended || end
    waiting.push(cb)

    next(); readAhead()
  }
}

<commit_msg>fix take logic<commit_after>function prop (map) {
  if('string' == typeof map) {
    var key = map
    return function (data) { return data[key] }
  }
  return map
}

function id (item) {
  return item
}

var map = exports.map =
function (read, map) {
  map = prop(map) || id
  return function (end, cb) {
    read(end, function (end, data) {
      var data = !end ? map(data) : null
      cb(end, data)
    })
  }
}

var asyncMap = exports.asyncMap =
function (read, map) {
  if(!map) return read
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    read(null, function (end, data) {
      if(end) return cb(end, data)
      map(data, cb)
    })
  }
}

var filter = exports.filter =
function (read, test) {
  //regexp
  if('object' === typeof test
    && 'function' === typeof test.test)
    test = test.test.bind(test)
  test = prop(test) || id
  return function next (end, cb) {
    read(end, function (end, data) {
      if(!end && !test(data))
        return next(end, cb)
      cb(end, data)
    })
  }
}

var through = exports.through =
function (read, op, onEnd) {
  var a = false
  function once (abort) {
    if(a || !onEnd) return
    a = true
    onEnd(abort === true ? null : abort)
  }

  return function (end, cb) {
    return read(end, function (end, data) {
      if(!end) op && op(data)
      else once(end)
      cb(end, data)
    })
  }
}

var take = exports.take =
function (read, test) {
  var ended = false, more
  if('number' === typeof test) {
    var n = test; test = function () {
      return n --
    }
  }
  return function (end, cb) {
    if(ended) return cb(ended)
    if(1 === more) end = true
    if(ended = end) return read(ended, cb)

    read(null, function (end, data) {
      if(ended = ended || end) return cb(ended)
      if(!(more = test(data))) {
        ended = true
        read(true, function (end, data) {
          cb(ended, data)
        })
      }
      else
        cb(null, data)
    })
  }
}

var unique = exports.unique = function (read, field, invert) {
  field = prop(field) || id
  var seen = {}
  return filter(read, function (data) {
    var key = field(data)
    if(seen[key]) return !!invert //false, by default
    else seen[key] = true
    return !invert //true by default
  })
}

var nonUnique = exports.nonUnique = function (read, field) {
  return unique(read, field, true)
}

var group = exports.group =
function (read, size) {
  var ended; size = size || 5
  var queue = []

  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)
    //this means that we read an end before.
    if(ended) return cb(ended)

    read(null, function next(end, data) {
      if(ended = ended || end) {
        if(!queue.length)
          return cb(ended)

        var _queue = queue; queue = []
        return cb(null, _queue)
      }
      queue.push(data)
      if(queue.length < size)
        return read(null, next)

      var _queue = queue; queue = []
      cb(null, _queue)
    })
  }
}

var flatten = exports.flatten = function (read) {
  var chunk
  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)

    if(chunk && chunk.length)
      return cb(null, chunk.shift())

    read(null, function (err, data) {
      if(err) return cb(err)
      chunk = data

      if(chunk && chunk.length)
        return cb(null, chunk.shift())
    })
  }
}

var nextTick = process.nextTick

var highWaterMark = exports.highWaterMark =
function (read, highWaterMark) {
  var buffer = [], waiting = [], ended, reading = false
  highWaterMark = highWaterMark || 10

  function readAhead () {
    while(waiting.length && (buffer.length || ended))
      waiting.shift()(ended, ended ? null : buffer.shift())
  }

  function next () {
    if(ended || reading || buffer.length >= highWaterMark)
      return
    reading = true
    return read(ended, function (end, data) {
      reading = false
      ended = ended || end
      if(data != null) buffer.push(data)

      next(); readAhead()
    })
  }

  nextTick(next)

  return function (end, cb) {
    ended = ended || end
    waiting.push(cb)

    next(); readAhead()
  }
}

<|endoftext|>


<commit_before>var u      = require('pull-core')
var sources = require('./sources')
var sinks = require('./sinks')

var prop   = u.prop
var id     = u.id
var tester = u.tester

var map = exports.map =
function (read, map) {
  map = prop(map) || id
  return function (abort, cb) {
    read(abort, function (end, data) {
      try {
      data = !end ? map(data) : null
      } catch (err) {
        return read(err, function () {
          return cb(err)
        })
      }
      cb(end, data)
    })
  }
}

var asyncMap = exports.asyncMap =
function (read, map) {
  if(!map) return read
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    read(null, function (end, data) {
      if(end) return cb(end, data)
      map(data, cb)
    })
  }
}

var paraMap = exports.paraMap =
function (read, map, width) {
  if(!map) return read
  var ended = false, queue = [], _cb

  function drain () {
    if(!_cb) return
    var cb = _cb
    _cb = null
    if(queue.length)
      return cb(null, queue.shift())
    else if(ended && !n)
      return cb(ended)
    _cb = cb
  }

  function pull () {
    read(null, function (end, data) {
      if(end) {
        ended = end
        return drain()
      }
      n++
      map(data, function (err, data) {
        n--

        queue.push(data)
        drain()
      })

      if(n < width && !ended)
        pull()
    })
  }

  var n = 0
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    //continue to read while there are less than 3 maps in flight
    _cb = cb
    if(queue.length || ended)
      pull(), drain()
    else pull()
  }
  return highWaterMark(asyncMap(read, map), width)
}

var filter = exports.filter =
function (read, test) {
  //regexp
  test = tester(test)
  return function next (end, cb) {
    var sync, loop = true
    while(loop) {
      loop = false
      sync = true
      read(end, function (end, data) {
        if(!end && !test(data))
          return sync ? loop = true : next(end, cb)
        cb(end, data)
      })
      sync = false
    }
  }
}

var filterNot = exports.filterNot =
function (read, test) {
  test = tester(test)
  return filter(read, function (e) {
    return !test(e)
  })
}

var through = exports.through =
function (read, op, onEnd) {
  var a = false
  function once (abort) {
    if(a || !onEnd) return
    a = true
    onEnd(abort === true ? null : abort)
  }

  return function (end, cb) {
    if(end) once(end)
    return read(end, function (end, data) {
      if(!end) op && op(data)
      else once(end)
      cb(end, data)
    })
  }
}

var take = exports.take =
function (read, test, opts) {
  opts = opts || {}
  var last = opts.last || false // whether the first item for which !test(item) should still pass
  var ended = false
  if('number' === typeof test) {
    last = true
    var n = test; test = function () {
      return --n
    }
  }

  return function (end, cb) {
    if(ended) return cb(ended)
    if(ended = end) return read(ended, cb)

    read(null, function (end, data) {
      if(ended = ended || end) return cb(ended)
      if(!test(data)) {
        ended = true
        read(true, function () {
          last ? cb(end, data) : cb(true)
        })
      }
      else
        cb(null, data)
    })
  }
}

var unique = exports.unique = function (read, field, invert) {
  field = prop(field) || id
  var seen = {}
  return filter(read, function (data) {
    var key = field(data)
    if(seen[key]) return !!invert //false, by default
    else seen[key] = true
    return !invert //true by default
  })
}

var nonUnique = exports.nonUnique = function (read, field) {
  return unique(read, field, true)
}

var group = exports.group =
function (read, size) {
  var ended; size = size || 5
  var queue = []

  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)
    //this means that we read an end before.
    if(ended) return cb(ended)

    read(null, function next(end, data) {
      if(ended = ended || end) {
        if(!queue.length)
          return cb(ended)

        var _queue = queue; queue = []
        return cb(null, _queue)
      }
      queue.push(data)
      if(queue.length < size)
        return read(null, next)

      var _queue = queue; queue = []
      cb(null, _queue)
    })
  }
}

var flatten = exports.flatten = function (read) {
  var _read
  return function (abort, cb) {
    if(_read) nextChunk()
    else      nextStream()

    function nextChunk () {
      _read(null, function (end, data) {
        if(end) nextStream()
        else    cb(null, data)
      })
    }
    function nextStream () {
      read(null, function (end, stream) {
        if(end)
          return cb(end)
        if(Array.isArray(stream) || stream && 'object' === typeof stream)
          stream = sources.values(stream)
        else if('function' != typeof stream)
          throw new Error('expected stream of streams')
        _read = stream
        nextChunk()
      })
    }
  }
}

var prepend =
exports.prepend =
function (read, head) {

  return function (abort, cb) {
    if(head !== null) {
      if(abort)
        return read(abort, cb)
      var _head = head
      head = null
      cb(null, _head)
    } else {
      read(abort, cb)
    }
  }

}

//var drainIf = exports.drainIf = function (op, done) {
//  sinks.drain(
//}

var _reduce = exports._reduce = function (read, reduce, initial) {
  return function (close, cb) {
    if(close) return read(close, cb)
    if(ended) return cb(ended)

    sinks.drain(function (item) {
      initial = reduce(initial, item)
    }, function (err, data) {
      ended = err || true
      if(!err) cb(null, initial)
      else     cb(ended)
    })
    (read)
  }
}

var nextTick = process.nextTick

var highWaterMark = exports.highWaterMark =
function (read, highWaterMark) {
  var buffer = [], waiting = [], ended, ending, reading = false
  highWaterMark = highWaterMark || 10

  function readAhead () {
    while(waiting.length && (buffer.length || ended))
      waiting.shift()(ended, ended ? null : buffer.shift())

    if (!buffer.length && ending) ended = ending;
  }

  function next () {
    if(ended || ending || reading || buffer.length >= highWaterMark)
      return
    reading = true
    return read(ended || ending, function (end, data) {
      reading = false
      ending = ending || end
      if(data != null) buffer.push(data)

      next(); readAhead()
    })
  }

  process.nextTick(next)

  return function (end, cb) {
    ended = ended || end
    waiting.push(cb)

    next(); readAhead()
  }
}

var flatMap = exports.flatMap =
function (read, mapper) {
  mapper = mapper || id
  var queue = [], ended

  return function (abort, cb) {
    if(queue.length) return cb(null, queue.shift())
    else if(ended)   return cb(ended)

    read(abort, function next (end, data) {
      if(end) ended = end
      else {
        var add = mapper(data)
        while(add && add.length)
          queue.push(add.shift())
      }

      if(queue.length) cb(null, queue.shift())
      else if(ended)   cb(ended)
      else             read(null, next)
    })
  }
}

<commit_msg>Make flatten respect abort, fixes #29<commit_after>var u      = require('pull-core')
var sources = require('./sources')
var sinks = require('./sinks')

var prop   = u.prop
var id     = u.id
var tester = u.tester

var map = exports.map =
function (read, map) {
  map = prop(map) || id
  return function (abort, cb) {
    read(abort, function (end, data) {
      try {
      data = !end ? map(data) : null
      } catch (err) {
        return read(err, function () {
          return cb(err)
        })
      }
      cb(end, data)
    })
  }
}

var asyncMap = exports.asyncMap =
function (read, map) {
  if(!map) return read
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    read(null, function (end, data) {
      if(end) return cb(end, data)
      map(data, cb)
    })
  }
}

var paraMap = exports.paraMap =
function (read, map, width) {
  if(!map) return read
  var ended = false, queue = [], _cb

  function drain () {
    if(!_cb) return
    var cb = _cb
    _cb = null
    if(queue.length)
      return cb(null, queue.shift())
    else if(ended && !n)
      return cb(ended)
    _cb = cb
  }

  function pull () {
    read(null, function (end, data) {
      if(end) {
        ended = end
        return drain()
      }
      n++
      map(data, function (err, data) {
        n--

        queue.push(data)
        drain()
      })

      if(n < width && !ended)
        pull()
    })
  }

  var n = 0
  return function (end, cb) {
    if(end) return read(end, cb) //abort
    //continue to read while there are less than 3 maps in flight
    _cb = cb
    if(queue.length || ended)
      pull(), drain()
    else pull()
  }
  return highWaterMark(asyncMap(read, map), width)
}

var filter = exports.filter =
function (read, test) {
  //regexp
  test = tester(test)
  return function next (end, cb) {
    var sync, loop = true
    while(loop) {
      loop = false
      sync = true
      read(end, function (end, data) {
        if(!end && !test(data))
          return sync ? loop = true : next(end, cb)
        cb(end, data)
      })
      sync = false
    }
  }
}

var filterNot = exports.filterNot =
function (read, test) {
  test = tester(test)
  return filter(read, function (e) {
    return !test(e)
  })
}

var through = exports.through =
function (read, op, onEnd) {
  var a = false
  function once (abort) {
    if(a || !onEnd) return
    a = true
    onEnd(abort === true ? null : abort)
  }

  return function (end, cb) {
    if(end) once(end)
    return read(end, function (end, data) {
      if(!end) op && op(data)
      else once(end)
      cb(end, data)
    })
  }
}

var take = exports.take =
function (read, test, opts) {
  opts = opts || {}
  var last = opts.last || false // whether the first item for which !test(item) should still pass
  var ended = false
  if('number' === typeof test) {
    last = true
    var n = test; test = function () {
      return --n
    }
  }

  return function (end, cb) {
    if(ended) return cb(ended)
    if(ended = end) return read(ended, cb)

    read(null, function (end, data) {
      if(ended = ended || end) return cb(ended)
      if(!test(data)) {
        ended = true
        read(true, function () {
          last ? cb(end, data) : cb(true)
        })
      }
      else
        cb(null, data)
    })
  }
}

var unique = exports.unique = function (read, field, invert) {
  field = prop(field) || id
  var seen = {}
  return filter(read, function (data) {
    var key = field(data)
    if(seen[key]) return !!invert //false, by default
    else seen[key] = true
    return !invert //true by default
  })
}

var nonUnique = exports.nonUnique = function (read, field) {
  return unique(read, field, true)
}

var group = exports.group =
function (read, size) {
  var ended; size = size || 5
  var queue = []

  return function (end, cb) {
    //this means that the upstream is sending an error.
    if(end) return read(ended = end, cb)
    //this means that we read an end before.
    if(ended) return cb(ended)

    read(null, function next(end, data) {
      if(ended = ended || end) {
        if(!queue.length)
          return cb(ended)

        var _queue = queue; queue = []
        return cb(null, _queue)
      }
      queue.push(data)
      if(queue.length < size)
        return read(null, next)

      var _queue = queue; queue = []
      cb(null, _queue)
    })
  }
}

var flatten = exports.flatten = function (read) {
  var _read
  return function (abort, cb) {
    if (abort) return read(abort, cb)
    if(_read) nextChunk()
    else      nextStream()

    function nextChunk () {
      _read(null, function (end, data) {
        if(end) nextStream()
        else    cb(null, data)
      })
    }
    function nextStream () {
      read(null, function (end, stream) {
        if(end)
          return cb(end)
        if(Array.isArray(stream) || stream && 'object' === typeof stream)
          stream = sources.values(stream)
        else if('function' != typeof stream)
          throw new Error('expected stream of streams')
        _read = stream
        nextChunk()
      })
    }
  }
}

var prepend =
exports.prepend =
function (read, head) {

  return function (abort, cb) {
    if(head !== null) {
      if(abort)
        return read(abort, cb)
      var _head = head
      head = null
      cb(null, _head)
    } else {
      read(abort, cb)
    }
  }

}

//var drainIf = exports.drainIf = function (op, done) {
//  sinks.drain(
//}

var _reduce = exports._reduce = function (read, reduce, initial) {
  return function (close, cb) {
    if(close) return read(close, cb)
    if(ended) return cb(ended)

    sinks.drain(function (item) {
      initial = reduce(initial, item)
    }, function (err, data) {
      ended = err || true
      if(!err) cb(null, initial)
      else     cb(ended)
    })
    (read)
  }
}

var nextTick = process.nextTick

var highWaterMark = exports.highWaterMark =
function (read, highWaterMark) {
  var buffer = [], waiting = [], ended, ending, reading = false
  highWaterMark = highWaterMark || 10

  function readAhead () {
    while(waiting.length && (buffer.length || ended))
      waiting.shift()(ended, ended ? null : buffer.shift())

    if (!buffer.length && ending) ended = ending;
  }

  function next () {
    if(ended || ending || reading || buffer.length >= highWaterMark)
      return
    reading = true
    return read(ended || ending, function (end, data) {
      reading = false
      ending = ending || end
      if(data != null) buffer.push(data)

      next(); readAhead()
    })
  }

  process.nextTick(next)

  return function (end, cb) {
    ended = ended || end
    waiting.push(cb)

    next(); readAhead()
  }
}

var flatMap = exports.flatMap =
function (read, mapper) {
  mapper = mapper || id
  var queue = [], ended

  return function (abort, cb) {
    if(queue.length) return cb(null, queue.shift())
    else if(ended)   return cb(ended)

    read(abort, function next (end, data) {
      if(end) ended = end
      else {
        var add = mapper(data)
        while(add && add.length)
          queue.push(add.shift())
      }

      if(queue.length) cb(null, queue.shift())
      else if(ended)   cb(ended)
      else             read(null, next)
    })
  }
}

<|endoftext|>


<commit_before>require.paths.unshift(
    __dirname + '/lib/node',
    __dirname + '/server',
    __dirname + '/shared',
    __dirname
);

var express = require('express'),
    settings = require('settings');

var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.methodOverride());
app.use(express.staticProvider('client'));
app.use(express.staticProvider('shared'));

app.error(function(err, req, res){
    res.send(err, 500);
});

require('api')(app, settings);
require('tiles')(app, settings);
require('export')(app, settings);
require('providers')(app, settings);
require('bootstrap')(app, settings);

if (app.settings.env !== 'test') {
    app.listen(settings.port);
    console.log('Started TileMill on port %d.', settings.port);
}
<commit_msg>Remove unused methodOverride() middleware.<commit_after>require.paths.unshift(
    __dirname + '/lib/node',
    __dirname + '/server',
    __dirname + '/shared',
    __dirname
);

var express = require('express'),
    settings = require('settings');

var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.staticProvider('client'));
app.use(express.staticProvider('shared'));

require('api')(app, settings);
require('tiles')(app, settings);
require('export')(app, settings);
require('providers')(app, settings);
require('bootstrap')(app, settings);

app.error(function(err, req, res){
    res.send(err, 500);
});

if (app.settings.env !== 'test') {
    app.listen(settings.port);
    console.log('Started TileMill on port %d.', settings.port);
}
<|endoftext|>


<commit_before>require.paths.unshift(__dirname + '/lib/node');

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    rmrf = require('./rm-rf'),
    Step = require('step'),
    mess = require('mess'),
    events = require('events'),
    _ = require('underscore')._;

var Project = require('./project').Project;
var ProjectList = require('./project').ProjectList;
var settings = require('./settings');
var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.methodOverride());
app.use(express.staticProvider('client'));

app.get('/api', function(req, res, params) {
  res.send({
    api: 'basic',
    version: 1.0
  });
});

app.get('/api/project/:projectId?', function(req, res, next) {
    if (req.param('projectId')) {
        var project = new Project({ id: req.param('projectId') });
        project.fetch({
            success: function(model, resp) { res.send(model.toJSON()) },
            error: function(model, resp) { res.send(resp, 500); }
        });
    }
    else {
        var list = new ProjectList();
        list.fetch({
            success: function(coll, resp) { res.send(coll.toJSON()) },
            error: function(coll, resp) { res.send(resp, 500) }
        });
    }
});

app.put('/api/project/:projectId', function(req, res, next) {
    var project = new Project(req.body);
    project.save({}, {
        success: function(model, resp) { res.send(model.toJSON()) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.post('/api/project/:projectId', function(req, res, next) {
    var project = new Project(req.body);
    project.save({}, {
        success: function(model, resp) { res.send(model.toJSON()) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.del('/api/project/:projectId', function(req, res, next) {
    var project = new Project({ id: req.param('projectId') });
    project.destroy({
        success: function(model, resp) { res.send({}) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.error(function(err, req, res){
    res.send(err, 500);
});

/*
Project.prototype.validate = function(stylesheets, callback) {
    Step(
        function() {
            var group = this.group();
            if (stylesheets.length !== 0) {
                _.each(stylesheets, function(stylesheet) {
                    new(mess.Parser)({
                        filename: stylesheet.id
                    }).parse(stylesheet.data, function(err, tree) {
                        if (!err) {
                            try {
                                tree.toCSS({ compress: false });
                                group()(null);
                            } catch (e) {
                                group()(e);
                            }
                        } else {
                            group()(err);
                        }
                    });
                });
            }
            else {
                group()(new Error('No stylesheets found.'));
            }
        },
        function(err, res) {
            callback(err);
        }
    );
};
*/

require('./providers/providers')(app, settings);
require('./inspect')(app, settings);

// Note that tilehandler must come last as its route rule acts as a "catchall"
// @TODO: Either prefix the tile endpoint or come up with some other method of
// allowing better route handling.
require('./tilehandler')(app, settings);

// "Bootstrap" (aka install) the application.
require('./bootstrap')(app, settings);

if (app.settings.env !== 'test') {
    app.listen(settings.port);
    console.log('Started TileMill on port %d.', settings.port);
}
<commit_msg>Whoops, need to pass attributes to be saved.<commit_after>require.paths.unshift(__dirname + '/lib/node');

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    rmrf = require('./rm-rf'),
    Step = require('step'),
    mess = require('mess'),
    events = require('events'),
    _ = require('underscore')._;

var Project = require('./project').Project;
var ProjectList = require('./project').ProjectList;
var settings = require('./settings');
var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.methodOverride());
app.use(express.staticProvider('client'));

app.get('/api', function(req, res, params) {
  res.send({
    api: 'basic',
    version: 1.0
  });
});

app.get('/api/project/:projectId?', function(req, res, next) {
    if (req.param('projectId')) {
        var project = new Project({ id: req.param('projectId') });
        project.fetch({
            success: function(model, resp) { res.send(model.toJSON()) },
            error: function(model, resp) { res.send(resp, 500); }
        });
    }
    else {
        var list = new ProjectList();
        list.fetch({
            success: function(coll, resp) { res.send(coll.toJSON()) },
            error: function(coll, resp) { res.send(resp, 500) }
        });
    }
});

app.put('/api/project/:projectId', function(req, res, next) {
    var project = new Project(req.body);
    project.save(req.body, {
        success: function(model, resp) { res.send(model.toJSON()) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.post('/api/project/:projectId', function(req, res, next) {
    var project = new Project(req.body);
    project.save(req.body, {
        success: function(model, resp) { res.send(model.toJSON()) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.del('/api/project/:projectId', function(req, res, next) {
    var project = new Project({ id: req.param('projectId') });
    project.destroy({
        success: function(model, resp) { res.send({}) },
        error: function(model, resp) { res.send(resp, 500); }
    });
});

app.error(function(err, req, res){
    res.send(err, 500);
});

/*
Project.prototype.validate = function(stylesheets, callback) {
    Step(
        function() {
            var group = this.group();
            if (stylesheets.length !== 0) {
                _.each(stylesheets, function(stylesheet) {
                    new(mess.Parser)({
                        filename: stylesheet.id
                    }).parse(stylesheet.data, function(err, tree) {
                        if (!err) {
                            try {
                                tree.toCSS({ compress: false });
                                group()(null);
                            } catch (e) {
                                group()(e);
                            }
                        } else {
                            group()(err);
                        }
                    });
                });
            }
            else {
                group()(new Error('No stylesheets found.'));
            }
        },
        function(err, res) {
            callback(err);
        }
    );
};
*/

require('./providers/providers')(app, settings);
require('./inspect')(app, settings);

// Note that tilehandler must come last as its route rule acts as a "catchall"
// @TODO: Either prefix the tile endpoint or come up with some other method of
// allowing better route handling.
require('./tilehandler')(app, settings);

// "Bootstrap" (aka install) the application.
require('./bootstrap')(app, settings);

if (app.settings.env !== 'test') {
    app.listen(settings.port);
    console.log('Started TileMill on port %d.', settings.port);
}
<|endoftext|>


<commit_before>;(function(){
	var period = {
		YEAR: {set: 'setFullYear'},
 		MONTH: {set: 'setMonth'},
 		DAY: {set: 'setDate'}
	}
	var mDay = 1000 * 60 * 60 * 24;
	var dispatch = ['toLocaleString', 'toLocaleDateString', 'toDateString', 'toString'];

	getLastDayOfMonth = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(tDate.getMonth() + 1);
 		tDate.setDate(0);
 		return tDate.getDate();
 	}
 	getLastDayOfYear = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(0);
 		tDate.setFullYear(tDate.getFullYear() + 1);
 		tDate.setDate(0);
 		return getDayOfYear(tDate);
 	}
 	getDayOfYear = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(0);
 		tDate.setDate(0);
 		return Math.round(((date.millis || date.getTime).call(date) - tDate.getTime()) / mDay);
 	}
 	getDayOfWeek = function(date){
 		return copyDate(date).getDay() || 7;
 	}
 	getWeekOfYear = function(date){
 		var tDate = copyDate(date);
 		tDate.setDate(tDate.getDate() + 4 - getDayOfWeek(date))
 		return Math.ceil(((tDate - new Date(tDate.getFullYear(), 0, 1)) / mDay + 1) / 7);
 	}
 	diff = function(date, diffDate){
 		var tDate = copyDate(date);
		var tDiffDate = copyDate(diffDate);
		tDate.setHours(0, 0, 0, 0);
		tDiffDate.setHours(0, 0, 0, 0);
		return Math.round((tDiffDate.getTime() - tDate.getTime()) / mDay);
 	}
 	monthDiff = function(date, diffDate){
 		var tDate = copyDate(date);
		var tDiffDate = copyDate(diffDate);
 		return (tDiffDate.getFullYear() * 12 + tDiffDate.getMonth()) -
 			(tDate.getFullYear() * 12 + tDate.getMonth());
 	}

	Timeless = function(y, d, m){
		if (!(this instanceof Timeless))
			return new Timeless(y, d, m);
		var timeless;
		if (y === undefined)
 			timeless = new Date();
 		else if (typeof d === 'number')
 			timeless = new Date([y, d, m]);
 		else
 			timeless = copyDate(y);
 		timeless.setHours(0, 0, 0, 0);

 		var lastDayOfMonth = getLastDayOfMonth(timeless);
 		var lastDayOfYear = getLastDayOfYear(timeless);
 		var dayOfYear = getDayOfYear(timeless);
 		var weekOfYear = getWeekOfYear(timeless);
 		var dayOfWeek = getDayOfWeek(timeless);

 		this.withYear = function(year){
 			return withPeriod(timeless, period.YEAR, year);
 		}
 		this.withMonthOfYear = function(month){
 			if (month < 1 || month > 12)
 				throw new OutOfRangeException('monthOfYear out of range');
 			return withPeriod(timeless, period.MONTH, month - 1);
		}
 		this.withDayOfMonth = function(day){
 			if (day < 1 || day > lastDayOfMonth)
 				throw new OutOfRangeException('dayOfMonth out of range');
 			return withPeriod(timeless, period.DAY, day);
 		}
 		this.withDayOfYear = function(day){
 			if (day < 1 || day > lastDayOfYear)
 				throw new OutOfRangeException('dayOfYear out of range');
 			var tDate = new Date(timeless);
 			tDate.setDate(1);
 			tDate.setMonth(0);
 			return withPeriod(tDate, period.DAY, day);
 		}
 		this.withDayOfWeek = function(day){
 			if (day < 1 || day > 7)
 				throw new OutOfRangeException('dayOfWeek out of range');
 			return withPeriod(timeless, period.DAY, timeless.getDate() + (day - dayOfWeek));
 		}
 		this.withWeekOfYear = function(week){
 			if (week < 1 || week > 53)
 				throw new OutOfRangeException('weekOfYear out of range');
 			return withPeriod(timeless, period.DAY, timeless.getDate() + (week - weekOfYear) * 7);
 		}
 		this.plusYears = function(years){
 			return withPeriod(timeless, period.YEAR, timeless.getFullYear() + parseInt(years));
 		}
 		this.plusMonths = function(months){
 			return withPeriod(timeless, period.MONTH, timeless.getMonth() + parseInt(months));
 		}
 		this.plusDays = function(days){
 			return withPeriod(timeless, period.DAY, timeless.getDate() + parseInt(days));
 		}
 		this.plusWeeks = function(weeks){
 			return withPeriod(timeless, period.DAY, timeless.getDate() + parseInt(weeks) * 7);
 		}

 		this.lastDayOfMonth = function(){
 			return lastDayOfMonth;
 		}
 		this.lastDayOfYear = function(){
 			return lastDayOfYear;
 		}
 		this.year = function(){
 			return timeless.getFullYear();
 		}
 		this.monthOfYear = function(){
 			return timeless.getMonth() + 1;
 		}
 		this.dayOfMonth = function(){
 			return timeless.getDate();
 		}
 		this.dayOfYear = function(){
 			return dayOfYear;
 		}
 		this.weekOfYear = function(){
 			return weekOfYear;
 		}
 		this.dayOfWeek = function(){
 			return dayOfWeek;
 		}
 		this.millis = function(){
 			return timeless.getTime();
 		}
 		this.milliseconds = function(){
 			return this.millis();
 		}
 		this.diff = function(diffDate){
 			return diff(timeless, diffDate);
 		}
 		this.monthDiff = function(diffDate){
 			return monthDiff(timeless, diffDate);
 		}
 		for (var i = 0; i < dispatch.length; i++){
 			this[dispatch[i]] = (function(m){
 				return function(){
 					return timeless[m]();
 				}
 			})(dispatch[i]);
 		}
 		return this;
	}

	function withPeriod(date, uPeriod, value){
		if (isNaN(value))
			throw IllegalArgumentException('argument is not a number');
		var tDate = new Date(date);
 		if (uPeriod !== period.DAY){
	 		var currentDay = tDate.getDate();
 			tDate.setDate(1);
 			tDate[uPeriod.set](value);
 			value = Math.min(currentDay, Timeless.lastDayOfMonth(tDate));
 		}
 		tDate.setDate(value);
 		return new Timeless(tDate);
	}
	function copyDate(date){
		if (date instanceof Timeless)
			return new Date(date.millis());
		return new Date(date);
	}

	var Exception = function(n, m){
		return {
			name: n,
			message: m,
			toString: function(){return n + ': ' + m}
		}
	}
	var OutOfRangeException = function(m){
		return Exception('OutOfRangeException', m);
	}
	var IllegalArgumentException = function(m){
		return Exception('IllegalArgumentException', m);
	}

	Timeless.year = function(date){
		return (date.year || date.getFullYear).call(date);
	}
	Timeless.monthOfYear = function(date){
		return new Timeless(date).monthOfYear();
	}
	Timeless.dayOfMonth = function(date){
		return (date.dayOfMonth || date.getDate).call(date);
	}
	Timeless.lastDayOfMonth = getLastDayOfMonth;
	Timeless.lastDayOfYear = getLastDayOfYear;
	Timeless.dayOfYear = getDayOfYear;
	Timeless.dayOfWeek = getDayOfWeek;
	Timeless.weekOfYear = getWeekOfYear;
	Timeless.dayOfWeek = getDayOfWeek;
	Timeless.diff = diff;
	Timeless.monthDiff = monthDiff;
	Timeless.today = function(){
		return new Timeless().millis();
	}
})();
<commit_msg>Changed the function of period and added WEEK<commit_after>;(function(){
	function safeSet(setter, value){
		var currentDay = this.getDate();
		this.setDate(1);
		this[setter](value);
		this.setDate(Math.min(currentDay, getLastDayOfMonth(this)));
	}
	var period = {
		YEAR: {
			set: function(y){
				safeSet.call(this, 'setFullYear', y);
			}
		},
 		MONTH: {
 			set: function(m){
 				safeSet.call(this, 'setMonth', m);
			}
		},
 		DAY: {
 			set: function(d){
 				this.setDate(d);
 			}
 		},
 		WEEK: {
 			set: function(w){
 				period.DAY.set.call(this, this.getDate() + (w - getWeekOfYear(this)) * 7);
 			}
 		}
	}
	var mDay = 1000 * 60 * 60 * 24;
	var dispatch = ['toLocaleString', 'toLocaleDateString', 'toDateString', 'toString'];

	getLastDayOfMonth = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(tDate.getMonth() + 1);
 		tDate.setDate(0);
 		return tDate.getDate();
 	}
 	getLastDayOfYear = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(0);
 		tDate.setFullYear(tDate.getFullYear() + 1);
 		tDate.setDate(0);
 		return getDayOfYear(tDate);
 	}
 	getDayOfYear = function(date){
		var tDate = copyDate(date);
 		tDate.setDate(1);
 		tDate.setMonth(0);
 		tDate.setDate(0);
 		return Math.round(((date.millis || date.getTime).call(date) - tDate.getTime()) / mDay);
 	}
 	getDayOfWeek = function(date){
 		return copyDate(date).getDay() || 7;
 	}
 	getWeekOfYear = function(date){
 		var tDate = copyDate(date);
 		tDate.setDate(tDate.getDate() + 4 - getDayOfWeek(date))
 		return Math.ceil(((tDate - new Date(tDate.getFullYear(), 0, 1)) / mDay + 1) / 7);
 	}
 	diff = function(date, diffDate){
 		var tDate = copyDate(date);
		var tDiffDate = copyDate(diffDate);
		tDate.setHours(0, 0, 0, 0);
		tDiffDate.setHours(0, 0, 0, 0);
		return Math.round((tDiffDate.getTime() - tDate.getTime()) / mDay);
 	}
 	monthDiff = function(date, diffDate){
 		var tDate = copyDate(date);
		var tDiffDate = copyDate(diffDate);
 		return (tDiffDate.getFullYear() * 12 + tDiffDate.getMonth()) -
 			(tDate.getFullYear() * 12 + tDate.getMonth());
 	}

	Timeless = function(y, d, m){
		if (!(this instanceof Timeless))
			return new Timeless(y, d, m);
		var timeless;
		if (y === undefined)
 			timeless = new Date();
 		else if (typeof d === 'number')
 			timeless = new Date([y, d, m]);
 		else
 			timeless = copyDate(y);
 		timeless.setHours(0, 0, 0, 0);

 		var lastDayOfMonth = getLastDayOfMonth(timeless);
 		var lastDayOfYear = getLastDayOfYear(timeless);
 		var dayOfYear = getDayOfYear(timeless);
 		var weekOfYear = getWeekOfYear(timeless);
 		var dayOfWeek = getDayOfWeek(timeless);

 		this.withYear = function(year){
 			return withPeriod(timeless, period.YEAR, year);
 		}
 		this.withMonthOfYear = function(month){
 			if (month < 1 || month > 12)
 				throw new OutOfRangeException('monthOfYear out of range');
 			return withPeriod(timeless, period.MONTH, month - 1);
		}
 		this.withDayOfMonth = function(day){
 			if (day < 1 || day > lastDayOfMonth)
 				throw new OutOfRangeException('dayOfMonth out of range');
 			return withPeriod(timeless, period.DAY, day);
 		}
 		this.withDayOfYear = function(day){
 			if (day < 1 || day > lastDayOfYear)
 				throw new OutOfRangeException('dayOfYear out of range');
 			var tDate = new Date(timeless);
 			tDate.setDate(1);
 			tDate.setMonth(0);
 			return withPeriod(tDate, period.DAY, day);
 		}
 		this.withDayOfWeek = function(day){
 			if (day < 1 || day > 7)
 				throw new OutOfRangeException('dayOfWeek out of range');
 			return withPeriod(timeless, period.DAY, timeless.getDate() + (day - dayOfWeek));
 		}
 		this.withWeekOfYear = function(week){
 			if (week < 1 || week > 53)
 				throw new OutOfRangeException('weekOfYear out of range');
 			return withPeriod(timeless, period.WEEK, week);
 		}
 		this.plusYears = function(years){
 			return withPeriod(timeless, period.YEAR, timeless.getFullYear() + parseInt(years));
 		}
 		this.plusMonths = function(months){
 			return withPeriod(timeless, period.MONTH, timeless.getMonth() + parseInt(months));
 		}
 		this.plusDays = function(days){
 			return withPeriod(timeless, period.DAY, timeless.getDate() + parseInt(days));
 		}
 		this.plusWeeks = function(weeks){
 			return withPeriod(timeless, period.WEEK, weekOfYear + parseInt(weeks));
 		}

 		this.lastDayOfMonth = function(){
 			return lastDayOfMonth;
 		}
 		this.lastDayOfYear = function(){
 			return lastDayOfYear;
 		}
 		this.year = function(){
 			return timeless.getFullYear();
 		}
 		this.monthOfYear = function(){
 			return timeless.getMonth() + 1;
 		}
 		this.dayOfMonth = function(){
 			return timeless.getDate();
 		}
 		this.dayOfYear = function(){
 			return dayOfYear;
 		}
 		this.weekOfYear = function(){
 			return weekOfYear;
 		}
 		this.dayOfWeek = function(){
 			return dayOfWeek;
 		}
 		this.millis = function(){
 			return timeless.getTime();
 		}
 		this.milliseconds = function(){
 			return this.millis();
 		}
 		this.diff = function(diffDate){
 			return diff(timeless, diffDate);
 		}
 		this.monthDiff = function(diffDate){
 			return monthDiff(timeless, diffDate);
 		}
 		for (var i = 0; i < dispatch.length; i++){
 			this[dispatch[i]] = (function(m){
 				return function(){
 					return timeless[m]();
 				}
 			})(dispatch[i]);
 		}
 		return this;
	}

	function withPeriod(date, uPeriod, value){
		if (isNaN(value))
			throw IllegalArgumentException('argument is not a number');
		var tDate = new Date(date);
		uPeriod.set.call(tDate, value);
 		return new Timeless(tDate);
	}
	function copyDate(date){
		if (date instanceof Timeless)
			return new Date(date.millis());
		return new Date(date);
	}

	var Exception = function(n, m){
		return {
			name: n,
			message: m,
			toString: function(){return n + ': ' + m}
		}
	}
	var OutOfRangeException = function(m){
		return Exception('OutOfRangeException', m);
	}
	var IllegalArgumentException = function(m){
		return Exception('IllegalArgumentException', m);
	}

	Timeless.year = function(date){
		return (date.year || date.getFullYear).call(date);
	}
	Timeless.monthOfYear = function(date){
		return new Timeless(date).monthOfYear();
	}
	Timeless.dayOfMonth = function(date){
		return (date.dayOfMonth || date.getDate).call(date);
	}
	Timeless.lastDayOfMonth = getLastDayOfMonth;
	Timeless.lastDayOfYear = getLastDayOfYear;
	Timeless.dayOfYear = getDayOfYear;
	Timeless.dayOfWeek = getDayOfWeek;
	Timeless.weekOfYear = getWeekOfYear;
	Timeless.dayOfWeek = getDayOfWeek;
	Timeless.diff = diff;
	Timeless.monthDiff = monthDiff;
	Timeless.today = function(){
		return new Timeless().millis();
	}
})();
<|endoftext|>


<commit_before>
require('should');

// Utils
// -----

// cheating with hygene:

global.Hyperloop = {
  defineClass: function (name) {
    return new ClassInterface(name);
  },
  method: function (receiver, name) {
    return {
      call: function () {
        var args = Array.prototype.slice.call(arguments);
        return String(receiver) + ' # ' + name + [''].concat(args).join('/');
      }
    };
  }
};

// cheating for undefined identifiers:

global.MyClass = 'MyClass';

// simple faker:

var receiver = {
  toString: function () { return '{RECEIVER}' },
  method: function () { return this },
  cast: function (to) { return '@' + to }
};

// fake meta-class

function ClassInterface (name) {
  this._name = name;
  this._methods = [];
  this._implements = [];
  this._protocols = [];
}

ClassInterface.prototype.toString = function () {
  return '{' + this._name + '}';
};

ClassInterface.prototype.implements = function (parent) {
  this._implements.push(parent);
  return this;
};

ClassInterface.prototype.protocol = function (protocol) {
  this._protocols.push(protocol);
  return this;
};

ClassInterface.prototype.build = function () {
  return {
    name: this._name,
    implements: this._implements,
    protocols: this._protocols,
    methods: this._methods,
  };
};

// Tests
// -----

describe "Objective-C" {

  describe "Use macro" {
    it "should work" {
      (use hyperloop).should.eql('use hyperloop');
    }
  }

  describe "Method invocation" {
    it "should work with no argument" {
      receiver@method().should.eql('{RECEIVER} # method');
    }

    it "should work with 1 argument" {
      receiver@method('arg').should.eql('{RECEIVER} # method:/arg');
    }

    it "should work with more than one argument" {
      receiver@method('arg1', withPieces:'arg2').should.eql('{RECEIVER} # method:withPieces:/arg1/arg2');
    }
  }

  describe "Casting" {
    it "should work with literals" {
      (receiver as 'Literal').should.eql('@Literal');
    }

    it "should work with identifiers" {
      (receiver as AClass).should.eql('@AClass');
    }

    it "should work with pointers" {
      // No space
      (receiver as (AClass*)).should.eql('@AClass *');
      // With space
      (receiver as (AClass *)).should.eql('@AClass *');
      // More than one star, no spaces
      (receiver as (AClass**)).should.eql('@AClass * *');
      // More than one star, with spaces
      (receiver as (AClass * *)).should.eql('@AClass * *');
      // More than one as parens
      (receiver as ((AClass *) *)).should.eql('@AClass * *');
    }
  }

  describe "Classes" {
    // We could have used `.properties` instead of `.eql` to test only specified
    // properties. This is way more verbose, but also way more solid.

    it "should work with empty classes" {
      var clazz = class native MyClass {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [],
        methods: []
      });
    }

    it "should work with `extends`" {
      var clazz = class native MyClass extends NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `implements`" {
      var clazz = class native MyClass implements NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `protocol`" {
      var clazz = class native MyClass protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    it "should work with `protocol` and `extends`" {
      var clazz = class native MyClass extends NSObject protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    TODO "method with no arguments"
    TODO "method with one argument"
    TODO "method with more than one argument"
    TODO "automatic method argument casting"

  }

}
<commit_msg>New tests group, macro name collisions<commit_after>
require('should');

// Utils
// -----

// cheating with hygene:

global.Hyperloop = {
  defineClass: function (name) {
    return new ClassInterface(name);
  },
  method: function (receiver, name) {
    return {
      call: function () {
        var args = Array.prototype.slice.call(arguments);
        return String(receiver) + ' # ' + name + [''].concat(args).join('/');
      }
    };
  }
};

// cheating for undefined identifiers:

global.MyClass = 'MyClass';

// simple faker:

var receiver = {
  toString: function () { return '{RECEIVER}' },
  method: function () { return this },
  cast: function (to) { return '@' + to }
};

// fake meta-class

function ClassInterface (name) {
  this._name = name;
  this._methods = [];
  this._implements = [];
  this._protocols = [];
}

ClassInterface.prototype.toString = function () {
  return '{' + this._name + '}';
};

ClassInterface.prototype.implements = function (parent) {
  this._implements.push(parent);
  return this;
};

ClassInterface.prototype.protocol = function (protocol) {
  this._protocols.push(protocol);
  return this;
};

ClassInterface.prototype.build = function () {
  return {
    name: this._name,
    implements: this._implements,
    protocols: this._protocols,
    methods: this._methods,
  };
};

// Tests
// -----

describe "Objective-C" {

  describe "Macro name collisions" {
    it "should not happen on 'use'" {
      var use = 42;

      use.should.eql(42);
    }

    it "should not happen on 'as'" {
      var as = 42;

      as.should.eql(42);
    }
  }

  describe "Use macro" {
    it "should work" {
      (use hyperloop).should.eql('use hyperloop');
    }
  }

  describe "Method invocation" {
    it "should work with no argument" {
      receiver@method().should.eql('{RECEIVER} # method');
    }

    it "should work with 1 argument" {
      receiver@method('arg').should.eql('{RECEIVER} # method:/arg');
    }

    it "should work with more than one argument" {
      receiver@method('arg1', withPieces:'arg2').should.eql('{RECEIVER} # method:withPieces:/arg1/arg2');
    }
  }

  describe "Casting" {
    it "should work with literals" {
      (receiver as 'Literal').should.eql('@Literal');
    }

    it "should work with identifiers" {
      (receiver as AClass).should.eql('@AClass');
    }

    it "should work with pointers" {
      // No space
      (receiver as (AClass*)).should.eql('@AClass *');
      // With space
      (receiver as (AClass *)).should.eql('@AClass *');
      // More than one star, no spaces
      (receiver as (AClass**)).should.eql('@AClass * *');
      // More than one star, with spaces
      (receiver as (AClass * *)).should.eql('@AClass * *');
      // More than one as parens
      (receiver as ((AClass *) *)).should.eql('@AClass * *');
    }
  }

  describe "Classes" {
    // We could have used `.properties` instead of `.eql` to test only specified
    // properties. This is way more verbose, but also way more solid.

    it "should work with empty classes" {
      var clazz = class native MyClass {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [],
        methods: []
      });
    }

    it "should work with `extends`" {
      var clazz = class native MyClass extends NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `implements`" {
      var clazz = class native MyClass implements NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `protocol`" {
      var clazz = class native MyClass protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    it "should work with `protocol` and `extends`" {
      var clazz = class native MyClass extends NSObject protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    TODO "method with no arguments"
    TODO "method with one argument"
    TODO "method with more than one argument"
    TODO "automatic method argument casting"

  }

}
<|endoftext|>


<commit_before>const { app } = require('electron').remote
import React from 'react'
import {
  SegmentedControl,
  SegmentedControlItem,
  Text,
  TitleBar,
  Window
} from 'react-desktop/macOs'

import AboutPane from './AboutPane'
import AdvancedPane from './AdvancedPane'
import GeneralPane from './GeneralPane'
import UploadPane from './UploadPane'

export default class extends React.Component {
  componentDidMount () {
    this.resizeWindow()
  }

  componentDidUpdate () {
    this.resizeWindow()
  }

  constructor (props) {
    super(props)

    this.handleClose = this.handleClose.bind(this)
    this.handleMinimize = this.handleMinimize.bind(this)
    this.handleResize = this.handleResize.bind(this)

    this.state = {
      isFullscreen: false,
      selected: 'general'
    }
  }

  handleClose () {
    app.pane.hide()
  }

  handleMinimize () {
    app.pane.minimize()
  }

  handleResize () {
    if (app.pane.isMaximized()) {
      app.pane.unmaximize()
    } else {
      app.pane.maximize()
    }
  }

  render () {
    return (
      <Window>
        <TitleBar
          controls
          onCloseClick={this.handleClose}
          onMinimizeClick={this.handleMinimize}
          onResizeClick={this.handleResize}
          title="Eidetica Settings"
          />

        <SegmentedControl box>
          {this.renderItem('General', <GeneralPane />)}
          {this.renderItem('Uploads', <UploadPane />)}
          {this.renderItem('Advanced', <AdvancedPane />)}
          {this.renderItem('About', <AboutPane />)}
        </SegmentedControl>
      </Window>
    )
  }

  renderItem (title, component) {
    let safeTitle = title.toLowerCase().replace(' ', '-')

    return (
      <SegmentedControlItem
        title={title}
        selected={this.state.selected === safeTitle}
        onSelect={() => this.setState({ selected: safeTitle })} >
        {component}
      </SegmentedControlItem>
    )
  }

  resizeWindow () {
    let height = document.querySelector('#root').clientHeight
    let width = app.pane.getSize()[0]

    app.pane.setSize(width, height, true)
  }
}
<commit_msg>[#39] Remove the Advanced panel<commit_after>const { app } = require('electron').remote
import React from 'react'
import {
  SegmentedControl,
  SegmentedControlItem,
  Text,
  TitleBar,
  Window
} from 'react-desktop/macOs'

import AboutPane from './AboutPane'
import GeneralPane from './GeneralPane'
import UploadPane from './UploadPane'

export default class extends React.Component {
  componentDidMount () {
    this.resizeWindow()
  }

  componentDidUpdate () {
    this.resizeWindow()
  }

  constructor (props) {
    super(props)

    this.handleClose = this.handleClose.bind(this)
    this.handleMinimize = this.handleMinimize.bind(this)
    this.handleResize = this.handleResize.bind(this)

    this.state = {
      isFullscreen: false,
      selected: 'general'
    }
  }

  handleClose () {
    app.pane.hide()
  }

  handleMinimize () {
    app.pane.minimize()
  }

  handleResize () {
    if (app.pane.isMaximized()) {
      app.pane.unmaximize()
    } else {
      app.pane.maximize()
    }
  }

  render () {
    return (
      <Window>
        <TitleBar
          controls
          onCloseClick={this.handleClose}
          onMinimizeClick={this.handleMinimize}
          onResizeClick={this.handleResize}
          title="Eidetica Settings"
          />

        <SegmentedControl box>
          {this.renderItem('General', <GeneralPane />)}
          {this.renderItem('Uploads', <UploadPane />)}
          {this.renderItem('About', <AboutPane />)}
        </SegmentedControl>
      </Window>
    )
  }

  renderItem (title, component) {
    let safeTitle = title.toLowerCase().replace(' ', '-')

    return (
      <SegmentedControlItem
        title={title}
        selected={this.state.selected === safeTitle}
        onSelect={() => this.setState({ selected: safeTitle })} >
        {component}
      </SegmentedControlItem>
    )
  }

  resizeWindow () {
    let height = document.querySelector('#root').clientHeight
    let width = app.pane.getSize()[0]

    app.pane.setSize(width, height, true)
  }
}
<|endoftext|>


<commit_before>export default {
  // Dependencies for a default Sanity installation
  core: {
    '@sanity/base': '^0.0.17',
    '@sanity/components': '^0.0.11',
    '@sanity/default-layout': '^0.0.4',
    '@sanity/default-login': '^0.0.2',
    '@sanity/desk-tool': '^0.1.3',
    'react': '^15.3.0',
    'react-dom': '^15.3.0'
  },

  // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io)
  plugin: {
    dev: {
      '@sanity/check': '^0.0.2',
      'babel-cli': '^6.9.0',
      'babel-eslint': '^6.0.4',
      'babel-plugin-syntax-class-properties': '^6.8.0',
      'babel-plugin-transform-class-properties': '^6.9.1',
      'babel-preset-es2015': '^6.9.0',
      'babel-preset-react': '^6.5.0',
      'eslint': '^3.4.0',
      'eslint-config-sanity': '^1.1.3',
      'eslint-plugin-react': '^6.3.0',
      'rimraf': '^2.5.2'
    },
    prod: {
      'in-publish': '^2.0.0'
    }
  }
}
<commit_msg>Bump version ranges<commit_after>export default {
  // Dependencies for a default Sanity installation
  core: {
    '@sanity/base': '^0.0.23',
    '@sanity/components': '^0.0.27',
    '@sanity/default-layout': '^0.0.4',
    '@sanity/default-login': '^0.0.2',
    '@sanity/desk-tool': '^0.1.9',
    'react': '^15.3.0',
    'react-dom': '^15.3.0'
  },

  // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io)
  plugin: {
    dev: {
      '@sanity/check': '^0.0.2',
      'babel-cli': '^6.9.0',
      'babel-eslint': '^6.0.4',
      'babel-plugin-syntax-class-properties': '^6.8.0',
      'babel-plugin-transform-class-properties': '^6.9.1',
      'babel-preset-es2015': '^6.9.0',
      'babel-preset-react': '^6.5.0',
      'eslint': '^3.4.0',
      'eslint-config-sanity': '^1.1.3',
      'eslint-plugin-react': '^6.3.0',
      'rimraf': '^2.5.2'
    },
    prod: {
      'in-publish': '^2.0.0'
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

const cloneDeep = require('lodash.clonedeep');

const addMonths = require('date-fns/add_months')
const addWeeks = require('date-fns/add_weeks');
const addDays = require('date-fns/add_days')
const addSeconds = require('date-fns/add_seconds')

const setISODay = require('date-fns/set_iso_day');
const getISODay = require('date-fns/get_iso_day');
const setHours = require('date-fns/set_hours')
const setMinutes = require('date-fns/set_minutes')
const setSeconds = require('date-fns/set_seconds')

module.exports.isRelative = function isRelative(v) {
	return v && (v.relativeMonths >= 0 || v.relativeWeeks >= 0 || v.relativeDays >= 0);
};

module.exports.combine = function(a, b) {
	const result = cloneDeep(a);
	Object.keys(b).forEach(key => result[key] = b[key]);
	return result;
};

function currentTime(encounter) {
	if(encounter.options.now) {
		return encounter.options.now;
	} else {
		return encounter.options.now = new Date();
	}
}
module.exports.currentTime = currentTime;

function toDate(date, now) {
	return new Date(
		typeof date.year !== 'undefined' ? date.year : now.getFullYear(),
		typeof date.month !== 'undefined' ? date.month : now.getMonth(),
		typeof date.day !== 'undefined' ? date.day : now.getDate()
	);
}

module.exports.toDate = toDate;

function mapYear(r, e) {
	const now = module.exports.currentTime(e);
	if(r.adjusters) {
		r.adjusters.forEach(a => a(r, now));
	}

	const result = new DateValue(e.language);

	if(typeof r.relativeYear !== 'undefined') {
		result.year = now.getFullYear() + r.relativeYear;
		result.month = now.getMonth();
	}

	if(typeof r.relativeMonths !== 'undefined') {
		const time = addMonths(toDate(result, now), r.relativeMonths);
		result.year = time.getFullYear();
		result.month = time.getMonth();
	}

	if(typeof r.year !== 'undefined') {
		result.year = r.year;
	}

	if(typeof r.month !== 'undefined') {
		result.month = r.month;
	}

	return result;
}

module.exports.mapYear = mapYear;
module.exports.mapMonth = mapYear;

function resolveDate(r, e) {
	const result = mapYear(r, e);

	const now = toDate(result, currentTime(e));

	if(typeof result.year === 'undefined') {
		result.year = now.getFullYear();
	}

	if(typeof result.month === 'undefined') {
		result.month = now.getMonth();
	}

	if(typeof r.relativeDays !== 'undefined') {
		const date = addDays(toDate(result, now), r.relativeDays);
		result.year = date.getFullYear();
		result.month = date.getMonth();
		result.day = date.getDate();
	} else {
		if(typeof r.day !== 'undefined') {
			result.day = r.day;
		} else {
			result.day = now.getDate();
		}
	}

	if(typeof r.dayOfWeek !== 'undefined') {
		if(typeof r.month === 'undefined') {
			// Reset to first month
			result.month = 0;
		}

		if(typeof r.day === 'undefined') {
			// Reset to first day
			result.day = 1;
		}

		let date = toDate(result, now);

		const currentDayOfWeek = getISODay(date);
		if(currentDayOfWeek > r.dayOfWeek) {
			date = addWeeks(date, 1);
		}
		date = setISODay(date, r.dayOfWeek);

		for(let i=1; i<r.dayOfWeekOrdinal; i++) {
			date = addWeeks(date, 1);
		}

		result.year = date.getFullYear();
		result.month = date.getMonth();
		result.day = date.getDate();
	}

	return result;
}

module.exports.mapDate = resolveDate;

function resolveTime(r, e, now, result) {
	result = result || new DateValue(e.language);

	let time = currentTime(e);

	if(r.relative > 0) {
		time = addSeconds(time, r.relative);
	} else {
		if(typeof r.hour !== 'undefined') {
			time = setHours(time, r.hour);
		}

		if(typeof r.minute !== 'undefined') {
			time = setMinutes(time, r.minute);
		} else {
			time = setMinutes(time, 0);
		}

		if(typeof r.second !== 'undefined') {
			time = setSeconds(time, r.second);
		} else {
			time = setSeconds(time, 0);
		}
	}

	result.hour = time.getHours();
	result.minute = time.getMinutes();
	result.precision = r.precision || result.precision || 'normal';
	return result;
}

module.exports.mapTime = resolveTime;

module.exports.mapDateTime = function(r, e) {
	const result = resolveDate(r, e);

	return resolveTime(r, e, result.toDate(), result);
}

class DateValue {
	constructor(language) {
		Object.defineProperty(this, 'language', {
			value: language
		});
	}

	toDate(now) {
		return module.exports.toDate(this, now || new Date());
	}
}
<commit_msg>Correctly transfer times to date<commit_after>'use strict';

const cloneDeep = require('lodash.clonedeep');

const addMonths = require('date-fns/add_months')
const addWeeks = require('date-fns/add_weeks');
const addDays = require('date-fns/add_days')
const addSeconds = require('date-fns/add_seconds')

const setISODay = require('date-fns/set_iso_day');
const getISODay = require('date-fns/get_iso_day');
const setHours = require('date-fns/set_hours')
const setMinutes = require('date-fns/set_minutes')
const setSeconds = require('date-fns/set_seconds')

module.exports.isRelative = function isRelative(v) {
	return v && (v.relativeMonths >= 0 || v.relativeWeeks >= 0 || v.relativeDays >= 0);
};

module.exports.combine = function(a, b) {
	const result = cloneDeep(a);
	Object.keys(b).forEach(key => result[key] = b[key]);
	return result;
};

function currentTime(encounter) {
	if(encounter.options.now) {
		return encounter.options.now;
	} else {
		return encounter.options.now = new Date();
	}
}
module.exports.currentTime = currentTime;

function toDate(date, now) {
	return new Date(
		typeof date.year !== 'undefined' ? date.year : now.getFullYear(),
		typeof date.month !== 'undefined' ? date.month : now.getMonth(),
		typeof date.day !== 'undefined' ? date.day : now.getDate(),
		typeof date.hour !== 'undefined' ? date.hour : 0,
		typeof date.minute !== 'undefined' ? date.minute : 0,
		typeof date.second !== 'undefined' ? date.second : 0
	);
}

module.exports.toDate = toDate;

function mapYear(r, e) {
	const now = module.exports.currentTime(e);
	if(r.adjusters) {
		r.adjusters.forEach(a => a(r, now));
	}

	const result = new DateValue(e.language);

	if(typeof r.relativeYear !== 'undefined') {
		result.year = now.getFullYear() + r.relativeYear;
		result.month = now.getMonth();
	}

	if(typeof r.relativeMonths !== 'undefined') {
		const time = addMonths(toDate(result, now), r.relativeMonths);
		result.year = time.getFullYear();
		result.month = time.getMonth();
	}

	if(typeof r.year !== 'undefined') {
		result.year = r.year;
	}

	if(typeof r.month !== 'undefined') {
		result.month = r.month;
	}

	return result;
}

module.exports.mapYear = mapYear;
module.exports.mapMonth = mapYear;

function resolveDate(r, e) {
	const result = mapYear(r, e);

	const now = toDate(result, currentTime(e));

	if(typeof result.year === 'undefined') {
		result.year = now.getFullYear();
	}

	if(typeof result.month === 'undefined') {
		result.month = now.getMonth();
	}

	if(typeof r.relativeDays !== 'undefined') {
		const date = addDays(toDate(result, now), r.relativeDays);
		result.year = date.getFullYear();
		result.month = date.getMonth();
		result.day = date.getDate();
	} else {
		if(typeof r.day !== 'undefined') {
			result.day = r.day;
		} else {
			result.day = now.getDate();
		}
	}

	if(typeof r.dayOfWeek !== 'undefined') {
		if(typeof r.month === 'undefined') {
			// Reset to first month
			result.month = 0;
		}

		if(typeof r.day === 'undefined') {
			// Reset to first day
			result.day = 1;
		}

		let date = toDate(result, now);

		const currentDayOfWeek = getISODay(date);
		if(currentDayOfWeek > r.dayOfWeek) {
			date = addWeeks(date, 1);
		}
		date = setISODay(date, r.dayOfWeek);

		for(let i=1; i<r.dayOfWeekOrdinal; i++) {
			date = addWeeks(date, 1);
		}

		result.year = date.getFullYear();
		result.month = date.getMonth();
		result.day = date.getDate();
	}

	return result;
}

module.exports.mapDate = resolveDate;

function resolveTime(r, e, now, result) {
	result = result || new DateValue(e.language);

	let time = currentTime(e);

	if(r.relative > 0) {
		time = addSeconds(time, r.relative);
	} else {
		if(typeof r.hour !== 'undefined') {
			time = setHours(time, r.hour);
		}

		if(typeof r.minute !== 'undefined') {
			time = setMinutes(time, r.minute);
		} else {
			time = setMinutes(time, 0);
		}

		if(typeof r.second !== 'undefined') {
			time = setSeconds(time, r.second);
		} else {
			time = setSeconds(time, 0);
		}
	}

	result.hour = time.getHours();
	result.minute = time.getMinutes();
	result.precision = r.precision || result.precision || 'normal';
	return result;
}

module.exports.mapTime = resolveTime;

module.exports.mapDateTime = function(r, e) {
	const result = resolveDate(r, e);

	return resolveTime(r, e, result.toDate(), result);
}

class DateValue {
	constructor(language) {
		Object.defineProperty(this, 'language', {
			value: language
		});
	}

	toDate(now) {
		return module.exports.toDate(this, now || new Date());
	}
}
<|endoftext|>


<commit_before>const resolve = require('resolve-pathname')
const $ = window.jQuery

const npmurl = require('./javascript').npmurl
const composerurl = require('./php').composerurl
const createLink = require('../helpers').createLink

module.exports.process = function process () {
  switch (window.pathdata.last) {
    case 'composer.json':
      composerjson()
      break
    case 'package.json':
      packagejson()
      break
    case 'elm-package.json':
      elmpackagejson()
      break
  }
}

function composerjson () {
  var depsOpen = false

  $('.blob-code-inner').each((_, elem) => {
    elem = $(elem)
    let line = elem.text().trim()

    if (line.match(/"require"/) || line.match(/"require-dev"/) ||
        line.match(/"suggest"/) || line.match(/"replace"/) || line.match(/"conflict"/)) {
      depsOpen = true
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(elem, composerurl)
    }
  })
}

function packagejson () {
  var depsOpen = false
  var contributorsOpen = false
  var authorOpen = false

  $('.blob-code-inner').each((_, rawelem) => {
    let elem = $(rawelem)
    let line = elem.text().trim()

    if (line.match(/"dependencies"/) || line.match(/"devDependencies"/) ||
        line.match(/"peerDependencies"/) || line.match(/"optionalDependencies"/)) {
      depsOpen = true
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (line.match(/"contributors"/) || line.match(/"authors"/)) {
      contributorsOpen = true
    }

    if (line.match(']')) {
      contributorsOpen = false
    }

    if (line.match(/"author"/) && line.match('{')) {
      authorOpen = true
    }

    if (line.match('}')) {
      authorOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(elem, npmurl)
    }

    if (!contributorsOpen && !authorOpen && line.match(/"name":/)) {
      let name = elem.find('.pl-s').eq(1).text().trim().slice(1, -1)
      let url = 'https://npmjs.com/package/' + name
      createLink(rawelem, name, {url, kind: 'maybe'})
    }

    if (line.match(/"main":/) || line.match(/"module":/) || line.match(/"es2015":/) || line.match(/"esnext":/) || // Files for different Node.js versions
        (line.match(/"browser":/) && !line.match(/"browser": {/)) || line.match(/"web":/) || // Files for web browsers
        line.match(/"unpkg":/) || line.match(/"jsdelivr":/) || line.match(/"runkitExampleFilename":/) || // Files for popular CDNs and examples
        line.match(/"source":/) || line.match(/"src":/) || line.match(/"typings":/) || line.match(/"types":/) || // Files for sources and typings
        line.match(/"node":/) || line.match(/"deno":/) // Files for different runtimes
    ) {
      let main = elem.find('.pl-s').eq(1).text().trim().slice(1, -1)
      let url = resolve(main, location.pathname)
      createLink(rawelem, main, url)
    }
  })
}

function lineWithUrlFetcher (elem, urlfetcher) {
  let link = elem.find('.pl-s').eq(0)
  let moduleName = link.text().trim().slice(1, -1)

  urlfetcher(moduleName)
    .then(url => {
      createLink(link.get(0), moduleName, url)
    })
    .catch(() => {})
}

function elmpackagejson () {
  var depsOpen = false
  var srcDirectoriesOpen = false

  $('.blob-code-inner').each((_, elem) => {
    elem = $(elem)
    let line = elem.text().trim()

    if (line.match(/"dependencies"/)) {
      depsOpen = true
      return
    }

    if (line.match(/"source-directories"/)) {
      srcDirectoriesOpen = true
      return
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (line.match(']')) {
      srcDirectoriesOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(
        elem,
        (moduleName) =>
          Promise.resolve({
            url: `http://package.elm-lang.org/packages/${moduleName}/latest`,
            kind: 'external'
          })
      )
    }

    if (srcDirectoriesOpen && elem.find('.pl-s').length === 1) {
      let path = elem.find('.pl-s').text().slice(1, -1)
      if (path && path.length > 1) {
        createLink(elem.get(0), path, path)
      }
    }
  })
}
<commit_msg>Support for linking binary files<commit_after>const resolve = require('resolve-pathname')
const $ = window.jQuery

const npmurl = require('./javascript').npmurl
const composerurl = require('./php').composerurl
const createLink = require('../helpers').createLink

module.exports.process = function process () {
  switch (window.pathdata.last) {
    case 'composer.json':
      composerjson()
      break
    case 'package.json':
      packagejson()
      break
    case 'elm-package.json':
      elmpackagejson()
      break
  }
}

function composerjson () {
  var depsOpen = false

  $('.blob-code-inner').each((_, elem) => {
    elem = $(elem)
    let line = elem.text().trim()

    if (line.match(/"require"/) || line.match(/"require-dev"/) ||
        line.match(/"suggest"/) || line.match(/"replace"/) || line.match(/"conflict"/)) {
      depsOpen = true
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(elem, composerurl)
    }
  })
}

function packagejson () {
  var depsOpen = false
  var contributorsOpen = false
  var authorOpen = false
  var binOpen = false

  $('.blob-code-inner').each((_, rawelem) => {
    let elem = $(rawelem)
    let line = elem.text().trim()

    if (line.match(/"dependencies"/) || line.match(/"devDependencies"/) ||
        line.match(/"peerDependencies"/) || line.match(/"optionalDependencies"/)) {
      depsOpen = true
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (line.match(/"contributors"/) || line.match(/"authors"/)) {
      contributorsOpen = true
    }

    if (line.match(']')) {
      contributorsOpen = false
    }

    if (line.match(/"author"/) && line.match('{')) {
      authorOpen = true
    }

    if (line.match('}')) {
      authorOpen = false
    }

    if (line.match(/"bin"/) && line.match('{')) {
      binOpen = true
    }

    if (line.match('}')) {
      binOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(elem, npmurl)
    }

    if (!contributorsOpen && !authorOpen && line.match(/"name":/)) {
      let name = elem.find('.pl-s').eq(1).text().trim().slice(1, -1)
      let url = 'https://npmjs.com/package/' + name
      createLink(rawelem, name, {url, kind: 'maybe'})
    }

    if (binOpen && line.split(':').length == 2) {
      let main = elem.find('.pl-s').eq(1).text().trim().slice(1, -1)
      let url = resolve(main, location.pathname)
      createLink(rawelem, main, url)
    }

    if (line.match(/"main":/) || line.match(/"module":/) || line.match(/"es2015":/) || line.match(/"esnext":/) || // Files for different Node.js versions
        (line.match(/"browser":/) && !line.match(/"browser": {/)) || line.match(/"web":/) || // Files for web browsers
        line.match(/"unpkg":/) || line.match(/"jsdelivr":/) || line.match(/"runkitExampleFilename":/) || // Files for popular CDNs and examples
        line.match(/"source":/) || line.match(/"src":/) || line.match(/"typings":/) || line.match(/"types":/) || // Files for sources and typings
        line.match(/"node":/) || line.match(/"deno":/) || // Files for different runtimes
        (line.match(/"bin":/) && !line.match(/"bin": {/)) // Executable file
    ) {
      let main = elem.find('.pl-s').eq(1).text().trim().slice(1, -1)
      let url = resolve(main, location.pathname)
      createLink(rawelem, main, url)
    }
  })
}

function lineWithUrlFetcher (elem, urlfetcher) {
  let link = elem.find('.pl-s').eq(0)
  let moduleName = link.text().trim().slice(1, -1)

  urlfetcher(moduleName)
    .then(url => {
      createLink(link.get(0), moduleName, url)
    })
    .catch(() => {})
}

function elmpackagejson () {
  var depsOpen = false
  var srcDirectoriesOpen = false

  $('.blob-code-inner').each((_, elem) => {
    elem = $(elem)
    let line = elem.text().trim()

    if (line.match(/"dependencies"/)) {
      depsOpen = true
      return
    }

    if (line.match(/"source-directories"/)) {
      srcDirectoriesOpen = true
      return
    }

    if (line.match('}')) {
      depsOpen = false
    }

    if (line.match(']')) {
      srcDirectoriesOpen = false
    }

    if (depsOpen && elem.find('.pl-s').length === 2) {
      lineWithUrlFetcher(
        elem,
        (moduleName) =>
          Promise.resolve({
            url: `http://package.elm-lang.org/packages/${moduleName}/latest`,
            kind: 'external'
          })
      )
    }

    if (srcDirectoriesOpen && elem.find('.pl-s').length === 1) {
      let path = elem.find('.pl-s').text().slice(1, -1)
      if (path && path.length > 1) {
        createLink(elem.get(0), path, path)
      }
    }
  })
}
<|endoftext|>


<commit_before>;(function(exports) {
  var Ctx = function() {
    this.first = function(x) {
      return x[0];
    };

    this.rest = function(x) {
      return x.slice(1);
    };

    this.print = function(x) {
      console.log(x);
      return x;

  var Ctx = function(scope, parent) {
    this.scope = scope;
  };
    };
  };

  var interpret = function(input, ctx) {
    if (ctx === undefined) {
      return interpret(input, new Ctx());
    } else if (input.value !== undefined) {
      return input.value;
    } else {
      if (input[0].type === "identifier") {
        return ctx[input[0].value].apply(this, interpret(input.slice(1), ctx));
      } else {
        return input.slice(0).map(function(x) {
          return interpret(x, ctx);
        });
      }
    }
  };

  var atDepth = function(output, depth) {
    if (depth === 0) {
      return output;
    } else {
      return atDepth(output[output.length - 1], depth - 1);
    }
  };

  var type = function(input) {
    if (!isNaN(parseFloat(input))) {
      return { type:'number', value: parseFloat(input) };
    } else if (input[0] === '"' && input.slice(-1) === '"') {
      return { type:'string', value: input.slice(1, -1) };
    } else {
      return { type:'identifier', value: input };
    }
  };

  var parenthesize = function(input) {
    var output = [];
    var depth = 0;
    while (input.length > 0) {
      var token = input.shift();
      if (token === "(") {
        atDepth(output, depth++).push([]);
      } else if (token === ")") {
        depth--;
      } else {
        atDepth(output, depth).push(type(token));
      }
    }

    return output.pop();
  };

  var tokenize = function(input) {
    return input.split('"').map(function(x, i) {
                   return i % 2 === 0 ? x : x.replace(/ /g, "spaceholder");
                 }).join('"')
                .replace(/\(/g, ' ( ')
                .replace(/\)/g, ' ) ')
                .trim()
                .split(/ +/)
                .map(function(x) {
                  return x.replace(/spaceholder/g, " ");
                });
  };

  var parse = function(input) {
    return parenthesize(tokenize(input));
  };

  exports.tinyLisp = {};
  exports.tinyLisp.parse = parse;
  exports.tinyLisp.interpret = interpret;
})(typeof exports === 'undefined' ? this : exports);
<commit_msg>Allow hierarchical Ctxs.<commit_after>;(function(exports) {
  var Ctx = function() {
    this.first = function(x) {
      return x[0];
    };

    this.rest = function(x) {
      return x.slice(1);
    };

    this.print = function(x) {
      console.log(x);
      return x;

  var Ctx = function(scope, parent) {
    this.scope = scope;
    this.parent = parent;
  };
    };
  };

  var interpret = function(input, ctx) {
    if (ctx === undefined) {
      return interpret(input, new Ctx());
    } else if (input.value !== undefined) {
      return input.value;
    } else {
      if (input[0].type === "identifier") {
        return ctx[input[0].value].apply(this, interpret(input.slice(1), ctx));
      } else {
        return input.slice(0).map(function(x) {
          return interpret(x, ctx);
        });
      }
    }
  };

  var atDepth = function(output, depth) {
    if (depth === 0) {
      return output;
    } else {
      return atDepth(output[output.length - 1], depth - 1);
    }
  };

  var type = function(input) {
    if (!isNaN(parseFloat(input))) {
      return { type:'number', value: parseFloat(input) };
    } else if (input[0] === '"' && input.slice(-1) === '"') {
      return { type:'string', value: input.slice(1, -1) };
    } else {
      return { type:'identifier', value: input };
    }
  };

  var parenthesize = function(input) {
    var output = [];
    var depth = 0;
    while (input.length > 0) {
      var token = input.shift();
      if (token === "(") {
        atDepth(output, depth++).push([]);
      } else if (token === ")") {
        depth--;
      } else {
        atDepth(output, depth).push(type(token));
      }
    }

    return output.pop();
  };

  var tokenize = function(input) {
    return input.split('"').map(function(x, i) {
                   return i % 2 === 0 ? x : x.replace(/ /g, "spaceholder");
                 }).join('"')
                .replace(/\(/g, ' ( ')
                .replace(/\)/g, ' ) ')
                .trim()
                .split(/ +/)
                .map(function(x) {
                  return x.replace(/spaceholder/g, " ");
                });
  };

  var parse = function(input) {
    return parenthesize(tokenize(input));
  };

  exports.tinyLisp = {};
  exports.tinyLisp.parse = parse;
  exports.tinyLisp.interpret = interpret;
})(typeof exports === 'undefined' ? this : exports);
<|endoftext|>


<commit_before>/*
 * Leaflet Search Plugin 1.0.0
 * https://github.com/stefanocudini/leaflet-search
 *
 * Copyright 2012, Stefano Cudini - stefano.cudini@gmail.com
 * Licensed under the MIT license.
 */

L.Control.Search = L.Control.extend({
	includes: L.Mixin.Events,

	options: {
		position: 'topleft',
		layer: new L.LayerGroup(),	//layer where search elements, default: empty layer
		text: 'Search...',	//placeholder value
		propFilter: 'title',	//property of elements filtered by _filterRecords()
		initial: true
	},

	initialize: function(options) {
		L.Util.setOptions(this, options);
		//this._recordsCache = this._updateRecords();//create table text,latlng
		this._inputSize = this.options.text.length;
	},

	onAdd: function (map) {
		this._map = map;
		this._container = L.DomUtil.create('div', 'leaflet-control-search');
		this._tooltip = this._createTooltip('search-tooltip', this._container);
		this._input = this._createInput(this.options.text, 'search-input', this._container);
		this._createButton(this.options.text, 'search-button', this._container);
		return this._container;
	},

//	onRemove: function(map) {
//TODO
//	},

	showTooltip: function() {//must be before of _createButton
		this._input.focus();
		this._tooltip.style.display = 'block';
	},

	hideTooltip: function() {
//		this._input.blur();
		this._tooltip.style.display = 'none';
	},

	showInput: function() {//must be before of _createButton
		this._input.style.display = 'block';
		this._input.focus();
	},

	hideInput: function() {
		this.hideTooltip();
		this._input.blur();
		this._input.value ='';
		this._input.size = this._inputSize;
		this._input.style.display = 'none';
	},

	_switchInput: function() {
		if(this._input.style.display == 'none')
			this.showInput();
		else
			this.hideInput();
	},

	_createRecord: function(text, latlng, container) {//make record(tag a) insert into tooltip
		var rec = L.DomUtil.create('a', 'search-record', container);
			rec.href='#',
			rec.innerHTML = text;

		L.DomEvent
			.disableClickPropagation(rec)
			.addListener(rec, 'click', function(e) {
				//this._map.panTo(latlng);
				this._input.value = text;
				this._input.focus();
				this.hideTooltip();
			},this);

		return rec;
	},

	_fillTooltip: function(items) {//fill tooltip with links
		if(items.length==0) return false;
		this._tooltip.innerHTML = '';
		for(i in items)
			this._createRecord(items[i][0], items[i][1], this._tooltip);
		this.showTooltip();
	},

	_createInput: function (text, className, container) {
		var input = L.DomUtil.create('input', className, container);
		input.type = 'text';
		input.size = this._inputSize,
		input.value = '';
		input.placeholder = text;
		input.style.display = 'none';

		L.DomEvent
			.disableClickPropagation(input)
			.addListener(input, 'keyup', this._filterRecords, this)
//			.addListener(input, 'blur', function() {
//				var that = this;
//				setTimeout(function() {
//					that.hideTooltip();
//					that.hideInput();
//				},200);
//			},this);

		return input;
	},

	_createButton: function (text, className, container) {
		var button = L.DomUtil.create('a', className, container);
		button.href = '#';
		button.title = text;

		L.DomEvent
			.disableClickPropagation(button)
			.addListener(button, 'click', function() {
				if(!this._recordsCache)		//initialize records
					this._recordsCache = this._updateRecords();//create table text,latlng
				this._switchInput();
			}, this);

		return button;
	},

	_createTooltip: function(className, container) {
		return L.DomUtil.create('div', className, container);
	},

	_updateRecords: function() {	//fill this._recordsCache with all values: text,latlng
		var markers = this.options.layer._layers,
			propFilter = this.options.propFilter,
			vals = {};

		this.options.layer.eachLayer(function(marker) {
			var text = marker.options[propFilter] || '';
			vals[text]= marker.getLatLng();
		},this);

		return vals;
	},

	_filterRecords: function() {	//filter this._recordsCache with this._input.value

		var inputText = this._input.value,
			I = this.options.initial ? '^' : '',  //search for initial text
			reg = new RegExp(I + inputText,'i'),
			records = this._recordsCache,
			results = [];

		this._input.size = inputText.length<this._inputSize ? this._inputSize : inputText.length;
		//autoresize this._input

		for(text in records)
		{
			var latlng = records[text];
			if(reg.test(text))//filter
				results.push([text,latlng]);
		}
		this._fillTooltip(results);
	}

});

<commit_msg>optimized _filterRecords()<commit_after>/*
 * Leaflet Search Plugin 1.0.0
 * https://github.com/stefanocudini/leaflet-search
 *
 * Copyright 2012, Stefano Cudini - stefano.cudini@gmail.com
 * Licensed under the MIT license.
 */

L.Control.Search = L.Control.extend({
	includes: L.Mixin.Events,

	options: {
		position: 'topleft',
		layer: new L.LayerGroup(),	//layer where search elements, default: empty layer
		text: 'Search...',	//placeholder value
		propFilter: 'title',	//property of elements filtered by _filterRecords()
		initial: true
	},

	initialize: function(options) {
		L.Util.setOptions(this, options);
		//this._recordsCache = this._updateRecords();//create table text,latlng
		this._inputMinSize = this.options.text.length;
	},

	onAdd: function (map) {
		this._map = map;
		this._container = L.DomUtil.create('div', 'leaflet-control-search');
		this._tooltip = this._createTooltip('search-tooltip', this._container);
		this._input = this._createInput(this.options.text, 'search-input', this._container);
		this._createButton(this.options.text, 'search-button', this._container);
		return this._container;
	},

//	onRemove: function(map) {
//TODO
//	},

	showTooltip: function() {//must be before of _createButton
		this._input.focus();
		this._tooltip.style.display = 'block';
	},

	hideTooltip: function() {
//		this._input.blur();
		this._tooltip.style.display = 'none';
	},

	showInput: function() {//must be before of _createButton
		this._input.style.display = 'block';
		this._input.focus();
	},

	hideInput: function() {
		this.hideTooltip();
		this._input.blur();
		this._input.value ='';
		this._input.size = this._inputMinSize;
		this._input.style.display = 'none';
	},

	_switchInput: function() {
		if(this._input.style.display == 'none')
			this.showInput();
		else
			this.hideInput();
	},

	_createRecord: function(text, latlng, container) {//make record(tag a) insert into tooltip
		var rec = L.DomUtil.create('a', 'search-record', container);
			rec.href = '#',
			rec.innerHTML = text;

		L.DomEvent
			.disableClickPropagation(rec)
			.addListener(rec, 'click', function(e) {
				//this._map.panTo(latlng);
				this._input.value = text;
				this._input.focus();
				this.hideTooltip();
			},this);

		return rec;
	},

	_fillTooltip: function(items) {//fill tooltip with links
		this._tooltip.innerHTML = '';
		if(items.length)
		{
			for(i in items)
				this._createRecord(items[i][0], items[i][1], this._tooltip);
			this.showTooltip();
		}
		else
			this.hideTooltip();
	},

	_createInput: function (text, className, container) {
		var input = L.DomUtil.create('input', className, container);
		input.type = 'text';
		input.size = this._inputMinSize,
		input.value = '';
		input.placeholder = text;
		input.style.display = 'none';

		L.DomEvent
			.disableClickPropagation(input)
			.addListener(input, 'keyup', this._inputAutoresize, this)
			.addListener(input, 'keyup', this._filterRecords, this)
//			.addListener(input, 'blur', function() {
//				var that = this;
//				setTimeout(function() {
//					that.hideTooltip();
//					that.hideInput();
//				},200);
//			},this);
		return input;
	},

	_inputAutoresize: function() {	//autoresize this._input
		this._input.size = this._input.value.length<this._inputMinSize ? this._inputMinSize : this._input.value.length;
	},

	_createButton: function (text, className, container) {
		var button = L.DomUtil.create('a', className, container);
		button.href = '#';
		button.title = text;

		L.DomEvent
			.disableClickPropagation(button)
			.addListener(button, 'click', function() {
				if(!this._recordsCache)		//initialize records
					this._recordsCache = this._updateRecords();//create table text,latlng
				this._switchInput();
			}, this);

		return button;
	},

	_createTooltip: function(className, container) {
		return L.DomUtil.create('div', className, container);
	},

	_updateRecords: function() {	//fill this._recordsCache with all values: text,latlng
		var markers = this.options.layer._layers,
			propFilter = this.options.propFilter,
			vals = {};

		this.options.layer.eachLayer(function(marker) {
			var text = marker.options[propFilter] || '';
			vals[text]= marker.getLatLng();
		},this);

		return vals;
	},

	_filterRecords: function() {	//filter this._recordsCache with this._input.value

		var inputText = this._input.value,
			I = this.options.initial ? '^' : '',  //search for initial text
			reg = new RegExp(I + inputText,'i'),
			records = this._recordsCache,
			results = [];

		if(inputText.length)
		{
			for(text in records)
			{
				var latlng = records[text],
					found = reg.test(text);

				if(found)//filter
					results.push([text,latlng]);
			}
		}
		this._fillTooltip(results);
	}

});

<|endoftext|>