-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
280 lines (236 loc) · 9.12 KB
/
extension.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import fs from 'node:fs';
import path from 'node:path';
import url from 'node:url';
import child_process from 'node:child_process';
import assert from 'node:assert';
import shellQuote from 'shell-quote';
/**
* @typedef {Object} ExtensionOptions - The configuration options for the extension. These are all configurable via `config.yaml`.
* @property {string=} buildCommand - A custom build command. Default to `next build`.
* @property {string=} buildOnly - Build the Next.js app and exit. Defaults to `false`.
* @property {boolean=} dev - Enable dev mode. Defaults to `false`.
* @property {string=} installCommand - A custom install command. Defaults to `npm install`.
* @property {number=} port - A port for the Next.js server. Defaults to `3000`.
* @property {boolean=} prebuilt - Instruct the extension to skip executing the `buildCommand`. Defaults to `false`.
*/
// Memoized Configuration
let CONFIG;
/**
* Assert that a given option is a specific type
*
* @param {string} name The name of the option
* @param {any=} option The option value
* @param {string} expectedType The expected type (i.e. `'string'`, `'number'`, `'boolean'`, etc.)
*/
function assertType(name, option, expectedType) {
if (option) {
const found = typeof option;
assert.strictEqual(found, expectedType, `${name} must be type ${expectedType}. Received: ${found}`);
}
}
/**
* Resolves the incoming extension options into a config for use throughout the extension
* @param {ExtensionOptions} options - The options object to be resolved into a configuration
* @returns {Required<ExtensionOptions>}
*/
function resolveConfig(options) {
if (CONFIG) return CONFIG; // return memoized config
// Environment Variables take precedence
switch (process.env.HARPERDB_NEXTJS_MODE) {
case 'dev':
options.dev = true;
break;
case 'build':
options.buildOnly = true;
options.dev = false;
options.prebuilt = false;
break;
case 'prod':
options.dev = false;
break;
default:
break;
}
assertType('buildCommand', options.buildCommand, 'string');
assertType('dev', options.dev, 'boolean');
assertType('installCommand', options.installCommand, 'string');
assertType('port', options.port, 'number');
assertType('prebuilt', options.prebuilt, 'boolean');
// Memoize config resolution
return (CONFIG = {
buildCommand: options.buildCommand ?? 'next build',
buildOnly: options.buildOnly ?? false,
dev: options.dev ?? false,
installCommand: options.installCommand ?? 'npm install',
port: options.port ?? 3000,
prebuilt: options.prebuilt ?? false,
});
}
class NextJSAppVerificationError extends Error {}
const nextJSAppCache = {};
/**
* This function verifies if the input is a Next.js app through a couple of
* verification methods. It does not return nor throw anything. It will either
* succeed (and return the path to the Next.js main file), or log an error to
* `logger.fatal` and exit the process with exit code 1.
*
* Additionally, it memoizes previous verifications.
*
* @param {string} componentPath
* @returns {string} The path to the Next.js main file
*/
function assertNextJSApp(componentPath) {
try {
if (nextJSAppCache[componentPath]) {
return nextJSAppCache[componentPath];
}
if (!fs.existsSync(componentPath)) {
throw new NextJSAppVerificationError(`The folder ${componentPath} does not exist`);
}
if (!fs.statSync(componentPath).isDirectory) {
throw new NextJSAppVerificationError(`The path ${componentPath} is not a folder`);
}
// Couple options to check if its a Next.js project
// 1. Check for Next.js config file (next.config.{js|mjs|ts})
// - This file is not required for a Next.js project
// 2. Check package.json for Next.js dependency
// - It could be listed in `dependencies` or `devDependencies` (and maybe even `peerDependencies` or `optionalDependencies`)
// - Also not required. Users can use `npx next ...`
// 3. Check for `.next` folder
// - This could be a reasonable fallback if we want to support pre-built Next.js apps
// A combination of options 1 and 2 should be sufficient for our purposes.
// Edge case: app does not have a config and are using `npx` (or something similar) to execute Next.js
// Check for Next.js Config
const configExists =
fs.existsSync(path.join(componentPath, 'next.config.js')) ||
fs.existsSync(path.join(componentPath, 'next.config.mjs')) ||
fs.existsSync(path.join(componentPath, 'next.config.ts'));
// Check for dependency
let nextjsPath;
const packageJSONPath = path.join(componentPath, 'package.json');
if (fs.existsSync(packageJSONPath)) {
let packageJSON = JSON.parse(fs.readFileSync(packageJSONPath));
for (let dependencyList of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
if (packageJSON[dependencyList]?.['next']) {
const nextJSPackageJSONPath = path.join(componentPath, 'node_modules', 'next', 'package.json');
if (fs.existsSync(nextJSPackageJSONPath)) {
const nextJSPackageJSON = JSON.parse(fs.readFileSync(nextJSPackageJSONPath));
if (nextJSPackageJSON.main) {
nextjsPath = path.join(componentPath, 'node_modules', 'next', nextJSPackageJSON.main);
break;
}
}
}
}
}
if (!configExists && !nextjsPath) {
throw new NextJSAppVerificationError(
`Could not determine if ${componentPath} is a Next.js project. It is missing both a Next.js config file and the "next" dependency in package.json`
);
}
nextJSAppCache[componentPath] = nextjsPath;
return nextjsPath;
} catch (error) {
if (error instanceof NextJSAppVerificationError) {
logger.fatal(`Component path is not a Next.js application: `, error.message);
} else {
logger.fatal(`Unexpected Error thrown during Next.js Verification: `, error);
}
process.exit(1);
}
}
/**
* Execute a command as a promise and wait for it to exit before resolving.
*
* Will automatically stream output to stdio when log level is set to debug.
* @param {string} commandInput The command string to be parsed and executed
* @param {string} componentPath The path to the application component
* @param {boolean=} debug Print debugging information. Defaults to false
*/
function executeCommand(commandInput, componentPath) {
return new Promise((resolve, reject) => {
const [command, ...args] = shellQuote.parse(commandInput);
const cp = child_process.spawn(command, args, {
cwd: componentPath,
env: { ...process.env, PATH: `${process.env.PATH}:${componentPath}/node_modules/.bin` },
stdio: logger.log_level === 'debug' ? 'inherit' : 'ignore',
});
cp.on('error', (error) => {
if (error.code === 'ENOENT') {
logger.fatal(`Command: \`${commandInput}\` not found. Make sure it is included in PATH.`);
}
reject(error);
});
cp.on('exit', (exitCode) => {
logger.debug(`Command: \`${commandInput}\` exited with ${exitCode}`);
resolve(exitCode);
});
});
}
/**
* This method is executed once, on the main thread, and is responsible for
* returning a Resource Extension that will subsequently be executed once,
* on the main thread.
*
* The Resource Extension is responsible for installing application component
* dependencies and running the application build command.
*
* @param {ExtensionOptions} options
* @returns
*/
export function startOnMainThread(options = {}) {
const config = resolveConfig(options);
logger.debug('Next.js Extension Configuration:', JSON.stringify(config, undefined, 2));
return {
async setupDirectory(_, componentPath) {
logger.info(`Next.js Extension is setting up ${componentPath}`);
assertNextJSApp(componentPath);
if (!fs.existsSync(path.join(componentPath, 'node_modules'))) {
await executeCommand(config.installCommand, componentPath);
}
if (!config.prebuilt && !config.dev) {
await executeCommand(config.buildCommand, componentPath);
if (config.buildOnly) process.exit(0);
}
return true;
},
};
}
/**
* This method is executed on each worker thread, and is responsible for
* returning a Resource Extension that will subsequently be executed on each
* worker thread.
*
* The Resource Extension is responsible for creating the Next.js server, and
* hooking into the global HarperDB server.
*
* @param {ExtensionOptions} options
* @returns
*/
export function start(options = {}) {
const config = resolveConfig(options);
return {
async handleDirectory(_, componentPath) {
logger.info(`Next.js Extension is creating Next.js Request Handlers for ${componentPath}`);
const nextJSMainPath = assertNextJSApp(componentPath);
const next = (await import(nextJSMainPath)).default;
const app = next({ dir: componentPath, dev: config.dev });
await app.prepare();
const requestHandler = app.getRequestHandler();
const servers = options.server.http(
(request) => {
return requestHandler(request._nodeRequest, request._nodeResponse, url.parse(request._nodeRequest.url, true));
},
{ port: config.port }
);
if (config.dev) {
const upgradeHandler = app.getUpgradeHandler();
servers[0].on('upgrade', (req, socket, head) => {
return upgradeHandler(req, socket, head);
});
}
logger.info(`Next.js App available on localhost:${config.port}`);
return true;
},
};
}