-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
101 lines (83 loc) · 1.91 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*jslint node: true */
"use strict";
var liburl = require("url"),
u = require("underscore"),
errors = require("./errors");
function up(path) {
var brk;
if (!path || path === "/") {
throw new Error("cannot move up from root");
}
if (path.slice(-1) === "/") {
path = path.slice(0, -1);
}
if (path.slice(0, 1) === "/") {
path = path.slice(1);
}
brk = path.lastIndexOf("/");
if (brk >= 0) {
path = path.slice(0, brk);
} else {
path = "";
}
return "/" + path;
}
function down(path, elem) {
if (path.slice(0, 1) === "/") {
path = path.slice(1);
}
if (path.slice(-1) === "/") {
path = path.slice(0, -1);
}
if (elem.slice(0, 1) !== "/") {
elem = "/" + elem;
}
return path + elem;
}
function build(req, newPath, query) {
var spec = {
protocol: req.protocol,
host: req.headers.host,
pathname: newPath
};
if (query) {
spec.query = query;
}
return liburl.format(spec);
}
exports.url = build;
exports.baseUrl = function (req) {
return build(req, "/");
};
exports.upUrl = function (req, query) {
return build(req, up(req.path), query);
};
exports.downUrl = function (req, seg, query) {
return build(req, down(req.path, seg), query);
};
exports.selfUrl = function (req, query) {
return build(req, req.path, query);
};
exports.foreignUrl = function (req, fpath, seg) {
var path = seg
? down(fpath, seg)
: fpath;
return build(req, path);
};
exports.hlink = function (url_s, attrs) {
var rval;
function build(url) {
var l = {href: url};
if (attrs) {
u.extend(l, attrs);
}
return l;
}
if (u.isArray(url_s)) {
rval = u.map(url_s, build);
} else {
rval = build(url_s);
}
return rval;
};
exports.errors = errors;