-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
commands.ts
435 lines (374 loc) · 11.5 KB
/
commands.ts
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import * as path from "node:path";
import { execSync } from "node:child_process";
import fse from "fs-extra";
import getPort, { makeRange } from "get-port";
import prettyMs from "pretty-ms";
import PackageJson from "@npmcli/package-json";
import pc from "picocolors";
import exitHook from "exit-hook";
import * as colors from "../colors";
import * as compiler from "../compiler";
import * as devServer from "../devServer";
import * as devServer_unstable from "../devServer_unstable";
import type { RemixConfig } from "../config";
import type { ViteDevOptions } from "../vite/dev";
import type { ViteBuildOptions } from "../vite/build";
import { readConfig } from "../config";
import { formatRoutes, type RoutesFormat } from "../config/format";
import { loadVitePluginContext } from "../vite/plugin";
import { detectPackageManager } from "./detectPackageManager";
import { transpile as convertFileToJS } from "./useJavascript";
import type { Options } from "../compiler/options";
import { createFileWatchCache } from "../compiler/fileWatchCache";
import { logger } from "../tux";
import * as profiler from "../vite/profiler";
type InitFlags = {
deleteScript?: boolean;
};
export async function init(
projectDir: string,
{ deleteScript = true }: InitFlags = {}
) {
let initScriptDir = path.join(projectDir, "remix.init");
let initScript = path.resolve(initScriptDir, "index.js");
if (!(await fse.pathExists(initScript))) {
return;
}
let initPackageJson = path.resolve(initScriptDir, "package.json");
let packageManager = detectPackageManager() ?? "npm";
if (await fse.pathExists(initPackageJson)) {
execSync(`${packageManager} install`, {
cwd: initScriptDir,
stdio: "ignore",
});
}
let initFn = require(initScript);
if (typeof initFn !== "function" && initFn.default) {
initFn = initFn.default;
}
try {
await initFn({ packageManager, rootDirectory: projectDir });
if (deleteScript) {
await fse.remove(initScriptDir);
}
} catch (error: unknown) {
if (error instanceof Error) {
error.message = `${colors.error("🚨 Oops, remix.init failed")}\n\n${
error.message
}`;
}
throw error;
}
}
/**
* Keep the function around in v2 so that users with `remix setup` in a script
* or postinstall hook can still run a build, but inform them that it's no
* longer necessary, and we can remove it in v3.
* @deprecated
*/
export function setup() {
console.warn(
"WARNING: The setup command is no longer necessary as of v2. This is a no-op. Please remove this from your dev and CI scripts, as it will be removed in v3."
);
}
export async function routes(
remixRoot?: string,
flags: {
config?: string;
json?: boolean;
} = {}
): Promise<void> {
let ctx = await loadVitePluginContext({
root: remixRoot,
configFile: flags.config,
});
let routes =
ctx?.remixConfig.routes ||
// v3 TODO: Remove this and require the presence of a Vite config
(await readConfig(remixRoot)).routes;
let format: RoutesFormat = flags.json ? "json" : "jsx";
console.log(formatRoutes(routes, format));
}
export async function build(
remixRoot: string,
mode?: string,
sourcemap: boolean = false
): Promise<void> {
mode = mode ?? "production";
logger.info(`building...` + pc.gray(` (NODE_ENV=${mode})`));
if (mode === "production" && sourcemap) {
logger.warn("🚨 source maps enabled in production", {
details: [
"You are using `--sourcemap` to enable source maps in production,",
"making your server-side code publicly visible in the browser.",
"This is highly discouraged!",
"If you insist, ensure that you are using environment variables for secrets",
"and are not hard-coding them in your source.",
],
});
}
let start = Date.now();
let config = await readConfig(remixRoot);
let options: Options = {
mode,
sourcemap,
};
if (mode === "development") {
let resolved = await resolveDev(config);
options.REMIX_DEV_ORIGIN = resolved.REMIX_DEV_ORIGIN;
}
let fileWatchCache = createFileWatchCache();
fse.emptyDirSync(config.assetsBuildDirectory);
await compiler
.build({ config, options, fileWatchCache, logger })
.catch((thrown) => {
compiler.logThrown(thrown);
process.exit(1);
});
logger.info("built" + pc.gray(` (${prettyMs(Date.now() - start)})`));
}
export async function viteBuild(
root?: string,
options: ViteBuildOptions = {}
): Promise<void> {
if (!root) {
root = process.env.REMIX_ROOT || process.cwd();
}
let { build } = await import("../vite/build");
if (options.profile) {
await profiler.start();
}
try {
await build(root, options);
} finally {
await profiler.stop(logger.info);
}
}
export async function watch(
remixRootOrConfig: string | RemixConfig,
mode?: string
): Promise<void> {
mode = mode ?? "development";
console.log(`Watching Remix app in ${mode} mode...`);
let config =
typeof remixRootOrConfig === "object"
? remixRootOrConfig
: await readConfig(remixRootOrConfig);
let resolved = await resolveDev(config);
void devServer.liveReload(config, { ...resolved, mode });
return await new Promise(() => {});
}
export async function dev(
remixRoot: string,
flags: {
command?: string;
manual?: boolean;
port?: number;
tlsKey?: string;
tlsCert?: string;
} = {}
) {
console.log(`\n 💿 remix dev\n`);
if (process.env.NODE_ENV && process.env.NODE_ENV !== "development") {
logger.warn(`overriding NODE_ENV=${process.env.NODE_ENV} to development`);
}
process.env.NODE_ENV = "development";
let config = await readConfig(remixRoot);
let resolved = await resolveDevServe(config, flags);
devServer_unstable.serve(config, resolved);
// keep `remix dev` alive by waiting indefinitely
await new Promise(() => {});
}
export async function viteDev(root: string, options: ViteDevOptions = {}) {
let { dev } = await import("../vite/dev");
if (options.profile) {
await profiler.start();
}
exitHook(() => profiler.stop(console.info));
await dev(root, options);
// keep `remix vite-dev` alive by waiting indefinitely
await new Promise(() => {});
}
let clientEntries = ["entry.client.tsx", "entry.client.js", "entry.client.jsx"];
let serverEntries = ["entry.server.tsx", "entry.server.js", "entry.server.jsx"];
let entries = ["entry.client", "entry.server"];
let conjunctionListFormat = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
let disjunctionListFormat = new Intl.ListFormat("en", {
style: "long",
type: "disjunction",
});
export async function generateEntry(
entry: string,
remixRoot: string,
flags: {
typescript?: boolean;
config?: string;
} = {}
) {
let ctx = await loadVitePluginContext({
root: remixRoot,
configFile: flags.config,
});
let { rootDirectory, appDirectory } = ctx
? {
rootDirectory: ctx.rootDirectory,
appDirectory: ctx.remixConfig.appDirectory,
}
: // v3 TODO: Remove this and require the presence of a Vite config
await readConfig(remixRoot);
// if no entry passed, attempt to create both
if (!entry) {
await generateEntry("entry.client", remixRoot, flags);
await generateEntry("entry.server", remixRoot, flags);
return;
}
if (!entries.includes(entry)) {
let entriesArray = Array.from(entries);
let list = conjunctionListFormat.format(entriesArray);
console.error(
colors.error(`Invalid entry file. Valid entry files are ${list}`)
);
return;
}
let pkgJson = await PackageJson.load(rootDirectory);
let deps = pkgJson.content.dependencies ?? {};
let serverRuntime = deps["@remix-run/deno"]
? "deno"
: deps["@remix-run/cloudflare"]
? "cloudflare"
: deps["@remix-run/node"]
? "node"
: undefined;
if (!serverRuntime) {
let serverRuntimes = [
"@remix-run/deno",
"@remix-run/cloudflare",
"@remix-run/node",
];
let formattedList = disjunctionListFormat.format(serverRuntimes);
console.error(
colors.error(
`Could not determine server runtime. Please install one of the following: ${formattedList}`
)
);
return;
}
let defaultsDirectory = path.resolve(__dirname, "..", "config", "defaults");
let defaultEntryClient = path.resolve(defaultsDirectory, "entry.client.tsx");
let defaultEntryServer = path.resolve(
defaultsDirectory,
ctx?.remixConfig.ssr === false &&
ctx?.remixConfig.future.v3_singleFetch !== true
? `entry.server.spa.tsx`
: `entry.server.${serverRuntime}.tsx`
);
let isServerEntry = entry === "entry.server";
let contents = isServerEntry
? await createServerEntry(rootDirectory, appDirectory, defaultEntryServer)
: await createClientEntry(rootDirectory, appDirectory, defaultEntryClient);
let useTypeScript = flags.typescript ?? true;
let outputExtension = useTypeScript ? "tsx" : "jsx";
let outputEntry = `${entry}.${outputExtension}`;
let outputFile = path.resolve(appDirectory, outputEntry);
if (!useTypeScript) {
let javascript = convertFileToJS(contents, {
cwd: rootDirectory,
filename: isServerEntry ? defaultEntryServer : defaultEntryClient,
});
await fse.writeFile(outputFile, javascript, "utf-8");
} else {
await fse.writeFile(outputFile, contents, "utf-8");
}
console.log(
colors.blue(
`Entry file ${entry} created at ${path.relative(
rootDirectory,
outputFile
)}.`
)
);
}
async function checkForEntry(
rootDirectory: string,
appDirectory: string,
entries: string[]
) {
for (let entry of entries) {
let entryPath = path.resolve(appDirectory, entry);
let exists = await fse.pathExists(entryPath);
if (exists) {
let relative = path.relative(rootDirectory, entryPath);
console.error(colors.error(`Entry file ${relative} already exists.`));
return process.exit(1);
}
}
}
async function createServerEntry(
rootDirectory: string,
appDirectory: string,
inputFile: string
) {
await checkForEntry(rootDirectory, appDirectory, serverEntries);
let contents = await fse.readFile(inputFile, "utf-8");
return contents;
}
async function createClientEntry(
rootDirectory: string,
appDirectory: string,
inputFile: string
) {
await checkForEntry(rootDirectory, appDirectory, clientEntries);
let contents = await fse.readFile(inputFile, "utf-8");
return contents;
}
let findPort = async () => getPort({ port: makeRange(3001, 3100) });
let resolveDev = async (
config: RemixConfig,
flags: {
port?: number;
tlsKey?: string;
tlsCert?: string;
} = {}
) => {
let { dev } = config;
let port = flags.port ?? dev.port ?? (await findPort());
let tlsKey = flags.tlsKey ?? dev.tlsKey;
if (tlsKey) tlsKey = path.resolve(tlsKey);
let tlsCert = flags.tlsCert ?? dev.tlsCert;
if (tlsCert) tlsCert = path.resolve(tlsCert);
let isTLS = tlsKey && tlsCert;
let REMIX_DEV_ORIGIN = process.env.REMIX_DEV_ORIGIN;
if (REMIX_DEV_ORIGIN === undefined) {
let scheme = isTLS ? "https" : "http";
REMIX_DEV_ORIGIN = `${scheme}://localhost:${port}`;
}
return {
port,
tlsKey,
tlsCert,
REMIX_DEV_ORIGIN: new URL(REMIX_DEV_ORIGIN),
};
};
let resolveDevServe = async (
config: RemixConfig,
flags: {
command?: string;
manual?: boolean;
port?: number;
tlsKey?: string;
tlsCert?: string;
} = {}
) => {
let { dev } = config;
let resolved = await resolveDev(config, flags);
let command = flags.command ?? dev.command;
let manual = flags.manual ?? dev.manual ?? false;
return {
...resolved,
command,
manual,
};
};