diff --git a/types/artifacts.d.ts b/types/artifacts.d.ts index 90ccd34f28f1..7c9d01dfdeec 100644 --- a/types/artifacts.d.ts +++ b/types/artifacts.d.ts @@ -17,6 +17,7 @@ type _TaskNode = import('../lighthouse-core/lib/tracehouse/main-thread-tasks.js' import Config from './config'; import Gatherer from './gatherer'; import {IcuMessage} from './i18n'; +import Protocol from './protocol'; export interface Artifacts extends BaseArtifacts, GathererArtifacts {} @@ -80,9 +81,9 @@ interface LegacyBaseArtifacts { /** Errors preventing page being installable as PWA. This moved to a regular artifact in Fraggle Rock. */ InstallabilityErrors: Artifacts.InstallabilityErrors; /** A set of page-load traces, keyed by passName. */ - traces: {[passName: string]: LH.Trace}; + traces: {[passName: string]: Trace}; /** A set of DevTools debugger protocol records, keyed by passName. */ - devtoolsLogs: {[passName: string]: LH.DevtoolsLog}; + devtoolsLogs: {[passName: string]: DevtoolsLog}; } /** @@ -125,7 +126,7 @@ export interface GathererArtifacts extends PublicGathererArtifacts,LegacyBaseArt /** CSS coverage information for styles used by page's final state. */ CSSUsage: {rules: LH.Crdp.CSS.RuleUsage[], stylesheets: Artifacts.CSSStyleSheetInfo[]}; /** The primary log of devtools protocol activity. Used in Fraggle Rock gathering. */ - DevtoolsLog: LH.DevtoolsLog; + DevtoolsLog: DevtoolsLog; /** Information on the document's doctype(or null if not present), specifically the name, publicId, and systemId. All properties default to an empty string if not present */ Doctype: Artifacts.Doctype | null; @@ -172,7 +173,7 @@ export interface GathererArtifacts extends PublicGathererArtifacts,LegacyBaseArt /** Information about tap targets including their position and size. */ TapTargets: Artifacts.TapTarget[]; /** The primary log of devtools protocol activity. Used in Fraggle Rock gathering. */ - Trace: LH.Trace; + Trace: Trace; /** Elements associated with metrics (ie: Largest Contentful Paint element). */ TraceElements: Artifacts.TraceElement[]; } @@ -608,8 +609,8 @@ declare module Artifacts { } interface MetricComputationDataInput { - devtoolsLog: LH.DevtoolsLog; - trace: LH.Trace; + devtoolsLog: DevtoolsLog; + trace: Trace; settings: Immutable; gatherContext: Artifacts['GatherContext']; simulator?: InstanceType; @@ -672,19 +673,19 @@ declare module Artifacts { /** The relative times from timeOrigin to key events, in milliseconds. */ timings: TraceTimes; /** The subset of trace events from the page's process, sorted by timestamp. */ - processEvents: Array; + processEvents: Array; /** The subset of trace events from the page's main thread, sorted by timestamp. */ - mainThreadEvents: Array; + mainThreadEvents: Array; /** The subset of trace events from the main frame, sorted by timestamp. */ - frameEvents: Array; + frameEvents: Array; /** The subset of trace events from the main frame and any child frames, sorted by timestamp. */ - frameTreeEvents: Array; + frameTreeEvents: Array; /** IDs for the trace's main frame, process, and thread. */ mainFrameIds: {pid: number, tid: number, frameId: string}; /** The list of frames committed in the trace. */ frames: Array<{id: string, url: string}>; /** The trace event marking the time at which the run should consider to have begun. Typically the same as the navigationStart but might differ due to SPA navigations, client-side redirects, etc. In the FR timespan case, this event is injected by Lighthouse itself. */ - timeOriginEvt: LH.TraceEvent; + timeOriginEvt: TraceEvent; } interface ProcessedNavigation { @@ -693,21 +694,21 @@ declare module Artifacts { /** The relative times from navigationStart to key metric events, in milliseconds. */ timings: NavigationTraceTimes; /** The trace event marking firstPaint, if it was found. */ - firstPaintEvt?: LH.TraceEvent; + firstPaintEvt?: TraceEvent; /** The trace event marking firstContentfulPaint, if it was found. */ - firstContentfulPaintEvt: LH.TraceEvent; + firstContentfulPaintEvt: TraceEvent; /** The trace event marking firstContentfulPaint from all frames, if it was found. */ - firstContentfulPaintAllFramesEvt: LH.TraceEvent; + firstContentfulPaintAllFramesEvt: TraceEvent; /** The trace event marking firstMeaningfulPaint, if it was found. */ - firstMeaningfulPaintEvt?: LH.TraceEvent; + firstMeaningfulPaintEvt?: TraceEvent; /** The trace event marking largestContentfulPaint, if it was found. */ - largestContentfulPaintEvt?: LH.TraceEvent; + largestContentfulPaintEvt?: TraceEvent; /** The trace event marking largestContentfulPaint from all frames, if it was found. */ - largestContentfulPaintAllFramesEvt?: LH.TraceEvent; + largestContentfulPaintAllFramesEvt?: TraceEvent; /** The trace event marking loadEventEnd, if it was found. */ - loadEvt?: LH.TraceEvent; + loadEvt?: TraceEvent; /** The trace event marking domContentLoadedEventEnd, if it was found. */ - domContentLoadedEvt?: LH.TraceEvent; + domContentLoadedEvt?: TraceEvent; /** * Whether the firstMeaningfulPaintEvt was the definitive event or a fallback to * firstMeaningfulPaintCandidate events had to be attempted. @@ -888,3 +889,98 @@ declare module Artifacts { type ConsoleMessage = ConsoleAPICall | ConsoleException | ConsoleProtocolLog; } + +export interface Trace { + traceEvents: TraceEvent[]; + metadata?: { + 'cpu-family'?: number; + }; + [futureProps: string]: any; +} + +/** The type of the Profile & ProfileChunk event in Chromium traces. Note that this is subtly different from Crdp.Profiler.Profile. */ +export interface TraceCpuProfile { + nodes?: Array<{id: number, callFrame: {functionName: string, url?: string}, parent?: number}> + samples?: Array + timeDeltas?: Array +} + +/** + * @see https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview + */ +export interface TraceEvent { + name: string; + cat: string; + args: { + fileName?: string; + snapshot?: string; + sync_id?: string; + beginData?: { + frame?: string; + startLine?: number; + url?: string; + }; + data?: { + frame?: string; + isLoadingMainFrame?: boolean; + documentLoaderURL?: string; + frames?: { + frame: string; + parent?: string; + processId?: number; + }[]; + page?: string; + readyState?: number; + requestId?: string; + startTime?: number; + timeDeltas?: TraceCpuProfile['timeDeltas']; + cpuProfile?: TraceCpuProfile; + callFrame?: Required['nodes'][0]['callFrame'] + /** Marker for each synthetic CPU profiler event for the range of _potential_ ts values. */ + _syntheticProfilerRange?: { + earliestPossibleTimestamp: number + latestPossibleTimestamp: number + } + stackTrace?: { + url: string + }[]; + styleSheetUrl?: string; + timerId?: string; + url?: string; + is_main_frame?: boolean; + cumulative_score?: number; + id?: string; + nodeId?: number; + impacted_nodes?: Array<{ + node_id: number, + old_rect?: Array, + new_rect?: Array, + }>; + score?: number; + weighted_score_delta?: number; + had_recent_input?: boolean; + compositeFailed?: number; + unsupportedProperties?: string[]; + size?: number; + }; + frame?: string; + name?: string; + labels?: string; + }; + pid: number; + tid: number; + /** Timestamp of the event in microseconds. */ + ts: number; + dur: number; + ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; + s?: 't'; + id?: string; + id2?: { + local?: string; + }; +} + +/** + * A record of DevTools Debugging Protocol events. + */ +export type DevtoolsLog = Array; diff --git a/types/config.d.ts b/types/config.d.ts index 52a1dec83425..3f0b9f7b1363 100644 --- a/types/config.d.ts +++ b/types/config.d.ts @@ -6,6 +6,7 @@ */ import Audit = require('../lighthouse-core/audits/audit.js'); +import {ScreenEmulationSettings, SharedFlagsSettings, ThrottlingSettings} from './externs'; import Gatherer from './gatherer'; import {IcuMessage} from './i18n'; @@ -19,7 +20,7 @@ declare module Config { */ interface Json { extends?: 'lighthouse:default' | string; - settings?: LH.SharedFlagsSettings; + settings?: SharedFlagsSettings; audits?: Config.AuditJson[] | null; categories?: Record | null; groups?: Record | null; @@ -63,7 +64,7 @@ declare module Config { interface FRContext { gatherMode?: Gatherer.GatherMode; configPath?: string; - settingsOverrides?: LH.SharedFlagsSettings; + settingsOverrides?: SharedFlagsSettings; } interface SharedPassNavigationJson { @@ -160,9 +161,9 @@ declare module Config { relevantAudits?: string[]; } - interface Settings extends Required { - throttling: Required; - screenEmulation: LH.ScreenEmulationSettings; + interface Settings extends Required { + throttling: Required; + screenEmulation: ScreenEmulationSettings; } interface Pass extends Required { diff --git a/types/externs.d.ts b/types/externs.d.ts index 7934d5e5a1ba..ca1cc8581a85 100644 --- a/types/externs.d.ts +++ b/types/externs.d.ts @@ -4,14 +4,13 @@ * 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 _Crdp from 'devtools-protocol/types/protocol'; -import _CrdpMappings from 'devtools-protocol/types/protocol-mapping'; import {ParseSelectorToTagNames} from 'typed-query-selector/parser'; +import Crdp from 'devtools-protocol/types/protocol'; import {Artifacts} from './artifacts'; import Budget from './budget'; +import {Locale} from './i18n'; import LHResult from './lhr'; -import Protocol from './protocol'; /** Merge properties of the types in union `T`. Where properties overlap, property types becomes the union of the two (or more) possible types. */ type MergeTypes = { @@ -38,6 +37,31 @@ declare global { var getCanonicalLocales: (locales?: string | Array) => Array; } + interface Window { + // Cached native functions/objects for use in case the page overwrites them. + // See: `executionContext.cacheNativesOnNewDocument`. + __nativePromise: PromiseConstructor; + __nativePerformance: Performance; + __nativeURL: typeof URL; + __ElementMatches: Element['matches']; + + /** Used for monitoring long tasks in the test page. */ + ____lastLongTask?: number; + + /** Used by FullPageScreenshot gatherer. */ + __lighthouseNodesDontTouchOrAllVarianceGoesAway: Map; + __lighthouseExecutionContextId?: number; + + // Not defined in tsc yet: https://github.com/microsoft/TypeScript/issues/40807 + requestIdleCallback(callback: (deadline: {didTimeout: boolean, timeRemaining: () => DOMHighResTimeStamp}) => void, options?: {timeout: number}): number; + } + + // Stricter querySelector/querySelectorAll using typed-query-selector. + interface ParentNode { + querySelector(selector: S): QuerySelectorParse | null; + querySelectorAll(selector: S): NodeListOf>; + } + /** Make properties K in T optional. */ type MakeOptional = { [P in Exclude]: T[P] @@ -60,7 +84,7 @@ declare global { T; /** Recursively makes all properties of T read-only. */ - export type Immutable = + type Immutable = T extends Function ? T : T extends Array ? ImmutableArray : T extends Map ? ImmutableMap : @@ -119,310 +143,169 @@ declare global { type CamelCasify = { [K in keyof T as KebabToCamelCase]: T[K]; } +} - module LH { - // re-export useful type modules under global LH module. - export import Crdp = _Crdp; - export import CrdpEvents = _CrdpMappings.Events; - export import CrdpCommands = _CrdpMappings.Commands; - - /** Simulation settings that control the amount of network & cpu throttling in the run. */ - interface ThrottlingSettings { - /** The round trip time in milliseconds. */ - rttMs?: number; - /** The network throughput in kilobits per second. */ - throughputKbps?: number; - // devtools settings - /** The network request latency in milliseconds. */ - requestLatencyMs?: number; - /** The network download throughput in kilobits per second. */ - downloadThroughputKbps?: number; - /** The network upload throughput in kilobits per second. */ - uploadThroughputKbps?: number; - // used by both - /** The amount of slowdown applied to the cpu (1/). */ - cpuSlowdownMultiplier?: number - } - - export interface PrecomputedLanternData { - additionalRttByOrigin: {[origin: string]: number}; - serverResponseTimeByOrigin: {[origin: string]: number}; - } - - export type Locale = 'en-US'|'en'|'en-AU'|'en-GB'|'en-IE'|'en-SG'|'en-ZA'|'en-IN'|'ar-XB'|'ar'|'bg'|'ca'|'cs'|'da'|'de'|'el'|'en-XA'|'en-XL'|'es'|'es-419'|'es-AR'|'es-BO'|'es-BR'|'es-BZ'|'es-CL'|'es-CO'|'es-CR'|'es-CU'|'es-DO'|'es-EC'|'es-GT'|'es-HN'|'es-MX'|'es-NI'|'es-PA'|'es-PE'|'es-PR'|'es-PY'|'es-SV'|'es-US'|'es-UY'|'es-VE'|'fi'|'fil'|'fr'|'he'|'hi'|'hr'|'hu'|'gsw'|'id'|'in'|'it'|'iw'|'ja'|'ko'|'lt'|'lv'|'mo'|'nl'|'nb'|'no'|'pl'|'pt'|'pt-PT'|'ro'|'ru'|'sk'|'sl'|'sr'|'sr-Latn'|'sv'|'ta'|'te'|'th'|'tl'|'tr'|'uk'|'vi'|'zh'|'zh-HK'|'zh-TW'; - - export type OutputMode = 'json' | 'html' | 'csv'; - - export type ScreenEmulationSettings = { - /** Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ - width: number; - /** Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ - height: number; - /** Overriding device scale factor value. 0 disables the override. */ - deviceScaleFactor: number; - /** Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. */ - mobile: boolean; - /** Whether screen emulation is disabled. If true, the other emulation settings are ignored. */ - disabled: boolean; - }; - - /** - * Options that are found in both the flags used by the Lighthouse module - * interface and the Config's `settings` object. - */ - interface SharedFlagsSettings { - /** The type(s) of report output to be produced. */ - output?: OutputMode|OutputMode[]; - /** The locale to use for the output. */ - locale?: Locale; - /** The maximum amount of time to wait for a page content render, in ms. If no content is rendered within this limit, the run is aborted with an error. */ - maxWaitForFcp?: number; - /** The maximum amount of time to wait for a page to load, in ms. */ - maxWaitForLoad?: number; - /** List of URL patterns to block. */ - blockedUrlPatterns?: string[] | null; - /** Comma-delimited list of trace categories to include. */ - additionalTraceCategories?: string | null; - /** Flag indicating the run should only audit. */ - auditMode?: boolean | string; - /** Flag indicating the run should only gather. */ - gatherMode?: boolean | string; - /** Flag indicating that the browser storage should not be reset for the audit. */ - disableStorageReset?: boolean; - - /** How Lighthouse should interpret this run in regards to scoring performance metrics and skipping mobile-only tests in desktop. Must be set even if throttling/emulation is being applied outside of Lighthouse. */ - formFactor?: 'mobile'|'desktop'; - /** Screen emulation properties (width, height, dpr, mobile viewport) to apply or an object of `{disabled: true}` if Lighthouse should avoid applying screen emulation. If either emulation is applied outside of Lighthouse, or it's being run on a mobile device, it typically should be set to disabled. For desktop, we recommend applying consistent desktop screen emulation. */ - screenEmulation?: Partial; - /** User Agent string to apply, `false` to not change the host's UA string, or `true` to use Lighthouse's default UA string. */ - emulatedUserAgent?: string | boolean; - - /** The method used to throttle the network. */ - throttlingMethod?: 'devtools'|'simulate'|'provided'; - /** The throttling config settings. */ - throttling?: ThrottlingSettings; - /** If present, the run should only conduct this list of audits. */ - onlyAudits?: string[] | null; - /** If present, the run should only conduct this list of categories. */ - onlyCategories?: string[] | null; - /** If present, the run should skip this list of audits. */ - skipAudits?: string[] | null; - /** List of extra HTTP Headers to include. */ - extraHeaders?: Crdp.Network.Headers | null; // See extraHeaders TODO in bin.js - /** How Lighthouse was run, e.g. from the Chrome extension or from the npm module */ - channel?: string - /** Precomputed lantern estimates to use instead of observed analysis. */ - precomputedLanternData?: PrecomputedLanternData | null; - /** The budget.json object for LightWallet. */ - budgets?: Array | null; - } - - /** - * Extends the flags in SharedFlagsSettings with flags used to configure the - * Lighthouse module but will not end up in the Config settings. - */ - export interface Flags extends SharedFlagsSettings { - /** The port to use for the debugging protocol, if manually connecting. */ - port?: number; - /** The hostname to use for the debugging protocol, if manually connecting. */ - hostname?: string; - /** The level of logging to enable. */ - logLevel?: 'silent'|'error'|'info'|'verbose'; - /** The path to the config JSON. */ - configPath?: string; - /** Run the specified plugins. */ - plugins?: string[]; - } - - /** - * Extends the flags accepted by the Lighthouse module with additional flags - * used just for controlling the CLI. - */ - export interface CliFlags extends Flags { - _: string[]; - chromeIgnoreDefaultFlags: boolean; - chromeFlags: string | string[]; - /** Output path for the generated results. */ - outputPath?: string; - /** Flag to save the trace contents and screenshots to disk. */ - saveAssets: boolean; - /** Flag to open the report immediately. */ - view: boolean; - /** Flag to enable error reporting. */ - enableErrorReporting?: boolean; - /** Flag to print a list of all audits + categories. */ - listAllAudits: boolean; - /** Flag to print a list of all required trace categories. */ - listTraceCategories: boolean; - /** A preset audit of selected audit categories to run. */ - preset?: 'experimental'|'perf'|'desktop'; - /** A flag to enable logLevel 'verbose'. */ - verbose: boolean; - /** A flag to enable logLevel 'silent'. */ - quiet: boolean; - /** A flag to print the normalized config for the given config and options, then exit. */ - printConfig: boolean; - /** Use the new Fraggle Rock navigation runner to gather CLI results. */ - fraggleRock: boolean; - /** Path to the file where precomputed lantern data should be read from. */ - precomputedLanternDataPath?: string; - /** Path to the file where precomputed lantern data should be written to. */ - lanternDataOutputPath?: string; - /** Path to the budget.json file for LightWallet. */ - budgetPath?: string | null; - - // The following are given defaults in cli-flags, so are not optional like in Flags or SharedFlagsSettings. - output: OutputMode[]; - port: number; - hostname: string; - } - - export interface RunnerResult { - lhr: LHResult; - report: string|string[]; - artifacts: Artifacts; - } - - export interface ReportCategory { - name: string; - description: string; - audits: ReportAudit[]; - } - - export interface ReportAudit { - id: string; - weight: number; - group: string; - } - - /** - * A record of DevTools Debugging Protocol events. - */ - export type DevtoolsLog = Array; - - export interface Trace { - traceEvents: TraceEvent[]; - metadata?: { - 'cpu-family'?: number; - }; - [futureProps: string]: any; - } - - /** The type of the Profile & ProfileChunk event in Chromium traces. Note that this is subtly different from Crdp.Profiler.Profile. */ - export interface TraceCpuProfile { - nodes?: Array<{id: number, callFrame: {functionName: string, url?: string}, parent?: number}> - samples?: Array - timeDeltas?: Array - } - - /** - * @see https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview - */ - export interface TraceEvent { - name: string; - cat: string; - args: { - fileName?: string; - snapshot?: string; - sync_id?: string; - beginData?: { - frame?: string; - startLine?: number; - url?: string; - }; - data?: { - frame?: string; - isLoadingMainFrame?: boolean; - documentLoaderURL?: string; - frames?: { - frame: string; - parent?: string; - processId?: number; - }[]; - page?: string; - readyState?: number; - requestId?: string; - startTime?: number; - timeDeltas?: TraceCpuProfile['timeDeltas']; - cpuProfile?: TraceCpuProfile; - callFrame?: Required['nodes'][0]['callFrame'] - /** Marker for each synthetic CPU profiler event for the range of _potential_ ts values. */ - _syntheticProfilerRange?: { - earliestPossibleTimestamp: number - latestPossibleTimestamp: number - } - stackTrace?: { - url: string - }[]; - styleSheetUrl?: string; - timerId?: string; - url?: string; - is_main_frame?: boolean; - cumulative_score?: number; - id?: string; - nodeId?: number; - impacted_nodes?: Array<{ - node_id: number, - old_rect?: Array, - new_rect?: Array, - }>; - score?: number; - weighted_score_delta?: number; - had_recent_input?: boolean; - compositeFailed?: number; - unsupportedProperties?: string[]; - size?: number; - }; - frame?: string; - name?: string; - labels?: string; - }; - pid: number; - tid: number; - /** Timestamp of the event in microseconds. */ - ts: number; - dur: number; - ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; - s?: 't'; - id?: string; - id2?: { - local?: string; - }; - } - - export interface DevToolsJsonTarget { - description: string; - devtoolsFrontendUrl: string; - id: string; - title: string; - type: string; - url: string; - webSocketDebuggerUrl: string; - } - } +/** Simulation settings that control the amount of network & cpu throttling in the run. */ +export interface ThrottlingSettings { + /** The round trip time in milliseconds. */ + rttMs?: number; + /** The network throughput in kilobits per second. */ + throughputKbps?: number; + // devtools settings + /** The network request latency in milliseconds. */ + requestLatencyMs?: number; + /** The network download throughput in kilobits per second. */ + downloadThroughputKbps?: number; + /** The network upload throughput in kilobits per second. */ + uploadThroughputKbps?: number; + // used by both + /** The amount of slowdown applied to the cpu (1/). */ + cpuSlowdownMultiplier?: number +} - interface Window { - // Cached native functions/objects for use in case the page overwrites them. - // See: `executionContext.cacheNativesOnNewDocument`. - __nativePromise: PromiseConstructor; - __nativePerformance: Performance; - __nativeURL: typeof URL; - __ElementMatches: Element['matches']; +export interface PrecomputedLanternData { + additionalRttByOrigin: {[origin: string]: number}; + serverResponseTimeByOrigin: {[origin: string]: number}; +} - /** Used for monitoring long tasks in the test page. */ - ____lastLongTask?: number; +export type OutputMode = 'json' | 'html' | 'csv'; + +export type ScreenEmulationSettings = { + /** Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ + width: number; + /** Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ + height: number; + /** Overriding device scale factor value. 0 disables the override. */ + deviceScaleFactor: number; + /** Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. */ + mobile: boolean; + /** Whether screen emulation is disabled. If true, the other emulation settings are ignored. */ + disabled: boolean; +}; - /** Used by FullPageScreenshot gatherer. */ - __lighthouseNodesDontTouchOrAllVarianceGoesAway: Map; - __lighthouseExecutionContextId?: number; +/** + * Options that are found in both the flags used by the Lighthouse module + * interface and the Config's `settings` object. + */ +export interface SharedFlagsSettings { + /** The type(s) of report output to be produced. */ + output?: OutputMode|OutputMode[]; + /** The locale to use for the output. */ + locale?: Locale; + /** The maximum amount of time to wait for a page content render, in ms. If no content is rendered within this limit, the run is aborted with an error. */ + maxWaitForFcp?: number; + /** The maximum amount of time to wait for a page to load, in ms. */ + maxWaitForLoad?: number; + /** List of URL patterns to block. */ + blockedUrlPatterns?: string[] | null; + /** Comma-delimited list of trace categories to include. */ + additionalTraceCategories?: string | null; + /** Flag indicating the run should only audit. */ + auditMode?: boolean | string; + /** Flag indicating the run should only gather. */ + gatherMode?: boolean | string; + /** Flag indicating that the browser storage should not be reset for the audit. */ + disableStorageReset?: boolean; + + /** How Lighthouse should interpret this run in regards to scoring performance metrics and skipping mobile-only tests in desktop. Must be set even if throttling/emulation is being applied outside of Lighthouse. */ + formFactor?: 'mobile'|'desktop'; + /** Screen emulation properties (width, height, dpr, mobile viewport) to apply or an object of `{disabled: true}` if Lighthouse should avoid applying screen emulation. If either emulation is applied outside of Lighthouse, or it's being run on a mobile device, it typically should be set to disabled. For desktop, we recommend applying consistent desktop screen emulation. */ + screenEmulation?: Partial; + /** User Agent string to apply, `false` to not change the host's UA string, or `true` to use Lighthouse's default UA string. */ + emulatedUserAgent?: string | boolean; + + /** The method used to throttle the network. */ + throttlingMethod?: 'devtools'|'simulate'|'provided'; + /** The throttling config settings. */ + throttling?: ThrottlingSettings; + /** If present, the run should only conduct this list of audits. */ + onlyAudits?: string[] | null; + /** If present, the run should only conduct this list of categories. */ + onlyCategories?: string[] | null; + /** If present, the run should skip this list of audits. */ + skipAudits?: string[] | null; + /** List of extra HTTP Headers to include. */ + extraHeaders?: Crdp.Network.Headers | null; // See extraHeaders TODO in bin.js + /** How Lighthouse was run, e.g. from the Chrome extension or from the npm module */ + channel?: string + /** Precomputed lantern estimates to use instead of observed analysis. */ + precomputedLanternData?: PrecomputedLanternData | null; + /** The budget.json object for LightWallet. */ + budgets?: Array | null; +} - // Not defined in tsc yet: https://github.com/microsoft/TypeScript/issues/40807 - requestIdleCallback(callback: (deadline: {didTimeout: boolean, timeRemaining: () => DOMHighResTimeStamp}) => void, options?: {timeout: number}): number; - } +/** + * Extends the flags in SharedFlagsSettings with flags used to configure the + * Lighthouse module but will not end up in the Config settings. + */ +export interface Flags extends SharedFlagsSettings { + /** The port to use for the debugging protocol, if manually connecting. */ + port?: number; + /** The hostname to use for the debugging protocol, if manually connecting. */ + hostname?: string; + /** The level of logging to enable. */ + logLevel?: 'silent'|'error'|'info'|'verbose'; + /** The path to the config JSON. */ + configPath?: string; + /** Run the specified plugins. */ + plugins?: string[]; +} - // Stricter querySelector/querySelectorAll using typed-query-selector. - interface ParentNode { - querySelector(selector: S): QuerySelectorParse | null; - querySelectorAll(selector: S): NodeListOf>; - } +/** + * Extends the flags accepted by the Lighthouse module with additional flags + * used just for controlling the CLI. + */ +export interface CliFlags extends Flags { + _: string[]; + chromeIgnoreDefaultFlags: boolean; + chromeFlags: string | string[]; + /** Output path for the generated results. */ + outputPath?: string; + /** Flag to save the trace contents and screenshots to disk. */ + saveAssets: boolean; + /** Flag to open the report immediately. */ + view: boolean; + /** Flag to enable error reporting. */ + enableErrorReporting?: boolean; + /** Flag to print a list of all audits + categories. */ + listAllAudits: boolean; + /** Flag to print a list of all required trace categories. */ + listTraceCategories: boolean; + /** A preset audit of selected audit categories to run. */ + preset?: 'experimental'|'perf'|'desktop'; + /** A flag to enable logLevel 'verbose'. */ + verbose: boolean; + /** A flag to enable logLevel 'silent'. */ + quiet: boolean; + /** A flag to print the normalized config for the given config and options, then exit. */ + printConfig: boolean; + /** Use the new Fraggle Rock navigation runner to gather CLI results. */ + fraggleRock: boolean; + /** Path to the file where precomputed lantern data should be read from. */ + precomputedLanternDataPath?: string; + /** Path to the file where precomputed lantern data should be written to. */ + lanternDataOutputPath?: string; + /** Path to the budget.json file for LightWallet. */ + budgetPath?: string | null; + + // The following are given defaults in cli-flags, so are not optional like in Flags or SharedFlagsSettings. + output: OutputMode[]; + port: number; + hostname: string; +} + +export interface RunnerResult { + lhr: LHResult; + report: string|string[]; + artifacts: Artifacts; +} + +export interface DevToolsJsonTarget { + description: string; + devtoolsFrontendUrl: string; + id: string; + title: string; + type: string; + url: string; + webSocketDebuggerUrl: string; } diff --git a/types/gatherer.d.ts b/types/gatherer.d.ts index 05c30b2f85e2..8de6e370a774 100644 --- a/types/gatherer.d.ts +++ b/types/gatherer.d.ts @@ -16,6 +16,7 @@ import {Artifacts, BaseArtifacts, GathererArtifacts} from './artifacts'; import Config from './config'; import {IcuMessage} from './i18n'; import Protocol from './protocol'; +import {Trace, DevtoolsLog} from './artifacts'; declare module Gatherer { /** The Lighthouse wrapper around a raw CDP session. */ @@ -69,8 +70,8 @@ declare module Gatherer { interface LoadData { networkRecords: Array; - devtoolsLog: LH.DevtoolsLog; - trace?: LH.Trace; + devtoolsLog: DevtoolsLog; + trace?: Trace; } type PhaseResultNonPromise = void | GathererArtifacts[keyof GathererArtifacts]; diff --git a/types/global-lh.d.ts b/types/global-lh.d.ts index ab7304a8dc72..7409e02c1c4c 100644 --- a/types/global-lh.d.ts +++ b/types/global-lh.d.ts @@ -9,6 +9,9 @@ import * as Artifacts_ from './artifacts'; import Audit_ from './audit'; import Budget_ from './budget'; import Config_ from './config'; +import _Crdp from 'devtools-protocol/types/protocol'; +import _CrdpMappings from 'devtools-protocol/types/protocol-mapping'; +import * as Externs from './externs'; import Gatherer_ from './gatherer'; import * as I18n from './i18n'; import LHError = require('../lighthouse-core/lib/lh-error.js'); @@ -29,15 +32,35 @@ declare global { export import FRArtifacts = Artifacts_.FRArtifacts; export import FRBaseArtifacts = Artifacts_.FRBaseArtifacts; export import GathererArtifacts = Artifacts_.GathererArtifacts; + export import DevtoolsLog = Artifacts_.DevtoolsLog; + export import Trace = Artifacts_.Trace; + export import TraceCpuProfile = Artifacts_.TraceCpuProfile; + export import TraceEvent = Artifacts_.TraceEvent; export import Audit = Audit_; export import Budget = Budget_; export import Config = Config_; + export import Crdp = _Crdp; + export import CrdpEvents = _CrdpMappings.Events; + export import CrdpCommands = _CrdpMappings.Commands; + + // externs.d.ts + export import ThrottlingSettings = Externs.ThrottlingSettings; + export import ScreenEmulationSettings = Externs.ScreenEmulationSettings; + export import SharedFlagsSettings = Externs.SharedFlagsSettings; + export import OutputMode = Externs.OutputMode; + export import PrecomputedLanternData = Externs.PrecomputedLanternData; + export import Flags = Externs.Flags; + export import CliFlags = Externs.CliFlags; + export import RunnerResult = Externs.RunnerResult; + export import DevToolsJsonTarget = Externs.DevToolsJsonTarget; + export import Gatherer = Gatherer_; export import LighthouseError = LHError; export import Result = LHResult; // i18n.d.ts. + export import Locale = I18n.Locale; export import IcuMessage = I18n.IcuMessage; export import RawIcu = I18n.RawIcu; export import FormattedIcu = I18n.FormattedIcu; diff --git a/types/i18n.d.ts b/types/i18n.d.ts index 261a254d34a3..e1606f147c1e 100644 --- a/types/i18n.d.ts +++ b/types/i18n.d.ts @@ -6,6 +6,8 @@ import {Util} from '../report/renderer/util.js'; +export type Locale = 'en-US'|'en'|'en-AU'|'en-GB'|'en-IE'|'en-SG'|'en-ZA'|'en-IN'|'ar-XB'|'ar'|'bg'|'ca'|'cs'|'da'|'de'|'el'|'en-XA'|'en-XL'|'es'|'es-419'|'es-AR'|'es-BO'|'es-BR'|'es-BZ'|'es-CL'|'es-CO'|'es-CR'|'es-CU'|'es-DO'|'es-EC'|'es-GT'|'es-HN'|'es-MX'|'es-NI'|'es-PA'|'es-PE'|'es-PR'|'es-PY'|'es-SV'|'es-US'|'es-UY'|'es-VE'|'fi'|'fil'|'fr'|'he'|'hi'|'hr'|'hu'|'gsw'|'id'|'in'|'it'|'iw'|'ja'|'ko'|'lt'|'lv'|'mo'|'nl'|'nb'|'no'|'pl'|'pt'|'pt-PT'|'ro'|'ru'|'sk'|'sl'|'sr'|'sr-Latn'|'sv'|'ta'|'te'|'th'|'tl'|'tr'|'uk'|'vi'|'zh'|'zh-HK'|'zh-TW'; + export type IcuMessage = { // NOTE: `i18nId` rather than just `id` to make tsc typing easier (vs type branding which won't survive JSON roundtrip). /** The id locating this message in the locale message json files. */ diff --git a/types/treemap.d.ts b/types/treemap.d.ts index 29ee1ecca59d..f892325012e5 100644 --- a/types/treemap.d.ts +++ b/types/treemap.d.ts @@ -5,6 +5,7 @@ */ import Audit from './audit'; +import {Locale} from './i18n'; declare module Treemap { interface Options { @@ -15,7 +16,7 @@ declare module Treemap { 'script-treemap-data': Audit.Result; }; configSettings: { - locale: LH.Locale; + locale: Locale; } } }