index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Constants
  3. */
  4. var SPLITTER = "\n at "
  5. /**
  6. * PostCSS helpers
  7. */
  8. module.exports = {
  9. sourceString: sourceString,
  10. message: formatMessage,
  11. try: tryCatch
  12. }
  13. /**
  14. * Returns GNU style source
  15. *
  16. * @param {Object} source
  17. */
  18. function sourceString(source) {
  19. var message = "<css input>"
  20. if (source) {
  21. if (source.input && source.input.file) {
  22. message = source.input.file
  23. }
  24. if (source.start) {
  25. message += ":" + source.start.line + ":" + source.start.column
  26. }
  27. }
  28. return message
  29. }
  30. /**
  31. * Returns a GNU style message
  32. *
  33. * @param {String} message
  34. * @param {Object} source a PostCSS source object
  35. * @return {String}
  36. */
  37. function formatMessage(message, source) {
  38. return sourceString(source) + ": " + message
  39. }
  40. /**
  41. * Do something and throw an error with enhanced exception (from given source)
  42. *
  43. * @param {Function} fn [description]
  44. * @param {[type]} source [description]
  45. */
  46. function tryCatch(fn, source) {
  47. try {
  48. return fn()
  49. }
  50. catch (err) {
  51. err.originalMessage = err.message
  52. err.message = formatMessage(err.message, source)
  53. // if source seems interesting, enhance error
  54. if (typeof source === "object") {
  55. // add a stack item if something interesting available
  56. if ((source.input && source.input.file) || source.start) {
  57. var stack = err.stack.split(SPLITTER)
  58. var firstStackItem = stack.shift()
  59. stack.unshift(sourceString(source))
  60. stack.unshift(firstStackItem)
  61. err.stack = stack.join(SPLITTER)
  62. }
  63. if (source.input && source.input.file) {
  64. err.fileName = source.input.file
  65. }
  66. if (source.start) {
  67. err.lineNumber = source.start.line
  68. err.columnNumber = source.start.column
  69. }
  70. }
  71. throw err
  72. }
  73. }