ecopages 0.2.1-beta.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,313 +1,416 @@
1
1
  #!/usr/bin/env node
2
- import { downloadTemplate } from "giget";
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
- import { spawn } from "node:child_process";
5
- import { join } from "node:path";
6
- import { parseArgs } from "node:util";
7
- import { Logger } from "@ecopages/logger";
8
- import { createLaunchPlan } from "./launch-plan.js";
9
- const logger = new Logger("[ecopages:cli]", { debug: process.env.ECOPAGES_LOGGER_DEBUG === "true" });
10
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
2
+
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { spawn } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+ import { Logger } from '@ecopages/logger';
9
+ import { createLaunchPlan, resolveEcoConfigFilePath } from './launch-plan.js';
10
+ import {
11
+ ECOPAGES_DEV_RESTART_EXIT_CODE,
12
+ ECOPAGES_DEV_RESTART_REASON_ENV,
13
+ isEcopagesEnvEnabled,
14
+ resolveDevelopmentRecoveryWatch,
15
+ } from '@ecopages/core/build';
16
+ import { fileSystem } from '@ecopages/file-system';
17
+ import { withBrandBanner } from './brand.js';
18
+
19
+ const logger = new Logger('[ecopages:cli]', { debug: isEcopagesEnvEnabled('ECOPAGES_LOGGER_DEBUG') });
20
+
21
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
22
+
11
23
  const sharedServerOptionDefinitions = {
12
- port: {
13
- type: "string",
14
- short: "p"
15
- },
16
- hostname: {
17
- type: "string",
18
- short: "n"
19
- },
20
- "base-url": {
21
- type: "string",
22
- short: "b"
23
- },
24
- debug: {
25
- type: "boolean",
26
- short: "d"
27
- },
28
- "react-fast-refresh": {
29
- type: "boolean",
30
- short: "r"
31
- },
32
- runtime: {
33
- type: "string"
34
- },
35
- help: {
36
- type: "boolean",
37
- short: "h"
38
- }
39
- };
40
- const initOptionDefinitions = {
41
- template: {
42
- type: "string"
43
- },
44
- repo: {
45
- type: "string"
46
- },
47
- help: {
48
- type: "boolean",
49
- short: "h"
50
- }
24
+ port: {
25
+ type: 'string',
26
+ short: 'p',
27
+ },
28
+ hostname: {
29
+ type: 'string',
30
+ short: 'n',
31
+ },
32
+ 'base-url': {
33
+ type: 'string',
34
+ short: 'b',
35
+ },
36
+ debug: {
37
+ type: 'boolean',
38
+ short: 'd',
39
+ },
40
+ runtime: {
41
+ type: 'string',
42
+ },
43
+ 'entry-file': {
44
+ type: 'string',
45
+ short: 'e',
46
+ },
47
+ config: {
48
+ type: 'string',
49
+ short: 'c',
50
+ },
51
+ help: {
52
+ type: 'boolean',
53
+ short: 'h',
54
+ },
51
55
  };
