@ohos-perf/core 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4457,6 +4457,178 @@ declare function executeAction(device: ActionDevice, app: string, action: Scenar
4457
4457
  output?: string;
4458
4458
  }>;
4459
4459
 
4460
+ /**
4461
+ * Autonomous UI exploration, the deterministic replacement for HapRay's
4462
+ * `haptest` (parity row 4).
4463
+ *
4464
+ * The shape is HapRay's: dump the screen, hash it, tap a clickable element
4465
+ * nobody has tapped on this screen yet, repeat until the step budget runs out.
4466
+ * What changes is everything that made its output unusable as evidence.
4467
+ *
4468
+ * - **Every choice is a total order.** HapRay's `random` strategy walks
4469
+ * whatever the RNG returns, so two runs of the same build explore different
4470
+ * screens and neither can be reproduced. Here `random` is a seeded
4471
+ * permutation: reproducible from the recorded seed, and different from the
4472
+ * document order when you want to shake a walk out of a local minimum.
4473
+ * - **A tap that changed nothing is recorded as such.** HapRay counts every
4474
+ * tap as a step forward. `no_change` separates "the screen moved" from "the
4475
+ * element was dead", so coverage is the number of distinct states reached
4476
+ * rather than the number of taps spent.
4477
+ * - **Visited is per screen.** A node id is only unique within one dump; two
4478
+ * screens can both have `button1`. Remembering a tap globally would skip the
4479
+ * second screen's element and report a screen as covered that never was.
4480
+ * - **An unparseable rect is skipped, not tapped at (0,0).** Tapping the
4481
+ * origin is a gesture on whatever happens to be in the corner.
4482
+ *
4483
+ * The walk does not analyze and does not collect: it is the "get somewhere
4484
+ * interesting" half of a scenario, and the scene it leaves behind is what
4485
+ * `analyze`, `report` and `query` consume.
4486
+ */
4487
+
4488
+ /** The three orders HapRay offers, kept under their names. */
4489
+ type ExplorationStrategy = 'depth_first' | 'breadth_first' | 'random';
4490
+ /** What exploration needs from a device. `Device` satisfies it structurally. */
4491
+ interface ExplorationDevice {
4492
+ /** The flattened on-screen tree, as `flattenUiTree` returns it. */
4493
+ dump(): Promise<readonly UiNode[]>;
4494
+ /** Tap the centre of `bounds`. Throws when the device refuses the gesture. */
4495
+ tap(bounds: string): Promise<void>;
4496
+ }
4497
+ interface ExplorationState {
4498
+ readonly tree: readonly UiNode[];
4499
+ /** Identities already tapped *on this tree's screen*. */
4500
+ readonly visited: ReadonlySet<string>;
4501
+ readonly strategy: ExplorationStrategy;
4502
+ /** Required by `random`; ignored by the ordered strategies. */
4503
+ readonly seed?: number;
4504
+ }
4505
+ /** The next tap, or `undefined` when this screen has nothing left to offer. */
4506
+ interface ExplorationAction {
4507
+ readonly kind: 'tap';
4508
+ readonly nodeId: string;
4509
+ readonly bounds: string;
4510
+ }
4511
+ /** Whether a tap moved the screen. */
4512
+ type ExplorationOutcome = 'navigated' | 'no_change';
4513
+ /** One tap, with the state hash either side of it. */
4514
+ interface ExplorationStep {
4515
+ readonly index: number;
4516
+ readonly nodeId: string;
4517
+ readonly bounds: string;
4518
+ /** The screen hash before the tap. */
4519
+ readonly before: string;
4520
+ /** The screen hash after it; equal to `before` means `no_change`. */
4521
+ readonly after: string;
4522
+ readonly outcome: ExplorationOutcome;
4523
+ }
4524
+ interface ExplorationResult {
4525
+ readonly strategy: ExplorationStrategy;
4526
+ /** Present for `random`; the value is the one the walk actually used. */
4527
+ readonly seed?: number;
4528
+ readonly steps: readonly ExplorationStep[];
4529
+ /** Distinct screen hashes reached, including the one it started on. */
4530
+ readonly statesReached: number;
4531
+ /** True when it stopped because this screen had no unvisited clickable. */
4532
+ readonly exhausted: boolean;
4533
+ }
4534
+ interface ExplorationOptions {
4535
+ /** Hard cap on taps. HapRay's default is 30. */
4536
+ readonly maxSteps: number;
4537
+ readonly strategy: ExplorationStrategy;
4538
+ /** Makes `random` reproducible. Defaults to 0, never to the clock. */
4539
+ readonly seed?: number;
4540
+ }
4541
+ /** A short hex digest of a screen, stable across runs and hosts. */
4542
+ declare function hashTree(tree: readonly UiNode[]): string;
4543
+ /**
4544
+ * The next tap on one screen.
4545
+ *
4546
+ * Returns `undefined` when every enabled, parseable clickable has been tapped
4547
+ * here — the signal that this screen is done, not that the walk is over.
4548
+ */
4549
+ declare function planNextAction(state: ExplorationState): ExplorationAction | undefined;
4550
+ /**
4551
+ * Walk the app until the step budget runs out or the screen is exhausted.
4552
+ *
4553
+ * `statesReached` counts distinct hashes rather than taps, so a walk that
4554
+ * bounced between two screens reports two states however many steps it spent.
4555
+ * The returned steps carry the hash either side of each tap: a saved run can be
4556
+ * re-read without the device, and two runs that disagree can be compared by
4557
+ * hash instead of by prose.
4558
+ */
4559
+ declare function explore(device: ExplorationDevice, options: ExplorationOptions): Promise<ExplorationResult>;
4560
+ /**
4561
+ * What {@link explorationDevice} needs from its caller.
4562
+ *
4563
+ * A structural subset of `Device`, so a real device satisfies it and a test can
4564
+ * supply a script. `now` and `sleep` are injected for the same reason the
4565
+ * scenario runner takes a clock: a settle that waited in real time would make
4566
+ * the test slow and the walk untestable.
4567
+ */
4568
+ interface ExplorationHost {
4569
+ /** The flattened on-screen tree, as `Device.uiTree` returns it. */
4570
+ dump(): Promise<readonly UiNode[]>;
4571
+ /** One tap at the centre of `bounds`. */
4572
+ tap(bounds: string): Promise<void>;
4573
+ now(): number;
4574
+ sleep(ms: number): Promise<void>;
4575
+ }
4576
+ interface ExplorationDeviceOptions {
4577
+ /**
4578
+ * How long a tap may take to change the screen before the walk calls it
4579
+ * dead. HapRay spends a fixed 5 s on every action; 5 s is a ceiling here,
4580
+ * paid in full only by an element that does nothing.
4581
+ */
4582
+ readonly settleMs?: number;
4583
+ /** How often to look while settling. */
4584
+ readonly pollMs?: number;
4585
+ }
4586
+ /**
4587
+ * Turn a host into the device {@link explore} drives.
4588
+ *
4589
+ * The one thing this adds is the settle: after each tap it re-dumps until the
4590
+ * screen changes or `settleMs` runs out, and caches the settled tree. Without
4591
+ * it a dump taken 20 ms after a tap catches the outgoing screen, the walk
4592
+ * hashes a screen it is about to leave, and the next tap aims at a node that
4593
+ * no longer exists — which is why HapRay waits a flat 5 s and calls it a
4594
+ * collection window. Polling pays that 5 s only when the element is dead.
4595
+ *
4596
+ * The cached tree is the one `explore` reads next, so a settle is never paid
4597
+ * for twice.
4598
+ */
4599
+ declare function explorationDevice(host: ExplorationHost, options?: ExplorationDeviceOptions): ExplorationDevice;
4600
+ /** The device surface {@link deviceExplorationHost} needs. `Device` satisfies it. */
4601
+ interface ExplorationTargetDevice {
4602
+ readonly id: string;
4603
+ /** A fresh flattened dump, as `Device.uiTree` returns. */
4604
+ uiTree(): Promise<readonly UiNode[]>;
4605
+ gesture(g: Gesture): Promise<GestureResult>;
4606
+ }
4607
+ /** What a settle needs from the host clock; injectable so tests never sleep. */
4608
+ interface ExplorationClock {
4609
+ now(): number;
4610
+ sleep(ms: number): Promise<void>;
4611
+ }
4612
+ /**
4613
+ * Adapt a real device to {@link ExplorationHost}.
4614
+ *
4615
+ * Two jobs, both of them refusals the exploration layer cannot make itself.
4616
+ *
4617
+ * - **Bounds become a point here.** The walk deals only in the `bounds` string
4618
+ * it read, so the conversion to a click has one home. A string that does not
4619
+ * parse is refused: HapRay taps (0,0) in that case, which is a gesture on
4620
+ * whatever occupies the corner.
4621
+ * - **The target must still be on screen.** Between the dump and the tap a
4622
+ * screen can move; clicking the old coordinates then hits whatever slid into
4623
+ * place. The tap re-dumps and refuses when no node carries those bounds.
4624
+ *
4625
+ * Acceptance is the `No Error` marker, the same rule every other gesture path
4626
+ * enforces — `uitest uiInput` exits 0 even when it refuses the gesture.
4627
+ */
4628
+ declare function deviceExplorationHost(device: ExplorationTargetDevice, options?: ExplorationDeviceOptions & {
4629
+ clock?: ExplorationClock;
4630
+ }): ExplorationDevice;
4631
+
4460
4632
  /**
4461
4633
  * The scenario runner: ordered steps, one capture window each.
4462
4634
  *
@@ -6159,4 +6331,4 @@ interface FlamegraphPageInput {
6159
6331
  */
