-
Notifications
You must be signed in to change notification settings - Fork 969
/
devHandler.js
246 lines (215 loc) · 7.27 KB
/
devHandler.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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import fs from 'fs'
import { argv } from 'process'
import concurrently from 'concurrently'
import { recordTelemetryAttributes } from '@redwoodjs/cli-helpers'
import { shutdownPort } from '@redwoodjs/internal/dist/dev'
import { getConfig, getConfigPath } from '@redwoodjs/project-config'
import { errorTelemetry } from '@redwoodjs/telemetry'
import { getPaths } from '../lib'
import c from '../lib/colors'
import { exitWithError } from '../lib/exit'
import { generatePrismaClient } from '../lib/generatePrismaClient'
import { getFreePort } from '../lib/ports'
const defaultApiDebugPort = 18911
export const handler = async ({
side = ['api', 'web'],
forward = '',
generate = true,
watchNodeModules = process.env.RWJS_WATCH_NODE_MODULES === '1',
apiDebugPort,
}) => {
recordTelemetryAttributes({
command: 'dev',
side: JSON.stringify(side),
generate,
watchNodeModules,
})
const rwjsPaths = getPaths()
// Starting values of ports from config (redwood.toml)
let apiPreferredPort = parseInt(getConfig().api.port)
let webPreferredPort = parseInt(getConfig().web.port)
// Assume we can have the ports we want
let apiAvailablePort = apiPreferredPort
let apiPortChangeNeeded = false
let webAvailablePort = webPreferredPort
let webPortChangeNeeded = false
// Check api port
if (side.includes('api')) {
apiAvailablePort = await getFreePort(apiPreferredPort)
if (apiAvailablePort === -1) {
exitWithError(undefined, {
message: `Could not determine a free port for the api server`,
})
}
apiPortChangeNeeded = apiAvailablePort !== apiPreferredPort
}
// Check web port
if (side.includes('web')) {
// Extract any ports the user forwarded to the webpack server and prefer that instead
const forwardedPortMatches = [
...forward.matchAll(/\-\-port(\=|\s)(?<port>[^\s]*)/g),
]
if (forwardedPortMatches.length) {
webPreferredPort = parseInt(forwardedPortMatches.pop().groups.port)
}
webAvailablePort = await getFreePort(webPreferredPort, [
apiPreferredPort,
apiAvailablePort,
])
if (webAvailablePort === -1) {
exitWithError(undefined, {
message: `Could not determine a free port for the web server`,
})
}
webPortChangeNeeded = webAvailablePort !== webPreferredPort
}
// Check for port conflict and exit with message if found
if (apiPortChangeNeeded || webPortChangeNeeded) {
let message = `The currently configured ports for the development server are unavailable. Suggested changes to your ports, which can be changed in redwood.toml, are:\n`
message += apiPortChangeNeeded
? ` - API to use port ${apiAvailablePort} instead of your currently configured ${apiPreferredPort}\n`
: ``
message += webPortChangeNeeded
? ` - Web to use port ${webAvailablePort} instead of your currently configured ${webPreferredPort}\n`
: ``
message += `\nCannot run the development server until your configured ports are changed or become available.`
exitWithError(undefined, {
message,
})
}
if (side.includes('api')) {
try {
await generatePrismaClient({
verbose: false,
force: false,
schema: rwjsPaths.api.dbSchema,
})
} catch (e) {
errorTelemetry(
process.argv,
`Error generating prisma client: ${e.message}`
)
console.error(c.error(e.message))
}
try {
await shutdownPort(apiAvailablePort)
} catch (e) {
errorTelemetry(process.argv, `Error shutting down "api": ${e.message}`)
console.error(
`Error whilst shutting down "api" port: ${c.error(e.message)}`
)
}
}
if (side.includes('web')) {
try {
await shutdownPort(webAvailablePort)
} catch (e) {
errorTelemetry(process.argv, `Error shutting down "web": ${e.message}`)
console.error(
`Error whilst shutting down "web" port: ${c.error(e.message)}`
)
}
}
const webpackDevConfig = require.resolve(
'@redwoodjs/core/config/webpack.development.js'
)
const getApiDebugFlag = () => {
// Passed in flag takes precedence
if (apiDebugPort) {
return `--debug-port ${apiDebugPort}`
} else if (argv.includes('--apiDebugPort')) {
return `--debug-port ${defaultApiDebugPort}`
}
const apiDebugPortInToml = getConfig().api.debugPort
if (apiDebugPortInToml) {
return `--debug-port ${apiDebugPortInToml}`
}
// Dont pass in debug port flag, unless configured
return ''
}
const redwoodConfigPath = getConfigPath()
const streamingSsrEnabled = getConfig().experimental.streamingSsr?.enabled
// @TODO (Streaming) Lot of temporary feature flags for started dev server.
// Written this way to make it easier to read
// 1. default: Vite (SPA)
let webCommand = `yarn cross-env NODE_ENV=development rw-vite-dev ${forward}`
// 2. Vite with SSR
if (streamingSsrEnabled) {
webCommand = `yarn cross-env NODE_ENV=development rw-dev-fe ${forward}`
}
// 3. Webpack (SPA): we will remove this override after v7
if (getConfig().web.bundler === 'webpack') {
if (streamingSsrEnabled) {
throw new Error(
'Webpack does not support SSR. Please switch your bundler to Vite in redwood.toml first'
)
} else {
webCommand = `yarn cross-env NODE_ENV=development RWJS_WATCH_NODE_MODULES=${
watchNodeModules ? '1' : ''
} webpack serve --config "${webpackDevConfig}" ${forward}`
}
}
/** @type {Record<string, import('concurrently').CommandObj>} */
const jobs = {
api: {
name: 'api',
command: `yarn cross-env NODE_ENV=development ${getDevNodeOptions()} yarn nodemon --quiet --watch "${redwoodConfigPath}" --exec "yarn rw-api-server-watch --port ${apiAvailablePort} ${getApiDebugFlag()} | rw-log-formatter"`,
prefixColor: 'cyan',
runWhen: () => fs.existsSync(rwjsPaths.api.src),
},
web: {
name: 'web',
command: webCommand,
prefixColor: 'blue',
cwd: rwjsPaths.web.base,
runWhen: () => fs.existsSync(rwjsPaths.web.src),
},
gen: {
name: 'gen',
command: 'yarn rw-gen-watch',
prefixColor: 'green',
runWhen: () => generate,
},
}
// TODO: Convert jobs to an array and supply cwd command.
const { result } = concurrently(
Object.keys(jobs)
.map((job) => {
if (side.includes(job) || job === 'gen') {
return jobs[job]
}
})
.filter((job) => job && job.runWhen()),
{
prefix: '{name} |',
timestampFormat: 'HH:mm:ss',
handleInput: true,
}
)
result.catch((e) => {
if (typeof e?.message !== 'undefined') {
errorTelemetry(
process.argv,
`Error concurrently starting sides: ${e.message}`
)
exitWithError(e)
}
})
}
/**
* Gets the NODE_OPTIONS environment variable from `process.env`, appending `--enable-source-maps` if it's not already there.
* See https://nodejs.org/api/cli.html#node_optionsoptions.
*
* @returns {string}
*/
export function getDevNodeOptions() {
const { NODE_OPTIONS } = process.env
const enableSourceMapsOption = '--enable-source-maps'
if (!NODE_OPTIONS) {
return `NODE_OPTIONS=${enableSourceMapsOption}`
}
if (NODE_OPTIONS.includes(enableSourceMapsOption)) {
return NODE_OPTIONS
}
return `${NODE_OPTIONS} ${enableSourceMapsOption}`
}