56
+
52
57
  function getMainHelpText() {
53
- return [
54
- `ecopages ${pkg.version}`,
55
- "",
56
- "Usage: ecopages <command> [options]",
57
- "",
58
- "Commands:",
59
- " init <dir> Initialize a new project from a template",
60
- " dev [entry] Start the development server",
61
- " dev:watch [entry] Start the development server with watch mode",
62
- " dev:hot [entry] Start the development server with hot reload",
63
- " build [entry] Build the project for production",
64
- " start [entry] Start the production server",
65
- " preview [entry] Preview the production build",
66
- "",
67
- "Global options:",
68
- " -h, --help Show help",
69
- " --version Show version"
70
- ].join("\n");
71
- }
72
- function getServerCommandHelpText(commandName, description) {
73
- return [
74
- `Usage: ecopages ${commandName} [entry] [options]`,
75
- "",
76
- description,
77
- "",
78
- "Options:",
79
- " -p, --port <port> Override ECOPAGES_PORT",
80
- " -n, --hostname <hostname> Override ECOPAGES_HOSTNAME",
81
- " -b, --base-url <baseUrl> Override ECOPAGES_BASE_URL",
82
- " -d, --debug Enable debug logging",
83
- " -r, --react-fast-refresh Enable React Fast Refresh for Bun HMR",
84
- " --runtime <runtime> Force bun or node",
85
- " -h, --help Show help"
86
- ].join("\n");
87
- }
88
- function getBuildCommandHelpText() {
89
- return [
90
- "Usage: ecopages build [entry] [options]",
91
- "",
92
- "Build the project for production.",
93
- "",
94
- "Options:",
95
- " -p, --port <port> Override ECOPAGES_PORT",
96
- " -n, --hostname <hostname> Override ECOPAGES_HOSTNAME",
97
- " -b, --base-url <baseUrl> Override ECOPAGES_BASE_URL",
98
- " -d, --debug Enable debug logging",
99
- " -r, --react-fast-refresh Enable React Fast Refresh for Bun HMR",
100
- " --runtime <runtime> Force bun or node",
101
- " -h, --help Show help"
102
- ].join("\n");
58
+ return [
59
+ 'Usage: ecopages <command> [options]',
60
+ '',
61
+ 'Commands:',
62
+ ' init [dir] Initialize a new project from a template',
63
+ ' dev Start the development server',
64
+ ' dev:watch Start the development server with watch mode',
65
+ ' build Build the project for production',
66
+ ' start Start the production server',
67
+ ' preview Preview the production build',
68
+ ' types Write virtual-module types for tsc, then exit',
69
+ '',
70
+ 'Global options:',
71
+ ' -e, --entry-file <file> Entry file (default: app.ts)',
72
+ ' -c, --config <file> Ecopages config file (default: eco.config.ts)',
73
+ ' -h, --help Show help',
74
+ ' --version Show version',
75
+ ].join('\n');
103
76
  }
