Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,17 @@ This command executes a set of user-flow definitions against the target URL and

## Configuration

The CLI supports the official [user-flow/lighthouse configuration](https://github.com/GoogleChrome/lighthouse/blob/master/docs/configuration.md).
The CLI supports the official [Lighthouse configuration](https://github.com/GoogleChrome/lighthouse/blob/main/docs/configuration.md).

Details on how to work with configurations can be found in the [configuratin section](./packages/cli/docs/lh-configuraton.md).
A flow gets its Lighthouse config from at most two sources: one global config for every flow (`--configPath`, or `collect.configPath` or `collect.config` in `.user-flowrc.json`) and `flowOptions.config` in the flow file. user-flow combines them like this:

1. `settings` are merged key by key, and the flow config wins. Every other top-level key, such as `audits` or `categories`, is taken whole from the flow config if it has one, otherwise from the global config.
2. If the result has no `extends`, user-flow adds `extends: 'lighthouse:default'`, so a settings-only config still runs the default audits.
3. A flow config with `artifacts` and no `extends` is complete. It runs exactly as written, without `extends`, and takes only `settings` from the global config. To add artifacts on top of the default config, set `extends: 'lighthouse:default'` yourself.

For a single setting, the order from lowest to highest priority is: Lighthouse default → global config → flow config → `flowOptions.flags` → options passed to a step.

The [Lighthouse configuration guide](https://push-based.github.io/user-flow/docs/cli/lighthouse-configuration) has examples and the full rules (also on [GitHub](https://github.com/push-based/user-flow/blob/main/packages/cli/docs/lh-configuraton.md)).


# Writing user flows for the CLI
Expand Down
42 changes: 42 additions & 0 deletions e2e/cli-e2e/mocks/user-flows/complete-config.uf.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// @ts-expect-error // This is a mock file!
import { UserFlowContext, UserFlowInteractionsFn, UserFlowProvider } from '@push-based/user-flow';
import DevtoolsLog from 'lighthouse/core/gather/gatherers/devtools-log.js';

const interactions: UserFlowInteractionsFn = async (ctx: UserFlowContext): Promise<any> => {
const { flow, collectOptions } = ctx;
const { url } = collectOptions;

await flow.navigate(url, {
name: `Navigate to ${url}`,
});
};

export default {
flowOptions: {
name: 'Complete Config Example',
// A complete config: it lists its own artifacts and does not extend the
// default config. The default config names the DevtoolsLog gatherer by
// path, this one gives its implementation.
config: {
artifacts: [
{ id: 'DevtoolsLog', gatherer: { implementation: DevtoolsLog } },
],
audits: ['network-requests'],
categories: {
network: {
title: 'Network',
auditRefs: [{ id: 'network-requests', weight: 0 }],
},
},
},
},
interactions,
launchOptions: {
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu'
]
}
} satisfies UserFlowProvider;
35 changes: 35 additions & 0 deletions e2e/cli-e2e/tests/collect/config.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,39 @@ describe('collect config', () => {
expect(stripNodeWarnings(stderr)).toBe('');
expect(code).toBe(0);
});

it<CliTest>('should collect a flow with a complete LH config', async ({
setupFns,
cli,
}) => {
setupFns.setupRcJson(DEFAULT_RC);
setupFns.setupUserFlows(USER_FLOW_MOCKS.COMPLETE_CONFIG);

const { code, stderr } = await cli.run('user-flow', ['collect']);

expect(stripNodeWarnings(stderr)).toBe('');
expect(code).toBe(0);
});

it<CliTest>('should collect a complete LH config with a global config that extends', async ({
setupFns,
cli,
}) => {
setupFns.setupRcJson({
...DEFAULT_RC,
collect: {
...DEFAULT_RC.collect,
config: {
extends: 'lighthouse:default',
settings: { onlyCategories: ['network'] },
},
},
});
setupFns.setupUserFlows(USER_FLOW_MOCKS.COMPLETE_CONFIG);

const { code, stderr } = await cli.run('user-flow', ['collect']);

expect(stripNodeWarnings(stderr)).toBe('');
expect(code).toBe(0);
});
});
1 change: 1 addition & 0 deletions e2e/cli-e2e/utils/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const E2E_DIR = 'tmp/e2e';

export const USER_FLOW_MOCKS = {
BASIC: 'e2e/cli-e2e/mocks/user-flows/basic-navigation.uf.mts',
COMPLETE_CONFIG: 'e2e/cli-e2e/mocks/user-flows/complete-config.uf.mts',
} as const;

