path.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. /* ------------------------------------------------------------------------ */
  3. const isBrowser = (typeof window !== 'undefined') && (window.window === window) && window.navigator
  4. const cwd = isBrowser ? window.location.href : process.cwd ()
  5. const urlRegexp = new RegExp ("^((https|http)://)?[a-z0-9A-Z]{3}\.[a-z0-9A-Z][a-z0-9A-Z]{0,61}?[a-z0-9A-Z]\.com|net|cn|cc (:s[0-9]{1-4})?/$")
  6. /* ------------------------------------------------------------------------ */
  7. const path = module.exports = {
  8. concat (a, b) {
  9. const a_endsWithSlash = (a[a.length - 1] === '/'),
  10. b_startsWithSlash = (b[0] === '/')
  11. return a + ((a_endsWithSlash || b_startsWithSlash) ? '' : '/') +
  12. ((a_endsWithSlash && b_startsWithSlash) ? b.substring (1) : b)
  13. },
  14. resolve (x) {
  15. if (path.isAbsolute (x)) {
  16. return path.normalize (x) }
  17. return path.normalize (path.concat (cwd, x))
  18. },
  19. normalize (x) {
  20. let output = [],
  21. skip = 0
  22. x.split ('/').reverse ().filter (x => x !== '.').forEach (x => {
  23. if (x === '..') { skip++ }
  24. else if (skip === 0) { output.push (x) }
  25. else { skip-- }
  26. })
  27. const result = output.reverse ().join ('/')
  28. return ((isBrowser && (result[0] === '/')) ? result[1] === '/' ? window.location.protocol : window.location.origin : '') + result
  29. },
  30. isData: x => x.indexOf ('data:') === 0,
  31. isURL: x => urlRegexp.test (x),
  32. isAbsolute: x => (x[0] === '/') || /^[^\/]*:/.test (x),
  33. relativeToFile (a, b) {
  34. return (path.isData (a) || path.isAbsolute (b)) ?
  35. path.normalize (b) :
  36. path.normalize (path.concat (a.split ('/').slice (0, -1).join ('/'), b))
  37. }
  38. }
  39. /* ------------------------------------------------------------------------ */