6160
6332
  declare function renderFlamegraphHtml(input: FlamegraphPageInput): string;
6161
6333
 
6162
- export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EXCLUDE_PATTERNS, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, IGNORED_ATTRIBUTES, type ImageComparison, IngestError, InstantQuery, type InventoryFile, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationPotential, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyseAnimations, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyNativePath, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evidence, executeAction, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hiperfRecordCommand, ingestScene, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, pairNativeMemory, paritySummary, parseBounds, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, queryDefinitions, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTrendHtml, renderTrendJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
6334
+ export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EXCLUDE_PATTERNS, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, type ExplorationAction, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStrategy, type ExplorationTargetDevice, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, IGNORED_ATTRIBUTES, type ImageComparison, IngestError, InstantQuery, type InventoryFile, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationPotential, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyseAnimations, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyNativePath, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, deviceExplorationHost, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evidence, executeAction, explorationDevice, explore, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hashTree, hiperfRecordCommand, ingestScene, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, pairNativeMemory, paritySummary, parseBounds, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTrendHtml, renderTrendJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
package/dist/index.js CHANGED
@@ -6172,8 +6172,8 @@ var PARITY_ROWS = [
6172
6172
  {
6173
6173
  row: 4,
6174
6174
  name: "HapTest autonomous exploration (`haptest`)",
6175
- status: "out",
6176
- reason: "HapRay's own implementation is nondeterministic and has no success verification; the agent skill drives selectors and drill-down queries deterministically instead."
6175
+ status: "ported",
6176
+ reason: ""
6177
6177
  },
6178
6178
  {
6179
6179
  row: 5,
@@ -7877,6 +7877,222 @@ function swipeInside(rect, direction, travel) {
7877
7877
  }
7878
7878
  }
7879
7879
 
7880
+ // src/scenario/explore.ts
7881
+ import { createHash as createHash2 } from "node:crypto";
7882
+ var DEFAULT_SEED = 0;
7883
+ var DIGEST_CHARS = 16;
7884
+ function canonical(tree) {
7885
+ const line = (node) => [
7886
+ node.depth,
7887
+ node.type,
7888
+ node.bundleName,
7889
+ node.abilityName,
7890
+ node.text,
7891
+ node.id,
7892
+ node.bounds,
7893
+ node.clickable ? "1" : "0",
7894
+ node.enabled ? "1" : "0",
7895
+ node.scrollable ? "1" : "0"
7896
+ ].map((field) => `${String(field).length}:${String(field)}`).join("");
7897
+ return tree.map(line).join("");
7898
+ }
7899
+ function hashTree(tree) {
7900
+ return createHash2("sha256").update(canonical(tree)).digest("hex").slice(0, DIGEST_CHARS);
7901
+ }
7902
+ function mulberry32(seed) {
7903
+ let state = seed >>> 0;
7904
+ return () => {
7905
+ state = state + 1831565813 >>> 0;
7906
+ let t = state;
7907
+ t = Math.imul(t ^ t >>> 15, t | 1);
7908
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
7909
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
7910
+ };
7911
+ }
7912
+ function shuffled(items, seed) {
7913
+ const out = [...items];
7914
+ const next = mulberry32(seed);
7915
+ for (let index = out.length - 1; index > 0; index -= 1) {
7916
+ const pick = Math.floor(next() * (index + 1));
7917
+ const held = out[index];
7918
+ out[index] = out[pick];
7919
+ out[pick] = held;
7920
+ }
7921
+ return out;
7922
+ }
7923
+ function identities(tree) {
7924
+ const seen = /* @__PURE__ */ new Map();
7925
+ const out = /* @__PURE__ */ new Map();
7926
+ for (const node of tree) {
7927
+ const base = node.id !== "" ? node.id : `at:${node.type}|${node.text}|${node.bounds}`;
7928
+ const occurrence = (seen.get(base) ?? 0) + 1;
7929
+ seen.set(base, occurrence);
7930
+ out.set(node, occurrence === 1 ? base : `${base}#${occurrence}`);
7931
+ }
7932
+ return out;
7933
+ }
7934
+ function rectOf(node) {
7935
+ return node.boundsRect ?? parseBounds(node.bounds);
7936
+ }
7937
+ function planNextAction(state) {
7938
+ const ids = identities(state.tree);
7939
+ const candidates = state.tree.filter(
7940
+ (node2) => node2.clickable && node2.enabled && rectOf(node2) !== void 0 && !state.visited.has(ids.get(node2))
7941
+ );
7942
+ if (candidates.length === 0) return void 0;
7943
+ let ordered2;
7944
+ switch (state.strategy) {
7945
+ case "depth_first":
7946
+ ordered2 = candidates;
7947
+ break;
7948
+ case "breadth_first":
7949
+ ordered2 = [...candidates].sort((a, b) => a.depth - b.depth);
7950
+ break;
7951
+ case "random":
7952
+ ordered2 = shuffled(candidates, state.seed ?? DEFAULT_SEED);
7953
+ break;
7954
+ }
7955
+ const node = ordered2[0];
7956
+ return { kind: "tap", nodeId: ids.get(node), bounds: node.bounds };
7957
+ }
7958
+ async function explore(device, options) {
7959
+ if (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1) {
7960
+ throw new Error(
7961
+ `explore: maxSteps must be a positive integer (got ${String(options.maxSteps)})`
7962
+ );
7963
+ }
7964
+ const seed = options.strategy === "random" ? options.seed ?? DEFAULT_SEED : void 0;
7965
+ const steps = [];
7966
+ const states = /* @__PURE__ */ new Set();
7967
+ const visitedByScreen = /* @__PURE__ */ new Map();
7968
+ let tree = await device.dump();
7969
+ let hash = hashTree(tree);
7970
+ states.add(hash);
7971
+ let exhausted = false;
7972
+ while (steps.length < options.maxSteps) {
7973
+ const visited = visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set();
7974
+ const action = planNextAction({
7975
+ tree,
7976
+ visited,
7977
+ strategy: options.strategy,
7978
+ ...seed === void 0 ? {} : { seed }
7979
+ });
7980
+ if (action === void 0) {
7981
+ exhausted = true;
7982
+ break;
7983
+ }
7984
+ visited.add(action.nodeId);
7985
+ visitedByScreen.set(hash, visited);
7986
+ await device.tap(action.bounds);
7987
+ tree = await device.dump();
7988
+ const after = hashTree(tree);
7989
+ states.add(after);
7990
+ steps.push({
7991
+ index: steps.length,
7992
+ nodeId: action.nodeId,
7993
+ bounds: action.bounds,
7994
+ before: hash,
7995
+ after,
7996
+ outcome: after === hash ? "no_change" : "navigated"
7997
+ });
7998
+ hash = after;
7999
+ }
8000
+ return {
8001
+ strategy: options.strategy,
8002
+ ...seed === void 0 ? {} : { seed },
8003
+ steps,
8004
+ statesReached: states.size,
8005
+ exhausted
8006
+ };
8007
+ }
8008
+ var DEFAULT_SETTLE_MS = 5e3;
8009
+ var DEFAULT_POLL_MS = 250;
8010
+ function explorationDevice(host, options = {}) {
8011
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
8012
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
8013
+ if (!Number.isSafeInteger(pollMs) || pollMs < 1) {
8014
+ throw new Error(`explorationDevice: pollMs must be a positive integer (got ${String(pollMs)})`);
8015
+ }
8016
+ if (!Number.isSafeInteger(settleMs) || settleMs < 0) {
8017
+ throw new Error(`explorationDevice: settleMs must be a non-negative integer (got ${String(settleMs)})`);
8018
+ }
8019
+ let settled;
8020
+ const read = async () => {
8021
+ if (settled === void 0) settled = await host.dump();
8022
+ return settled;
8023
+ };
8024
+ return {
8025
+ dump: read,
8026
+ async tap(bounds) {
8027
+ const before = hashTree(await read());
8028
+ await host.tap(bounds);
8029
+ const deadline = host.now() + settleMs;
8030
+ for (; ; ) {
8031
+ const next = await host.dump();
8032
+ if (hashTree(next) !== before) {
8033
+ settled = next;
8034
+ return;
8035
+ }
8036
+ const remaining = deadline - host.now();
8037
+ if (remaining <= 0) {
8038
+ settled = next;
8039
+ return;
8040
+ }
8041
+ await host.sleep(Math.min(pollMs, remaining));
8042
+ }
8043
+ }
8044
+ };
8045
+ }
8046
+ var ACCEPTED_MARKER3 = "No Error";
8047
+ function deviceExplorationHost(device, options = {}) {
8048
+ const clock = options.clock ?? {
8049
+ now: () => Date.now(),
8050
+ sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms))
8051
+ };
8052
+ const settleOptions = {
8053
+ ...options.settleMs === void 0 ? {} : { settleMs: options.settleMs },
8054
+ ...options.pollMs === void 0 ? {} : { pollMs: options.pollMs }
8055
+ };
8056
+ return explorationDevice(
8057
+ {
8058
+ dump: () => device.uiTree(),
8059
+ tap: async (bounds) => {
8060
+ const point = centreOfBounds(bounds);
8061
+ const tree = await device.uiTree();
8062
+ if (!tree.some((candidate) => candidate.bounds === bounds)) {
8063
+ throw new OhosPerfError(
8064
+ `exploration: no node on the current screen carries these bounds ${JSON.stringify(bounds)}; the target is not on the screen any more`,
8065
+ { code: "SCENARIO_EXPLORE_STALE" }
8066
+ );
8067
+ }
8068
+ const result = await device.gesture({ action: "click", x: point.x, y: point.y });
8069
+ if (!result.output.includes(ACCEPTED_MARKER3)) {
8070
+ throw new OhosPerfError(
8071
+ `exploration: uitest uiInput click did not report "${ACCEPTED_MARKER3}": ${result.output === "" ? "(no output)" : result.output}`,
8072
+ { code: "SCENARIO_ACTION_FAILED" }
8073
+ );
8074
+ }
8075
+ },
8076
+ now: () => clock.now(),
8077
+ sleep: (ms) => clock.sleep(ms)
8078
+ },
8079
+ settleOptions
8080
+ );
8081
+ }
8082
+ function centreOfBounds(bounds) {
8083
+ const rect = parseBounds(bounds);
8084
+ if (rect === void 0) {
8085
+ throw new OhosPerfError(
8086
+ `exploration: ${JSON.stringify(bounds)} is not a "[l,t][r,b]" bounds string; it has no centre to tap`,
8087
+ { code: "SCENARIO_EXPLORE_STALE" }
8088
+ );
8089
+ }
8090
+ return {
8091
+ x: Math.round((rect.left + rect.right) / 2),
8092
+ y: Math.round((rect.top + rect.bottom) / 2)
8093
+ };
8094
+ }
8095
+
7880
8096
  // src/scenario/runner.ts
