@ohos-perf/core 0.14.0 → 0.16.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +397 -178
  2. package/dist/index.js +407 -27
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -2127,6 +2127,106 @@ declare function nodeIdentity(node: UiNode): string;
2127
2127
  */
2128
2128
  declare function diffTrees(before: readonly UiNode[], after: readonly UiNode[]): UiTreeDiff;
2129
2129
 
2130
+ /**
2131
+ * Animation labelling for a start/end capture pair (HapRay parity row 31).
2132
+ *
2133
+ * Ported from `ui_detector/image_comparator.py` and the label bands in
2134
+ * `analyze/ui_analyzer.py`: crop a region from both screenshots, compare their
2135
+ * dHashes, and call the region an animation when the similarity falls under
2136
+ * 85%. The bands are HapRay's — `major_change` under 50, `moderate_change`
2137
+ * under 70, `minor_change` under 85 — and are kept so a reader who knows
2138
+ * HapRay's numbers reads the same ones here.
2139
+ *
2140
+ * ## Why this is narrower than HapRay
2141
+ *
2142
+ * HapRay's label rests on pixels alone, and pixels alone are not evidence of
2143
+ * an animation. A blinking text cursor, a system clock in the status bar and a
2144
+ * video frame all move under a region the app never re-rendered; conversely a
2145
+ * node the tree added but the screen never painted is a rendering defect, not
2146
+ * an animation. So a region is labelled only when *both* the pixels and the
2147
+ * tree moved inside it, and each half is reported so the caller can see the
2148
+ * agreement rather than take the label on trust. A pixel-only movement is
2149
+ * returned separately — it is a real observation, just not this label.
2150
+ *
2151
+ * ## Resolution dependence
2152
+ *
2153
+ * The dHash is computed at a fixed 9×8 grid, so a region smaller than that
2154
+ * grid cannot express its own detail: two 3×3 regions hash identically
2155
+ * whatever they contain. Regions below {@link MIN_HASH_PIXELS} are therefore
2156
+ * not labelled, and say so in `unmeasured`.
2157
+ */
2158
+ /** HapRay's similarity bands, as percentages. */
2159
+ declare const ANIMATION_BANDS: {
2160
+ readonly major: 50;
2161
+ readonly moderate: 70;
2162
+ readonly minor: 85;
2163
+ };
2164
+ /** A region smaller than this cannot fill the 9×8 hash grid. */
2165
+ declare const MIN_HASH_PIXELS: number;
2166
+ type AnimationSeverity = 'major_change' | 'moderate_change' | 'minor_change';
2167
+ /** How much the pixels inside one region moved between the two captures. */
2168
+ interface RegionPixelChange {
2169
+ readonly bounds: Rect;
2170
+ /** 0..1; 1 means the two hashes are identical. */
2171
+ readonly similarity: number;
2172
+ /** Fraction of the region's pixels whose channels differ by more than the tolerance. */
2173
+ readonly changedRatio: number;
2174
+ readonly dhashA: string;
2175
+ readonly dhashB: string;
2176
+ }
2177
+ /** A region both halves agree moved: an animation label. */
2178
+ interface AnimationLabel extends RegionPixelChange {
2179
+ readonly label: 'animation';
2180
+ readonly severity: AnimationSeverity;
2181
+ /** Tree differences whose bounds fall inside this region. */
2182
+ readonly treeChanges: number;
2183
+ }
2184
+ /** A region the pixels moved in while the tree did not. */
2185
+ interface PixelOnlyChange extends RegionPixelChange {
2186
+ readonly note: 'pixels changed, tree did not: not labelled an animation';
2187
+ }
2188
+ /** A region that was skipped, and why. */
2189
+ interface UnmeasuredRegion {
2190
+ readonly bounds: Rect;
2191
+ readonly reason: string;
2192
+ }
2193
+ interface AnimationAnalysis {
2194
+ readonly animations: AnimationLabel[];
2195
+ readonly pixelOnly: PixelOnlyChange[];
2196
+ readonly unmeasured: UnmeasuredRegion[];
2197
+ }
2198
+ /**
2199
+ * HapRay's severity band for a similarity percentage.
2200
+ *
2201
+ * Returns `undefined` at or above the 85% band: HapRay calls that
2202
+ * `no_change`, and a label for no change is not an animation.
2203
+ */
2204
+ declare function animationSeverity(similarityPercent: number): AnimationSeverity | undefined;
2205
+ /**
2206
+ * Crop a region out of an image.
2207
+ *
2208
+ * `right` and `bottom` are exclusive, matching `bounds` as `uitest` writes it
2209
+ * (`[0,0][8,4]` on an 8×4 screen). A region is clipped to the image rather
2210
+ * than refused: a node whose bounds run past the screen still has a visible
2211
+ * part, and that part is what the capture can speak about.
2212
+ */
2213
+ declare function cropRegion(image: RgbaImage, rect: Rect): RgbaImage;
2214
+ /** Compare one region across the two captures, or `undefined` when too small. */
2215
+ declare function compareRegion(a: RgbaImage, b: RgbaImage, rect: Rect, tolerance: number): RegionPixelChange | undefined;
2216
+ /**
2217
+ * Label the regions both halves agree moved.
2218
+ *
2219
+ * `treeRegions` are the bounds the tree diff reported, each with its count of
2220
+ * differences; `pixelOnlyBounds` is where to look when the tree reported
2221
+ * nothing at all — the whole screen, because there is no node to narrow it to.
2222
+ * A region whose pixels moved and whose tree did not is returned in
2223
+ * `pixelOnly`, never promoted.
2224
+ */
2225
+ declare function analyseAnimations(a: RgbaImage, b: RgbaImage, treeRegions: ReadonlyArray<{
2226
+ bounds: Rect;
2227
+ changes: number;
2228
+ }>, pixelOnlyBounds: Rect | undefined, tolerance: number): AnimationAnalysis;
2229
+
2130
2230
  /** What one side of the comparison contained, as the page and JSON report it. */