104
- function getInitCommandHelpText() {
105
- return [
106
- "Usage: ecopages init <dir> [options]",
107
- "",
108
- "Initialize a new project from a template.",
109
- "",
110
- "Options:",
111
- " --template <template> Template name from ecopages/examples/",
112
- " --repo <repo> GitHub repo in user/repo form",
113
- " -h, --help Show help"
114
- ].join("\n");
77
+
78
+ function getServerCommandHelpText(commandName, description, extraOptionLines = []) {
79
+ return [
80
+ `Usage: ecopages ${commandName} [options]`,
81
+ '',
82
+ description,
83
+ '',
84
+ 'Options:',
85
+ ' -p, --port <port> Override ECOPAGES_PORT',
86
+ ' -n, --hostname <hostname> Override ECOPAGES_HOSTNAME',
87
+ ' -b, --base-url <baseUrl> Override ECOPAGES_BASE_URL',
88
+ ' -d, --debug Enable debug logging',
89
+ ' --runtime <runtime> Force bun or node',
90
+ ' -e, --entry-file <file> Entry file (default: app.ts)',
91
+ ' -c, --config <file> Ecopages config file (default: eco.config.ts)',
92
+ ...extraOptionLines,
93
+ ' -h, --help Show help',
94
+ ].join('\n');
115
95
  }
96
+
116
97
  function parseCommandArguments(rawArgs, options) {
117
- return parseArgs({
118
- args: rawArgs,
119
- options,
120
- allowPositionals: true,
121
- strict: true
122
- });
98
+ return parseArgs({
99
+ args: rawArgs,
100
+ options,
101
+ allowPositionals: true,
102
+ strict: true,
103
+ });
123
104
  }
124
- function parseServerCommandArgs(rawArgs, commandName, description, mode = "server") {
125
- const { values, positionals } = parseCommandArguments(rawArgs, sharedServerOptionDefinitions);
126
- if (values.help) {
127
- console.log(mode === "build" ? getBuildCommandHelpText() : getServerCommandHelpText(commandName, description));
128
- return { help: true };
129
- }
130
- if (positionals.length > 1) {
131
- throw new Error(`Too many positional arguments provided for \`${commandName}\`.`);
132
- }
133
- return {
134
- entry: positionals[0] ?? "app.ts",
135
- options: {
136
- port: values.port,
137
- hostname: values.hostname,
138
- baseUrl: values["base-url"],
139
- debug: values.debug,
140
- reactFastRefresh: values["react-fast-refresh"],
141
- runtime: values.runtime
142
- }
143
- };
105
+
106
+ function parseServerCommandArgs(rawArgs, definition) {
107
+ const commandName = definition.name;
108
+ const valueOptions = definition.valueOptions ?? {};
109
+ const booleanOptions = definition.booleanOptions ?? {};
110
+ const { values, positionals } = parseCommandArguments(rawArgs, {
111
+ ...sharedServerOptionDefinitions,
112
+ ...Object.fromEntries(Object.keys(valueOptions).map((option) => [option, { type: 'string' }])),
113
+ ...booleanOptions,
114
+ });
115
+
116
+ if (values.help) {
117
+ console.log(
118
+ getServerCommandHelpText(commandName, definition.description, [
119
+ ...Object.values(valueOptions),
120
+ ...(definition.optionHelpLines ?? []),
121
+ ]),
122
+ );
123
+ return { help: true };
124
+ }
125
+
126
+ if (positionals.length > 0) {
127
+ throw new Error(
128
+ `Positional entry file arguments are not supported for \`${commandName}\`. Use --entry-file <file> instead.`,
129
+ );
130
+ }
131
+
132
+ const entry = values['entry-file'] ?? 'app.ts';
133
+
134
+ return {
135
+ entry,
136
+ keepGoing: Boolean(values['keep-going']),
137
+ options: {
138
+ port: values.port,
139
+ hostname: values.hostname,
140
+ baseUrl: values['base-url'],
141
+ debug: values.debug,
142
+ runtime: values.runtime,
143
+ configFile: values.config,
144
+ distDir: values['dist-dir'],
145
+ },
146
+ };
144
147
  }
145
- function parseInitCommandArgs(rawArgs) {
146
- const { values, positionals } = parseCommandArguments(rawArgs, initOptionDefinitions);
147
- if (values.help) {
148
- console.log(getInitCommandHelpText());
149
- return { help: true };
150
- }
151
- if (positionals.length !== 1) {
152
- throw new Error("The `init` command requires exactly one target directory argument.");
153
- }
154
- return {
155
- dir: positionals[0],
156
- template: values.template ?? "starter-jsx",
157
- repo: values.repo ?? "ecopages/ecopages"
158
- };
148
+
149
+ /**
150
+ * Signals the supervisor forwards to the child it runs.
151
+ *
152
+ * @remarks
153
+ * Without a handler, a signal ends the supervisor and leaves the child running as an orphan that keeps its
154
+ * port. Forwarding lets the child shut down first, and the supervisor exits from the child's `exit` event.
155
+ */
156
+ const FORWARDED_SIGNALS = ['SIGTERM', 'SIGINT'];
157
+
158
+ function runLaunchPlan(launchPlan, options = {}) {
159
+ if (Object.keys(launchPlan.envOverrides).length > 0) {
160
+ logger.debug(`Environment overrides: ${JSON.stringify(launchPlan.envOverrides)}`);
161
+ }
162
+
163
+ logger.debug(`Runtime: ${launchPlan.runtime}`);
164
+ logger.debug(`Running: ${launchPlan.command} ${launchPlan.commandArgs.join(' ')}`);
165
+
166
+ const child = spawn(launchPlan.command, launchPlan.commandArgs, {
167
+ stdio: 'inherit',
168
+ env: launchPlan.env,
169
+ });
170
+
171
+ const forwardSignal = (signal) => {
172
+ child.kill(signal);
173
+ };
174
+ for (const signal of FORWARDED_SIGNALS) {
175
+ process.on(signal, forwardSignal);
176
+ }
177
+
178
+ child.on('error', (error) => {
179
+ if (error && error.code === 'ENOENT') {
180
+ const hint =
181
+ launchPlan.runtime === 'bun'
182
+ ? 'Install Bun from https://bun.sh to continue.'
183
+ : 'Reinstall Node.js or run with --runtime bun if this app needs the Bun runtime.';
184
+ logger.error(`Command not found: ${launchPlan.command}. ${hint}`);
185
+ process.exit(1);
186
+ }
187
+
188
+ logger.error(`Failed to run command: ${error.message}`);
189
+ process.exit(1);
190
+ });
191
+
192
+ child.on('exit', (code) => {
193
+ for (const signal of FORWARDED_SIGNALS) {
194
+ process.off(signal, forwardSignal);
195
+ }
196
+
197
+ if (options.superviseDevRestarts && code === ECOPAGES_DEV_RESTART_EXIT_CODE) {
198
+ options.onDevRestart?.();
199
+ return;
200
+ }
201
+
202
+ if (code && options.onRestartFailure) {
203
+ logger.error(`The restarted development server exited with code ${code}.`);
204
+ options.onRestartFailure();
205
+ return;
206
+ }
207
+
208
+ process.exit(code || 0);
209
+ });
159
210
  }
160
- function runLaunchPlan(launchPlan) {
161
- if (Object.keys(launchPlan.envOverrides).length > 0) {
162
- logger.debug(`Environment overrides: ${JSON.stringify(launchPlan.envOverrides)}`);
163
- }
164
- logger.debug(`Runtime: ${launchPlan.runtime}`);
165
- logger.debug(`Running: ${launchPlan.command} ${launchPlan.commandArgs.join(" ")}`);
166
- const child = spawn(launchPlan.command, launchPlan.commandArgs, {
167
- stdio: "inherit",
168
- env: launchPlan.env
169
- });
170
- child.on("error", (error) => {
171
- if (error && error.code === "ENOENT") {
172
- const hint = launchPlan.runtime === "bun" ? "Install Bun from https://bun.sh to continue." : "Reinstall Node.js or run with --runtime bun if this app requires Bun.";
173
- logger.error(`Command not found: ${launchPlan.command}. ${hint}`);
174
- process.exit(1);
175
- }
176
- logger.error(`Failed to run command: ${error.message}`);
177
- process.exit(1);
178
- });
179
- child.on("exit", (code) => {
180
- process.exit(code || 0);
181
- });
211
+
212
+ /**
213
+ * Watches the project from before a restarted dev child launches until that child exits.
214
+ *
215
+ * @remarks
216
+ * A restarted child that exits with an error keeps the supervisor alive until the next change in the
217
+ * project or a linked workspace package, so an error in the config or a file it imports does not end
218
+ * the dev session. The watch starts before the child, so a fix saved while it was loading relaunches
219
+ * at once.
220
+ * @param {string} rootDir - Project root, the directory of the resolved config
221
+ */
222
+ async function watchProjectForRestart(rootDir) {
223
+ const { paths, ignored } = resolveDevelopmentRecoveryWatch(rootDir);
224
+ let changed = false;
225
+ let onNextChange;
226
+ const watcher = fileSystem.watch(paths, {
227
+ ignored,
228
+ onChange: () => {
229
+ changed = true;
230
+ onNextChange?.();
231
+ },
232
+ onError: (error) => {
233
+ logger.error('Cannot watch the project for the next restart', error);
234
+ process.exit(1);
235
+ },
236
+ });
237
+ await watcher.ready;
238
+
239
+ return {
240
+ close: () => watcher.close(),
241
+ /** Calls `relaunch` once: now if the project changed since the watch started, otherwise on the next change. */
242
+ relaunchOnChange(relaunch) {
243
+ const run = () => {
244
+ onNextChange = undefined;
245
+ void watcher.close();
246
+ relaunch();
247
+ };
248
+ if (changed) {
249
+ logger.info('The project changed since the restart. Restarting...');
250
+ run();
251
+ return;
252
+ }
253
+ logger.info('Waiting for a change in the project to restart.');
254
+ onNextChange = run;
255
+ },
256
+ };
182
257
  }
183
- async function runEntryCommand(args, options = {}, entryFile = "app.ts") {
184
- let launchPlan;
185
- if (!existsSync(entryFile)) {
186
- logger.error(`Error: Entry file "${entryFile}" not found in the current directory.`);
187
- process.exit(1);
188
- }
189
- try {
190
- launchPlan = await createLaunchPlan(args, options, entryFile);
191
- } catch (error) {
192
- const message = error instanceof Error ? error.message : String(error);
193
- logger.error(message);
194
- process.exit(1);
195
- }
196
- runLaunchPlan(launchPlan);
197
- }
198
- async function runInitCommand(rawArgs) {
199
- const parsed = parseInitCommandArgs(rawArgs);
200
- if (parsed.help) {
201
- return;
202
- }
203
- const { dir, template, repo } = parsed;
204
- if (existsSync(dir)) {
205
- logger.error(`Target directory already exists: ${dir}`);
206
- process.exit(1);
207
- }
208
- logger.info(`Creating target directory '${dir}'...`);
209
- try {
210
- await downloadTemplate(`github:${repo}/examples/${template}`, {
211
- dir,
212
- force: true
213
- });
214
- const pkgPath = join(dir, "package.json");
215
- if (existsSync(pkgPath)) {
216
- const projectPkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
217
- projectPkg.name = dir;
218
- writeFileSync(pkgPath, JSON.stringify(projectPkg, null, 2) + "\n");
219
- logger.info(`Renamed project to '${dir}'`);
220
- }
221
- logger.info("Project initialized! Run `bun install && bun dev` to start.");
222
- } catch (error) {
223
- const message = error instanceof Error ? error.message : String(error);
224
- logger.error(`Failed to fetch template: ${message}`);
225
- process.exit(1);
226
- }
258
+
259
+ /**
260
+ * Launch the entry file via the detected or forced runtime. Node and Bun get the same
261
+ * entry file and arguments.
262
+ * @param {string[]} args - Arguments to pass to the entry file
263
+ * @param {object} options - CLI options (watch, runtime, port, hostname, etc.)
264
+ * @param {string} entryFile - Entry file to run
265
+ */
266
+ async function runEntryCommand(args, options = {}, entryFile = 'app.ts', launchMode = 'start') {
267
+ const requiresBuiltBundle = launchMode === 'start';
268
+ const superviseDevRestarts = launchMode === 'dev';
269
+
270
+ if (!requiresBuiltBundle && !existsSync(entryFile)) {
271
+ logger.error(`Error: Entry file "${entryFile}" not found in the current directory.`);
272
+ process.exit(1);
273
+ }
274
+
275
+ const projectRoot = path.dirname(resolveEcoConfigFilePath(options) ?? path.resolve('eco.config.ts'));
276
+ const devRestartReason = 'configuration or environment change';
277
+
278
+ const launchChild = async (restartReason) => {
279
+ const restartWatch = restartReason ? await watchProjectForRestart(projectRoot) : undefined;
280
+ const relaunchOnChange = () => restartWatch.relaunchOnChange(() => void launchChild(devRestartReason));
281
+ let launchPlan;
282
+ try {
283
+ launchPlan = await createLaunchPlan(args, options, entryFile, launchMode);
284
+ } catch (error) {
285
+ const message = error instanceof Error ? error.message : String(error);
286
+ logger.error(message);
287
+ if (restartWatch) {
288
+ relaunchOnChange();
289
+ return;
290
+ }
291
+ process.exit(1);
292
+ }
293
+
294
+ if (restartReason) {
295
+ launchPlan.env[ECOPAGES_DEV_RESTART_REASON_ENV] = restartReason;
296
+ launchPlan.envOverrides[ECOPAGES_DEV_RESTART_REASON_ENV] = restartReason;
297
+ }
298
+
299
+ runLaunchPlan(launchPlan, {
300
+ superviseDevRestarts,
301
+ onDevRestart: () => {
302
+ void restartWatch?.close();
303
+ void launchChild(devRestartReason);
304
+ },
305
+ onRestartFailure: restartWatch ? relaunchOnChange : undefined,
306
+ });
307
+ };
308
+
309
+ await launchChild();
227
310
  }
311
+
228
312
  async function runServerCommand(rawArgs, definition) {
229
- const parsed = parseServerCommandArgs(rawArgs, definition.name, definition.description, definition.mode);
230
- if (parsed.help) {
231
- return;
232
- }
233
- await runEntryCommand(definition.entryArgs, { ...parsed.options, ...definition.optionOverrides }, parsed.entry);
313
+ const parsed = parseServerCommandArgs(rawArgs, definition);
314
+
315
+ if (parsed.help) {
316
+ return;
317
+ }
318
+
319
+ const entry = definition.resolveEntry?.() ?? parsed.entry;
320
+ const entryArgs = [...definition.entryArgs];
321
+ if (parsed.keepGoing) entryArgs.push('--keep-going');
322
+ await runEntryCommand(
323
+ entryArgs,
324
+ { ...parsed.options, ...definition.optionOverrides, entryFile: entry },
325
+ entry,
326
+ definition.launchMode ?? definition.name,
327
+ );
234
328
  }
235
- async function runCli(rawArgs = process.argv.slice(2)) {
236
- const [commandName, ...commandArgs] = rawArgs;
237
- if (!commandName || commandName === "--help" || commandName === "-h") {
238
- console.log(getMainHelpText());
239
- return;
240
- }
241
- if (commandName === "--version") {
242
- console.log(pkg.version);
243
- return;
244
- }
245
- try {
246
- switch (commandName) {
247
- case "init":
248
- await runInitCommand(commandArgs);
249
- return;
250
- case "dev":
251
- await runServerCommand(commandArgs, {
252
- name: "dev",
253
- description: "Start the development server.",
254
- entryArgs: ["--dev"],
255
- optionOverrides: { nodeEnv: "development" }
256
- });
257
- return;
258
- case "dev:watch":
259
- await runServerCommand(commandArgs, {
260
- name: "dev:watch",
261
- description: "Start the development server with watch mode.",
262
- entryArgs: ["--dev"],
263
- optionOverrides: { watch: true, nodeEnv: "development" }
264
- });
265
- return;
266
- case "dev:hot":
267
- await runServerCommand(commandArgs, {
268
- name: "dev:hot",
269
- description: "Start the development server with hot reload.",
270
- entryArgs: ["--dev"],
271
- optionOverrides: { hot: true, nodeEnv: "development" }
272
- });
273
- return;
274
- case "build":
275
- await runServerCommand(commandArgs, {
276
- name: "build",
277
- description: "Build the project for production.",
278
- entryArgs: ["--build"],
279
- optionOverrides: { nodeEnv: "production" },
280
- mode: "build"
281
- });
282
- return;
283
- case "start":
284
- await runServerCommand(commandArgs, {
285
- name: "start",
286
- description: "Start the production server.",
287
- entryArgs: [],
288
- optionOverrides: { nodeEnv: "production" }
289
- });
290
- return;
291
- case "preview":
292
- await runServerCommand(commandArgs, {
293
- name: "preview",
294
- description: "Preview the production build.",
295
- entryArgs: ["--preview"],
296
- optionOverrides: { nodeEnv: "production" }
297
- });
298
- return;
299
- default:
300
- throw new Error(`Unknown command \`${commandName}\`.`);
301
- }
302
- } catch (error) {
303
- const message = error instanceof Error ? error.message : String(error);
304
- logger.error(message);
305
- process.exit(1);
306
- }
329
+
330
+ /**
331
+ * Commands that run an entry file, keyed by name. `launchMode` defaults to the name,
332
+ * and `resolveEntry` replaces the app entry (`app.ts`) with another script.
333
+ */
334
+ const SERVER_COMMANDS = {
335
+ dev: {
336
+ description: 'Start the development server.',
337
+ entryArgs: ['--dev'],
338
+ launchMode: 'dev',
339
+ optionOverrides: { nodeEnv: 'development' },
340
+ },
341
+ 'dev:watch': {
342
+ description: 'Start the development server with watch mode.',
343
+ entryArgs: ['--dev'],
344
+ launchMode: 'dev',
345
+ optionOverrides: { watch: true, nodeEnv: 'development' },
346
+ },
347
+ build: {
348
+ description:
349
+ 'Build the project for production: pre-render the Pages in src/pages, optimize assets and images, and write the result to dist.',
350
+ entryArgs: ['--build'],
351
+ booleanOptions: { 'keep-going': { type: 'boolean' } },
352
+ optionHelpLines: [' --keep-going Continue the build after a Page fails to render'],
353
+ optionOverrides: { nodeEnv: 'production' },
354
+ },
355
+ start: {
356
+ description: 'Start the production server.',
357
+ entryArgs: [],
358
+ optionOverrides: { nodeEnv: 'production' },
359
+ valueOptions: {
360
+ 'dist-dir':
361
+ ' --dist-dir <dir> Build output directory to start (default: the only one)',
362
+ },
363
+ },
364
+ types: {
365
+ description:
366
+ 'Load eco.config.ts so processors write the types for virtual modules such as ecopages:images, then exit. The app entry does not run. Run it before tsc.',
367
+ entryArgs: [],
368
+ resolveEntry: () => fileURLToPath(import.meta.resolve('@ecopages/core/config/write-types')),
369
+ optionOverrides: { nodeEnv: 'production' },
370
+ },
371
+ preview: {
372
+ description: 'Build the project for production, then serve dist locally to preview it.',
373
+ entryArgs: ['--preview'],
374
+ optionOverrides: { nodeEnv: 'production' },
375
+ },
376
+ };
377
+
378
+ export async function runCli(rawArgs = process.argv.slice(2)) {
379
+ const [commandName, ...commandArgs] = rawArgs;
380
+
381
+ if (!commandName || commandName === '--help' || commandName === '-h') {
382
+ console.log(withBrandBanner(pkg.version, getMainHelpText()));
383
+ return;
384
+ }
385
+
386
+ if (commandName === '--version') {
387
+ console.log(pkg.version);
388
+ return;
389
+ }
390
+
391
+ try {
392
+ const serverCommand = Object.hasOwn(SERVER_COMMANDS, commandName) ? SERVER_COMMANDS[commandName] : undefined;
393
+ if (serverCommand) {
394
+ await runServerCommand(commandArgs, { name: commandName, ...serverCommand });
395
+ return;
396
+ }
397
+
398
+ switch (commandName) {
399
+ case 'init': {
400
+ const { runInitCommand } = await import('./init.js');
401
+ await runInitCommand(commandArgs, logger);
402
+ return;
403
+ }
404
+ default:
405
+ throw new Error(`Unknown command \`${commandName}\`.`);
406
+ }
407
+ } catch (error) {
408
+ const message = error instanceof Error ? error.message : String(error);
409
+ logger.error(message);
410
+ process.exit(1);
411
+ }
307
412
  }
413
+
308
414
  if (!process.env.VITEST) {
309
- runCli();
415
+ runCli();
310
416
  }
311
- export {
312
- runCli
313
- };