7881
8097
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
7882
8098
  import { join as join9 } from "node:path";
@@ -18018,7 +18234,7 @@ var TECH_RULES = [
18018
18234
  ];
18019
18235
 
18020
18236
  // src/hap/analyze.ts
18021
- import { createHash as createHash2 } from "node:crypto";
18237
+ import { createHash as createHash3 } from "node:crypto";
18022
18238
  var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
18023
18239
  var LARGEST_COUNT = 10;
18024
18240
  var EXPLAIN_PATHS = 5;
@@ -18026,7 +18242,7 @@ function byString6(a, b) {
18026
18242
  return a < b ? -1 : a > b ? 1 : 0;
18027
18243
  }
18028
18244
  function sha256(bytes) {
18029
- return createHash2("sha256").update(bytes).digest("hex");
18245
+ return createHash3("sha256").update(bytes).digest("hex");
18030
18246
  }
18031
18247
  function readPackage(archive) {
18032
18248
  const empty = { bundleName: "", versionName: "", versionCode: 0, appName: "" };
@@ -18590,6 +18806,7 @@ export {
18590
18806
  cropRegion,
18591
18807
  decodePng,
18592
18808
  defaultAnalyzers,
18809
+ deviceExplorationHost,
18593
18810
  dhash,
18594
18811
  diffTrees,
18595
18812
  discoverCases,
@@ -18597,11 +18814,14 @@ export {
18597
18814
  escapeHtml,
18598
18815
  evidence,
18599
18816
  executeAction,
18817
+ explorationDevice,
18818
+ explore,
18600
18819
  filterEmptyFrames,
18601
18820
  flattenUiTree,
18602
18821
  ftracePlugin,
18603
18822
  gpuPlugin,
18604
18823
  hapSection,
18824
+ hashTree,
18605
18825
  hiperfRecordCommand,
18606
18826
  ingestScene,
18607
18827
  isUnresolvedSymbol,
@@ -18632,6 +18852,7 @@ export {
18632
18852
  parseScenario,
18633
18853
  parseSelector,
18634
18854
  parseSmapsRollup,
18855
+ planNextAction,
18635
18856
  queryDefinitions,
18636
18857
  readHidumperCapture,
18637
18858
  readHilogText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohos-perf/core",
3
- "version": "0.17.2",
3
+ "version": "0.18.0",
4
4
  "description": "HarmonyOS performance analysis: capability probing, nine collectors, trace ingest, typed queries, twenty analyzers with provenance and fidelity, reports and a scenario runner",
5
5
  "keywords": [
6
6
  "harmonyos",