2131
2231
  interface UiDiffSide {
2132
2232
  readonly dir: string;
@@ -2155,6 +2255,19 @@ interface UiDiff {
2155
2255
  readonly image: ImageComparison | null;
2156
2256
  readonly tree: UiTreeDiff | null;
2157
2257
  readonly regions: Rect[];
2258
+ /**
2259
+ * Regions both the pixels and the tree agree moved between the two captures
2260
+ * (HapRay parity row 31). Empty for a tree-only comparison, which has no
2261
+ * pixels to compare.
2262
+ */
2263
+ readonly animations: AnimationAnalysis['animations'];
2264
+ /**
2265
+ * Regions whose pixels moved while the tree did not: a cursor blink, a video
2266
+ * frame, a system clock. Reported, never labelled an animation.
2267
+ */
2268
+ readonly pixelOnly: AnimationAnalysis['pixelOnly'];
2269
+ /** Regions too small for the dHash grid to say anything about. */
2270
+ readonly unmeasuredRegions: AnimationAnalysis['unmeasured'];
2158
2271
  readonly degraded: string[];
2159
2272
  }
2160
2273
  /** Where `compareSceneDirs` writes its artifacts. */
@@ -3958,6 +4071,289 @@ declare function renderScenesComparison(comparison: ScenesComparison): string;
3958
4071
  /** Sorts steps by id; exported for a caller assembling them from a run. */
3959
4072
  declare function sortSteps(steps: readonly SceneStep[]): SceneStep[];
3960
4073
 
4074
+ /**
4075
+ * One analyzer's share of a run.
4076
+ *
4077
+ * A skipped analyzer still gets a section, with `status: 'degraded'` and the
4078
+ * placeholder metric/evidence pair the engine synthesizes, so a report can
4079
+ * name the missing capability in place instead of dropping the section.
4080
+ */
4081
+ interface AnalyzerSection {
4082
+ readonly analyzerId: string;
4083
+ readonly status: 'measured' | 'degraded';
4084
+ readonly result: AnalyzeResult;
4085
+ }
4086
+ /** A whole run: the merged result plus the per-analyzer sections it came from. */
4087
+ interface AnalyzerRun {
4088
+ readonly result: AnalyzeResult;
4089
+ readonly sections: AnalyzerSection[];
4090
+ }
4091
+ /**
4092
+ * Runs every analyzer whose capability requirements are satisfied.
4093
+ *
4094
+ * Analyzers are sorted by `id` and run sequentially, so both the call order
4095
+ * and the merged output are deterministic regardless of the caller's array
4096
+ * order (D5). An analyzer with an unsatisfied requirement is not called: it
4097
+ * contributes one `<id>.degraded` proxy metric and one `degraded_capability`
4098
+ * evidence item naming the missing capabilities and the device's own reasons.
4099
+ * Every analyzer also contributes one {@link AnalyzerSection} to `sections`,
4100
+ * in the same id order, so a report can attribute each metric to its source.
4101
+ *
4102
+ * The returned arrays are new and sorted (`metrics` by `id`, `evidence` by
4103
+ * `(kind, window.startNs, id)`). Two analyzers emitting the same metric id
4104
+ * make the report ambiguous, so the whole run fails with
4105
+ * `DUPLICATE_METRIC_ID` instead of silently keeping one value; the same
4106
+ * integrity rule applies to evidence ids (`DUPLICATE_EVIDENCE_ID`). Neither
4107
+ * the context nor any analyzer (including its result arrays) is mutated.
4108
+ */
4109
+ declare function runAnalyzerSections(analyzers: readonly Analyzer[], ctx: AnalyzeContext): Promise<AnalyzerRun>;
4110
+ /**
4111
+ * Runs every analyzer and returns only the merged result.
4112
+ *
4113
+ * A thin wrapper over {@link runAnalyzerSections}; existing callers keep the
4114
+ * old shape and behavior exactly.
4115
+ */
4116
+ declare function runAnalyzers(analyzers: readonly Analyzer[], ctx: AnalyzeContext): Promise<AnalyzeResult>;
4117
+ /**
4118
+ * The analyzers an offline `analyze` run executes by default.
4119
+ *
4120
+ * Additional analyzers are appended as they are implemented; the function
4121
+ * returns a fresh array so callers may add or remove entries without
4122
+ * affecting another run.
4123
+ */
4124
+ declare function defaultAnalyzers(): Analyzer[];
4125
+
4126
+ /** The report document schema. A change to any shape below bumps this. */
4127
+ declare const REPORT_SCHEMA_VERSION = 1;
4128
+ /** Who produced the report; the version is the CLI package version. */
4129
+ interface ReportGenerator {
4130
+ name: string;
4131
+ version: string;
4132
+ }
4133
+ /** The scene the report describes. Inputs are copied, never referenced. */
4134
+ interface ReportScenario {
4135
+ app: {
4136
+ packageName: string;
4137
+ processNames: string[];
4138
+ };
4139
+ device: string;
4140
+ window: TimeRange;
4141
+ /** Capture start from `scene.json`; absent when the scene did not record one. */
4142
+ startedAtNs?: number;
4143
+ /**
4144
+ * The screenshot the bundle carries at `assets/screenshot.png`. Present only
4145
+ * when the scene had one, so a renderer can tell "no image" from "an image
4146
+ * whose size it was not told".
4147
+ */
4148
+ screenshot?: {
4149
+ width: number;
4150
+ height: number;
4151
+ };
4152
+ }
4153
+ /** One analyzer's contribution, ready for rendering. */
4154
+ interface ReportSection {
4155
+ /** The analyzer id, e.g. `frames`. Also the HTML section anchor. */
4156
+ id: string;
4157
+ title: string;
4158
+ status: 'measured' | 'degraded';
4159
+ /** The engine's explanation of why the analyzer was skipped. */
4160
+ degradedReason?: string;
4161
+ /** Sorted by `id`, as the engine emits them. */
4162
+ metrics: Metric[];
4163
+ /** Sorted by `(kind, window.startNs, id)`, as the engine emits them. */
4164
+ evidence: Evidence[];
4165
+ }
4166
+ interface ReportTotals {
4167
+ metrics: number;
4168
+ evidence: number;
4169
+ bySeverity: {
4170
+ info: number;
4171
+ warn: number;
4172
+ critical: number;
4173
+ };
4174
+ measured: number;
4175
+ degraded: number;
4176
+ }
4177
+ /** The complete, versioned report document. */
4178
+ interface ReportModel {
4179
+ schemaVersion: typeof REPORT_SCHEMA_VERSION;
4180
+ generator: ReportGenerator;
4181
+ scenario: ReportScenario;
4182
+ sections: ReportSection[];
4183
+ totals: ReportTotals;
4184
+ comparison?: BaselineComparison;
4185
+ }
4186
+ /** Everything `buildReport` needs; all values are already measured. */
4187
+ interface ReportInput {
4188
+ generator: ReportGenerator;
4189
+ app: AppIdentity;
4190
+ device: string;
4191
+ window: TimeRange;
4192
+ startedAtNs?: number;
4193
+ sections: readonly AnalyzerSection[];
4194
+ comparison?: BaselineComparison;
4195
+ /**
4196
+ * The scene's screenshot dimensions, when one was captured. The report copies
4197
+ * the file to `assets/screenshot.png` and renders it in the `ui` section; the
4198
+ * dimensions are here so the page can state them without decoding the PNG
4199
+ * again. Absent means no image was captured, and the page says so instead of
4200
+ * pointing at a file that does not exist.
4201
+ */
4202
+ screenshot?: {
4203
+ width: number;
4204
+ height: number;
4205
+ };
4206
+ }
4207
+ /** The compact roll-up written to `summary.json`. */
4208
+ interface ReportSummary {
4209
+ schemaVersion: typeof REPORT_SCHEMA_VERSION;
4210
+ app: string;
4211
+ device: string;
4212
+ window: TimeRange;
4213
+ sections: Array<{
4214
+ id: string;
4215
+ title: string;
4216
+ status: 'measured' | 'degraded';
4217
+ degradedReason?: string;
4218
+ metrics: number;
4219
+ evidence: number;
4220
+ }>;
4221
+ totals: ReportTotals;
4222
+ comparison?: Record<DeltaStatus, number>;
4223
+ }
4224
+ /**
4225
+ * Human titles for the analyzers shipped today.
4226
+ *
4227
+ * An id absent here titles as itself: a new analyzer renders honestly before
4228
+ * anyone writes its title, instead of failing the report.
4229
+ */
4230
+ declare const SECTION_TITLES: Readonly<Record<string, string>>;
4231
+ /**
4232
+ * Builds the report document from a section-aware engine run.
4233
+ *
4234
+ * The inputs are copied and sorted, never mutated. Sorting repeats the engine's
4235
+ * order so a model assembled by hand (as in tests) is just as deterministic as
4236
+ * one produced by `runAnalyzerSections` — the report must be byte-stable (D5)
4237
+ * no matter which layer produced its parts.
4238
+ */
4239
+ declare function buildReport(input: ReportInput): ReportModel;
4240
+ /** Collapses the model to its per-section counts and totals. */
4241
+ declare function summarizeReport(model: ReportModel): ReportSummary;
4242
+ /**
4243
+ * The canonical JSON serialization for `report.json` and `summary.json`.
4244
+ *
4245
+ * Two-space indent plus a trailing newline matches `analyze --json`, so a
4246
+ * consumer reads every document in this package the same way.
4247
+ */
4248
+ declare function renderReportJson(model: ReportModel): string;
4249
+ declare function renderSummaryJson(summary: ReportSummary): string;
4250
+
4251
+ /**
4252
+ * Multi-run trend aggregation (HapRay parity row 35, the aggregation half).
4253
+ *
4254
+ * HapRay's `PerfMulti.vue` accepts any set of report HTML files, extracts the
4255
+ * embedded JSON from each, and draws the total load and the per-category load
4256
+ * across them. It asks the user to filter by app, ROM version, app version and
4257
+ * scene — because the page has no model that could tell comparable runs from
4258
+ * incomparable ones, so the filtering is left to a human reading four
4259
+ * dropdowns.
4260
+ *
4261
+ * A trend line is a claim that the runs are comparable: that the same app was
4262
+ * measured the same way, and that a movement along the x axis is a change in
4263
+ * the app rather than a change in what was measured. So this module refuses
4264
+ * the inputs that make the claim false — different apps, a duplicated label —
4265
+ * and makes the rest of the claim visible: the ordering is stated, a metric a
4266
+ * run never emitted is a gap rather than a zero, and a delta is taken between
4267
+ * the first and last run that actually measured the metric.
4268
+ *
4269
+ * ## What a gap means
4270
+ *
4271
+ * Plotting 0 for "this run did not emit `frame.count`" would draw a collapse
4272
+ * to zero and a recovery, which is a much stronger claim than "the analyzer
4273
+ * did not run". The point is `null`, the series counts its `measured` points,
4274
+ * and the HTML prints the count beside the name. A *degraded* metric counts as
4275
+ * a gap too: its zero is the engine's stand-in for "nothing to read", so a
4276
+ * series of them is a series of gaps — kept, so the metric that was not
4277
+ * measured is named, but drawn as nothing.
4278
+ */
4279
+ /** One run's metrics, named and identified well enough to be compared. */
4280
+ interface TrendRun {
4281
+ /** Unique across the trend; the x-axis label. */
4282
+ readonly label: string;
4283
+ readonly app: string;
4284
+ readonly device: string;
4285
+ /** Capture start, when the run recorded one. Absent disables time ordering. */
4286
+ readonly startedAtNs?: number;
4287
+ readonly metrics: readonly Metric[];
4288
+ }
4289
+ /** One run's value for one metric; `null` when the run did not emit it. */
4290
+ interface TrendPoint {
4291
+ readonly label: string;
4292
+ readonly value: number | string | null;
4293
+ /** The metric's fidelity in this run, when it emitted the metric. */
4294
+ readonly fidelity?: Metric['fidelity'];
4295
+ }
4296
+ interface TrendSeries {
4297
+ readonly id: string;
4298
+ readonly unit: Metric['unit'];
4299
+ /** One point per run, in `TrendOrder` order. */
4300
+ readonly points: readonly TrendPoint[];
4301
+ /** How many runs emitted the metric. */
4302
+ readonly measured: number;
4303
+ /** Difference between the first and last measured numeric points. */
4304
+ readonly delta?: number;
4305
+ /** Percent change over the same two points; absent when the first is 0. */
4306
+ readonly deltaPct?: number;
4307
+ /**
4308
+ * `improved` / `regressed` / `unchanged` when the metric has a known
4309
+ * direction and both ends are numeric; absent otherwise. Unlike a two-way
4310
+ * comparison there is no `added`/`removed`/`incomparable` here: a series
4311
+ * exists because at least one run emitted it, and a metric with no known
4312
+ * direction simply carries no verdict.
4313
+ */
4314
+ readonly status?: 'improved' | 'regressed' | 'unchanged';
4315
+ /** Every run's fidelity, deduplicated and sorted; more than one means mixed. */
4316
+ readonly fidelities: readonly Metric['fidelity'][];
4317
+ }
4318
+ /** How the runs were ordered. Stated so a reader knows what the x axis means. */
4319
+ type TrendOrder = 'startedAtNs' | 'argument';
4320
+ interface Trend {
4321
+ readonly runs: readonly TrendRun[];
4322
+ readonly orderedBy: TrendOrder;
4323
+ /** Sorted by id, so two renders of the same input are byte-identical. */
4324
+ readonly series: readonly TrendSeries[];
4325
+ }
4326
+ /**
4327
+ * Aggregate two or more runs into one trend.
4328
+ *
4329
+ * Throws — rather than filtering silently — when the inputs cannot support the
4330
+ * claim: fewer than two runs, a duplicate label (the x axis would have two
4331
+ * points in one column), or runs from different apps. `device` is deliberately
4332
+ * not a refusal: a trend across two devices is a legitimate question, and the
4333
+ * runs table names the device of every point so the reader can see it.
4334
+ */
4335
+ declare function buildTrend(runs: readonly TrendRun[]): Trend;
4336
+ /** The canonical JSON serialization for `trend.json`. */
4337
+ declare function renderTrendJson(trend: Trend): string;
4338
+ /**
4339
+ * Flatten one saved report into a run.
4340
+ *
4341
+ * The report model is the input because it is what `report` writes to disk:
4342
+ * the metrics are already sorted by id per section, so the flattened list is
4343
+ * deterministic without a second sort. A section with no metrics contributes
4344
+ * nothing; the run's `metrics.length` is the sum the runs table reports.
4345
+ */
4346
+ declare function trendRunFromReport(label: string, model: ReportModel): TrendRun;
4347
+ /**
4348
+ * Render the trend as one self-contained HTML document.
4349
+ *
4350
+ * Same rules as the report page: no scripts, no external resources, every
4351
+ * interpolation escaped. The runs table names each run's label, app, device
4352
+ * and start so the reader can judge comparability themselves; the series
4353
+ * table carries the numbers a polyline cannot show.
4354
+ */
4355
+ declare function renderTrendHtml(trend: Trend): string;
4356
+
3961
4357
  /**
3962
4358
  * Executing one scenario action against a device.
3963
4359
  *
@@ -5410,58 +5806,6 @@ declare class ComponentReuseAnalyzer implements Analyzer {
5410
5806
  run(ctx: AnalyzeContext): Promise<AnalyzeResult>;
5411
5807
  }
5412
5808
 
5413
- /**
5414
- * One analyzer's share of a run.
5415
- *
5416
- * A skipped analyzer still gets a section, with `status: 'degraded'` and the
5417
- * placeholder metric/evidence pair the engine synthesizes, so a report can
5418
- * name the missing capability in place instead of dropping the section.
5419
- */
5420
- interface AnalyzerSection {
5421
- readonly analyzerId: string;
5422
- readonly status: 'measured' | 'degraded';
5423
- readonly result: AnalyzeResult;
5424
- }
5425
- /** A whole run: the merged result plus the per-analyzer sections it came from. */
5426
- interface AnalyzerRun {
5427
- readonly result: AnalyzeResult;
5428
- readonly sections: AnalyzerSection[];
5429
- }
5430
- /**
5431
- * Runs every analyzer whose capability requirements are satisfied.
5432
- *
5433
- * Analyzers are sorted by `id` and run sequentially, so both the call order
5434
- * and the merged output are deterministic regardless of the caller's array
5435
- * order (D5). An analyzer with an unsatisfied requirement is not called: it
5436
- * contributes one `<id>.degraded` proxy metric and one `degraded_capability`
5437
- * evidence item naming the missing capabilities and the device's own reasons.
5438
- * Every analyzer also contributes one {@link AnalyzerSection} to `sections`,
5439
- * in the same id order, so a report can attribute each metric to its source.
5440
- *
5441
- * The returned arrays are new and sorted (`metrics` by `id`, `evidence` by
5442
- * `(kind, window.startNs, id)`). Two analyzers emitting the same metric id
5443
- * make the report ambiguous, so the whole run fails with
5444
- * `DUPLICATE_METRIC_ID` instead of silently keeping one value; the same
5445
- * integrity rule applies to evidence ids (`DUPLICATE_EVIDENCE_ID`). Neither
5446
- * the context nor any analyzer (including its result arrays) is mutated.
5447
- */
5448
- declare function runAnalyzerSections(analyzers: readonly Analyzer[], ctx: AnalyzeContext): Promise<AnalyzerRun>;
5449
- /**
5450
- * Runs every analyzer and returns only the merged result.
5451
- *
5452
- * A thin wrapper over {@link runAnalyzerSections}; existing callers keep the
5453
- * old shape and behavior exactly.
5454
- */
5455
- declare function runAnalyzers(analyzers: readonly Analyzer[], ctx: AnalyzeContext): Promise<AnalyzeResult>;
5456
- /**
5457
- * The analyzers an offline `analyze` run executes by default.
5458
- *
5459
- * Additional analyzers are appended as they are implemented; the function
5460
- * returns a fresh array so callers may add or remove entries without
5461
- * affecting another run.
5462
- */
5463
- declare function defaultAnalyzers(): Analyzer[];
5464
-
5465
5809
  /**
5466
5810
  * Resolves the analyzed package to the identity every analyzer receives.
5467
5811
  *
@@ -5680,131 +6024,6 @@ declare function analyzeHap(bytes: Uint8Array, packageName: string): HapAnalysis
5680
6024
  /** Wrap an analysis as the `static-hap` section the report renderer takes. */
5681
6025
  declare function hapSection(analysis: HapAnalysis): AnalyzerSection;
5682
6026
 
5683
- /** The report document schema. A change to any shape below bumps this. */
5684
- declare const REPORT_SCHEMA_VERSION = 1;
5685
- /** Who produced the report; the version is the CLI package version. */
5686
- interface ReportGenerator {
5687
- name: string;
5688
- version: string;
5689
- }
5690
- /** The scene the report describes. Inputs are copied, never referenced. */
5691
- interface ReportScenario {
5692
- app: {
5693
- packageName: string;
5694
- processNames: string[];
5695
- };
5696
- device: string;
5697
- window: TimeRange;
5698
- /** Capture start from `scene.json`; absent when the scene did not record one. */
5699
- startedAtNs?: number;
5700
- /**
5701
- * The screenshot the bundle carries at `assets/screenshot.png`. Present only
5702
- * when the scene had one, so a renderer can tell "no image" from "an image
5703
- * whose size it was not told".
5704
- */
5705
- screenshot?: {
5706
- width: number;
5707
- height: number;
5708
- };
5709
- }
5710
- /** One analyzer's contribution, ready for rendering. */
5711
- interface ReportSection {
5712
- /** The analyzer id, e.g. `frames`. Also the HTML section anchor. */
5713
- id: string;
5714
- title: string;
5715
- status: 'measured' | 'degraded';
5716
- /** The engine's explanation of why the analyzer was skipped. */
5717
- degradedReason?: string;
5718
- /** Sorted by `id`, as the engine emits them. */
5719
- metrics: Metric[];
5720
- /** Sorted by `(kind, window.startNs, id)`, as the engine emits them. */
5721
- evidence: Evidence[];
5722
- }
5723
- interface ReportTotals {
5724
- metrics: number;
5725
- evidence: number;
5726
- bySeverity: {
5727
- info: number;
5728
- warn: number;
5729
- critical: number;
5730
- };
5731
- measured: number;
5732
- degraded: number;
5733
- }
5734
- /** The complete, versioned report document. */
5735
- interface ReportModel {
5736
- schemaVersion: typeof REPORT_SCHEMA_VERSION;
5737
- generator: ReportGenerator;
5738
- scenario: ReportScenario;
5739
- sections: ReportSection[];
5740
- totals: ReportTotals;
5741
- comparison?: BaselineComparison;
5742
- }
5743
- /** Everything `buildReport` needs; all values are already measured. */
5744
- interface ReportInput {
5745
- generator: ReportGenerator;
5746
- app: AppIdentity;
5747
- device: string;
5748
- window: TimeRange;
5749
- startedAtNs?: number;
5750
- sections: readonly AnalyzerSection[];
5751
- comparison?: BaselineComparison;
5752
- /**
5753
- * The scene's screenshot dimensions, when one was captured. The report copies
5754
- * the file to `assets/screenshot.png` and renders it in the `ui` section; the
5755
- * dimensions are here so the page can state them without decoding the PNG
5756
- * again. Absent means no image was captured, and the page says so instead of
5757
- * pointing at a file that does not exist.
5758
- */
5759
- screenshot?: {
5760
- width: number;
5761
- height: number;
5762
- };
5763
- }
5764
- /** The compact roll-up written to `summary.json`. */
5765
- interface ReportSummary {
5766
- schemaVersion: typeof REPORT_SCHEMA_VERSION;
5767
- app: string;
5768
- device: string;
5769
- window: TimeRange;
5770
- sections: Array<{
5771
- id: string;
5772
- title: string;
5773
- status: 'measured' | 'degraded';
5774
- degradedReason?: string;
5775
- metrics: number;
5776
- evidence: number;
5777
- }>;
5778
- totals: ReportTotals;
5779
- comparison?: Record<DeltaStatus, number>;
5780
- }
5781
- /**
5782
- * Human titles for the analyzers shipped today.
5783
- *
5784
- * An id absent here titles as itself: a new analyzer renders honestly before
5785
- * anyone writes its title, instead of failing the report.
5786
- */
5787
- declare const SECTION_TITLES: Readonly<Record<string, string>>;
5788
- /**
5789
- * Builds the report document from a section-aware engine run.
5790
- *
5791
- * The inputs are copied and sorted, never mutated. Sorting repeats the engine's
5792
- * order so a model assembled by hand (as in tests) is just as deterministic as
5793
- * one produced by `runAnalyzerSections` — the report must be byte-stable (D5)
5794
- * no matter which layer produced its parts.
5795
- */
5796
- declare function buildReport(input: ReportInput): ReportModel;
5797
- /** Collapses the model to its per-section counts and totals. */
5798
- declare function summarizeReport(model: ReportModel): ReportSummary;
5799
- /**
5800
- * The canonical JSON serialization for `report.json` and `summary.json`.
5801
- *
5802
- * Two-space indent plus a trailing newline matches `analyze --json`, so a
5803
- * consumer reads every document in this package the same way.
5804
- */
5805
- declare function renderReportJson(model: ReportModel): string;
5806
- declare function renderSummaryJson(summary: ReportSummary): string;
5807
-
5808
6027
  /**
5809
6028
  * One CSV row per metric, in model order (sections by id, metrics by id).
5810
6029
  *
@@ -5888,4 +6107,4 @@ interface FlamegraphPageInput {
5888
6107
  */
5889
6108
  declare function renderFlamegraphHtml(input: FlamegraphPageInput): string;
5890
6109
 
5891
- export { type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AppIdentity, type BaselineComparison, type BelowThresholdPattern, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, 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, 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 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, 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, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyzeHap, analyzeThreadWakeup, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, categorize, classifyNativePath, compareImages, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, createSceneLayout, 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, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
6110
+ 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, type BaselineComparison, type BelowThresholdPattern, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, 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, 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
@@ -5019,6 +5019,108 @@ function diffTrees(before, after) {
5019
5019
  import { existsSync as existsSync13, mkdirSync as mkdirSync8, readFileSync as readFileSync10, writeFileSync as writeFileSync7 } from "node:fs";
5020
5020
  import { join as join7, resolve } from "node:path";
5021
5021
 
5022
+ // src/ui/animation.ts
5023
+ var ANIMATION_BANDS = {
5024
+ major: 50,
5025
+ moderate: 70,
5026
+ minor: 85
5027
+ };
5028
+ var MIN_HASH_PIXELS = 9 * 8;
5029
+ function animationSeverity(similarityPercent) {
5030
+ if (similarityPercent < ANIMATION_BANDS.major) return "major_change";
5031
+ if (similarityPercent < ANIMATION_BANDS.moderate) return "moderate_change";
5032
+ if (similarityPercent < ANIMATION_BANDS.minor) return "minor_change";
5033
+ return void 0;
5034
+ }
5035
+ function cropRegion(image, rect) {
5036
+ const left = Math.max(0, Math.min(rect.left, rect.right));
5037
+ const right = Math.min(image.width, Math.max(rect.left, rect.right));
5038
+ const top = Math.max(0, Math.min(rect.top, rect.bottom));
5039
+ const bottom = Math.min(image.height, Math.max(rect.top, rect.bottom));
5040
+ const width = Math.max(0, right - left);
5041
+ const height = Math.max(0, bottom - top);
5042
+ const data = new Uint8Array(width * height * 4);
5043
+ for (let y = 0; y < height; y += 1) {
5044
+ const from = ((top + y) * image.width + left) * 4;
5045
+ data.set(image.data.subarray(from, from + width * 4), y * width * 4);
5046
+ }
5047
+ return { width, height, data };
5048
+ }
5049
+ function hammingHex(a, b) {
5050
+ let distance = 0;
5051
+ for (let i = 0; i < a.length; i += 1) {
5052
+ let xor = parseInt(a[i], 16) ^ parseInt(b[i], 16);
5053
+ while (xor !== 0) {
5054
+ distance += xor & 1;
5055
+ xor >>= 1;
5056
+ }
5057
+ }
5058
+ return distance;
5059
+ }
5060
+ function compareRegion(a, b, rect, tolerance) {
5061
+ const left = cropRegion(a, rect);
5062
+ const right = cropRegion(b, rect);
5063
+ const width = Math.min(left.width, right.width);
5064
+ const height = Math.min(left.height, right.height);
5065
+ if (width * height < MIN_HASH_PIXELS) return void 0;
5066
+ const dhashA = dhash(left);
5067
+ const dhashB = dhash(right);
5068
+ let changed = 0;
5069
+ let compared = 0;
5070
+ for (let y = 0; y < height; y += 1) {
5071
+ for (let x = 0; x < width; x += 1) {
5072
+ const at = (y * left.width + x) * 4;
5073
+ const bt = (y * right.width + x) * 4;
5074
+ compared += 1;
5075
+ if (Math.abs(left.data[at] - right.data[bt]) > tolerance || Math.abs(left.data[at + 1] - right.data[bt + 1]) > tolerance || Math.abs(left.data[at + 2] - right.data[bt + 2]) > tolerance || Math.abs(left.data[at + 3] - right.data[bt + 3]) > tolerance) {
5076
+ changed += 1;
5077
+ }
5078
+ }
5079
+ }
5080
+ return {
5081
+ bounds: rect,
5082
+ similarity: 1 - hammingHex(dhashA, dhashB) / 64,
5083
+ changedRatio: compared === 0 ? 0 : changed / compared,
5084
+ dhashA,
5085
+ dhashB
5086
+ };
5087
+ }
5088
+ function analyseAnimations(a, b, treeRegions, pixelOnlyBounds, tolerance) {
5089
+ const animations = [];
5090
+ const pixelOnly = [];
5091
+ const unmeasured = [];
5092
+ const consider = (bounds, treeChanges) => {
5093
+ const pixels = compareRegion(a, b, bounds, tolerance);
5094
+ if (pixels === void 0) {
5095
+ unmeasured.push({
5096
+ bounds,
5097
+ reason: `the region is smaller than the ${MIN_HASH_PIXELS}-pixel dHash grid, so its pixels cannot be compared`
5098
+ });
5099
+ return;
5100
+ }
5101
+ if (pixels.changedRatio === 0) return;
5102
+ if (treeChanges === 0) {
5103
+ pixelOnly.push({
5104
+ ...pixels,
5105
+ note: "pixels changed, tree did not: not labelled an animation"
5106
+ });
5107
+ return;
5108
+ }
5109
+ const severity = animationSeverity(pixels.similarity * 100);
5110
+ if (severity === void 0) return;
5111
+ animations.push({ ...pixels, label: "animation", severity, treeChanges });
5112
+ };
5113
+ for (const region of treeRegions) consider(region.bounds, region.changes);
5114
+ if (treeRegions.length === 0 && pixelOnlyBounds !== void 0) {
5115
+ consider(pixelOnlyBounds, 0);
5116
+ }
5117
+ const order = (x, y) => x.bounds.top - y.bounds.top || x.bounds.left - y.bounds.left || x.bounds.bottom - y.bounds.bottom || x.bounds.right - y.bounds.right;
5118
+ animations.sort(order);
5119
+ pixelOnly.sort(order);
5120
+ unmeasured.sort(order);
5121
+ return { animations, pixelOnly, unmeasured };
5122
+ }
5123
+
5022
5124
  // src/report/escape.ts
5023
5125
  function escapeHtml(value) {
5024
5126
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
@@ -5119,6 +5221,28 @@ function renderUiDiffHtml(diff) {
5119
5221
  "</table>"
5120
5222
  ].join("");
5121
5223
  })();
5224
+ const animationSection = (() => {
5225
+ const labels = diff.animations;
5226
+ const pixelOnly = diff.pixelOnly;
5227
+ const unmeasured = diff.unmeasuredRegions;
5228
+ if (labels.length === 0 && pixelOnly.length === 0 && unmeasured.length === 0) {
5229
+ return '<h2>Animations</h2><p class="meta">No region changed in both the pixels and the tree, so no animation is labelled.</p>';
5230
+ }
5231
+ const rect = (bounds) => `[${bounds.left},${bounds.top}][${bounds.right},${bounds.bottom}]`;
5232
+ const rows = [
5233
+ ...labels.map((item) => `<tr><td>animation (${escapeHtml(item.severity)})</td><td class="num">${rect(item.bounds)}</td><td class="num">${(item.similarity * 100).toFixed(1)}%</td><td class="num">${item.treeChanges}</td></tr>`),
5234
+ ...pixelOnly.map((item) => `<tr><td>pixels only, not labelled</td><td class="num">${rect(item.bounds)}</td><td class="num">${(item.similarity * 100).toFixed(1)}%</td><td class="num">0</td></tr>`),
5235
+ ...unmeasured.map((item) => `<tr><td>unmeasured: ${escapeHtml(item.reason)}</td><td class="num">${rect(item.bounds)}</td><td class="num">\u2014</td><td class="num">\u2014</td></tr>`)
5236
+ ].join("");
5237
+ return [
5238
+ "<h2>Animations</h2>",
5239
+ `<p class="meta">A region is labelled an animation only when its pixels moved and the tree reports a change inside it. A pixel-only movement \u2014 a cursor, a video frame, a system clock \u2014 is listed but not labelled. Bands follow HapRay: major under ${ANIMATION_BANDS.major}% similar, moderate under ${ANIMATION_BANDS.moderate}%, minor under ${ANIMATION_BANDS.minor}%.</p>`,
5240
+ "<table>",
5241
+ "<thead><tr><th>label</th><th>bounds</th><th>similarity</th><th>tree changes</th></tr></thead>",
5242
+ `<tbody>${rows}</tbody>`,
5243
+ "</table>"
5244
+ ].join("");
5245
+ })();
5122
5246
  const captureLines = [
5123
5247
  diff.a.startedAtMs === void 0 ? void 0 : `a captured at ${diff.a.startedAtMs} ms`,
5124
5248
  diff.b.startedAtMs === void 0 ? void 0 : `b captured at ${diff.b.startedAtMs} ms`
@@ -5143,6 +5267,7 @@ function renderUiDiffHtml(diff) {
5143
5267
  banner,
5144
5268
  screens,
5145
5269
  imageNumbers,
5270
+ animationSection,
5146
5271
  treeRows,
5147
5272
  "<footer>Generated by @ohos-perf/core. No scripts, no network access.</footer>",
5148
5273
  "</main>",
@@ -5193,6 +5318,19 @@ function collectRegions(tree) {
5193
5318
  );
5194
5319
  return regions;
5195
5320
  }
5321
+ function regionCounts(tree) {
5322
+ const counts = /* @__PURE__ */ new Map();
5323
+ const all = [...tree.added, ...tree.removed, ...tree.changed];
5324
+ for (const difference2 of all) {
5325
+ if (difference2.bounds === void 0) continue;
5326
+ const rect = difference2.bounds;
5327
+ const key = `${rect.left},${rect.top},${rect.right},${rect.bottom}`;
5328
+ const found = counts.get(key);
5329
+ if (found === void 0) counts.set(key, { bounds: rect, changes: 1 });
5330
+ else found.changes += 1;
5331
+ }
5332
+ return [...counts.values()];
5333
+ }
5196
5334
  function readSide(dir, side) {
5197
5335
  const layout = createSceneLayout(dir);
5198
5336
  const hasImage = existsSync13(layout.screenshotFile);
@@ -5242,6 +5380,13 @@ async function compareSceneDirs(a, b, opts) {
5242
5380
  };
5243
5381
  };
5244
5382
  const regions = collectRegions(tree);
5383
+ const animations = left.image === void 0 || right.image === void 0 || tree === null ? { animations: [], pixelOnly: [], unmeasured: [] } : analyseAnimations(
5384
+ left.image,
5385
+ right.image,
5386
+ regionCounts(tree),
5387
+ { left: 0, top: 0, right: left.image.width, bottom: left.image.height },
5388
+ opts.tolerance ?? 8
5389
+ );
5245
5390
  const diff = {
5246
5391
  schemaVersion: 1,
5247
5392
  a: side(dirA, left.image, left.nodes),
@@ -5249,6 +5394,9 @@ async function compareSceneDirs(a, b, opts) {
5249
5394
  image,
5250
5395
  tree,
5251
5396
  regions,
5397
+ animations: animations.animations,
5398
+ pixelOnly: animations.pixelOnly,
5399
+ unmeasuredRegions: animations.unmeasured,
5252
5400
  degraded
5253
5401
  };
5254
5402
  const outDir = resolve(opts.outDir);
@@ -6192,8 +6340,8 @@ var PARITY_ROWS = [
6192
6340
  {
6193
6341
  row: 31,
6194
6342
  name: "UI animation analysis",
6195
- status: "partial",
6196
- reason: "A start/end capture pair is compared by the same tree and image comparators, but the animation label itself is not emitted: dHash thresholds are unvalidated and resolution dependent.",
6343
+ status: "ported",
6344
+ reason: "",
6197
6345
  analyzer: "UiAnalyzer"
6198
6346
  },
6199
6347
  {
@@ -6206,7 +6354,7 @@ var PARITY_ROWS = [
6206
6354
  row: 33,
6207
6355
  name: "Report bundle, dashboard and update",
6208
6356
  status: "partial",
6209
- reason: "The typed report model, offline HTML, JSON/CSV/XLSX and baseline comparison are ported; the multi-version trend page and re-render-from-saved-inputs are not."
6357
+ reason: "The typed report model, offline HTML, JSON/CSV/XLSX, baseline comparison and the multi-run trend page are ported; re-rendering a bundle from its saved inputs is not."
6210
6358
  },
6211
6359
  {
6212
6360
  row: 34,
@@ -6217,8 +6365,8 @@ var PARITY_ROWS = [
6217
6365
  {
6218
6366
  row: 35,
6219
6367
  name: "Report comparison",
6220
- status: "partial",
6221
- reason: "Typed comparison and the scene+step pivot are ported; aggregating more than two reports into one trend is not."
6368
+ status: "ported",
6369
+ reason: ""
6222
6370
  }
6223
6371
  ];
6224
6372
  function paritySummary() {
@@ -6606,6 +6754,228 @@ function sortSteps(steps) {
6606
6754
  return [...steps].sort(byStepId);
6607
6755
  }
6608
6756
 
6757
+ // src/report/trend.ts
6758
+ function byString(a, b) {
6759
+ return a < b ? -1 : a > b ? 1 : 0;
6760
+ }
6761
+ function round32(value) {
6762
+ return Math.round(value * 1e3) / 1e3;
6763
+ }
6764
+ function buildTrend(runs) {
6765
+ if (runs.length < 2) {
6766
+ throw new Error("buildTrend: a trend needs at least two runs");
6767
+ }
6768
+ const seen = /* @__PURE__ */ new Set();
6769
+ for (const run of runs) {
6770
+ if (seen.has(run.label)) {
6771
+ throw new Error(`buildTrend: duplicate run label "${run.label}"`);
6772
+ }
6773
+ seen.add(run.label);
6774
+ }
6775
+ const apps = [...new Set(runs.map((run) => run.app))].sort();
6776
+ if (apps.length > 1) {
6777
+ throw new Error(
6778
+ `buildTrend: the runs measure different apps (${apps.join(", ")}); a trend is only comparable within one app`
6779
+ );
6780
+ }
6781
+ const timed = runs.every((run) => run.startedAtNs !== void 0);
6782
+ const orderedBy = timed ? "startedAtNs" : "argument";
6783
+ const ordered2 = timed ? [...runs].sort((a, b) => a.startedAtNs - b.startedAtNs) : [...runs];
6784
+ const ids = [...new Set(runs.flatMap((run) => run.metrics.map((metric2) => metric2.id)))].sort();
6785
+ const series = ids.map((id) => {
6786
+ const points = [];
6787
+ const fidelities = /* @__PURE__ */ new Set();
6788
+ let unit;
6789
+ for (const run of ordered2) {
6790
+ const metric2 = run.metrics.find((candidate) => candidate.id === id);
6791
+ if (metric2 === void 0 || metric2.degraded !== void 0) {
6792
+ points.push({ label: run.label, value: null });
6793
+ continue;
6794
+ }
6795
+ unit ??= metric2.unit;
6796
+ fidelities.add(metric2.fidelity);
6797
+ points.push({ label: run.label, value: metric2.value, fidelity: metric2.fidelity });
6798
+ }
6799
+ const measuredPoints = points.filter(
6800
+ (point) => point.value !== null && typeof point.value === "number"
6801
+ );
6802
+ const first = measuredPoints[0];
6803
+ const last = measuredPoints[measuredPoints.length - 1];
6804
+ const numeric = first === void 0 || last === void 0 || measuredPoints.length < 2 ? void 0 : { first: first.value, last: last.value };
6805
+ const delta2 = numeric === void 0 ? void 0 : numeric.last - numeric.first;
6806
+ const deltaPct = numeric === void 0 || numeric.first === 0 ? void 0 : round32((numeric.last - numeric.first) / Math.abs(numeric.first) * 100);
6807
+ const direction = METRIC_DIRECTIONS[id];
6808
+ let status;
6809
+ if (delta2 !== void 0 && direction !== void 0) {
6810
+ status = delta2 === 0 ? "unchanged" : direction === "lower" ? delta2 < 0 ? "improved" : "regressed" : delta2 > 0 ? "improved" : "regressed";
6811
+ }
6812
+ return {
6813
+ id,
6814
+ unit: unit ?? "none",
6815
+ points,
6816
+ measured: measuredPoints.length,
6817
+ ...delta2 === void 0 ? {} : { delta: delta2 },
6818
+ ...deltaPct === void 0 ? {} : { deltaPct },
6819
+ ...status === void 0 ? {} : { status },
6820
+ fidelities: [...fidelities].sort(byString)
6821
+ };
6822
+ });
6823
+ return { runs: ordered2, orderedBy, series };
6824
+ }
6825
+ function renderTrendJson(trend) {
6826
+ return `${JSON.stringify(trend, null, 2)}
6827
+ `;
6828
+ }
6829
+ function trendRunFromReport(label2, model) {
6830
+ return {
6831
+ label: label2,
6832
+ app: model.scenario.app.packageName,
6833
+ device: model.scenario.device,
6834
+ ...model.scenario.startedAtNs === void 0 ? {} : { startedAtNs: model.scenario.startedAtNs },
6835
+ metrics: model.sections.flatMap((section) => section.metrics)
6836
+ };
6837
+ }
6838
+ var STYLE2 = `
6839
+ :root { color-scheme: light; }
6840
+ * { box-sizing: border-box; }
6841
+ body { margin: 0; padding: 2rem 1.25rem 4rem; font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; color: #1c1f24; background: #f6f7f9; }
6842
+ main { max-width: 1100px; margin: 0 auto; }
6843
+ h1 { margin: 0 0 .25rem; font-size: 1.75rem; letter-spacing: -.02em; }
6844
+ h2 { margin: 0 0 .5rem; font-size: 1.1rem; }
6845
+ p { margin: .35rem 0; }
6846
+ code { font: 13px/1.4 ui-monospace, "Cascadia Code", Consolas, monospace; }
6847
+ .subtitle { color: #47505c; }
6848
+ .meta { color: #6b7480; font-size: .85rem; }
6849
+ .card { background: #fff; border: 1px solid #e2e5e9; border-radius: 8px; padding: 1rem 1.1rem; margin: 0 0 1rem; }
6850
+ table { width: 100%; border-collapse: collapse; font-size: .88rem; }
6851
+ th, td { text-align: left; padding: .35rem .5rem; border-bottom: 1px solid #eef0f2; vertical-align: top; }
6852
+ th { color: #5b6470; font-weight: 600; font-size: .78rem; text-transform: uppercase; letter-spacing: .04em; }
6853
+ td.num { text-align: right; font-variant-numeric: tabular-nums; }
6854
+ .dim { color: #6b7480; }
6855
+ .chip { display: inline-block; font-size: .72rem; font-weight: 600; padding: .08rem .45rem; border-radius: 999px; background: #eef1f4; text-transform: lowercase; }
6856
+ .chip.improved { background: #ecfdf3; color: #166534; }
6857
+ .chip.regressed { background: #fef2f2; color: #b91c1c; }
6858
+ .chip.unchanged { background: #eef1f4; color: #374151; }
6859
+ .chip.mixed { background: #fff7ed; color: #9a3412; }
6860
+ svg.spark { display: block; width: 100%; height: 90px; overflow: visible; }
6861
+ svg.spark polyline { fill: none; stroke: #2563eb; stroke-width: 1.5; }
6862
+ svg.spark circle { fill: #2563eb; }
6863
+ svg.spark .gap { fill: none; stroke: #9ca3af; stroke-dasharray: 2 3; stroke-width: 1; }
6864
+ footer { margin-top: 2rem; color: #6b7480; font-size: .8rem; }
6865
+ `.trim();
6866
+ function cellText(point) {
6867
+ return point.value === null ? "\u2014" : String(point.value);
6868
+ }
6869
+ function sparkline(series) {
6870
+ const width = 100;
6871
+ const height = 100;
6872
+ const pad = 4;
6873
+ const count = series.points.length;
6874
+ const numeric = series.points.map((point) => typeof point.value === "number" ? point.value : null);
6875
+ const values = numeric.filter((value) => value !== null);
6876
+ if (values.length < 2) return "";
6877
+ let min = Math.min(...values);
6878
+ let max = Math.max(...values);
6879
+ if (min === max) {
6880
+ min -= 1;
6881
+ max += 1;
6882
+ }
6883
+ const x = (index) => count === 1 ? width / 2 : pad + index * (width - pad * 2) / (count - 1);
6884
+ const y = (value) => height - pad - (value - min) / (max - min) * (height - pad * 2);
6885
+ const segments2 = [];
6886
+ let current = [];
6887
+ for (let index = 0; index < count; index += 1) {
6888
+ const value = numeric[index];
6889
+ if (value === null) {
6890
+ if (current.length > 0) segments2.push(current.join(" "));
6891
+ current = [];
6892
+ continue;
6893
+ }
6894
+ current.push(`${x(index).toFixed(2)},${y(value).toFixed(2)}`);
6895
+ }
6896
+ if (current.length > 0) segments2.push(current.join(" "));
6897
+ const lines = segments2.map(
6898
+ (segment) => `<polyline points="${segment}"/>`
6899
+ );
6900
+ const dots = series.points.map(
6901
+ (point, index) => typeof point.value === "number" ? `<circle cx="${x(index).toFixed(2)}" cy="${y(point.value).toFixed(2)}" r="1.6"/>` : ""
6902
+ ).filter((dot) => dot !== "");
6903
+ return `<svg class="spark" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="${escapeHtml(series.id)} across ${count} runs">${lines.join("")}${dots.join("")}</svg>`;
6904
+ }
6905
+ function renderTrendHtml(trend) {
6906
+ const orderNote = trend.orderedBy === "startedAtNs" ? "ordered by capture start time" : "in argument order (a run has no capture start time, so time order was not assumed)";
6907
+ const runRows = trend.runs.map(
6908
+ (run) => [
6909
+ "<tr>",
6910
+ `<td><code>${escapeHtml(run.label)}</code></td>`,
6911
+ `<td>${escapeHtml(run.app)}</td>`,
6912
+ `<td>${escapeHtml(run.device)}</td>`,
6913
+ `<td class="num">${run.startedAtNs === void 0 ? "\u2014" : escapeHtml(String(run.startedAtNs))}</td>`,
6914
+ `<td class="num">${run.metrics.length}</td>`,
6915
+ "</tr>"
6916
+ ].join("\n")
6917
+ );
6918
+ const seriesRows = trend.series.map((series) => {
6919
+ const mixed = series.fidelities.length > 1;
6920
+ const status = series.status === void 0 ? '<span class="dim">\u2014</span>' : `<span class="chip ${series.status}">${escapeHtml(series.status)}</span>`;
6921
+ const delta2 = series.delta === void 0 ? '<span class="dim">\u2014</span>' : escapeHtml(String(series.delta));
6922
+ const pct = series.deltaPct === void 0 ? '<span class="dim">\u2014</span>' : escapeHtml(`${series.deltaPct}%`);
6923
+ const spark = sparkline(series);
6924
+ return [
6925
+ "<tr>",
6926
+ `<td><code>${escapeHtml(series.id)}</code><div class="dim">${series.measured} of ${series.points.length} runs measured</div></td>`,
6927
+ `<td>${spark === "" ? '<span class="dim">not measured</span>' : spark}</td>`,
6928
+ ...series.points.map((point) => `<td class="num">${escapeHtml(cellText(point))}</td>`),
6929
+ `<td>${escapeHtml(series.unit)}</td>`,
6930
+ `<td class="num">${delta2}</td>`,
6931
+ `<td class="num">${pct}</td>`,
6932
+ `<td>${status}</td>`,
6933
+ `<td class="${mixed ? "chip mixed" : "dim"}">${escapeHtml(series.fidelities.join(", ") || "\u2014")}</td>`,
6934
+ "</tr>"
6935
+ ].join("\n");
6936
+ });
6937
+ return [
6938
+ "<!doctype html>",
6939
+ '<html lang="en">',
6940
+ "<head>",
6941
+ '<meta charset="utf-8">',
6942
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
6943
+ `<title>ohos-perf trend \u2014 ${escapeHtml(trend.runs[0]?.app ?? "")}</title>`,
6944
+ `<style>${STYLE2}</style>`,
6945
+ "</head>",
6946
+ "<body>",
6947
+ "<main>",
6948
+ "<header>",
6949
+ "<h1>ohos-perf trend</h1>",
6950
+ `<p class="subtitle">${escapeHtml(trend.runs[0]?.app ?? "")} \xB7 ${trend.runs.length} runs \xB7 ${trend.series.length} metrics</p>`,
6951
+ `<p class="meta">${escapeHtml(orderNote)}</p>`,
6952
+ "</header>",
6953
+ '<section class="card">',
6954
+ "<h2>Runs</h2>",
6955
+ "<table>",
6956
+ "<thead><tr><th>Run</th><th>App</th><th>Device</th><th>Started at (ns)</th><th>Metrics</th></tr></thead>",
6957
+ "<tbody>",
6958
+ ...runRows,
6959
+ "</tbody>",
6960
+ "</table>",
6961
+ "</section>",
6962
+ '<section class="card">',
6963
+ "<h2>Metrics</h2>",
6964
+ "<table>",
6965
+ "<thead><tr><th>Metric</th><th>Trend</th>" + trend.runs.map((run) => `<th>${escapeHtml(run.label)}</th>`).join("") + "<th>Unit</th><th>Delta</th><th>%</th><th>Status</th><th>Fidelity</th></tr></thead>",
6966
+ "<tbody>",
6967
+ ...seriesRows,
6968
+ "</tbody>",
6969
+ "</table>",
6970
+ "</section>",
6971
+ "<footer>Generated from measured run data. A dash is a run that did not emit the metric, never a zero. No scripts, no external resources.</footer>",
6972
+ "</main>",
6973
+ "</body>",
6974
+ "</html>",
6975
+ ""
6976
+ ].join("\n");
6977
+ }
6978
+
6609
6979
  // src/scenario/actions.ts
6610
6980
  var MAX_SCROLLS = 5;
6611
6981
  var DEFAULT_DISTANCE = 40;
@@ -14021,7 +14391,7 @@ var StartupAnalyzer = class {
14021
14391
 
14022
14392
  // src/analyze/hilog.ts
14023
14393
  var SAMPLE_LIMIT = 5;
14024
- function byString(a, b) {
14394
+ function byString2(a, b) {
14025
14395
  return a < b ? -1 : a > b ? 1 : 0;
14026
14396
  }
14027
14397
  function appProcessName8(ctx) {
@@ -14131,7 +14501,7 @@ var HilogAnalyzer = class {
14131
14501
  window: ctx.window
14132
14502
  })
14133
14503
  ];
14134
- metrics.sort((a, b) => byString(a.id, b.id));
14504
+ metrics.sort((a, b) => byString2(a.id, b.id));
14135
14505
  const process2 = appProcessName8(ctx);
14136
14506
  const items = byRule.filter((rule) => rule.matches.length > 0).map((rule) => {
14137
14507
  const first = rule.matches[0];
@@ -14183,7 +14553,7 @@ function byEvidenceOrder9(a, b) {
14183
14553
  // src/analyze/ui.ts
14184
14554
  var NO_SCREENSHOT = "no screenshot in this scene";
14185
14555
  var NO_TREE = "no UI tree in this scene";
14186
- function byString2(a, b) {
14556
+ function byString3(a, b) {
14187
14557
  return a < b ? -1 : a > b ? 1 : 0;
14188
14558
  }
14189
14559
  function appProcessName9(ctx) {
@@ -14340,7 +14710,7 @@ var UiAnalyzer = class {
14340
14710
  ...treeMetrics(ctx, nodes),
14341
14711
  ...imageMetrics(ctx, image, ctx.screenshotError ?? NO_SCREENSHOT)
14342
14712
  ];
14343
- metrics.sort((a, b) => byString2(a.id, b.id));
14713
+ metrics.sort((a, b) => byString3(a.id, b.id));
14344
14714
  const items = nodes === void 0 ? [] : (() => {
14345
14715
  const stats = treeStats(nodes);
14346
14716
  return [evidence({
@@ -15948,7 +16318,7 @@ var SymbolsAnalyzer = class {
15948
16318
  const unresolvedWeight = unresolved.reduce((sum, row2) => sum + row2.samples, 0);
15949
16319
  const total = resolvedWeight + unresolvedWeight;
15950
16320
  const hasSymbolTable = ctx.perf.hasSymbolTable();
15951
- const files = [...new Set(resolved.map((row2) => row2.filePath).filter((path) => path !== ""))].sort(byString3);
16321
+ const files = [...new Set(resolved.map((row2) => row2.filePath).filter((path) => path !== ""))].sort(byString4);
15952
16322
  const top = resolved[0];
15953
16323
  const prov = {
15954
16324
  collector: "hiperf",
@@ -16076,7 +16446,7 @@ function share2(samples, total) {
16076
16446
  function formatShare(value) {
16077
16447
  return `${value}%`;
16078
16448
  }
16079
- function byString3(a, b) {
16449
+ function byString4(a, b) {
16080
16450
  return a < b ? -1 : a > b ? 1 : 0;
16081
16451
  }
16082
16452
  function byMetricId14(a, b) {
@@ -16996,7 +17366,7 @@ import { createHash as createHash2 } from "node:crypto";
16996
17366
  var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
16997
17367
  var LARGEST_COUNT = 10;
16998
17368
  var EXPLAIN_PATHS = 5;
16999
- function byString4(a, b) {
17369
+ function byString5(a, b) {
17000
17370
  return a < b ? -1 : a > b ? 1 : 0;
17001
17371
  }
17002
17372
  function sha256(bytes) {
@@ -17048,7 +17418,7 @@ function findDuplicates(archive, inventory) {
17048
17418
  const groups = [];
17049
17419
  for (const [hash, files] of byHash) {
17050
17420
  if (files.length < 2) continue;
17051
- const sorted = [...files].sort((a, b) => byString4(a.path, b.path));
17421
+ const sorted = [...files].sort((a, b) => byString5(a.path, b.path));
17052
17422
  const size = sorted[0].size;
17053
17423
  groups.push({
17054
17424
  sha256: hash,
@@ -17058,7 +17428,7 @@ function findDuplicates(archive, inventory) {
17058
17428
  paths: sorted.map((file) => file.path)
17059
17429
  });
17060
17430
  }
17061
- return groups.sort((a, b) => byString4(a.sha256, b.sha256));
17431
+ return groups.sort((a, b) => byString5(a.sha256, b.sha256));
17062
17432
  }
17063
17433
  function findOversized(inventory) {
17064
17434
  return inventory.filter((file) => file.size > CATEGORY_MAX_BYTES[file.category]).map((file) => ({
@@ -17066,7 +17436,7 @@ function findOversized(inventory) {
17066
17436
  category: file.category,
17067
17437
  size: file.size,
17068
17438
  threshold: CATEGORY_MAX_BYTES[file.category]
17069
- })).sort((a, b) => b.size - a.size || byString4(a.path, b.path));
17439
+ })).sort((a, b) => b.size - a.size || byString5(a.path, b.path));
17070
17440
  }
17071
17441
  function categoryTotals(inventory) {
17072
17442
  const totals = /* @__PURE__ */ new Map();
@@ -17079,7 +17449,7 @@ function categoryTotals(inventory) {
17079
17449
  compressedSize: (current?.compressedSize ?? 0) + file.compressedSize
17080
17450
  });
17081
17451
  }
17082
- return [...totals.values()].sort((a, b) => byString4(a.name, b.name));
17452
+ return [...totals.values()].sort((a, b) => byString5(a.name, b.name));
17083
17453
  }
17084
17454
  function listPaths(paths) {
17085
17455
  const shown = paths.slice(0, EXPLAIN_PATHS).join(", ");
@@ -17171,7 +17541,7 @@ function buildMetrics(analysis) {
17171
17541
  window: OFFLINE_WINDOW
17172
17542
  }));
17173
17543
  }
17174
- return metrics.sort((a, b) => byString4(a.id, b.id));
17544
+ return metrics.sort((a, b) => byString5(a.id, b.id));
17175
17545
  }
17176
17546
  function buildEvidence(analysis) {
17177
17547
  const subject = { process: analysis.package.bundleName === "" ? analysis.package.name : analysis.package.bundleName };
@@ -17223,7 +17593,7 @@ function buildEvidence(analysis) {
17223
17593
  key: file.path
17224
17594
  }));
17225
17595
  }
17226
- return items.sort((a, b) => byString4(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString4(a.id, b.id));
17596
+ return items.sort((a, b) => byString5(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString5(a.id, b.id));
17227
17597
  }
17228
17598
  function analyzeHap(bytes, packageName) {
17229
17599
  const archive = openZip(bytes);
@@ -17239,7 +17609,7 @@ function analyzeHap(bytes, packageName) {
17239
17609
  size: inventory.reduce((sum, file) => sum + file.size, 0),
17240
17610
  compressedSize: inventory.reduce((sum, file) => sum + file.compressedSize, 0)
17241
17611
  };
17242
- const largest = [...inventory].sort((a, b) => b.size - a.size || byString4(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
17612
+ const largest = [...inventory].sort((a, b) => b.size - a.size || byString5(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
17243
17613
  const analysis = {
17244
17614
  schemaVersion: 1,
17245
17615
  package: { name: packageName, ...packageBlock },
@@ -17289,18 +17659,18 @@ var SECTION_TITLES = {
17289
17659
  ui: "UI",
17290
17660
  vsync: "VSync"
17291
17661
  };
17292
- function byString5(a, b) {
17662
+ function byString6(a, b) {
17293
17663
  return a < b ? -1 : a > b ? 1 : 0;
17294
17664
  }
17295
17665
  function byEvidenceOrder13(a, b) {
17296
- return byString5(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString5(a.id, b.id);
17666
+ return byString6(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString6(a.id, b.id);
17297
17667
  }
17298
17668
  function emptySeverityCounts() {
17299
17669
  return { info: 0, warn: 0, critical: 0 };
17300
17670
  }
17301
17671
  function buildReport(input) {
17302
- const sections = [...input.sections].sort((a, b) => byString5(a.analyzerId, b.analyzerId)).map((section) => {
17303
- const metrics = [...section.result.metrics].sort((a, b) => byString5(a.id, b.id));
17672
+ const sections = [...input.sections].sort((a, b) => byString6(a.analyzerId, b.analyzerId)).map((section) => {
17673
+ const metrics = [...section.result.metrics].sort((a, b) => byString6(a.id, b.id));
17304
17674
  const evidence2 = [...section.result.evidence].sort(byEvidenceOrder13);
17305
17675
  const reason = evidence2.find((item) => item.kind === "degraded_capability")?.explain;
17306
17676
  return {
@@ -17472,7 +17842,7 @@ function metricNote(metric2) {
17472
17842
  }
17473
17843
  return "";
17474
17844
  }
17475
- var STYLE2 = `
17845
+ var STYLE3 = `
17476
17846
  :root { color-scheme: light; }
17477
17847
  * { box-sizing: border-box; }
17478
17848
  body { margin: 0; padding: 2rem 1.25rem 4rem; font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; color: #1c1f24; background: #f6f7f9; }
@@ -17626,7 +17996,7 @@ function renderReportHtml(model) {
17626
17996
  '<meta charset="utf-8">',
17627
17997
  '<meta name="viewport" content="width=device-width, initial-scale=1">',
17628
17998
  `<title>ohos-perf report \u2014 ${escapeHtml(scenario.app.packageName)}</title>`,
17629
- `<style>${STYLE2}</style>`,
17999
+ `<style>${STYLE3}</style>`,
17630
18000
  "</head>",
17631
18001
  "<body>",
17632
18002
  "<main>",
@@ -18033,7 +18403,7 @@ function totalWeight(stacks) {
18033
18403
  }
18034
18404
  return total;
18035
18405
  }
18036
- var STYLE3 = `
18406
+ var STYLE4 = `
18037
18407
  :root { color-scheme: light; }
18038
18408
  * { box-sizing: border-box; }
18039
18409
  body { margin: 0; padding: 2rem 1.25rem 4rem; font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; color: #1c1f24; background: #f6f7f9; }
@@ -18056,7 +18426,7 @@ function renderFlamegraphHtml(input) {
18056
18426
  '<meta charset="utf-8">',
18057
18427
  '<meta name="viewport" content="width=device-width, initial-scale=1">',
18058
18428
  `<title>Flame graph \u2014 ${escapeHtml(input.app)}</title>`,
18059
- `<style>${STYLE3}</style>`,
18429
+ `<style>${STYLE4}</style>`,
18060
18430
  "</head>",
18061
18431
  "<body>",
18062
18432
  "<main>",
@@ -18079,6 +18449,7 @@ function renderFlamegraphHtml(input) {
18079
18449
  ].join("\n");
18080
18450
  }
18081
18451
  export {
18452
+ ANIMATION_BANDS,
18082
18453
  BinderAnalyzer,
18083
18454
  BinderQuery,
18084
18455
  CATEGORY_EXTENSIONS,
@@ -18132,6 +18503,7 @@ export {
18132
18503
  MAX_QUERY_LIMIT,
18133
18504
  METRIC_DIRECTIONS,
18134
18505
  MIN_BUFFER_PAGES,
18506
+ MIN_HASH_PIXELS,
18135
18507
  MemMeasureQuery,
18136
18508
  MemoryAnalyzer,
18137
18509
  MemoryMeasureAnalyzer,
@@ -18166,17 +18538,21 @@ export {
18166
18538
  UitestCollector,
18167
18539
  VsyncAnalyzer,
18168
18540
  aggregateUnreleased,
18541
+ analyseAnimations,
18169
18542
  analyzeHap,
18170
18543
  analyzeThreadWakeup,
18544
+ animationSeverity,
18171
18545
  buildDepGraph,
18172
18546
  buildHiprofilerConfig,
18173
18547
  buildInventory,
18174
18548
  buildMatrix,
18175
18549
  buildNativeTimeline,
18176
18550
  buildReport,
18551
+ buildTrend,
18177
18552
  categorize,
18178
18553
  classifyNativePath,
18179
18554
  compareImages,
18555
+ compareRegion,
18180
18556
  compareResults,
18181
18557
  compareSceneDirs,
18182
18558
  compareScenes,
@@ -18191,6 +18567,7 @@ export {
18191
18567
  computeVsyncAnomalies,
18192
18568
  connect,
18193
18569
  createSceneLayout,
18570
+ cropRegion,
18194
18571
  decodePng,
18195
18572
  defaultAnalyzers,
18196
18573
  dhash,
@@ -18251,6 +18628,8 @@ export {
18251
18628
  renderReportXlsx,
18252
18629
  renderScenesComparison,
18253
18630
  renderSummaryJson,
18631
+ renderTrendHtml,
18632
+ renderTrendJson,
18254
18633
  renderUiDiffHtml,
18255
18634
  resolveAppIdentity,
18256
18635
  resolveAppIpids,
@@ -18265,6 +18644,7 @@ export {
18265
18644
  sortSteps,
18266
18645
  summarizeReport,
18267
18646
  tableRowCounts,
18647
+ trendRunFromReport,
18268
18648
  unknownQueryError,
18269
18649
  validateRules,
18270
18650
  writeProcfsSamples,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohos-perf/core",
3
- "version": "0.14.0",
3
+ "version": "0.16.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",