export const DEFAULT_RC = {
Expand Down
93 changes: 85 additions & 8 deletions packages/cli/docs/lh-configuraton.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,95 @@ Lighthouse itself can get configured over a json object where any detail regards
The official docs on [how to configure lighthouse](https://github.com/GoogleChrome/lighthouse/blob/main/docs/configuration.md) are located in their repository's docs.
The [default lighthouse config](https://github.com/GoogleChrome/lighthouse/blob/946075bb7f0858861067d161a414bdccc0a19007/core/config/constants.js#L92) can be found in their repository's source.

The CLI will start lighthouse as with its default configuration.
Unless configured otherwise, the CLI starts lighthouse with its default configuration.

### Configuration Options
### Where configuration can live

The CLI provides multiple ways of configuration, every one with a different granularity.
Each flow gets its Lighthouse config from at most two sources: one **global** config shared by every flow, and the **flow** config in the flow file.

Places to put configurations:
- in a `.user-flowrc.json` - used for all flows (**global**)
- in the console as CLI param - used for all flows, overwrites rc file (**global**)
- in a `<user-flow-name>.uf.mts` - used for 1 specific flow (**local**)
| Level | Place | Applies to |
| ------ | ------------------------------------------- | ------------------------- |
| Global | `--configPath` on the command line | Every flow in this run |
| Global | `collect.configPath` in `.user-flowrc.json` | Every flow in the project |
| Global | `collect.config` in `.user-flowrc.json` | Every flow in the project |
| Flow | `flowOptions.config` in a `*.uf.mts` file | That one flow |

Local configurations will overwrite global configurations.
There is only ever one global config. `--configPath` on the command line replaces `collect.configPath` from the rc file. A path and an inline config can't be mixed, though: if the rc file has `collect.config` and you pass `--configPath`, the run stops with `configPath and config can't be used together`.

### How the configs are combined

For each flow, user-flow builds a single config and passes it to Lighthouse's `startFlow`. It gets there in four steps.

1. The flow config is laid over the global config. `settings` are merged key by key, and the flow wins when both set the same key. Every other top-level key, such as `audits`, `categories` or `artifacts`, is taken whole from the flow config if it has one, and from the global config otherwise. They are not combined, so flow `audits` replace the global `audits`.
2. If the result has no `extends`, user-flow adds `extends: 'lighthouse:default'`. Without it, a config that only sets `settings` would run no audits at all. Configs that define their own artifacts are the exception, see [Complete configs](#complete-configs).
3. Lighthouse resolves `extends` by merging the config into its default config. Artifacts are matched by `id`, audits and category `auditRefs` are added to the default ones, and `settings` override the default settings. An array inside `settings`, such as `onlyCategories`, replaces the default array instead of extending it. A config without `extends` is used exactly as written.
4. `flowOptions.flags` and the options passed to a step override `settings` for that step. Step options, as in `flow.navigate(url, { onlyCategories: ['performance'] })`, win over `flowOptions.flags`.

For a single setting, the order from lowest to highest priority is:

Lighthouse default → global config → flow config → `flowOptions.flags` → step options

#### Example

**.user-flowrc.json (collect.config)**
```json
{
"settings": {
"formFactor": "mobile",
"onlyCategories": ["performance", "accessibility"]
},
"audits": ["my-global-audit"]
}
```

**user-flows/checkout.uf.mts (flowOptions.config)**
```typescript
config: {
settings: { formFactor: 'desktop' },
audits: ['my-flow-audit'],
}
```

For the checkout flow, Lighthouse receives:

```json
{
"extends": "lighthouse:default",
"settings": {
"formFactor": "desktop",
"onlyCategories": ["performance", "accessibility"]
},
"audits": ["my-flow-audit"]
}
```

`formFactor` comes from the flow and `onlyCategories` from the global config. `my-global-audit` is gone because the flow sets its own `audits`. Lighthouse then runs `my-flow-audit` next to its default audits.

### Complete configs

Some configs bring every artifact, audit and category they need and are written to run without the default config. Configs exported by Lighthouse plugin packages are a common case. If user-flow added `extends` to one of them, Lighthouse would merge its artifacts with the default ones, and that fails when both describe the same artifact differently.

user-flow therefore treats a flow config with `artifacts` and no `extends` as complete. For a complete config it:

- does not add `extends`, so Lighthouse runs the config as written, the same as `startFlow(page, { config })`;
- takes only `settings` from the global config, and ignores a global `extends`, `audits` or `categories` for this flow.

**user-flows/soft-navigation.uf.mts**
```typescript
import { softNavigationConfig } from '@push-based/lighthouse-soft-navigation';

export default {
flowOptions: { name: 'Soft navigation', config: softNavigationConfig() },
interactions: async ({ flow, collectOptions: { url } }) => {
await flow.navigate(url);
},
};
```

> [!IMPORTANT]
> To add your own artifacts on top of the default config, set `extends: 'lighthouse:default'` yourself. Without it the config counts as complete, and the report only contains the audits it lists. Lighthouse treats a config without `extends` the same way.

### Where to put the config

Custom configurations can be provided over a external `.json` file using `--configPath <path/to/config.json>`.
This option is also available in the `.user-flowrc.json` file under the `collect.configPath` property.
Expand Down
18 changes: 18 additions & 0 deletions packages/cli/src/lib/commands/collect/utils/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,25 @@ export function getLhConfigFromArgv(rc: Partial<Pick<CollectCommandArgv, 'config
return cfg;
}

/**
* A config that lists its own `artifacts` and has no `extends` is complete:
* Lighthouse runs it as it is. Extending the default config merges its
* artifacts with the default ones by id, which fails when the two describe the
* same gatherer differently.
*/
export function isCompleteLhConfig(cfg: Config = {}): boolean {
return !!cfg.artifacts && !cfg.extends;
}

export function mergeLhConfig(globalCfg: Config = {}, localCfg: Config = {}): Config {
if (isCompleteLhConfig(localCfg)) {
logVerbose(`LH Configuration is used from a user flow file`);
// Only the global settings apply, a global `extends` would turn the
// complete config into an extension of another config.
const settings = { ...globalCfg?.settings, ...localCfg.settings };
return Object.keys(settings).length ? { ...localCfg, settings } : { ...localCfg };
}

let cfg = { ...globalCfg };

if (localCfg) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from 'vitest';
import { Config } from 'lighthouse';
import { isCompleteLhConfig, mergeLhConfig } from './index.js';

vi.mock('../../../../core/loggin');

const completeConfig: Config = {
artifacts: [{ id: 'Custom', gatherer: 'custom-gatherer' }],
audits: ['custom-audit'],
categories: {
custom: { title: 'Custom', auditRefs: [{ id: 'custom-audit', weight: 1 }] },
},
};

describe('isCompleteLhConfig', () => {
it('should be true for a config with artifacts and no extends', () => {
expect(isCompleteLhConfig(completeConfig)).toBe(true);
});

it('should be false for a config that extends another config', () => {
expect(
isCompleteLhConfig({ ...completeConfig, extends: 'lighthouse:default' }),
).toBe(false);
});

it('should be false for a config without artifacts', () => {
expect(isCompleteLhConfig({ settings: { onlyCategories: ['performance'] } })).toBe(false);
expect(isCompleteLhConfig()).toBe(false);
});
});

describe('mergeLhConfig', () => {
it('should extend the default config if none is given', () => {
expect(mergeLhConfig()).toStrictEqual({
extends: 'lighthouse:default',
settings: {},
});
});

it('should add extends to a config without artifacts', () => {
expect(
mergeLhConfig({}, { settings: { onlyCategories: ['performance'] } }),
).toStrictEqual({
extends: 'lighthouse:default',
settings: { onlyCategories: ['performance'] },
});
});

it('should keep a given extends', () => {
expect(
mergeLhConfig({ extends: 'lighthouse:desktop' } as Config, {}),
).toStrictEqual({ extends: 'lighthouse:desktop', settings: {} });
});

it('should let the flow config override the global config', () => {
expect(
mergeLhConfig(
{ settings: { onlyCategories: ['performance'], formFactor: 'mobile' } },
{ settings: { formFactor: 'desktop' } },
),
).toStrictEqual({
extends: 'lighthouse:default',
settings: { onlyCategories: ['performance'], formFactor: 'desktop' },
});
});

it('should not add extends to a complete flow config', () => {
const cfg = mergeLhConfig({}, completeConfig);
expect(cfg).toStrictEqual(completeConfig);
expect(cfg).not.toHaveProperty('extends');
});

it('should take only settings from the global config for a complete flow config', () => {
const cfg = mergeLhConfig(
{
extends: 'lighthouse:default',
audits: ['global-audit'],
settings: { onlyCategories: ['custom'], formFactor: 'mobile' },
},
{ ...completeConfig, settings: { formFactor: 'desktop' } },
);
expect(cfg).toStrictEqual({
...completeConfig,
settings: { onlyCategories: ['custom'], formFactor: 'desktop' },
});
expect(cfg).not.toHaveProperty('extends');
});
});
Loading
Loading