utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /*!
  2. * Stylus - utils
  3. * Copyright (c) Automattic <developer.wordpress.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var nodes = require('./nodes')
  10. , basename = require('path').basename
  11. , relative = require('path').relative
  12. , join = require('path').join
  13. , isAbsolute = require('path').isAbsolute
  14. , glob = require('glob')
  15. , fs = require('fs');
  16. /**
  17. * Check if `path` looks absolute.
  18. *
  19. * @param {String} path
  20. * @return {Boolean}
  21. * @api private
  22. */
  23. exports.absolute = isAbsolute || function(path){
  24. // On Windows the path could start with a drive letter, i.e. a:\\ or two leading backslashes.
  25. // Also on Windows, the path may have been normalized to forward slashes, so check for this too.
  26. return path.substr(0, 2) == '\\\\' || '/' === path.charAt(0) || /^[a-z]:[\\\/]/i.test(path);
  27. };
  28. /**
  29. * Attempt to lookup `path` within `paths` from tail to head.
  30. * Optionally a path to `ignore` may be passed.
  31. *
  32. * @param {String} path
  33. * @param {String} paths
  34. * @param {String} ignore
  35. * @return {String}
  36. * @api private
  37. */
  38. exports.lookup = function(path, paths, ignore){
  39. var lookup
  40. , i = paths.length;
  41. // Absolute
  42. if (exports.absolute(path)) {
  43. try {
  44. fs.statSync(path);
  45. return path;
  46. } catch (err) {
  47. // Ignore, continue on
  48. // to trying relative lookup.
  49. // Needed for url(/images/foo.png)
  50. // for example
  51. }
  52. }
  53. // Relative
  54. while (i--) {
  55. try {
  56. lookup = join(paths[i], path);
  57. if (ignore == lookup) continue;
  58. fs.statSync(lookup);
  59. return lookup;
  60. } catch (err) {
  61. // Ignore
  62. }
  63. }
  64. };
  65. /**
  66. * Like `utils.lookup` but uses `glob` to find files.
  67. *
  68. * @param {String} path
  69. * @param {String} paths
  70. * @param {String} ignore
  71. * @return {Array}
  72. * @api private
  73. */
  74. exports.find = function(path, paths, ignore) {
  75. var lookup
  76. , found
  77. , i = paths.length;
  78. // Absolute
  79. if (exports.absolute(path)) {
  80. if ((found = glob.sync(path)).length) {
  81. return found;
  82. }
  83. }
  84. // Relative
  85. while (i--) {
  86. lookup = join(paths[i], path);
  87. if (ignore == lookup) continue;
  88. if ((found = glob.sync(lookup)).length) {
  89. return found;
  90. }
  91. }
  92. };
  93. /**
  94. * Lookup index file inside dir with given `name`.
  95. *
  96. * @param {String} name
  97. * @return {Array}
  98. * @api private
  99. */
  100. exports.lookupIndex = function(name, paths, filename){
  101. // foo/index.styl
  102. var found = exports.find(join(name, 'index.styl'), paths, filename);
  103. if (!found) {
  104. // foo/foo.styl
  105. found = exports.find(join(name, basename(name).replace(/\.styl/i, '') + '.styl'), paths, filename);
  106. }
  107. if (!found && !~name.indexOf('node_modules')) {
  108. // node_modules/foo/.. or node_modules/foo.styl/..
  109. found = lookupPackage(join('node_modules', name));
  110. }
  111. return found;
  112. function lookupPackage(dir) {
  113. var pkg = exports.lookup(join(dir, 'package.json'), paths, filename);
  114. if (!pkg) {
  115. return /\.styl$/i.test(dir) ? exports.lookupIndex(dir, paths, filename) : lookupPackage(dir + '.styl');
  116. }
  117. var main = require(relative(__dirname, pkg)).main;
  118. if (main) {
  119. found = exports.find(join(dir, main), paths, filename);
  120. } else {
  121. found = exports.lookupIndex(dir, paths, filename);
  122. }
  123. return found;
  124. }
  125. };
  126. /**
  127. * Format the given `err` with the given `options`.
  128. *
  129. * Options:
  130. *
  131. * - `filename` context filename
  132. * - `context` context line count [8]
  133. * - `lineno` context line number
  134. * - `column` context column number
  135. * - `input` input string
  136. *
  137. * @param {Error} err
  138. * @param {Object} options
  139. * @return {Error}
  140. * @api private
  141. */
  142. exports.formatException = function(err, options){
  143. var lineno = options.lineno
  144. , column = options.column
  145. , filename = options.filename
  146. , str = options.input
  147. , context = options.context || 8
  148. , context = context / 2
  149. , lines = ('\n' + str).split('\n')
  150. , start = Math.max(lineno - context, 1)
  151. , end = Math.min(lines.length, lineno + context)
  152. , pad = end.toString().length;
  153. var context = lines.slice(start, end).map(function(line, i){
  154. var curr = i + start;
  155. return ' '
  156. + Array(pad - curr.toString().length + 1).join(' ')
  157. + curr
  158. + '| '
  159. + line
  160. + (curr == lineno
  161. ? '\n' + Array(curr.toString().length + 5 + column).join('-') + '^'
  162. : '');
  163. }).join('\n');
  164. err.message = filename
  165. + ':' + lineno
  166. + ':' + column
  167. + '\n' + context
  168. + '\n\n' + err.message + '\n'
  169. + (err.stylusStack ? err.stylusStack + '\n' : '');
  170. // Don't show JS stack trace for Stylus errors
  171. if (err.fromStylus) err.stack = 'Error: ' + err.message;
  172. return err;
  173. };
  174. /**
  175. * Assert that `node` is of the given `type`, or throw.
  176. *
  177. * @param {Node} node
  178. * @param {Function} type
  179. * @param {String} param
  180. * @api public
  181. */
  182. exports.assertType = function(node, type, param){
  183. exports.assertPresent(node, param);
  184. if (node.nodeName == type) return;
  185. var actual = node.nodeName
  186. , msg = 'expected '
  187. + (param ? '"' + param + '" to be a ' : '')
  188. + type + ', but got '
  189. + actual + ':' + node;
  190. throw new Error('TypeError: ' + msg);
  191. };
  192. /**
  193. * Assert that `node` is a `String` or `Ident`.
  194. *
  195. * @param {Node} node
  196. * @param {String} param
  197. * @api public
  198. */
  199. exports.assertString = function(node, param){
  200. exports.assertPresent(node, param);
  201. switch (node.nodeName) {
  202. case 'string':
  203. case 'ident':
  204. case 'literal':
  205. return;
  206. default:
  207. var actual = node.nodeName
  208. , msg = 'expected string, ident or literal, but got ' + actual + ':' + node;
  209. throw new Error('TypeError: ' + msg);
  210. }
  211. };
  212. /**
  213. * Assert that `node` is a `RGBA` or `HSLA`.
  214. *
  215. * @param {Node} node
  216. * @param {String} param
  217. * @api public
  218. */
  219. exports.assertColor = function(node, param){
  220. exports.assertPresent(node, param);
  221. switch (node.nodeName) {
  222. case 'rgba':
  223. case 'hsla':
  224. return;
  225. default:
  226. var actual = node.nodeName
  227. , msg = 'expected rgba or hsla, but got ' + actual + ':' + node;
  228. throw new Error('TypeError: ' + msg);
  229. }
  230. };
  231. /**
  232. * Assert that param `name` is given, aka the `node` is passed.
  233. *
  234. * @param {Node} node
  235. * @param {String} name
  236. * @api public
  237. */
  238. exports.assertPresent = function(node, name){
  239. if (node) return;
  240. if (name) throw new Error('"' + name + '" argument required');
  241. throw new Error('argument missing');
  242. };
  243. /**
  244. * Unwrap `expr`.
  245. *
  246. * Takes an expressions with length of 1
  247. * such as `((1 2 3))` and unwraps it to `(1 2 3)`.
  248. *
  249. * @param {Expression} expr
  250. * @return {Node}
  251. * @api public
  252. */
  253. exports.unwrap = function(expr){
  254. // explicitly preserve the expression
  255. if (expr.preserve) return expr;
  256. if ('arguments' != expr.nodeName && 'expression' != expr.nodeName) return expr;
  257. if (1 != expr.nodes.length) return expr;
  258. if ('arguments' != expr.nodes[0].nodeName && 'expression' != expr.nodes[0].nodeName) return expr;
  259. return exports.unwrap(expr.nodes[0]);
  260. };
  261. /**
  262. * Coerce JavaScript values to their Stylus equivalents.
  263. *
  264. * @param {Mixed} val
  265. * @param {Boolean} [raw]
  266. * @return {Node}
  267. * @api public
  268. */
  269. exports.coerce = function(val, raw){
  270. switch (typeof val) {
  271. case 'function':
  272. return val;
  273. case 'string':
  274. return new nodes.String(val);
  275. case 'boolean':
  276. return new nodes.Boolean(val);
  277. case 'number':
  278. return new nodes.Unit(val);
  279. default:
  280. if (null == val) return nodes.null;
  281. if (Array.isArray(val)) return exports.coerceArray(val, raw);
  282. if (val.nodeName) return val;
  283. return exports.coerceObject(val, raw);
  284. }
  285. };
  286. /**
  287. * Coerce a javascript `Array` to a Stylus `Expression`.
  288. *
  289. * @param {Array} val
  290. * @param {Boolean} [raw]
  291. * @return {Expression}
  292. * @api private
  293. */
  294. exports.coerceArray = function(val, raw){
  295. var expr = new nodes.Expression;
  296. val.forEach(function(val){
  297. expr.push(exports.coerce(val, raw));
  298. });
  299. return expr;
  300. };
  301. /**
  302. * Coerce a javascript object to a Stylus `Expression` or `Object`.
  303. *
  304. * For example `{ foo: 'bar', bar: 'baz' }` would become
  305. * the expression `(foo 'bar') (bar 'baz')`. If `raw` is true
  306. * given `obj` would become a Stylus hash object.
  307. *
  308. * @param {Object} obj
  309. * @param {Boolean} [raw]
  310. * @return {Expression|Object}
  311. * @api public
  312. */
  313. exports.coerceObject = function(obj, raw){
  314. var node = raw ? new nodes.Object : new nodes.Expression
  315. , val;
  316. for (var key in obj) {
  317. val = exports.coerce(obj[key], raw);
  318. key = new nodes.Ident(key);
  319. if (raw) {
  320. node.set(key, val);
  321. } else {
  322. node.push(exports.coerceArray([key, val]));
  323. }
  324. }
  325. return node;
  326. };
  327. /**
  328. * Return param names for `fn`.
  329. *
  330. * @param {Function} fn
  331. * @return {Array}
  332. * @api private
  333. */
  334. exports.params = function(fn){
  335. return fn
  336. .toString()
  337. .match(/\(([^)]*)\)/)[1].split(/ *, */);
  338. };
  339. /**
  340. * Merge object `b` with `a`.
  341. *
  342. * @param {Object} a
  343. * @param {Object} b
  344. * @param {Boolean} [deep]
  345. * @return {Object} a
  346. * @api private
  347. */
  348. exports.merge = function(a, b, deep) {
  349. for (var k in b) {
  350. if (deep && a[k]) {
  351. var nodeA = exports.unwrap(a[k]).first
  352. , nodeB = exports.unwrap(b[k]).first;
  353. if ('object' == nodeA.nodeName && 'object' == nodeB.nodeName) {
  354. a[k].first.vals = exports.merge(nodeA.vals, nodeB.vals, deep);
  355. } else {
  356. a[k] = b[k];
  357. }
  358. } else {
  359. a[k] = b[k];
  360. }
  361. }
  362. return a;
  363. };
  364. /**
  365. * Returns an array with unique values.
  366. *
  367. * @param {Array} arr
  368. * @return {Array}
  369. * @api private
  370. */
  371. exports.uniq = function(arr){
  372. var obj = {}
  373. , ret = [];
  374. for (var i = 0, len = arr.length; i < len; ++i) {
  375. if (arr[i] in obj) continue;
  376. obj[arr[i]] = true;
  377. ret.push(arr[i]);
  378. }
  379. return ret;
  380. };
  381. /**
  382. * Compile selector strings in `arr` from the bottom-up
  383. * to produce the selector combinations. For example
  384. * the following Stylus:
  385. *
  386. * ul
  387. * li
  388. * p
  389. * a
  390. * color: red
  391. *
  392. * Would return:
  393. *
  394. * [ 'ul li a', 'ul p a' ]
  395. *
  396. * @param {Array} arr
  397. * @param {Boolean} leaveHidden
  398. * @return {Array}
  399. * @api private
  400. */
  401. exports.compileSelectors = function(arr, leaveHidden){
  402. var selectors = []
  403. , Parser = require('./selector-parser')
  404. , indent = (this.indent || '')
  405. , buf = [];
  406. function parse(selector, buf) {
  407. var parts = [selector.val]
  408. , str = new Parser(parts[0], parents, parts).parse().val
  409. , parents = [];
  410. if (buf.length) {
  411. for (var i = 0, len = buf.length; i < len; ++i) {
  412. parts.push(buf[i]);
  413. parents.push(str);
  414. var child = new Parser(buf[i], parents, parts).parse();
  415. if (child.nested) {
  416. str += ' ' + child.val;
  417. } else {
  418. str = child.val;
  419. }
  420. }
  421. }
  422. return str.trim();
  423. }
  424. function compile(arr, i) {
  425. if (i) {
  426. arr[i].forEach(function(selector){
  427. if (!leaveHidden && selector.isPlaceholder) return;
  428. if (selector.inherits) {
  429. buf.unshift(selector.val);
  430. compile(arr, i - 1);
  431. buf.shift();
  432. } else {
  433. selectors.push(indent + parse(selector, buf));
  434. }
  435. });
  436. } else {
  437. arr[0].forEach(function(selector){
  438. if (!leaveHidden && selector.isPlaceholder) return;
  439. var str = parse(selector, buf);
  440. if (str) selectors.push(indent + str);
  441. });
  442. }
  443. }
  444. compile(arr, arr.length - 1);
  445. // Return the list with unique selectors only
  446. return exports.uniq(selectors);
  447. };
  448. /**
  449. * Attempt to parse string.
  450. *
  451. * @param {String} str
  452. * @return {Node}
  453. * @api private
  454. */
  455. exports.parseString = function(str){
  456. var Parser = require('./parser')
  457. , parser
  458. , ret;
  459. try {
  460. parser = new Parser(str);
  461. ret = parser.list();
  462. } catch (e) {
  463. ret = new nodes.Literal(str);
  464. }
  465. return ret;
  466. };