forked from sweetpi/cassert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (44 loc) · 1.15 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var callsite = require('callsite')
, fs = require('fs')
, path = require('path')
, AssertionError = require('assert').AssertionError
, sms = require('source-map-support');
/**
* Enable the module only if not in the `production` environment.
*/
module.exports = (process.env.NODE_ENV === 'production')
? function() {}
: assert
/**
* Asserts that `expression` is true.
*/
function assert(expression)
{
if (expression) return
var stack = callsite().map(sms.wrapCallSite)
, file = stack[1].getFileName()
, line = stack[1].getLineNumber()
var err = new AssertionError({
message: getAssertionExpression(file, line),
stackStartFunction: stack[0].getFunction()
})
throw err
}
/**
* Gets the expression inside the assertion on line number
* `lineno` of `file`.
*/
function getAssertionExpression(file, lineno)
{
var ext = path.extname(file);
line = readJsLine(file, lineno);
return line.match(/assert\s*(.*)/)[1]
}
/**
* Reads `file` and returns line number `lineno`.
*/
function readJsLine(file, lineno)
{
var src = fs.readFileSync(file, 'utf8')
return src.split('\n')[lineno - 1]
}