This repository was archived by the owner on Feb 4, 2025. It is now read-only.
forked from netlify/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrules-proxy.js
More file actions
135 lines (121 loc) · 3.89 KB
/
Copy pathrules-proxy.js
File metadata and controls
135 lines (121 loc) · 3.89 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
const fs = require('fs')
const path = require('path')
const url = require('url')
const chokidar = require('chokidar')
const cookie = require('cookie')
const { parseAllRedirects } = require('netlify-redirect-parser')
const redirector = require('netlify-redirector')
const { NETLIFYDEVWARN, NETLIFYDEVLOG } = require('./logo')
// Parse, normalize and validate all redirects from `_redirects` files
// and `netlify.toml`
const parseRedirectRules = async function ({ redirectsFiles, configPath }) {
try {
const rules = await parseAllRedirects({ redirectsFiles, netlifyConfigPath: configPath })
return rules.map(normalizeRule)
} catch (error) {
console.error(`${NETLIFYDEVWARN} Warnings while parsing redirects:
${error.message}`)
return []
}
}
// `netlify-redirector` does not handle the same shape as the backend:
// - `parameters` is called `params`
// - `destination` is called `to`
// - `conditions.role|country|language` are capitalized
const normalizeRule = function ({
parameters,
destination,
conditions: { role, country, language, ...conditions },
...rule
}) {
return {
...rule,
params: parameters,
to: destination,
conditions: {
...conditions,
...(role && { Role: role }),
...(country && { Country: country }),
...(language && { Language: language }),
},
}
}
const onChanges = function (files, listener) {
files.forEach((file) => {
const watcher = chokidar.watch(file)
watcher.on('change', listener)
watcher.on('unlink', listener)
})
}
const getLanguage = function (headers) {
if (headers['accept-language']) {
return headers['accept-language'].split(',')[0].slice(0, 2)
}
return 'en'
}
const getCountry = function () {
return 'us'
}
const createRewriter = async function ({ distDir, projectDir, jwtSecret, jwtRoleClaim, configPath }) {
let matcher = null
const redirectsFiles = [...new Set([path.resolve(distDir, '_redirects'), path.resolve(projectDir, '_redirects')])]
const getRedirectRules = parseRedirectRules.bind(undefined, { redirectsFiles, configPath })
let rules = await getRedirectRules()
const watchedRedirectFiles = configPath === undefined ? redirectsFiles : [...redirectsFiles, configPath]
onChanges(watchedRedirectFiles, async () => {
console.log(
`${NETLIFYDEVLOG} Reloading redirect rules from`,
watchedRedirectFiles.filter(fs.existsSync).map((configFile) => path.relative(projectDir, configFile)),
)
rules = await getRedirectRules()
matcher = null
})
const getMatcher = async () => {
if (matcher) return matcher
if (rules.length !== 0) {
return (matcher = await redirector.parseJSON(JSON.stringify(rules), {
jwtSecret,
jwtRoleClaim,
}))
}
return {
match() {
return null
},
}
}
return async function rewriter(req) {
const matcherFunc = await getMatcher()
const reqUrl = new url.URL(
req.url,
`${req.protocol || (req.headers.scheme && `${req.headers.scheme}:`) || 'http:'}//${
req.hostname || req.headers.host
}`,
)
const cookieValues = cookie.parse(req.headers.cookie || '')
const headers = {
'x-language': cookieValues.nf_lang || getLanguage(req.headers),
'x-country': cookieValues.nf_country || getCountry(req),
...req.headers,
}
// Definition: https://github.com/netlify/libredirect/blob/e81bbeeff9f7c260a5fb74cad296ccc67a92325b/node/src/redirects.cpp#L28-L60
const matchReq = {
scheme: reqUrl.protocol.replace(/:.*$/, ''),
host: reqUrl.hostname,
path: reqUrl.pathname,
query: reqUrl.search.slice(1),
headers,
cookieValues,
getHeader: (name) => headers[name.toLowerCase()] || '',
getCookie: (key) => cookieValues[key] || '',
}
const match = matcherFunc.match(matchReq)
return match
}
}
module.exports = {
parseRedirectRules,
onChanges,
getLanguage,
createRewriter,
}