-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdev.ts
More file actions
575 lines (505 loc) · 22 KB
/
dev.ts
File metadata and controls
575 lines (505 loc) · 22 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import open from 'open';
import select from '@inquirer/select';
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Logger, Messages, SfError } from '@salesforce/core';
import type { WebAppDevResult, DevServerError } from '../../config/types.js';
import type { WebAppManifest } from '../../config/manifest.js';
import { ManifestWatcher } from '../../config/ManifestWatcher.js';
import { DevServerManager } from '../../server/DevServerManager.js';
import { ProxyServer } from '../../proxy/ProxyServer.js';
import { discoverWebapp, DEFAULT_DEV_COMMAND, type DiscoveredWebapp } from '../../config/webappDiscovery.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-app-dev', 'webapp.dev');
export default class WebappDev extends SfCommand<WebAppDevResult> {
public static readonly summary = messages.getMessage('summary');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly flags = {
name: Flags.string({
summary: messages.getMessage('flags.name.summary'),
description: messages.getMessage('flags.name.description'),
char: 'n',
required: false,
}),
url: Flags.string({
summary: messages.getMessage('flags.url.summary'),
description: messages.getMessage('flags.url.description'),
char: 'u',
required: false,
}),
port: Flags.integer({
summary: messages.getMessage('flags.port.summary'),
description: messages.getMessage('flags.port.description'),
char: 'p',
default: 4545,
}),
'target-org': Flags.requiredOrg(),
open: Flags.boolean({
summary: messages.getMessage('flags.open.summary'),
description: messages.getMessage('flags.open.description'),
char: 'b',
default: false,
}),
};
private manifestWatcher: ManifestWatcher | null = null;
private devServerManager: DevServerManager | null = null;
private proxyServer: ProxyServer | null = null;
private logger: Logger | null = null;
/**
* Open the proxy URL in the default browser
*/
private static async openBrowser(url: string): Promise<void> {
await open(url);
}
/**
* Prompt user to select a webapp from multiple discovered webapps
* Uses interactive arrow-key selection (standard SF CLI pattern)
*/
private static async promptWebappSelection(webapps: DiscoveredWebapp[]): Promise<DiscoveredWebapp> {
const WARNING = '\u26A0\uFE0F'; // ⚠️
const choices = webapps.map((webapp) => {
if (webapp.hasManifest) {
// Has manifest - show name only
return {
name: webapp.name,
value: webapp,
};
} else {
// No manifest - show warning symbol
return {
name: `${webapp.name} - ${WARNING} No Manifest`,
value: webapp,
};
}
});
return select({
message: messages.getMessage('prompt.select-webapp'),
choices,
});
}
// eslint-disable-next-line complexity
public async run(): Promise<WebAppDevResult> {
const { flags } = await this.parse(WebappDev);
// Initialize logger from @salesforce/core for debug logging
// Logger respects SF_LOG_LEVEL environment variable
this.logger = await Logger.child('WebappDev');
// Declare variables outside try block for catch block access
let manifest: WebAppManifest | null = null;
let devServerUrl: string | null = null;
let orgUsername = '';
try {
// Step 1: Discover and select webapp
this.logger.debug('Discovering webapplication.json manifest(s)...');
const { webapp: discoveredWebapp, allWebapps, autoSelected } = await discoverWebapp(flags.name);
// Handle multiple webapps case - prompt user to select
let selectedWebapp: DiscoveredWebapp;
if (!discoveredWebapp) {
this.log(messages.getMessage('info.multiple-webapps-found', [String(allWebapps.length)]));
selectedWebapp = await WebappDev.promptWebappSelection(allWebapps);
} else {
selectedWebapp = discoveredWebapp;
// Show info message if webapp was auto-selected because user is inside its folder
if (autoSelected) {
this.log(messages.getMessage('info.webapp-auto-selected', [selectedWebapp.name]));
}
}
// The webapp directory path (where the webapp lives)
const webappDir = selectedWebapp.path;
// AC2: Clean up any orphaned dev server from a previous session
// Must happen after webapp discovery so we know the correct directory for the PID file
const killedOrphan = await DevServerManager.cleanupOrphanedProcess(webappDir, this.logger);
if (killedOrphan) {
this.log('Cleaned up orphaned dev server from a previous session.');
}
this.logger.debug(`Using webapp: ${selectedWebapp.name} at ${selectedWebapp.relativePath}`);
// Step 2: Handle manifest-based vs no-manifest webapps
if (selectedWebapp.hasManifest && selectedWebapp.manifestPath) {
// Webapp has manifest - load and watch it
this.manifestWatcher = new ManifestWatcher({
manifestPath: selectedWebapp.manifestPath,
watch: true,
});
this.manifestWatcher.initialize();
manifest = this.manifestWatcher.getManifest();
// Check if manifest is effectively empty (no dev configuration)
// Note: manifest is guaranteed non-null here since initialize() throws on failure
const hasDevConfig = manifest?.dev?.url != null || manifest?.dev?.command != null;
if (!hasDevConfig) {
// Manifest exists but has no dev configuration - show empty manifest warning
this.warn(
messages.getMessage('warning.empty-manifest', [
selectedWebapp.name,
selectedWebapp.relativePath,
selectedWebapp.name,
DEFAULT_DEV_COMMAND,
])
);
}
// Use selectedWebapp.name (already calculated with folder name fallback during discovery)
this.log(messages.getMessage('info.using-webapp', [selectedWebapp.name, selectedWebapp.relativePath]));
this.logger.debug(`Manifest loaded: ${selectedWebapp.name}`);
// Setup manifest change handler
this.manifestWatcher.on('change', (event) => {
this.log(messages.getMessage('info.manifest-changed', [event.type]));
if (event.type === 'changed' && event.manifest) {
this.log(messages.getMessage('info.manifest-reloaded'));
// Check for dev.url changes (can be updated dynamically)
const oldDevUrl = manifest?.dev?.url;
const newDevUrl = event.manifest.dev?.url;
if (newDevUrl && oldDevUrl !== newDevUrl) {
this.log(messages.getMessage('info.dev-url-changed', [newDevUrl]));
this.proxyServer?.updateDevServerUrl(newDevUrl);
}
// Check for dev.command changes (cannot be changed while running)
if (event.manifest.dev?.command && event.manifest.dev.command !== manifest?.dev?.command) {
this.warn(messages.getMessage('warning.dev-command-changed', [event.manifest.dev.command]));
}
// Update proxy server with new manifest (for routing changes)
this.proxyServer?.updateManifest(event.manifest);
// Update manifest reference to reflect all changes
manifest = event.manifest;
}
});
this.manifestWatcher.on('error', (error: SfError) => {
this.warn(messages.getMessage('error.manifest-watch-failed', [error.message]));
});
} else {
// No manifest - show warning and use defaults
this.warn(
messages.getMessage('warning.no-manifest', [
selectedWebapp.name,
selectedWebapp.relativePath,
selectedWebapp.name,
DEFAULT_DEV_COMMAND,
])
);
this.log(messages.getMessage('info.using-webapp', [selectedWebapp.name, selectedWebapp.relativePath]));
}
// Step 3: Determine dev server URL
// Priority: --url flag > manifest dev.url > manifest dev.command > default command (for no-manifest)
if (flags.url) {
devServerUrl = flags.url;
this.logger.debug(`Using explicit dev server URL: ${devServerUrl}`);
} else if (manifest?.dev?.url) {
devServerUrl = manifest.dev.url;
this.logger.debug(`Using dev server URL from manifest: ${devServerUrl}`);
} else {
// Determine command: from manifest or default
const devCommand = manifest?.dev?.command ?? DEFAULT_DEV_COMMAND;
if (!selectedWebapp.hasManifest) {
this.logger.debug(messages.getMessage('info.using-defaults', [devCommand]));
}
// Start dev server from the webapp directory
this.logger.debug(`Starting dev server with command: ${devCommand}`);
this.devServerManager = new DevServerManager({
command: devCommand,
cwd: webappDir,
});
// Setup dev server event handlers
this.devServerManager.on('ready', (url: string) => {
this.logger?.debug(`Dev server ready at: ${url}`);
// Clear any dev server error when server starts successfully
this.proxyServer?.clearActiveDevServerError();
});
this.devServerManager.on('error', (error: SfError | DevServerError) => {
// Set error for proxy to display in browser (if proxy is running)
// Don't log here - the error will be thrown and displayed by the main catch block
if ('stderrLines' in error && Array.isArray(error.stderrLines) && 'title' in error && 'type' in error) {
this.proxyServer?.setActiveDevServerError(error);
}
this.logger?.debug(`Dev server error: ${error.message}`);
});
this.devServerManager.on('exit', () => {
this.logger?.debug('Dev server stopped');
});
this.devServerManager.start();
// Wait for dev server to be ready
devServerUrl = await new Promise<string>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(
new SfError('Dev server did not start within 30 seconds.', 'DevServerTimeoutError', [
'The dev server may be taking longer than expected to start',
'Check if the dev server command is correct in webapplication.json',
'Try running the dev server command manually to see if it starts',
])
);
}, 30_000);
this.devServerManager?.on('ready', (url: string) => {
clearTimeout(timeout);
resolve(url);
});
this.devServerManager?.on('error', (error: SfError) => {
clearTimeout(timeout);
reject(error);
});
});
}
// Step 3: Get org info for authentication
const orgConnection = flags['target-org'].getConnection(undefined);
orgUsername = flags['target-org'].getUsername() ?? orgConnection.getUsername() ?? 'unknown';
this.logger.debug(`Using authentication for org: ${orgUsername}`);
// Step 4: Start proxy server
this.logger.debug(`Starting proxy server on port ${flags.port}...`);
const salesforceInstanceUrl = orgConnection.instanceUrl;
this.proxyServer = new ProxyServer({
devServerUrl,
salesforceInstanceUrl,
port: flags.port,
manifest: manifest ?? undefined,
orgAlias: orgUsername,
});
await this.proxyServer.start();
const proxyUrl = this.proxyServer.getProxyUrl();
this.logger.debug(`Proxy server running on ${proxyUrl}`);
// Listen for dev server status changes (minimal output)
this.proxyServer.on('dev-server-up', (url: string) => {
this.logger?.debug(messages.getMessage('info.dev-server-detected', [url]));
});
this.proxyServer.on('dev-server-down', (url: string) => {
this.log(messages.getMessage('warning.dev-server-unreachable-status', [url]));
this.log(messages.getMessage('info.start-dev-server-hint'));
});
// AC1+AC4: Listen for "restart dev server" requests from the interactive error page
this.proxyServer.on('restartDevServer', () => {
this.logger?.info('Received restartDevServer request from error page');
const doRestart = async (): Promise<void> => {
// Stop existing dev server
if (this.devServerManager) {
this.log('Stopping current dev server for restart...');
await this.devServerManager.stop();
this.devServerManager = null;
}
// Small delay for port release
await new Promise((resolve) => setTimeout(resolve, 1000));
// Re-create and start
const devCommand = manifest?.dev?.command ?? DEFAULT_DEV_COMMAND;
this.devServerManager = new DevServerManager({
command: devCommand,
cwd: webappDir,
});
this.devServerManager.on('ready', (readyUrl: string) => {
this.logger?.debug(`Dev server restarted at: ${readyUrl}`);
this.proxyServer?.clearActiveDevServerError();
this.proxyServer?.updateDevServerUrl(readyUrl);
});
this.devServerManager.on('error', (error: SfError | DevServerError) => {
if (
'stderrLines' in error &&
Array.isArray(error.stderrLines) &&
'title' in error &&
'type' in error
) {
this.proxyServer?.setActiveDevServerError(error);
}
});
this.devServerManager.on('exit', () => {
this.logger?.debug('Restarted dev server stopped');
});
this.devServerManager.start();
this.log('Dev server restart initiated from error page.');
};
doRestart().catch((err) => {
this.logger?.error(`Failed to restart dev server: ${err instanceof Error ? err.message : String(err)}`);
});
});
// AC4: Listen for "force kill dev server" requests from the interactive error page
this.proxyServer.on('forceKillDevServer', () => {
this.logger?.info('Received forceKillDevServer request from error page');
if (this.devServerManager) {
const pid = this.devServerManager.getPid();
if (pid) {
try {
process.kill(pid, 'SIGKILL');
this.logger?.warn(`Force-killed dev server process: PID=${pid}`);
this.log(`Dev server force-killed (PID: ${pid}).`);
} catch (err) {
this.logger?.error(
`Failed to force-kill PID=${pid}: ${err instanceof Error ? err.message : String(err)}`
);
}
}
this.devServerManager = null;
}
});
// AC1: Listen for "start dev server" requests from the interactive error page
this.proxyServer.on('startDevServer', () => {
this.logger?.info('Received startDevServer request from error page');
if (!this.devServerManager) {
const devCommand = manifest?.dev?.command ?? DEFAULT_DEV_COMMAND;
this.devServerManager = new DevServerManager({
command: devCommand,
cwd: webappDir,
});
this.devServerManager.on('ready', (readyUrl: string) => {
this.logger?.debug(`Dev server ready at: ${readyUrl}`);
this.proxyServer?.clearActiveDevServerError();
this.proxyServer?.updateDevServerUrl(readyUrl);
});
this.devServerManager.on('error', (error: SfError | DevServerError) => {
if (
'stderrLines' in error &&
Array.isArray(error.stderrLines) &&
'title' in error &&
'type' in error
) {
this.proxyServer?.setActiveDevServerError(error);
}
this.logger?.debug(`Dev server error: ${error.message}`);
});
this.devServerManager.on('exit', () => {
this.logger?.debug('Dev server stopped');
});
this.devServerManager.start();
this.log('Dev server start initiated from error page.');
} else {
this.logger?.debug('Dev server manager already exists, ignoring start request');
}
});
// Step 5: Check if dev server is reachable (non-blocking warning)
if (devServerUrl) {
await this.checkDevServerHealth(devServerUrl);
}
// Step 6: Open browser if requested
if (flags.open) {
this.logger.debug('Opening browser...');
await WebappDev.openBrowser(proxyUrl);
}
// Display usage instructions
this.log('');
this.log(messages.getMessage('info.ready-for-development', [proxyUrl, devServerUrl ?? 'N/A']));
this.log(messages.getMessage('info.press-ctrl-c'));
this.log('');
// Keep the command running until interrupted or dev server exits
await new Promise<void>((resolve) => {
// Exit if dev server exits with SIGINT (user pressed Ctrl+C)
if (this.devServerManager) {
this.devServerManager.on('exit', (code: number | null, signal: string | null) => {
if (signal === 'SIGINT') {
this.logger?.debug('Dev server received SIGINT, exiting command');
resolve();
}
});
}
// CRITICAL: Use prependOnceListener to add our handlers BEFORE sfCommand's handlers
// sfCommand adds process.on('SIGINT', () => this.exit(130)) which throws ExitError
// By using prependOnceListener, our resolve() runs FIRST, allowing clean shutdown
// This is especially important when there's no dev server (explicit URL mode)
process.prependOnceListener('SIGINT', () => {
this.logger?.debug('Received SIGINT signal, initiating graceful shutdown');
resolve();
});
process.prependOnceListener('SIGTERM', () => {
this.logger?.debug('Received SIGTERM signal, initiating graceful shutdown');
resolve();
});
});
// Return result (never reached, but required for type safety)
return {
url: proxyUrl,
devServerUrl: devServerUrl ?? '',
};
} catch (error) {
// Cleanup on error
await this.cleanup();
// Re-throw as SfError if not already
if (error instanceof SfError) {
throw error;
}
// Wrap unknown errors (include plain objects e.g. DevServerError with .message/.title)
const errorMessage =
error instanceof Error
? error.message
: typeof error === 'object' && error !== null && 'message' in error
? String((error as { message?: unknown }).message)
: typeof error === 'object' && error !== null && 'title' in error
? String((error as { title?: unknown }).title)
: String(error);
throw new SfError(`Failed to start webapp dev command: ${errorMessage}`, 'UnexpectedError', [
'This is an unexpected error',
'Please try again',
'If the problem persists, check the command logs with SF_LOG_LEVEL=debug',
]);
}
}
/**
* Oclif lifecycle method - called when command exits (including Ctrl+C)
* This is the proper way to handle cleanup in oclif commands
*/
protected async finally(): Promise<void> {
// Cleanup all resources silently
// Don't show messages here as this runs on ALL exits (errors, Ctrl+C, etc)
await this.cleanup();
}
/**
* Check if dev server is reachable (non-blocking health check)
*/
private async checkDevServerHealth(devServerUrl: string): Promise<void> {
try {
const response = await fetch(devServerUrl, {
method: 'HEAD',
signal: AbortSignal.timeout(3000), // 3 second timeout
});
if (response.ok) {
this.logger?.debug(messages.getMessage('info.dev-server-healthy', [devServerUrl]));
} else {
this.warn(messages.getMessage('warning.dev-server-not-responding', [devServerUrl, String(response.status)]));
}
} catch (error) {
// Dev server not reachable - show warning but don't fail
this.warn(messages.getMessage('warning.dev-server-unreachable', [devServerUrl]));
this.warn(messages.getMessage('warning.dev-server-start-hint'));
this.logger?.debug(`Dev server check error: ${(error as Error).message}`);
}
}
/**
* Cleanup all resources (proxy, dev server, file watcher)
*/
private async cleanup(): Promise<void> {
// Stop proxy server
if (this.proxyServer) {
try {
await this.proxyServer.stop();
this.logger?.debug('Proxy server stopped');
} catch (error) {
this.logger?.debug(`Failed to stop proxy server: ${(error as Error).message}`);
}
this.proxyServer = null;
}
// Stop dev server
if (this.devServerManager) {
try {
await this.devServerManager.stop();
this.logger?.debug('Dev server stopped');
} catch (error) {
this.logger?.debug(`Failed to stop dev server: ${(error as Error).message}`);
}
this.devServerManager = null;
}
// Stop manifest watcher
if (this.manifestWatcher) {
try {
await this.manifestWatcher.stop();
this.logger?.debug('Manifest watcher stopped');
} catch (error) {
this.logger?.debug(`Failed to stop manifest watcher: ${(error as Error).message}`);
}
this.manifestWatcher = null;
}
this.logger?.debug('Cleanup complete');
}
}