Skip to content

feat(dev-server): integrate with preview app command #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .mocharc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"recursive": true,
"reporter": "spec",
"timeout": 600000,
"node-option": ["loader=ts-node/esm"]
"node-option": ["loader=ts-node/esm", "loader=esmock"]
}
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,4 @@ FLAG DESCRIPTIONS
This person can be anyone in the world!
```

_See code: [src/commands/hello/world.ts](https://github.com/salesforcecli/plugin-lightning-dev/blob/1.0.25/src/commands/hello/world.ts)_

<!-- commandsstop -->
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@
"author": "Salesforce",
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@lwc/lwc-dev-server": "^7.1.1-6.6.4",
"@lwc/sfdc-lwc-compiler": "^7.1.1-6.6.4",
"@lwrjs/api": "0.13.0-alpha.12",
"@oclif/core": "^3.26.6",
"@salesforce/core": "^7.3.9",
"@salesforce/kit": "^3.1.2",
"@salesforce/lwc-dev-mobile-core": "4.0.0-alpha.1",
"@salesforce/sf-plugins-core": "^9.0.14",
"tar": "^7.2.0",
"lwc": "6.6.4",
"lwr": "0.13.0-alpha.12",
"@lwrjs/api": "0.13.0-alpha.12"
"tar": "^7.2.0"
},
"devDependencies": {
"@oclif/plugin-command-snapshot": "^5.1.9",
Expand All @@ -22,6 +24,7 @@
"@salesforce/plugin-command-reference": "^3.0.88",
"@types/tar": "^6.1.13",
"eslint-plugin-sf-plugin": "^1.18.5",
"esmock": "^2.6.5",
"oclif": "^4.11.3",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
Expand Down
3 changes: 3 additions & 0 deletions src/commands/lightning/preview/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages, Logger, Org } from '@salesforce/core';
import { PreviewUtils } from '@salesforce/lwc-dev-mobile-core';
import { OrgUtils } from '../../../shared/orgUtils.js';
import { startLWCServer } from '../../../lwc-dev-server/index.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-lightning-dev', 'lightning.preview.app');
Expand Down Expand Up @@ -55,6 +56,8 @@ export default class LightningPreviewApp extends SfCommand<void> {
const { flags } = await this.parse(LightningPreviewApp);
const logger = await Logger.child(this.ctor.name);

await startLWCServer(logger);

if (flags['device-type'] === Platform.desktop) {
await this.desktopPreview(logger, flags);
} else if (flags['device-type'] === Platform.ios) {
Expand Down
76 changes: 76 additions & 0 deletions src/lwc-dev-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2023, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import path from 'node:path';
import process from 'node:process';
import { LWCServer, LogLevel, ServerConfig, Workspace, startLwcDevServer } from '@lwc/lwc-dev-server';
import { Logger } from '@salesforce/core';

const DEV_SERVER_PORT = 8081;
Copy link
Collaborator

@ravijayaramappa ravijayaramappa Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The port needs to be configurable. This a pretty popular port number and we should anticipate that it might not be available. Can we add a new flag to sf lightning preview app command?

Copy link
Contributor

@maliroteh-sf maliroteh-sf Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ravijayaramappa we may need to run it by Marcelino to discuss this. For example:

  • Should it be required or optional flag
  • If it is optional and omitted what should we default to
  • What if the user uses a --port flag to pass in a port but lwc.config.json also has a port defined in it. Should we update the content of the config file and overwrite with the new flag?
  • etc.

Maybe we should utilize our slack channel to discuss further with him and the devs?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that idea of just putting it in the lwc.config.json. So that the user can add it once and forget it. Created W-15962937 to track.


/**
* Map sf cli log level to lwc dev server log level
* https://github.com/salesforcecli/cli/wiki/Code-Your-Plugin#logging-levels
*
* @param cliLogLevel
* @returns number
*/
function mapLogLevel(cliLogLevel: number): number {
switch (cliLogLevel) {
case 10:
return LogLevel.verbose;
case 20:
return LogLevel.debug;
case 30:
return LogLevel.info;
case 40:
return LogLevel.warn;
case 50:
return LogLevel.error;
case 60:
return LogLevel.silent;
default:
return LogLevel.error;
}
}

function createLWCServerConfig(source: string, logger: Logger): ServerConfig {
const rootDir = path.resolve(source, 'force-app/main/default');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the config be placed elsewhere? My guess is this path reflects a Salesforce VSCode project, as shown in the attached screenshot. The config is for LWR server and LWC server, right? Then, would the root folder be a more appropriate place for the config file to be created?

image

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the config file will be at the root folder. The value for rootDir usually indicates to the server as to where the components can be found.

And looking at line 58 I see that process.cwd() is being used as the base path (which I think would be the same as the root directory for an SFDX project)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's resolve-ing to force-app/main/default so the config file is getting attempted to be created there instead of root of the project?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lwc-dev-server supports multiple workspaces and the config is used to figure out where does the components live, sfdx project [workspace=sfcli in this case] follows an opinionated folder structure and isn't required to have lwr.config or either lwc.config. But let me know if my understanding is incorrect

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way I'm reading this code is that it is creating a ServerConfig object in <root dir>/force-app/main/default. I assume the object that's created inside this method is eventually going to be replaced by values that are read from lwc.config.json in that folder.

You say in your comment that lwc.config(.json) isn't required in the folder. Yes, the code is resolve-ing it, implying that there exists a json there.

Here's what I'm trying to do for myself, @rax-it . I'm working on this repo too and I'm trying to figure out where the lwc.config.json exists. As for where it should exist, that, I don't know. So when I found your draft PR and read the code I naturally thought <root dir>/force-app/main/default is the folder and trying to confirm with you.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sfdctaka I think I may have understood the root of your confusion here. There are 2 concepts of root directory, each serving a different purpose.

For an SFDX project, the root directory of the entire SFDX project is the folder where the file sfdx-project.json is located at. lwr.config.json should also be placed at this same location.

Now inside the lwr.config.json there are various configuration flags/values. One of those flags is rootDir and it means a different thing. rootDir tells the dev server where to look for when resolving modules/components.

Suppose you have an SFDX project located at ~/Desktop/MyProject and that this project has an lwc component called helloWorld (which would be located at ~/Desktop/MyProject/force-app/main/default/lwc/helloWorld.

By setting rootDir = ~/Desktop/MyProject/force-app/main/default you are telling the dev server that, when requests come in to serve helloWorld (and any other components/modules that it may be referencing) then the dev server should start looking at the location defined by rootDir to search for the components.

If you have further questions on this, feel free to reach out to me on slack (so we don't pollute the comments/feed of this PR)

@rax-it The assumption that for SFDX projects, the modules/components will always be under force-app/main/default is not true. We would need to look at the content of sfdx-project.json and process packageDirectories where it would tell us where the packages are. I've seen code for processing sfdx-project.json a long while ago and can't remember off the top of my head what it would involve. I'll look around to see if I can find it and will post link(s) here if I do.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maliroteh-sf I added sfdx config handling as per what information was available in developer docs.
Let me know if you find more info about it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that sounds about right. I also was looking at sfdxPackageDirsPattern which is subsequently used for example by getModulesDirs or by componentEntries

const namespacePaths: string[] = [rootDir];

return {
rootDir,
port: DEV_SERVER_PORT,
protocol: 'wss',
host: 'localhost',
paths: namespacePaths,
workspace: Workspace.SfCli,
targets: ['LEX'], // should this be something else?
logLevel: mapLogLevel(logger.getLevel()),
};
}

export async function startLWCServer(logger: Logger): Promise<LWCServer> {
const config = createLWCServerConfig(process.cwd(), logger);
let lwcDevServer: LWCServer | null = await startLwcDevServer(config);

const cleanup = (): void => {
if (lwcDevServer) {
lwcDevServer.stopServer();
lwcDevServer = null;
}
};

// normal exit flow
process.on('exit', cleanup);
// when a user presses ctrl+c
process.on('SIGINT', cleanup);
// when a user kills the process
process.on('SIGTERM', cleanup);

return lwcDevServer;
}
18 changes: 14 additions & 4 deletions test/commands/lightning/preview/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { stubSpinner, stubUx } from '@salesforce/sf-plugins-core';
import { Messages } from '@salesforce/core';
import { PreviewUtils } from '@salesforce/lwc-dev-mobile-core';
import { Config } from '@oclif/core';
import esmock from 'esmock';
import LightningPreviewApp from '../../../../src/commands/lightning/preview/app.js';
import { OrgUtils } from '../../../../src/shared/orgUtils.js';

Expand All @@ -22,11 +23,20 @@ describe('lightning preview app', () => {
const testOrgData = new MockTestOrgData();
const testAppId = '06m8b000002vpFSAAY';
const testServerUrl = 'wss://localhost:1234';
let MockedLightningPreviewApp: typeof LightningPreviewApp;

beforeEach(async () => {
stubUx($$.SANDBOX);
stubSpinner($$.SANDBOX);
await $$.stubAuths(testOrgData);
MockedLightningPreviewApp = await esmock<typeof LightningPreviewApp>(
'../../../../src/commands/lightning/preview/app.js',
{
'../../../../src/lwc-dev-server/index.js': {
startLWCServer: async () => ({ stopServer: () => {} }),
},
}
);
});

afterEach(() => {
Expand All @@ -36,7 +46,7 @@ describe('lightning preview app', () => {
it('throws when app not found', async () => {
try {
$$.SANDBOX.stub(OrgUtils, 'getAppId').resolves(undefined);
await LightningPreviewApp.run(['--name', 'blah', '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', 'blah', '-o', testOrgData.username]);
} catch (err) {
expect(err)
.to.be.an('error')
Expand All @@ -50,7 +60,7 @@ describe('lightning preview app', () => {
$$.SANDBOX.stub(PreviewUtils, 'generateWebSocketUrlForLocalDevServer').throws(
new Error('Cannot determine LDP url.')
);
await LightningPreviewApp.run(['--name', 'Sales', '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', 'Sales', '-o', testOrgData.username]);
} catch (err) {
expect(err).to.be.an('error').with.property('message', 'Cannot determine LDP url.');
}
Expand All @@ -69,9 +79,9 @@ describe('lightning preview app', () => {
$$.SANDBOX.stub(PreviewUtils, 'generateWebSocketUrlForLocalDevServer').returns(testServerUrl);
const runCmdStub = $$.SANDBOX.stub(Config.prototype, 'runCommand').resolves();
if (appName) {
await LightningPreviewApp.run(['--name', appName, '-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['--name', appName, '-o', testOrgData.username]);
} else {
await LightningPreviewApp.run(['-o', testOrgData.username]);
await MockedLightningPreviewApp.run(['-o', testOrgData.username]);
}

expect(runCmdStub.calledOnce);
Expand Down
36 changes: 36 additions & 0 deletions test/lwc-dev-server/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright (c) 2024, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { expect } from 'chai';
import { Logger } from '@salesforce/core';
import { LWCServer } from '@lwc/lwc-dev-server';
import esmock from 'esmock';
import * as devServer from '../../src/lwc-dev-server/index.js';

describe('lwc-dev-server', () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have a test which can use a sample sfdx project and start the lwc dev server and stop it successfully? Like a sanity end-2-end test.

const server = {
stopServer: () => {},
} as LWCServer;
let lwcDevServer: typeof devServer;

before(async () => {
lwcDevServer = await esmock<typeof devServer>('../../src/lwc-dev-server/index.js', {
'@lwc/lwc-dev-server': {
startLwcDevServer: async () => server,
},
});
});

it('exports a startLWCServer function', () => {
expect(lwcDevServer.startLWCServer).to.be.a('function');
});

it('calling startLWCServer returns an LWCServer', async () => {
const s = await lwcDevServer.startLWCServer({ getLevel: () => 10 } as Logger);
expect(s).to.equal(server);
});
});
Loading
Loading