Skip to content
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

Adds a validator module to Bubblewrap #134

Merged
merged 7 commits into from
Apr 14, 2020
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ projects for Android Applications that launch Progressive Web App (PWA) using

## Bubblewrap Components

- **[bubblewrap/core](./packages/core):** a javascript library for generating, building and updating TWA projects.
- **[bubblewrap/core](./packages/core):** a javascript library for generating, building and
updating TWA projects.
- **[bubblewrap/cli](./packages/cli):** a command-line version of Bubblewrap.
- **[bubblewrap/validator](./packages/validator):** library to validate the correctness and
Copy link
Collaborator

Choose a reason for hiding this comment

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

tiniest nit: could you say "a library to...", so that the sentence has the same form as the previous two bullet points?

compare Trusted Web Activity projects against the quality criteria.

## Contributing

Expand Down
5 changes: 5 additions & 0 deletions packages/cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
"license": "Apache-2.0",
"dependencies": {
"@bubblewrap/core": "^0.6.0",
"@bubblewrap/validator": "^0.6.0",
"@types/color": "^3.0.0",
"@types/inquirer": "^6.5.0",
"@types/minimist": "^1.2.0",
"@types/valid-url": "^1.0.2",
"color": "^3.1.2",
"colors": "^1.4.0",
"inquirer": "^7.0.4",
"minimist": "^1.2.2",
"valid-url": "^1.0.9"
Expand Down
5 changes: 5 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ module.exports = (): void => {
const log = new Log('cli');
const args = process.argv.slice(2);
cli.run(args)
.then((result) => {
if (!result) {
process.exit(1);
}
})
.catch((err: Error) => {
log.error(err.message);
process.exit(1);
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm not quite sure what you're doing here. Isn't this the last code to be called in the execution of the program? Why would you need to call process.exit() ? Is it just to make the return code 1?

I'm dubious about using process.exit in general since it's not obvious from the caller of this method that the entire program could terminate. Is there some way to make the method return the exit code - so 1 in the two cases you call process.exit in and 0 otherwise?

Copy link
Member Author

Choose a reason for hiding this comment

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

cli/src/index.ts is the entry point for the CLI application - a "main" method (TypeScript doesn't have a main). The reason it calls process.exit(1) is to signal an abnormal termination. In case the program is being invoked as part of a build pipeline, this signals that the CLI failed and the whole pipeline can be aborted.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Could we instead do:

const success = await cli.run(args)
    .then((result) => {
        return result;
    })
    .catch((error) => {
        // ...
        return false;
    });
process.exit(success ? 0 : 1);

Copy link
Member Author

Choose a reason for hiding this comment

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

Updated the code.

Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/lib/Cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ import {update} from './cmds/update';
import {help} from './cmds/help';
import {build} from './cmds/build';
import {init} from './cmds/init';
import {validate} from './cmds/validate';
import {loadOrCreateConfig} from './config';

export class Cli {
async run(args: string[]): Promise<void> {
async run(args: string[]): Promise<boolean> {
const config = await loadOrCreateConfig();

const parsedArgs = minimist(args);
Expand All @@ -35,7 +36,9 @@ export class Cli {
case 'update':
return await update(parsedArgs);
case 'build':
return await build(config);
return await build(config, parsedArgs);
case 'validate':
return await validate(parsedArgs);
default:
throw new Error(`"${command}" is not a valid command!`);
}
Expand Down
28 changes: 27 additions & 1 deletion packages/cli/src/lib/cmds/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
import {AndroidSdkTools, Config, GradleWrapper, JdkHelper, Log, TwaManifest}
from '@bubblewrap/core';
import * as inquirer from 'inquirer';
import * as path from 'path';
import {validatePassword} from '../inputHelpers';
import {PwaValidator, PwaValidationResult} from '@bubblewrap/validator';
import {printValidationResult} from '../pwaValidationHelper';
import {ParsedArgs} from 'minimist';

interface SigningKeyPasswords {
keystorePassword: string;
Expand Down Expand Up @@ -68,7 +72,19 @@ async function getPasswords(log: Log): Promise<SigningKeyPasswords> {
};
}

export async function build(config: Config, log = new Log('build')): Promise<void> {
async function startValidation(): Promise<PwaValidationResult> {
const manifestFile = path.join(process.cwd(), 'twa-manifest.json');
const twaManifest = await TwaManifest.fromFile(manifestFile);
return PwaValidator.validate(new URL(twaManifest.startUrl, twaManifest.webManifestUrl));
}

export async function build(
config: Config, args: ParsedArgs, log = new Log('build')): Promise<boolean> {
let pwaValidationPromise;
if (!args.skipPwaValidation) {
pwaValidationPromise = startValidation();
}

const jdkHelper = new JdkHelper(process, config);
const androidSdkTools = new AndroidSdkTools(process, config, jdkHelper);

Expand All @@ -92,6 +108,15 @@ export async function build(config: Config, log = new Log('build')): Promise<voi
'./app-release-unsigned-aligned.apk', // output file
);

if (!args.skipPwaValidation) {
log.info('Checking PWA Quality Criteria...');
const pwaValidationResult = (await pwaValidationPromise)!;
printValidationResult(pwaValidationResult, log);
if (pwaValidationResult.status === 'FAIL') {
log.warn('PWA Quality Criteria check failed.');
}
}

// And sign APK
log.info('Signing...');
const outputFile = './app-release-signed.apk';
Expand All @@ -105,4 +130,5 @@ export async function build(config: Config, log = new Log('build')): Promise<voi
);

log.info(`Signed Android App generated at "${outputFile}"`);
return true;
}
16 changes: 14 additions & 2 deletions packages/cli/src/lib/cmds/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const HELP_MESSAGES = new Map<string, string>(
'help ................ shows this menu',
'init ................ initializes a new TWA Project',
'update .............. updates an existing TWA Project with the latest bubblewrap template',
'validate ............ validates if an URL matches the PWA Quality Criteria for Trusted' +
' Web Activity',
].join('\n')],
['init', [
'Usage:',
Expand All @@ -44,6 +46,10 @@ const HELP_MESSAGES = new Map<string, string>(
'',
'',
'bubblewrap build',
'',
'',
'Options:',
'--skipPwaValidation ....... skips validating the wrapped PWA against the Quality Criteria',
].join('\n')],
['update', [
'Usage:',
Expand All @@ -58,15 +64,21 @@ const HELP_MESSAGES = new Map<string, string>(
'--skipVersionUpgrade ....... skips upgrading appVersion and appVersionCode',
'--manifest ................. directory where the client should look for twa-manifest.json',
].join('\n')],
['validate', [
'Usage:',
'',
'',
'bubblewrap validate --url=[pwa-url]',
].join('\n')],
],
);

export async function help(args: ParsedArgs, log = new Log('help')): Promise<void> {
export async function help(args: ParsedArgs, log = new Log('help')): Promise<boolean> {
// minimist uses an `_` object to store details.
const command = args._[1];
const message = HELP_MESSAGES.get(command) || HELP_MESSAGES.get('main');

// We know we have a message for 'main', in case the command is invalid.
log.info(message!);
return;
return true;
}
3 changes: 2 additions & 1 deletion packages/cli/src/lib/cmds/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ async function createSigningKey(twaManifest: TwaManifest, config: Config): Promi
});
}

export async function init(args: ParsedArgs, config: Config): Promise<void> {
export async function init(args: ParsedArgs, config: Config): Promise<boolean> {
log.info('Fetching Manifest: ', args.manifest);
let twaManifest = await TwaManifest.fromWebManifest(args.manifest);
twaManifest = await confirmTwaConfig(twaManifest);
Expand All @@ -204,4 +204,5 @@ export async function init(args: ParsedArgs, config: Config): Promise<void> {
await twaManifest.saveToFile('./twa-manifest.json');
await twaGenerator.createTwaProject(targetDirectory, twaManifest);
await createSigningKey(twaManifest, config);
return true;
}
5 changes: 3 additions & 2 deletions packages/cli/src/lib/cmds/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function updateVersions(twaManifest: TwaManifest, appVersionNameArg: strin
* @param {string} [args.appVersionName] Value to be used for appVersionName when upgrading
* versions. Ignored if `args.skipVersionUpgrade` is set to true.
*/
export async function update(args: ParsedArgs): Promise<void> {
export async function update(args: ParsedArgs): Promise<boolean> {
const targetDirectory = args.directory || process.cwd();
const manifestFile = args.manifest || path.join(process.cwd(), 'twa-manifest.json');
const twaManifest = await TwaManifest.fromFile(manifestFile);
Expand All @@ -86,5 +86,6 @@ export async function update(args: ParsedArgs): Promise<void> {
}

const twaGenerator = new TwaGenerator();
return await twaGenerator.createTwaProject(targetDirectory, twaManifest);
await twaGenerator.createTwaProject(targetDirectory, twaManifest);
return true;
}
34 changes: 34 additions & 0 deletions packages/cli/src/lib/cmds/validate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright 2020 Google Inc. All Rights Reserved.
*
* 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 {PwaValidator} from '@bubblewrap/validator';
import {Log} from '@bubblewrap/core';
import {ParsedArgs} from 'minimist';
import {printValidationResult} from '../pwaValidationHelper';

const log = new Log('validate');

/**
* Runs the PwaValidator to check a given URL agains the Quality criteria. More information on the
* Quality Criteria available at: https://web.dev/using-a-pwa-in-your-android-app/#quality-criteria
* @param {ParsedArgs} args
*/
export async function validate(args: ParsedArgs): Promise<boolean> {
log.info('Validating URL: ', args.url);
const validationResult = await PwaValidator.validate(new URL(args.url));
printValidationResult(validationResult, log);
return validationResult.status === 'PASS';
}
34 changes: 34 additions & 0 deletions packages/cli/src/lib/pwaValidationHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {PwaValidationResult} from '@bubblewrap/validator';
import {red, green, bold, underline, gray} from 'colors';
import {Log} from '@bubblewrap/core';

export function printValidationResult(validationResult: PwaValidationResult, log: Log): void {
log.info('');
log.info('Check the full PageSpeed Insights report at:');
log.info(`- ${validationResult.psiWebUrl}`);
log.info('');

const performanceValue = validationResult.scores.performance.status === 'PASS' ?
green(validationResult.scores.performance.printValue) :
red(validationResult.scores.performance.printValue);

const pwaValue = validationResult.scores.pwa.status === 'PASS' ?
green(validationResult.scores.pwa.printValue) :
red(validationResult.scores.pwa.printValue);

const overallStatus = validationResult.status === 'PASS' ?
green(validationResult.status) : red(validationResult.status);

const accessibilityValue = gray(validationResult.scores.accessibility.printValue);

log.info('');
log.info(underline('Quality Criteria scores'));
log.info(`Lighthouse Performance score: ......... ${performanceValue}`);
log.info(`Lighthouse PWA check: ................. ${pwaValue}`);
log.info('');
log.info(underline('Other scores'));
log.info(`Lighthouse Accessibility score......... ${accessibilityValue}`);
log.info('');
log.info(underline('Summary'));
log.info(bold(`Overall result: ....................... ${overallStatus}`));
}
24 changes: 24 additions & 0 deletions packages/validator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!---

Copyright 2019 Google Inc. All Rights Reserved.

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.
-->
# Bubblewrap Validator

Bubblewrap Validator is a JavaScript library that helps developers to verify if their
andreban marked this conversation as resolved.
Show resolved Hide resolved
[Trusted Web Activity][1] project is well formed as well as validating if the Progressive Web
App(PWA) used inside it matchs the [minimun quality criteria][2].

[1]: https://developers.google.com/web/android/trusted-web-activity/
[2]: https://web.dev/using-a-pwa-in-your-android-app/#quality-criteria
11 changes: 11 additions & 0 deletions packages/validator/jasmine.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"spec_dir": "dist/spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": true
}
73 changes: 73 additions & 0 deletions packages/validator/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading