@ohos-perf/cli 0.1.0 → 0.11.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 (2) hide show
  1. package/dist/index.js +921 -87
  2. package/package.json +49 -39
package/dist/index.js CHANGED
@@ -1,6 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/commands.ts
4
+ import { readFileSync, statSync } from "fs";
5
+ import {
6
+ OhosPerfError as OhosPerfError2,
7
+ parseScenario
8
+ } from "@ohos-perf/core";
9
+
3
10
  // src/doctor.ts
11
+ import { OhosPerfError } from "@ohos-perf/core";
4
12
  function byId(a, b) {
5
13
  if (a.id < b.id) return -1;
6
14
  if (a.id > b.id) return 1;
@@ -14,10 +22,16 @@ function safeMessage(err) {
14
22
  return "<unprintable error>";
15
23
  }
16
24
  }
25
+ function failureLine(err) {
26
+ if (err instanceof OhosPerfError && err.code !== void 0) {
27
+ return `${err.code}: ${safeMessage(err)}`;
28
+ }
29
+ return safeMessage(err);
30
+ }
17
31
  function message(err) {
18
32
  return safeMessage(err);
19
33
  }
20
- async function doctorReport(deps2) {
34
+ async function doctorReport(deps2, target) {
21
35
  const hdc = { ok: false };
22
36
  try {
23
37
  hdc.path = await deps2.resolveHdc();
@@ -38,7 +52,7 @@ async function doctorReport(deps2) {
38
52
  let capabilities = [];
39
53
  let probeError;
40
54
  try {
41
- const connected = await deps2.connectDevice();
55
+ const connected = await deps2.connectDevice(target);
42
56
  const matrix = await connected.capabilities();
43
57
  device = { id: connected.id, kind: connected.kind, abi: connected.abi };
44
58
  capabilities = [...matrix.all()].sort(byId);
@@ -74,7 +88,7 @@ function json(value) {
74
88
  return JSON.stringify(value, null, 2) + "\n";
75
89
  }
76
90
  async function runDoctor(deps2, opts) {
77
- const report = await doctorReport(deps2.doctor);
91
+ const report = await doctorReport(deps2.doctor, opts.target);
78
92
  const exitCode = report.hdc.ok ? 0 : 1;
79
93
  if (opts.json) return { stdout: json(report), stderr: "", exitCode };
80
94
  let stdout = "";
@@ -109,7 +123,7 @@ async function runDoctor(deps2, opts) {
109
123
  return { stdout, stderr: "", exitCode };
110
124
  }
111
125
  async function runCaps(deps2, opts) {
112
- const report = await deps2.capsReport();
126
+ const report = await deps2.capsReport(opts.target);
113
127
  if (!report.hdcOk) {
114
128
  return { stdout: "", stderr: `hdc unavailable: ${report.hdcError}
115
129
  `, exitCode: 1 };
@@ -136,7 +150,7 @@ async function runAnalyze(deps2, sceneDir, opts) {
136
150
  `;
137
151
  return { stdout: metrics + summary, stderr: "", exitCode: 0 };
138
152
  } catch (err) {
139
- return { stdout: "", stderr: `${safeMessage(err)}
153
+ return { stdout: "", stderr: `${failureLine(err)}
140
154
  `, exitCode: 1 };
141
155
  }
142
156
  }
@@ -153,13 +167,43 @@ async function runCollect(deps2, req, opts) {
153
167
  const samples = [
154
168
  ...result.hiperf === void 0 ? [] : [`hiperf ${result.hiperf.samples}`],
155
169
  ...result.hidumper === void 0 ? [] : [`hidumper ${result.hidumper.frames}`],
156
- ...result.ui === void 0 ? [] : [`ui ${result.ui.nodes}`]
170
+ ...result.ui === void 0 ? [] : [`ui ${result.ui.nodes}`],
171
+ ...result.screenshot === void 0 ? [] : [`screenshot ${result.screenshot.width}x${result.screenshot.height}`]
157
172
  ];
158
173
  if (samples.length > 0) stdout += `samples ${samples.join(", ")}
174
+ `;
175
+ if (result.soDir !== void 0) stdout += `symbols ${result.soDir}
159
176
  `;
160
177
  return { stdout, stderr: "", exitCode: 0 };
161
178
  } catch (err) {
162
- return { stdout: "", stderr: `${safeMessage(err)}
179
+ return { stdout: "", stderr: `${failureLine(err)}
180
+ `, exitCode: 1 };
181
+ }
182
+ }
183
+ function gestureSummary(gesture) {
184
+ switch (gesture.action) {
185
+ case "click":
186
+ return `click ${gesture.x} ${gesture.y}`;
187
+ case "swipe": {
188
+ const velocity = gesture.velocity === void 0 ? "" : ` (velocity ${gesture.velocity})`;
189
+ return `swipe ${gesture.fromX},${gesture.fromY} -> ${gesture.toX},${gesture.toY}${velocity}`;
190
+ }
191
+ case "key":
192
+ return `key ${gesture.key}`;
193
+ case "inputText":
194
+ return `input ${gesture.x} ${gesture.y} ${JSON.stringify(gesture.text)}`;
195
+ case "text":
196
+ return `text ${JSON.stringify(gesture.text)}`;
197
+ }
198
+ }
199
+ async function runGesture(deps2, req, opts) {
200
+ try {
201
+ const result = await deps2.gesture(req);
202
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
203
+ return { stdout: `${gestureSummary(req.gesture)} accepted
204
+ `, stderr: "", exitCode: 0 };
205
+ } catch (err) {
206
+ return { stdout: "", stderr: `${failureLine(err)}
163
207
  `, exitCode: 1 };
164
208
  }
165
209
  }
@@ -172,7 +216,7 @@ async function runQuery(deps2, req, opts) {
172
216
  const rows = result.rows.map((row) => JSON.stringify(row) + "\n").join("");
173
217
  return { stdout: summary + rows, stderr: "", exitCode: 0 };
174
218
  } catch (err) {
175
- return { stdout: "", stderr: `${safeMessage(err)}
219
+ return { stdout: "", stderr: `${failureLine(err)}
176
220
  `, exitCode: 1 };
177
221
  }
178
222
  }
@@ -201,7 +245,178 @@ async function runCompare(deps2, req, opts) {
201
245
  return { stdout: rows.join("") + `totals ${totals}
202
246
  `, stderr: "", exitCode: 0 };
203
247
  } catch (err) {
204
- return { stdout: "", stderr: `${safeMessage(err)}
248
+ return { stdout: "", stderr: `${failureLine(err)}
249
+ `, exitCode: 1 };
250
+ }
251
+ }
252
+ async function runUiCompare(deps2, req, opts) {
253
+ try {
254
+ const result = await deps2.uiCompare(req);
255
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
256
+ const lines = [];
257
+ if (result.tree === null) {
258
+ lines.push("tree not compared (no ui.json on either side)\n");
259
+ } else {
260
+ lines.push(
261
+ `tree ${result.tree.added} added, ${result.tree.removed} removed, ${result.tree.changed} changed, ${result.tree.unchanged} unchanged
262
+ `
263
+ );
264
+ }
265
+ if (result.image === null) {
266
+ lines.push("image not compared (no screenshot.png on either side)\n");
267
+ } else {
268
+ lines.push(
269
+ `image similarity ${result.image.similarity} (hamming ${result.image.hamming}/64), changed ${result.image.changedRatio} at tolerance ${result.image.tolerance}
270
+ `
271
+ );
272
+ }
273
+ lines.push(`regions ${result.regions}
274
+ `);
275
+ for (const line of result.degraded) lines.push(`degraded ${line}
276
+ `);
277
+ lines.push(`wrote ${result.files.join(", ")} in ${result.outDir}
278
+ `);
279
+ return { stdout: lines.join(""), stderr: "", exitCode: 0 };
280
+ } catch (err) {
281
+ return { stdout: "", stderr: `${failureLine(err)}
282
+ `, exitCode: 1 };
283
+ }
284
+ }
285
+ async function runReport(deps2, req, opts) {
286
+ try {
287
+ const result = await deps2.report(req);
288
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
289
+ const sections = result.sections.degraded === 0 ? `sections ${result.sections.total} measured
290
+ ` : `sections ${result.sections.measured} measured, ${result.sections.degraded} degraded
291
+ `;
292
+ const comparison = result.comparison === void 0 ? "" : `comparison ${DELTA_ORDER.map(
293
+ (status) => `${status} ${result.comparison[status]}`
294
+ ).join(", ")}
295
+ `;
296
+ return {
297
+ stdout: `report ${result.outDir}/report.html
298
+ artifacts ${result.files.join(" ")}
299
+ ` + sections + `totals ${result.metrics} metrics, ${result.evidence} evidence (info ${result.bySeverity.info}, warn ${result.bySeverity.warn}, critical ${result.bySeverity.critical})
300
+ ` + comparison,
301
+ stderr: "",
302
+ exitCode: 0
303
+ };
304
+ } catch (err) {
305
+ return { stdout: "", stderr: `${failureLine(err)}
306
+ `, exitCode: 1 };
307
+ }
308
+ }
309
+ async function runHap(deps2, req, opts) {
310
+ const pathError = packagePathError(req.packagePath);
311
+ if (pathError !== void 0) return { stdout: "", stderr: `${pathError}
312
+ `, exitCode: 1 };
313
+ try {
314
+ const result = await deps2.hap(req);
315
+ if (opts.json) {
316
+ return {
317
+ stdout: json({ analysis: result.analysis, capabilities: result.capabilities }),
318
+ stderr: "",
319
+ exitCode: 0
320
+ };
321
+ }
322
+ const analysis = result.analysis;
323
+ const app = analysis.package;
324
+ const identity = [app.bundleName === "" ? "" : app.bundleName, app.versionName].filter((part) => part !== "").join(" ");
325
+ const version = app.versionCode === 0 ? "" : ` (${app.versionCode})`;
326
+ const label = app.appName === "" ? "" : ` ${app.appName}`;
327
+ let stdout = `package ${app.name}${identity === "" ? "" : ` ${identity}${version}`}${label}
328
+ `;
329
+ stdout += `files ${analysis.totals.files}, ${analysis.totals.size} bytes (${analysis.totals.compressedSize} compressed)
330
+ `;
331
+ stdout += analysis.technologies.length === 0 ? "tech none detected\n" : analysis.technologies.map(
332
+ (entry) => `tech ${entry.type} (rule ${entry.ruleId}) ${entry.files.length} file(s), ${entry.bytes} bytes
333
+ `
334
+ ).join("");
335
+ const wasted = analysis.duplicates.reduce((sum, group) => sum + group.wastedBytes, 0);
336
+ stdout += `duplicates ${analysis.duplicates.length} group(s), ${wasted} bytes wasted
337
+ `;
338
+ stdout += `oversized ${analysis.oversized.length} file(s)
339
+ `;
340
+ if (analysis.largest.length > 0) {
341
+ stdout += `largest ${analysis.largest.map((file) => `${file.path} ${file.size} bytes`).join("\n ")}
342
+ `;
343
+ }
344
+ if (result.outDir !== void 0 && result.artifacts !== void 0) {
345
+ stdout += `wrote ${result.artifacts.join(", ")} in ${result.outDir}
346
+ `;
347
+ }
348
+ return { stdout, stderr: "", exitCode: 0 };
349
+ } catch (err) {
350
+ return { stdout: "", stderr: `${failureLine(err)}
351
+ `, exitCode: 1 };
352
+ }
353
+ }
354
+ function packagePathError(packagePath) {
355
+ let stats;
356
+ try {
357
+ stats = statSync(packagePath);
358
+ } catch {
359
+ return `no such package: ${packagePath}`;
360
+ }
361
+ if (!stats.isFile()) return `not a file: ${packagePath}`;
362
+ const dot = packagePath.lastIndexOf(".");
363
+ const extension = dot <= 0 ? "" : packagePath.slice(dot + 1).toLowerCase();
364
+ if (extension !== "hap" && extension !== "hsp" && extension !== "zip") {
365
+ return `not a package (expected .hap, .hsp or .zip): ${packagePath}`;
366
+ }
367
+ return void 0;
368
+ }
369
+ async function runScenarioCommand(deps2, input, opts) {
370
+ let scenario;
371
+ try {
372
+ let text;
373
+ try {
374
+ text = readFileSync(input.scenarioPath, "utf8");
375
+ } catch (err) {
376
+ throw new OhosPerfError2(
377
+ `cannot read scenario ${input.scenarioPath}: ${safeMessage(err)}`,
378
+ { code: "SCENARIO_UNREADABLE", cause: err }
379
+ );
380
+ }
381
+ scenario = parseScenario(text);
382
+ } catch (err) {
383
+ return { stdout: "", stderr: `${failureLine(err)}
384
+ `, exitCode: 1 };
385
+ }
386
+ try {
387
+ const result = await deps2.run({
388
+ scenario,
389
+ scenarioPath: input.scenarioPath,
390
+ outDir: input.outDir,
391
+ ...input.target === void 0 ? {} : { target: input.target },
392
+ ...input.rounds === void 0 ? {} : { rounds: input.rounds },
393
+ ...input.only === void 0 ? {} : { only: input.only },
394
+ ...input.keepGoing === true ? { keepGoing: true } : {}
395
+ });
396
+ if (opts.json) {
397
+ return {
398
+ stdout: json(result),
399
+ stderr: "",
400
+ exitCode: result.status === "failed" ? 1 : 0
401
+ };
402
+ }
403
+ const ok = result.steps.filter((step) => step.status === "ok").length;
404
+ const failed = result.steps.length - ok;
405
+ const lines = result.steps.map((step) => {
406
+ const scene = step.sceneDir === void 0 ? "" : ` ${step.sceneDir}`;
407
+ const error = step.status === "ok" ? "" : ` ${step.error ?? "failed"}`;
408
+ return `${step.status === "ok" ? "ok " : "failed"} ${step.id} round ${step.round}${scene}${error}`;
409
+ });
410
+ const summary = failed === 0 ? `steps ${ok}/${result.steps.length} ok` : `steps ${ok}/${result.steps.length} ok, ${failed} failed`;
411
+ return {
412
+ stdout: `${lines.map((line) => `${line}
413
+ `).join("")}${summary}
414
+ `,
415
+ stderr: "",
416
+ exitCode: result.status === "failed" ? 1 : 0
417
+ };
418
+ } catch (err) {
419
+ return { stdout: "", stderr: `${failureLine(err)}
205
420
  `, exitCode: 1 };
206
421
  }
207
422
  }
@@ -217,25 +432,97 @@ function runTools(deps2, opts) {
217
432
  });
218
433
  return { stdout: lines.join(""), stderr: "", exitCode: 0 };
219
434
  } catch (err) {
220
- return { stdout: "", stderr: `${safeMessage(err)}
435
+ return { stdout: "", stderr: `${failureLine(err)}
436
+ `, exitCode: 1 };
437
+ }
438
+ }
439
+ function targetsOf(opts) {
440
+ return {
441
+ ...opts.instancePath === void 0 ? {} : { instancePath: opts.instancePath },
442
+ ...opts.imageRoot === void 0 ? {} : { imageRoot: opts.imageRoot },
443
+ ...opts.emulatorPath === void 0 ? {} : { emulatorPath: opts.emulatorPath }
444
+ };
445
+ }
446
+ async function runEmulatorList(deps2, opts) {
447
+ try {
448
+ const instances = await deps2.emulator.list(targetsOf(opts));
449
+ if (opts.json) return { stdout: json({ instances }), stderr: "", exitCode: 0 };
450
+ if (instances.length === 0) return { stdout: "no emulator instances\n", stderr: "", exitCode: 0 };
451
+ const rows = instances.map((instance) => [
452
+ instance.name,
453
+ instance.running ? "yes" : "no",
454
+ instance.target ?? "\u2014",
455
+ instance.apiVersion ?? "\u2014",
456
+ instance.osVersion ?? "\u2014"
457
+ ]);
458
+ const header = ["NAME", "RUNNING", "TARGET", "API", "IMAGE"];
459
+ const widths = header.map((cell, column) => Math.max(cell.length, ...rows.map((row) => row[column].length)));
460
+ const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
461
+ const body = [header, ...rows].map((cells) => line(cells) + "\n").join("");
462
+ return { stdout: body, stderr: "", exitCode: 0 };
463
+ } catch (err) {
464
+ return { stdout: "", stderr: `${failureLine(err)}
465
+ `, exitCode: 1 };
466
+ }
467
+ }
468
+ async function runEmulatorStart(deps2, name, opts) {
469
+ try {
470
+ const result = await deps2.emulator.start(name, {
471
+ ...targetsOf(opts),
472
+ ...opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
473
+ });
474
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
475
+ const line = result.alreadyRunning ? `${result.name} was already running on ${result.target}
476
+ ` : `${result.name} started on ${result.target} (booted in ${Math.round(result.waitedMs / 1e3)}s)
477
+ `;
478
+ return { stdout: line, stderr: "", exitCode: 0 };
479
+ } catch (err) {
480
+ return { stdout: "", stderr: `${failureLine(err)}
481
+ `, exitCode: 1 };
482
+ }
483
+ }
484
+ async function runEmulatorStop(deps2, name, opts) {
485
+ try {
486
+ const result = await deps2.emulator.stop(name, targetsOf(opts));
487
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
488
+ const line = result.wasRunning ? `${result.name} stopped
489
+ ` : `${result.name} was not running
490
+ `;
491
+ return { stdout: line, stderr: "", exitCode: 0 };
492
+ } catch (err) {
493
+ return { stdout: "", stderr: `${failureLine(err)}
494
+ `, exitCode: 1 };
495
+ }
496
+ }
497
+ async function runEmulatorCreate(deps2, req, opts) {
498
+ try {
499
+ const instance = await deps2.emulator.create(req);
500
+ if (opts.json) return { stdout: json(instance), stderr: "", exitCode: 0 };
501
+ const line = `Created ${instance.name} (${req.deviceType}, ${req.osVersion}) at ${instance.instancePath}
502
+ `;
503
+ return { stdout: line, stderr: "", exitCode: 0 };
504
+ } catch (err) {
505
+ return { stdout: "", stderr: `${failureLine(err)}
221
506
  `, exitCode: 1 };
222
507
  }
223
508
  }
224
509
 
225
510
  // src/deps.ts
226
- import { existsSync, readFileSync } from "fs";
227
- import { stat } from "fs/promises";
228
- import { dirname, join, resolve } from "path";
511
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
512
+ import { copyFile, mkdir, stat, writeFile } from "fs/promises";
513
+ import { basename, dirname, join, resolve } from "path";
229
514
  import { fileURLToPath } from "url";
230
515
  import {
231
516
  BinderQuery,
232
517
  CallstackQuery,
233
518
  CapabilityMatrix,
519
+ EmulatorClient,
520
+ EmulatorLifecycle,
234
521
  FrameQuery,
235
522
  Hdc,
236
523
  InstantQuery,
237
524
  MemMeasureQuery,
238
- OhosPerfError,
525
+ OhosPerfError as OhosPerfError3,
239
526
  PerfQuery,
240
527
  ProcessQuery,
241
528
  SchedQuery,
@@ -245,26 +532,44 @@ import {
245
532
  ThreadStateQuery,
246
533
  connect,
247
534
  createSceneLayout,
535
+ decodePng,
248
536
  defaultAnalyzers,
249
537
  ingestScene,
250
538
  lookupQuery,
251
539
  queryDefinitions,
252
540
  readHidumperCapture,
253
541
  readProcfsSamples,
542
+ readHilogText,
543
+ parseHilogText,
544
+ analyzeHap,
545
+ buildReport,
254
546
  compareResults,
547
+ compareSceneDirs,
548
+ UI_DIFF_FILES,
549
+ renderEvidenceCsv,
550
+ renderMetricsCsv,
551
+ renderReportHtml,
552
+ renderReportJson,
553
+ renderReportXlsx,
554
+ renderSummaryJson,
555
+ renderFlamegraphHtml,
556
+ renderFlamegraphSvg,
557
+ hapSection,
255
558
  readSceneMetadata,
256
559
  readUiTree,
257
560
  resolveAppIdentity,
561
+ ScenarioRunner,
258
562
  resolveQueryLimit,
259
- runAnalyzers,
563
+ runAnalyzerSections,
260
564
  runNamedQuery,
565
+ summarizeReport,
261
566
  unknownQueryError
262
567
  } from "@ohos-perf/core";
263
568
  var here = dirname(fileURLToPath(import.meta.url));
264
569
  var manifestPath = join(here, "../package.json");
265
570
  function packageVersion(path = manifestPath) {
266
571
  try {
267
- const pkg = JSON.parse(readFileSync(path, "utf8"));
572
+ const pkg = JSON.parse(readFileSync2(path, "utf8"));
268
573
  const version = typeof pkg.version === "string" ? pkg.version.trim() : "";
269
574
  return version === "" ? "0.0.0" : version;
270
575
  } catch {
@@ -286,23 +591,35 @@ var TABLE_RULES = [
286
591
  { id: "trace.sched", collector: "hitrace", tables: ["sched_slice", "instant"] },
287
592
  { id: "trace.binder", collector: "hitrace", tables: ["callstack", "args", "data_dict", "process", "thread", "trace_range"] },
288
593
  { id: "trace.thread_state", collector: "hitrace", tables: ["thread_state", "thread", "process"] },
594
+ // GC and component-build events are callstack rows scoped through thread and
595
+ // process; without either join the analyzers would crash rather than degrade.
596
+ { id: "trace.ark", collector: "hitrace", tables: ["callstack", "thread", "process"] },
597
+ // VSync groups are `frame_slice` rows attributed through `process`; a trace
598
+ // with one and not the other cannot scope the cadence to the app.
599
+ { id: "render.vsync", collector: "hitrace", tables: ["frame_slice", "process"] },
289
600
  // Scene artifacts, not tables: `procfs.jsonl`, `hidumper.json` and `ui.json`
290
601
  // are satisfied by the parsed artifact the caller passes in.
291
602
  { id: "mem.procfs", collector: "procfs", tables: ["procfs.jsonl"] },
292
603
  { id: "render.fps_live", collector: "hidumper", tables: ["hidumper.json"] },
293
604
  { id: "ui.tree", collector: "uitest", tables: ["ui.json"] },
605
+ { id: "ui.capture", collector: "uitest", tables: ["screenshot.png"] },
606
+ { id: "hilog.stream", collector: "hilog", tables: ["hilog.log"] },
294
607
  { id: "perf.samples", collector: "hiperf", tables: ["perf_sample"], perf: true },
295
- // `mem.native_hook` is the design's hiprofiler-memory row. Offline it is
296
- // satisfied by the memory-plugin tables, exactly as `trace.frames` is
297
- // satisfied by `frame_slice` + `process` rather than by the hitrace binary.
298
- // The analyzer joins both tables, so a trace missing the filter table would
299
- // crash rather than degrade; requiring both keeps the matrix honest. An
300
- // ftrace-only scene does not offer it, and the engine reports `mem-measure`
301
- // as skipped.
608
+ // `mem.native_hook` is the design's hiprofiler-memory row, and two plugins
609
+ // feed it. The memory plugin's `process_measure` tables back `mem-measure`;
610
+ // the nativehook plugin's `native_hook*` tables back `native-memory`. A
611
+ // scene carries one family or the other, so requiring the memory tables
612
+ // alone would degrade `native-memory` on the very capture
613
+ // `--plugins nativehook` produces. Either family satisfies the row; the
614
+ // analyzers that need a specific one degrade on their own with a reason
615
+ // naming the missing input. An ftrace-only scene offers neither.
302
616
  {
303
617
  id: "mem.native_hook",
304
618
  collector: "hiprofiler",
305
- tables: ["process_measure", "process_measure_filter"]
619
+ anyOf: [
620
+ ["process_measure", "process_measure_filter"],
621
+ ["native_hook"]
622
+ ]
306
623
  }
307
624
  ];
308
625
  function artifactPresent(name, artifacts) {
@@ -313,11 +630,21 @@ function artifactPresent(name, artifacts) {
313
630
  return artifacts.hidumper !== void 0;
314
631
  case "ui.json":
315
632
  return (artifacts.uiTree?.length ?? 0) > 0;
633
+ case "screenshot.png":
634
+ return artifacts.screenshot !== void 0;
635
+ case "hilog.log":
636
+ return (artifacts.hilog?.length ?? 0) > 0;
316
637
  default:
317
638
  return false;
318
639
  }
319
640
  }
320
- var ARTIFACT_NAMES = /* @__PURE__ */ new Set(["procfs.jsonl", "hidumper.json", "ui.json"]);
641
+ var ARTIFACT_NAMES = /* @__PURE__ */ new Set([
642
+ "procfs.jsonl",
643
+ "hidumper.json",
644
+ "ui.json",
645
+ "screenshot.png",
646
+ "hilog.log"
647
+ ]);
321
648
  function offlineCapabilities(db, artifacts, perfDb) {
322
649
  const tablesOf = (target) => new Set(
323
650
  target.query(
@@ -329,9 +656,8 @@ function offlineCapabilities(db, artifacts, perfDb) {
329
656
  const states = [];
330
657
  for (const rule of TABLE_RULES) {
331
658
  const source = rule.perf === true ? perfTables : tables;
332
- const present = rule.tables.every(
333
- (name) => ARTIFACT_NAMES.has(name) ? artifactPresent(name, artifacts) : source.has(name)
334
- );
659
+ const has = (name) => ARTIFACT_NAMES.has(name) ? artifactPresent(name, artifacts) : source.has(name);
660
+ const present = rule.anyOf === void 0 ? (rule.tables ?? []).every(has) : rule.anyOf.some((family) => family.every(has));
335
661
  if (!present) continue;
336
662
  if (rule.perf === true && perfDb !== void 0) {
337
663
  const first = rule.tables[0];
@@ -348,54 +674,96 @@ async function isDirectory(path) {
348
674
  return false;
349
675
  }
350
676
  }
351
- async function analyzeScene(open, sceneDir, app) {
677
+ function analyzeContext(opened) {
678
+ const db = opened.scene.traceDb;
679
+ return {
680
+ db,
681
+ frames: new FrameQuery(db),
682
+ processes: new ProcessQuery(db),
683
+ threads: new ThreadQuery(db),
684
+ sched: new SchedQuery(db),
685
+ instant: new InstantQuery(db),
686
+ threadStates: new ThreadStateQuery(db),
687
+ callstacks: new CallstackQuery(db),
688
+ // A hiperf capture lives in its own converted database; the trace
689
+ // database has no perf_* tables, so reading them from `db` would
690
+ // silently report no samples.
691
+ perf: new PerfQuery(opened.scene.perfDb ?? db),
692
+ binder: new BinderQuery(db),
693
+ startup: new StartupQuery(db),
694
+ // memory-plugin writes an .htrace that converts into trace.db, so the
695
+ // tables are in `db`, not in the separate perf database.
696
+ memMeasure: new MemMeasureQuery(db),
697
+ ...opened.samples.length > 0 ? { procfs: opened.samples } : {},
698
+ ...opened.uiTree === void 0 ? {} : { ui: opened.uiTree },
699
+ ...opened.screenshot === void 0 ? {} : { screenshot: opened.screenshot },
700
+ ...opened.screenshotError === void 0 ? {} : { screenshotError: opened.screenshotError },
701
+ ...opened.hidumper === void 0 ? {} : { hidumper: opened.hidumper },
702
+ ...opened.hilog === void 0 ? {} : { hilog: [...opened.hilog] },
703
+ ...opened.metadata !== void 0 ? { metadata: opened.metadata } : {},
704
+ app: opened.app,
705
+ // The whole database: a CLI run has no capture window to honour.
706
+ window: { startNs: 0, endNs: Number.MAX_SAFE_INTEGER },
707
+ caps: opened.caps,
708
+ deviceId: "offline"
709
+ };
710
+ }
711
+ function sceneWindow(opened) {
712
+ try {
713
+ const rows = opened.scene.traceDb.query(
714
+ "SELECT MIN(start_ts) AS start_ts, MAX(end_ts) AS end_ts FROM trace_range"
715
+ );
716
+ const row = rows[0];
717
+ if (row !== void 0 && typeof row.start_ts === "number" && typeof row.end_ts === "number" && row.end_ts > row.start_ts) {
718
+ return { startNs: row.start_ts, endNs: row.end_ts };
719
+ }
720
+ } catch {
721
+ }
722
+ return { startNs: 0, endNs: Number.MAX_SAFE_INTEGER };
723
+ }
724
+ function flamegraphInputs(opened) {
725
+ const perf = new PerfQuery(opened.scene.perfDb ?? opened.scene.traceDb);
726
+ const threadIds = [...new Set(perf.threads([...opened.app.pids]).map((t) => t.threadId))].sort((a, b) => a - b);
727
+ const stacks = perf.foldedStacks(threadIds, { startNs: 0, endNs: Number.MAX_SAFE_INTEGER });
728
+ const hiperf = opened.metadata?.capture?.hiperf;
729
+ const symbolizationRequested = typeof hiperf?.symbolized === "boolean" ? hiperf.symbolized : null;
730
+ return { stacks, symbolizationRequested };
731
+ }
732
+ async function analyzeSceneDetailed(open, sceneDir, app, options = {}) {
352
733
  const opened = await open(sceneDir, app);
353
734
  try {
354
- const db = opened.scene.traceDb;
355
- const context = {
356
- db,
357
- frames: new FrameQuery(db),
358
- processes: new ProcessQuery(db),
359
- threads: new ThreadQuery(db),
360
- sched: new SchedQuery(db),
361
- instant: new InstantQuery(db),
362
- threadStates: new ThreadStateQuery(db),
363
- callstacks: new CallstackQuery(db),
364
- // A hiperf capture lives in its own converted database; the trace
365
- // database has no perf_* tables, so reading them from `db` would
366
- // silently report no samples.
367
- perf: new PerfQuery(opened.scene.perfDb ?? db),
368
- binder: new BinderQuery(db),
369
- startup: new StartupQuery(db),
370
- // memory-plugin writes an .htrace that converts into trace.db, so the
371
- // tables are in `db`, not in the separate perf database.
372
- memMeasure: new MemMeasureQuery(db),
373
- ...opened.samples.length > 0 ? { procfs: opened.samples } : {},
374
- ...opened.hidumper === void 0 ? {} : { hidumper: opened.hidumper },
375
- ...opened.metadata !== void 0 ? { metadata: opened.metadata } : {},
735
+ const run = await runAnalyzerSections(defaultAnalyzers(), analyzeContext(opened));
736
+ return {
737
+ run,
376
738
  app: opened.app,
377
- // The whole database: a CLI run has no capture window to honour.
378
- window: { startNs: 0, endNs: Number.MAX_SAFE_INTEGER },
379
- caps: opened.caps,
380
- deviceId: "offline"
739
+ device: opened.metadata?.deviceId ?? "offline",
740
+ window: sceneWindow(opened),
741
+ ...opened.metadata?.startedAtNs === void 0 ? {} : { startedAtNs: opened.metadata.startedAtNs },
742
+ ...opened.screenshot === void 0 ? {} : {
743
+ screenshot: { width: opened.screenshot.width, height: opened.screenshot.height },
744
+ screenshotFile: opened.layout.screenshotFile
745
+ },
746
+ ...options.flamegraph === true ? { flamegraph: flamegraphInputs(opened) } : {}
381
747
  };
382
- return await runAnalyzers(defaultAnalyzers(), context);
383
748
  } finally {
384
749
  opened.scene.close();
385
750
  }
386
751
  }
752
+ async function analyzeScene(open, sceneDir, app) {
753
+ return (await analyzeSceneDetailed(open, sceneDir, app)).run.result;
754
+ }
387
755
  function readAnalysisFile(path) {
388
756
  let parsed;
389
757
  try {
390
- parsed = JSON.parse(readFileSync(path, "utf8"));
758
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
391
759
  } catch (err) {
392
- throw new OhosPerfError(
760
+ throw new OhosPerfError3(
393
761
  `cannot read analysis ${path}: ${safeMessage(err)}`,
394
762
  { code: "COMPARE_BAD_INPUT", cause: err }
395
763
  );
396
764
  }
397
765
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.metrics) || !Array.isArray(parsed.evidence)) {
398
- throw new OhosPerfError(
766
+ throw new OhosPerfError3(
399
767
  `analysis ${path} has no metrics/evidence arrays; pass a scene directory or the output of \`ohos-perf analyze --json\``,
400
768
  { code: "COMPARE_BAD_INPUT" }
401
769
  );
@@ -404,9 +772,10 @@ function readAnalysisFile(path) {
404
772
  }
405
773
  function realDeps(version = packageVersion(), overrides = {}) {
406
774
  const resolveHdc = () => (overrides.hdc ?? new Hdc()).resolvePath();
407
- const connectDevice = overrides.connectDevice ?? (() => connect());
775
+ const connectDevice = overrides.connectDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
408
776
  const ingest = overrides.ingest ?? ingestScene;
409
- const collectDevice = overrides.collectDevice ?? (() => connect());
777
+ const collectDevice = overrides.collectDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
778
+ const gestureDevice = overrides.gestureDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
410
779
  const doctor = {
411
780
  resolveHdc,
412
781
  async resolveStreamer() {
@@ -415,6 +784,17 @@ function realDeps(version = packageVersion(), overrides = {}) {
415
784
  },
416
785
  connectDevice
417
786
  };
787
+ const emulatorClient = (o) => new EmulatorClient({
788
+ ...o.emulatorPath === void 0 ? {} : { emulatorPath: o.emulatorPath },
789
+ ...o.instancePath === void 0 ? {} : { instancePath: o.instancePath },
790
+ ...o.imageRoot === void 0 ? {} : { imageRoot: o.imageRoot }
791
+ });
792
+ const emulator = {
793
+ list: (o) => new EmulatorLifecycle({ client: emulatorClient(o) }).list(),
794
+ start: (name, o) => new EmulatorLifecycle({ client: emulatorClient(o) }).start(name, o.timeoutMs === void 0 ? {} : { timeoutMs: o.timeoutMs }),
795
+ stop: (name, o) => new EmulatorLifecycle({ client: emulatorClient(o) }).stop(name),
796
+ create: (req) => new EmulatorLifecycle({ client: emulatorClient(req) }).create(req)
797
+ };
418
798
  const openOfflineScene = async (sceneDir, app) => {
419
799
  const layout = createSceneLayout(resolve(sceneDir));
420
800
  const scene = await ingest(new Streamer(), layout);
@@ -427,6 +807,21 @@ function realDeps(version = packageVersion(), overrides = {}) {
427
807
  const samples = declared("procfs") ? readProcfsSamples(layout.procfsFile) : [];
428
808
  const hidumper = declared("hidumper") ? readHidumperCapture(layout.hidumperFile) : void 0;
429
809
  const uiTree = declared("uitest") ? readUiTree(layout.uiFile) : void 0;
810
+ const screenshotFile = declared("screenshot") ? layout.screenshotFile : void 0;
811
+ let screenshot;
812
+ let screenshotError;
813
+ if (screenshotFile !== void 0 && existsSync(screenshotFile)) {
814
+ try {
815
+ screenshot = decodePng(new Uint8Array(readFileSync2(screenshotFile)));
816
+ } catch (err) {
817
+ screenshotError = safeMessage(err);
818
+ }
819
+ }
820
+ const hilogText = declared("hilog") ? readHilogText(layout) : void 0;
821
+ const hilog = hilogText === void 0 ? void 0 : parseHilogText(hilogText, {
822
+ ...metadata?.capture === void 0 ? {} : { year: new Date(metadata.capture.startedAtMs).getUTCFullYear() },
823
+ captureNs: (metadata?.capture?.startedAtMs ?? 0) * 1e6
824
+ });
430
825
  let appIdentity;
431
826
  if (app !== void 0) {
432
827
  appIdentity = resolveAppIdentity(processes, app);
@@ -451,12 +846,17 @@ function realDeps(version = packageVersion(), overrides = {}) {
451
846
  {
452
847
  procfsSamples: samples,
453
848
  ...hidumper === void 0 ? {} : { hidumper },
454
- ...uiTree === void 0 ? {} : { uiTree }
849
+ ...uiTree === void 0 ? {} : { uiTree },
850
+ ...screenshot === void 0 ? {} : { screenshot },
851
+ ...hilog === void 0 ? {} : { hilog }
455
852
  },
456
853
  scene.perfDb
457
854
  ),
458
855
  ...uiTree === void 0 ? {} : { uiTree },
459
- ...hidumper === void 0 ? {} : { hidumper }
856
+ ...screenshot === void 0 ? {} : { screenshot },
857
+ ...screenshotError === void 0 ? {} : { screenshotError },
858
+ ...hidumper === void 0 ? {} : { hidumper },
859
+ ...hilog === void 0 ? {} : { hilog }
460
860
  };
461
861
  } catch (err) {
462
862
  scene.close();
@@ -466,14 +866,19 @@ function realDeps(version = packageVersion(), overrides = {}) {
466
866
  return {
467
867
  doctor,
468
868
  version,
469
- async capsReport() {
869
+ emulator,
870
+ async gesture(req) {
871
+ const device = await gestureDevice(req.target);
872
+ return device.gesture(req.gesture);
873
+ },
874
+ async capsReport(target) {
470
875
  try {
471
876
  await resolveHdc();
472
877
  } catch (err) {
473
878
  return { hdcOk: false, hdcError: safeMessage(err), capabilities: [] };
474
879
  }
475
880
  try {
476
- const device = await connectDevice();
881
+ const device = await connectDevice(target);
477
882
  const matrix = await device.capabilities();
478
883
  return { hdcOk: true, capabilities: matrix.all() };
479
884
  } catch (err) {
@@ -492,9 +897,13 @@ function realDeps(version = packageVersion(), overrides = {}) {
492
897
  return runNamedQuery(
493
898
  {
494
899
  db: opened.scene.traceDb,
900
+ // A `--hiperf` scene keeps perf_sample/perf_thread in perf.db;
901
+ // omitting this made every frame.load.* query return [] on device.
902
+ ...opened.scene.perfDb === void 0 ? {} : { perfDb: opened.scene.perfDb },
495
903
  app: opened.app,
496
904
  caps: opened.caps,
497
- ...opened.uiTree === void 0 ? {} : { uiTree: opened.uiTree }
905
+ ...opened.uiTree === void 0 ? {} : { uiTree: opened.uiTree },
906
+ ...opened.hilog === void 0 ? {} : { hilog: opened.hilog }
498
907
  },
499
908
  req.name,
500
909
  args,
@@ -509,6 +918,128 @@ function realDeps(version = packageVersion(), overrides = {}) {
509
918
  const [baseline, current] = await Promise.all([load(req.baseline), load(req.current)]);
510
919
  return compareResults(baseline, current);
511
920
  },
921
+ async uiCompare(req) {
922
+ const diff = await compareSceneDirs(req.a, req.b, { outDir: req.outDir });
923
+ return {
924
+ outDir: resolve(req.outDir),
925
+ files: [...UI_DIFF_FILES],
926
+ tree: diff.tree === null ? null : {
927
+ added: diff.tree.added.length,
928
+ removed: diff.tree.removed.length,
929
+ changed: diff.tree.changed.length,
930
+ unchanged: diff.tree.unchanged
931
+ },
932
+ image: diff.image === null ? null : {
933
+ hamming: diff.image.hamming,
934
+ similarity: diff.image.similarity,
935
+ changedRatio: diff.image.changedRatio,
936
+ tolerance: diff.image.tolerance
937
+ },
938
+ regions: diff.regions.length,
939
+ degraded: [...diff.degraded]
940
+ };
941
+ },
942
+ async report(req) {
943
+ const detailed = await analyzeSceneDetailed(
944
+ openOfflineScene,
945
+ req.sceneDir,
946
+ req.app,
947
+ { flamegraph: true }
948
+ );
949
+ let comparison;
950
+ if (req.baseline !== void 0) {
951
+ const baseline = await (await isDirectory(req.baseline) ? analyzeScene(openOfflineScene, req.baseline) : readAnalysisFile(req.baseline));
952
+ comparison = compareResults(baseline, detailed.run.result);
953
+ }
954
+ const model = buildReport({
955
+ generator: { name: "@ohos-perf/core", version },
956
+ app: detailed.app,
957
+ device: detailed.device,
958
+ window: detailed.window,
959
+ ...detailed.startedAtNs === void 0 ? {} : { startedAtNs: detailed.startedAtNs },
960
+ sections: detailed.run.sections,
961
+ ...comparison === void 0 ? {} : { comparison },
962
+ ...detailed.screenshot === void 0 ? {} : { screenshot: detailed.screenshot }
963
+ });
964
+ const artifacts = [
965
+ ["report.html", renderReportHtml(model)],
966
+ ["report.json", renderReportJson(model)],
967
+ ["summary.json", renderSummaryJson(summarizeReport(model))],
968
+ ["metrics.csv", renderMetricsCsv(model)],
969
+ ["evidence.csv", renderEvidenceCsv(model)],
970
+ ["report.xlsx", renderReportXlsx(model)]
971
+ ];
972
+ const flamegraph = detailed.flamegraph;
973
+ if (flamegraph !== void 0 && flamegraph.stacks.length > 0) {
974
+ const share = model.sections.find((section) => section.id === "symbols")?.metrics.find((metric) => metric.id === "symbol.unresolved.share")?.value;
975
+ artifacts.push(
976
+ ["flamegraph.svg", renderFlamegraphSvg(flamegraph.stacks)],
977
+ ["flamegraph.html", renderFlamegraphHtml({
978
+ stacks: flamegraph.stacks,
979
+ app: detailed.app.packageName,
980
+ window: detailed.window,
981
+ unresolvedShare: typeof share === "number" ? share : null,
982
+ symbolizationRequested: flamegraph.symbolizationRequested
983
+ })]
984
+ );
985
+ }
986
+ const outDir = resolve(req.outDir);
987
+ await mkdir(outDir, { recursive: true });
988
+ for (const [name, content] of artifacts) {
989
+ await writeFile(join(outDir, name), content);
990
+ }
991
+ const files = artifacts.map(([name]) => name);
992
+ if (detailed.screenshotFile !== void 0 && detailed.screenshot !== void 0) {
993
+ await mkdir(join(outDir, "assets"), { recursive: true });
994
+ await copyFile(detailed.screenshotFile, join(outDir, "assets", "screenshot.png"));
995
+ files.push("assets/screenshot.png");
996
+ }
997
+ return {
998
+ outDir,
999
+ files,
1000
+ sections: {
1001
+ total: model.sections.length,
1002
+ measured: model.totals.measured,
1003
+ degraded: model.totals.degraded
1004
+ },
1005
+ metrics: model.totals.metrics,
1006
+ evidence: model.totals.evidence,
1007
+ bySeverity: { ...model.totals.bySeverity },
1008
+ ...model.comparison === void 0 ? {} : { comparison: { ...model.comparison.totals } }
1009
+ };
1010
+ },
1011
+ async hap(req) {
1012
+ const analysis = analyzeHap(readFileSync2(req.packagePath), basename(req.packagePath));
1013
+ const capabilities = [{
1014
+ id: "static.hap",
1015
+ available: true,
1016
+ collector: "offline",
1017
+ fidelity: "exact",
1018
+ probe: { command: "", stdout: "", stderr: "", code: 0 }
1019
+ }];
1020
+ if (req.outDir === void 0) return { analysis, capabilities };
1021
+ const model = buildReport({
1022
+ generator: { name: "@ohos-perf/core", version },
1023
+ app: {
1024
+ packageName: analysis.package.bundleName === "" ? analysis.package.name : analysis.package.bundleName,
1025
+ pids: [],
1026
+ processNames: []
1027
+ },
1028
+ device: "offline",
1029
+ window: { startNs: 0, endNs: 0 },
1030
+ sections: [hapSection(analysis)]
1031
+ });
1032
+ const artifacts = [
1033
+ ["hap.json", JSON.stringify(analysis, null, 2) + "\n"],
1034
+ ["hap.html", renderReportHtml(model)]
1035
+ ];
1036
+ const outDir = resolve(req.outDir);
1037
+ await mkdir(outDir, { recursive: true });
1038
+ for (const [name, content] of artifacts) {
1039
+ await writeFile(join(outDir, name), content);
1040
+ }
1041
+ return { analysis, capabilities, outDir, artifacts: artifacts.map(([name]) => name) };
1042
+ },
512
1043
  tools() {
513
1044
  return queryDefinitions().map((definition) => ({
514
1045
  name: definition.name,
@@ -517,9 +1048,19 @@ function realDeps(version = packageVersion(), overrides = {}) {
517
1048
  returns: definition.returns
518
1049
  }));
519
1050
  },
1051
+ async run(req) {
1052
+ const device = await connect(req.target === void 0 ? {} : { target: req.target });
1053
+ const runner = new ScenarioRunner(device, {
1054
+ outDir: resolve(req.outDir),
1055
+ ...req.rounds === void 0 ? {} : { rounds: req.rounds },
1056
+ ...req.only === void 0 ? {} : { only: req.only },
1057
+ ...req.keepGoing === true ? { keepGoing: true } : {}
1058
+ });
1059
+ return runner.run(req.scenario);
1060
+ },
520
1061
  async collect(req) {
521
1062
  const sceneDir = resolve(req.out);
522
- const device = await collectDevice();
1063
+ const device = await collectDevice(req.target);
523
1064
  const session = await device.collect({
524
1065
  app: req.app,
525
1066
  durationMs: req.durationMs,
@@ -530,8 +1071,11 @@ function realDeps(version = packageVersion(), overrides = {}) {
530
1071
  hiprofiler: req.hiprofiler.plugins === void 0 ? {} : { plugins: req.hiprofiler.plugins }
531
1072
  },
532
1073
  ...req.hiperf === void 0 ? {} : { hiperf: req.hiperf },
1074
+ ...req.soDir === void 0 ? {} : { soDir: req.soDir },
533
1075
  ...req.hidumper === true ? { hidumper: true } : {},
534
- ...req.uitest === true ? { uitest: true } : {}
1076
+ ...req.uitest === true ? { uitest: true } : {},
1077
+ ...req.screenshot === true ? { screenshot: true } : {},
1078
+ ...req.hilog === true ? { hilog: true } : {}
535
1079
  });
536
1080
  const scene = await session.ingest();
537
1081
  try {
@@ -541,9 +1085,22 @@ function realDeps(version = packageVersion(), overrides = {}) {
541
1085
  sceneDir,
542
1086
  device: { id: device.id, kind: device.kind },
543
1087
  collectors: meta?.capture?.collectors ?? [],
544
- ...meta?.capture?.hiperf === void 0 ? {} : { hiperf: { samples: meta.capture.hiperf.samples } },
1088
+ ...meta?.capture?.hiperf === void 0 ? {} : {
1089
+ hiperf: {
1090
+ samples: meta.capture.hiperf.samples,
1091
+ ...meta.capture.hiperf.symbolized === void 0 ? {} : { symbolized: meta.capture.hiperf.symbolized }
1092
+ }
1093
+ },
1094
+ ...req.soDir === void 0 ? {} : { soDir: resolve(req.soDir) },
545
1095
  ...meta?.capture?.hidumper === void 0 ? {} : { hidumper: { frames: meta.capture.hidumper.frames } },
546
- ...meta?.capture?.uitest === void 0 ? {} : { ui: { nodes: meta.capture.uitest.nodes } }
1096
+ ...meta?.capture?.uitest === void 0 ? {} : { ui: { nodes: meta.capture.uitest.nodes } },
1097
+ ...meta?.capture?.screenshot === void 0 ? {} : {
1098
+ screenshot: {
1099
+ width: meta.capture.screenshot.width,
1100
+ height: meta.capture.screenshot.height
1101
+ }
1102
+ },
1103
+ ...meta?.capture?.hilog === void 0 ? {} : { hilog: { lines: meta.capture.hilog.lines } }
547
1104
  };
548
1105
  } finally {
549
1106
  scene.close();
@@ -558,14 +1115,14 @@ import { Command } from "commander";
558
1115
  // src/collect.ts
559
1116
  import {
560
1117
  HIPROFILER_PLUGIN_NAMES,
561
- OhosPerfError as OhosPerfError2
1118
+ OhosPerfError as OhosPerfError4
562
1119
  } from "@ohos-perf/core";
563
1120
  var MAX_TIMEOUT_MS = 2147483647;
564
1121
  function parseDurationSeconds(raw) {
565
1122
  const text = raw.trim();
566
1123
  const match = /^(\d+(?:\.\d+)?|\.\d+)s?$/.exec(text);
567
1124
  const seconds = match === null ? Number.NaN : Number(match[1]);
568
- const bad = (why) => new OhosPerfError2(
1125
+ const bad = (why) => new OhosPerfError4(
569
1126
  `invalid --duration ${JSON.stringify(raw)}: ${why} (expected a positive whole number of milliseconds, e.g. 10 or 10s)`,
570
1127
  { code: "COLLECT_BAD_DURATION" }
571
1128
  );
@@ -588,7 +1145,7 @@ function parseDurationSeconds(raw) {
588
1145
  function parsePluginList(raw) {
589
1146
  const names = raw.split(",").map((name) => name.trim());
590
1147
  if (names.length === 0 || names.some((name) => name === "")) {
591
- throw new OhosPerfError2(
1148
+ throw new OhosPerfError4(
592
1149
  `invalid --plugins ${JSON.stringify(raw)}: expected a comma-separated list of ` + HIPROFILER_PLUGIN_NAMES.join(", "),
593
1150
  { code: "COLLECT_BAD_PLUGIN" }
594
1151
  );
@@ -596,7 +1153,7 @@ function parsePluginList(raw) {
596
1153
  const plugins = [];
597
1154
  for (const name of names) {
598
1155
  if (!HIPROFILER_PLUGIN_NAMES.includes(name)) {
599
- throw new OhosPerfError2(
1156
+ throw new OhosPerfError4(
600
1157
  `unknown hiprofiler plugin ${JSON.stringify(name)}; expected one of ${HIPROFILER_PLUGIN_NAMES.join(", ")}`,
601
1158
  { code: "COLLECT_BAD_PLUGIN" }
602
1159
  );
@@ -608,23 +1165,64 @@ function parsePluginList(raw) {
608
1165
  return plugins;
609
1166
  }
610
1167
 
1168
+ // src/gesture.ts
1169
+ var COORDINATE = /^\d+$/;
1170
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
1171
+ function parseCoordinate(raw, label) {
1172
+ const value = Number(raw);
1173
+ if (!COORDINATE.test(raw) || !Number.isSafeInteger(value)) {
1174
+ throw new Error(
1175
+ `invalid ${label}: expected a non-negative whole number, got ${JSON.stringify(raw)}`
1176
+ );
1177
+ }
1178
+ return value;
1179
+ }
1180
+ function parseVelocity(raw) {
1181
+ const value = Number(raw);
1182
+ if (!COORDINATE.test(raw) || !Number.isSafeInteger(value) || value < 200 || value > 4e4) {
1183
+ throw new Error(
1184
+ `invalid --velocity: expected a whole number from 200 to 40000, got ${JSON.stringify(raw)}`
1185
+ );
1186
+ }
1187
+ return value;
1188
+ }
1189
+ function parseKey(raw) {
1190
+ if (raw === "Back" || raw === "Home" || raw === "Power") return raw;
1191
+ const value = Number(raw);
1192
+ if (/^[1-9]\d*$/.test(raw) && Number.isSafeInteger(value)) return value;
1193
+ throw new Error(
1194
+ `invalid <key>: expected Back, Home, Power or a positive key code, got ${JSON.stringify(raw)}`
1195
+ );
1196
+ }
1197
+ function parseText(raw) {
1198
+ if (raw === "") {
1199
+ throw new Error("invalid <text>: expected a non-empty string");
1200
+ }
1201
+ if (CONTROL_CHARS.test(raw)) {
1202
+ throw new Error(
1203
+ `invalid <text>: expected no control characters, got ${JSON.stringify(raw)}`
1204
+ );
1205
+ }
1206
+ return raw;
1207
+ }
1208
+
611
1209
  // src/query.ts
612
- import { MAX_QUERY_LIMIT, OhosPerfError as OhosPerfError3, resolveQueryLimit as resolveQueryLimit2 } from "@ohos-perf/core";
1210
+ import { MAX_QUERY_LIMIT, OhosPerfError as OhosPerfError5, resolveQueryLimit as resolveQueryLimit2 } from "@ohos-perf/core";
613
1211
  function parseQueryArgs(raw) {
614
1212
  let value;
615
1213
  try {
616
1214
  value = JSON.parse(raw);
617
1215
  } catch {
618
- throw new OhosPerfError3("invalid --args: not valid JSON", { code: "QUERY_BAD_ARGS" });
1216
+ throw new OhosPerfError5("invalid --args: not valid JSON", { code: "QUERY_BAD_ARGS" });
619
1217
  }
620
1218
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
621
- throw new OhosPerfError3("invalid --args: expected a JSON object", { code: "QUERY_BAD_ARGS" });
1219
+ throw new OhosPerfError5("invalid --args: expected a JSON object", { code: "QUERY_BAD_ARGS" });
622
1220
  }
623
1221
  return value;
624
1222
  }
625
1223
  function parseLimit(raw) {
626
1224
  const text = raw.trim();
627
- const bad = () => new OhosPerfError3(
1225
+ const bad = () => new OhosPerfError5(
628
1226
  `limit must be an integer between 1 and ${MAX_QUERY_LIMIT}, got ${JSON.stringify(raw)}`,
629
1227
  { code: "QUERY_BAD_LIMIT" }
630
1228
  );
@@ -636,7 +1234,25 @@ function parseLimit(raw) {
636
1234
  }
637
1235
  }
638
1236
 
1237
+ // src/run.ts
1238
+ function parseOnly(raw) {
1239
+ const ids = raw.split(",").map((id) => id.trim());
1240
+ if (ids.some((id) => id === "")) {
1241
+ throw new Error(
1242
+ `invalid --only ${JSON.stringify(raw)}: an empty step id names no step; expected a comma-separated list of ids`
1243
+ );
1244
+ }
1245
+ return ids;
1246
+ }
1247
+
639
1248
  // src/program.ts
1249
+ function targetOptionsOf(opts) {
1250
+ return {
1251
+ ...opts.instancePath === void 0 ? {} : { instancePath: opts.instancePath },
1252
+ ...opts.imageRoot === void 0 ? {} : { imageRoot: opts.imageRoot },
1253
+ ...opts.emulator === void 0 ? {} : { emulatorPath: opts.emulator }
1254
+ };
1255
+ }
640
1256
  function buildProgram(deps2, io, opts = {}) {
641
1257
  const program2 = new Command();
642
1258
  program2.configureOutput({
@@ -645,10 +1261,10 @@ function buildProgram(deps2, io, opts = {}) {
645
1261
  });
646
1262
  if (opts.exitOverride) program2.exitOverride();
647
1263
  program2.name("ohos-perf").description("Performance analysis for OpenHarmony devices and captured traces").version(deps2.version);
648
- program2.command("doctor").description("check the hdc/trace_streamer toolchain and the attached device").option("--json", "print the report as JSON").action(async (opts2) => {
1264
+ program2.command("doctor").description("check the hdc/trace_streamer toolchain and the attached device").option("--target <id>", "probe this hdc target instead of the first connected one").option("--json", "print the report as JSON").action(async (opts2) => {
649
1265
  io.emit(await runDoctor(deps2, opts2));
650
1266
  });
651
- program2.command("caps").description("print the capability matrix of the attached device").option("--json", "print the capabilities as JSON").action(async (opts2) => {
1267
+ program2.command("caps").description("print the capability matrix of the attached device").option("--target <id>", "probe this hdc target instead of the first connected one").option("--json", "print the capabilities as JSON").action(async (opts2) => {
652
1268
  io.emit(await runCaps(deps2, opts2));
653
1269
  });
654
1270
  program2.command("analyze").description("analyze a captured scene directory (trace.db or trace.htrace)").argument("<scene-dir>", "directory containing trace.db / trace.htrace").option("--app <packageName>", "app package name, for evidence wording").option("--json", "print the analysis result as JSON").action(async (sceneDir, opts2) => {
@@ -660,12 +1276,15 @@ function buildProgram(deps2, io, opts = {}) {
660
1276
  ).requiredOption("--duration <seconds>", "capture duration in seconds (10 or 10s)").requiredOption("--out <dir>", "scene output directory").option("--procfs", "also sample /proc memory state for the app").option("--cold-start <ability>", "launch this ability before capturing").option("--hiprofiler", "capture through hiprofiler instead of hitrace").option(
661
1277
  "--plugins <list>",
662
1278
  "hiprofiler plugins, comma-separated: ftrace, gpu, xpower, nativehook, memory"
663
- ).option("--hiperf", "also capture a hiperf perf.data (debuggable app only)").option("--hidumper", "also sample the RenderService fps and hitch counters").option("--uitest", "also dump the on-screen UI tree").option("--json", "print the result as JSON").action(async (opts2) => {
1279
+ ).option("--hiperf", "also capture a hiperf perf.data (debuggable app only)").option(
1280
+ "--so-dir <dir>",
1281
+ "host directory of shared objects to symbolize the hiperf capture with"
1282
+ ).option("--hidumper", "also sample the RenderService fps and hitch counters").option("--uitest", "also dump the on-screen UI tree").option("--screenshot", "also capture the whole screen into screenshot.png").option("--hilog", "also stream the device log (hilog) for the capture window").option("--target <id>", "capture from this hdc target instead of the first connected one").option("--json", "print the result as JSON").action(async (opts2) => {
664
1283
  let durationMs;
665
1284
  try {
666
1285
  durationMs = parseDurationSeconds(opts2.duration);
667
1286
  } catch (err) {
668
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1287
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
669
1288
  `, exitCode: 1 });
670
1289
  return;
671
1290
  }
@@ -677,12 +1296,20 @@ function buildProgram(deps2, io, opts = {}) {
677
1296
  });
678
1297
  return;
679
1298
  }
1299
+ if (opts2.soDir !== void 0 && opts2.hiperf !== true) {
1300
+ io.emit({
1301
+ stdout: "",
1302
+ stderr: "invalid --so-dir: --hiperf is required\n",
1303
+ exitCode: 1
1304
+ });
1305
+ return;
1306
+ }
680
1307
  let hiprofilerRequest;
681
1308
  if (opts2.hiprofiler === true) {
682
1309
  try {
683
1310
  hiprofilerRequest = opts2.plugins === void 0 ? {} : { plugins: parsePluginList(opts2.plugins) };
684
1311
  } catch (err) {
685
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1312
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
686
1313
  `, exitCode: 1 });
687
1314
  return;
688
1315
  }
@@ -704,8 +1331,12 @@ function buildProgram(deps2, io, opts = {}) {
704
1331
  ...opts2.coldStart !== void 0 ? { coldStart: opts2.coldStart } : {},
705
1332
  ...hiprofilerRequest === void 0 ? {} : { hiprofiler: hiprofilerRequest },
706
1333
  ...opts2.hiperf === true ? { hiperf: {} } : {},
1334
+ ...opts2.soDir === void 0 ? {} : { soDir: opts2.soDir },
707
1335
  ...opts2.hidumper === true ? { hidumper: true } : {},
708
- ...opts2.uitest === true ? { uitest: true } : {}
1336
+ ...opts2.uitest === true ? { uitest: true } : {},
1337
+ ...opts2.screenshot === true ? { screenshot: true } : {},
1338
+ ...opts2.hilog === true ? { hilog: true } : {},
1339
+ ...opts2.target === void 0 ? {} : { target: opts2.target }
709
1340
  }, { json: opts2.json }));
710
1341
  });
711
1342
  program2.command("query").description("run one named drill-down query against a captured scene").argument("<scene-dir>", "directory containing trace.db / trace.htrace").argument("<name>", "named query; list them with `ohos-perf tools`").option("--app <packageName>", "app package name, overriding scene.json").option("--args <json>", "query arguments as a JSON object").option("--limit <n>", "maximum rows to return (default 100, max 1000)").option("--json", "print the result as JSON").action(async (sceneDir, name, opts2) => {
@@ -715,7 +1346,7 @@ function buildProgram(deps2, io, opts = {}) {
715
1346
  args = opts2.args === void 0 ? void 0 : parseQueryArgs(opts2.args);
716
1347
  limit = opts2.limit === void 0 ? void 0 : parseLimit(opts2.limit);
717
1348
  } catch (err) {
718
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1349
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
719
1350
  `, exitCode: 1 });
720
1351
  return;
721
1352
  }
@@ -730,9 +1361,212 @@ function buildProgram(deps2, io, opts = {}) {
730
1361
  program2.command("compare").description("compare a current analysis against a baseline").argument("<baseline>", "scene directory or `analyze --json` file").argument("<current>", "scene directory or `analyze --json` file").option("--json", "print the comparison as JSON").action(async (baseline, current, opts2) => {
731
1362
  io.emit(await runCompare(deps2, { baseline, current }, { json: opts2.json }));
732
1363
  });
1364
+ program2.command("ui-compare").description("compare two captures by UI tree and screenshot").argument("<a>", "scene directory for side a").argument("<b>", "scene directory for side b").requiredOption("--out <dir>", "output directory for ui-diff.json/html and marked PNGs").option("--json", "print the comparison as JSON").action(async (a, b, opts2) => {
1365
+ io.emit(await runUiCompare(deps2, { a, b, outDir: opts2.out }, { json: opts2.json }));
1366
+ });
1367
+ program2.command("report").description("analyze a scene and write report.html, JSON, summary, CSV and XLSX").argument("<scene-dir>", "directory containing trace.db / trace.htrace").requiredOption("--out <dir>", "output directory for the report artifacts").option("--app <packageName>", "app package name, for evidence wording").option("--baseline <input>", "scene directory or `analyze --json` file to compare against").option("--json", "print the artifact manifest as JSON").action(
1368
+ async (sceneDir, opts2) => {
1369
+ io.emit(
1370
+ await runReport(
1371
+ deps2,
1372
+ {
1373
+ sceneDir,
1374
+ outDir: opts2.out,
1375
+ ...opts2.app === void 0 ? {} : { app: opts2.app },
1376
+ ...opts2.baseline === void 0 ? {} : { baseline: opts2.baseline }
1377
+ },
1378
+ { json: opts2.json }
1379
+ )
1380
+ );
1381
+ }
1382
+ );
1383
+ program2.command("hap").description("inspect a .hap/.hsp package offline: files, sizes, technologies, duplicates").argument("<package>", "path to a .hap, .hsp or .zip file").option("--out <dir>", "write hap.json and hap.html to this directory").option("--json", "print the analysis as JSON").action(async (packagePath, opts2) => {
1384
+ io.emit(
1385
+ await runHap(
1386
+ deps2,
1387
+ {
1388
+ packagePath,
1389
+ ...opts2.out === void 0 ? {} : { outDir: opts2.out }
1390
+ },
1391
+ { json: opts2.json }
1392
+ )
1393
+ );
1394
+ });
1395
+ program2.command("run").description("run a declarative scenario, capturing one scene per step").argument("<scenario>", "scenario JSON file").requiredOption("--out <dir>", "run output directory (one scene per step)").option("--target <id>", "run against this hdc target instead of the first connected one").option("--rounds <n>", "repeat every step this many times (overrides the scenario)").option("--only <ids>", "comma-separated step ids to run, in scenario order").option("--keep-going", "continue after a failed step instead of stopping").option("--json", "print the run result as JSON").action(async (scenarioPath, opts2) => {
1396
+ let rounds;
1397
+ let only;
1398
+ try {
1399
+ if (opts2.rounds !== void 0) {
1400
+ if (!/^[1-9]\d*$/.test(opts2.rounds)) {
1401
+ throw new Error(
1402
+ `invalid --rounds ${JSON.stringify(opts2.rounds)}: expected a positive whole number`
1403
+ );
1404
+ }
1405
+ rounds = Number(opts2.rounds);
1406
+ }
1407
+ only = opts2.only === void 0 ? void 0 : parseOnly(opts2.only);
1408
+ } catch (err) {
1409
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1410
+ `, exitCode: 1 });
1411
+ return;
1412
+ }
1413
+ io.emit(await runScenarioCommand(deps2, {
1414
+ scenarioPath,
1415
+ outDir: opts2.out,
1416
+ ...opts2.target === void 0 ? {} : { target: opts2.target },
1417
+ ...rounds === void 0 ? {} : { rounds },
1418
+ ...only === void 0 ? {} : { only },
1419
+ ...opts2.keepGoing === true ? { keepGoing: true } : {}
1420
+ }, { json: opts2.json }));
1421
+ });
733
1422
  program2.command("tools").description("list the named drill-down queries an agent can call").option("--json", "print the query definitions as JSON").action((opts2) => {
734
1423
  io.emit(runTools(deps2, opts2));
735
1424
  });
1425
+ const withEmulatorTargets = (cmd) => cmd.option("--instance-path <dir>", "emulator instance root (overrides discovery)").option("--image-root <dir>", "emulator image root (overrides discovery)").option("--emulator <path>", "path to the HarmonyOS Emulator executable");
1426
+ const emulator = program2.command("emulator").description("manage HarmonyOS emulator instances");
1427
+ withEmulatorTargets(
1428
+ emulator.command("list").description("list emulator instances and the target each one owns").option("--json", "print the instances as JSON")
1429
+ ).action(async (opts2) => {
1430
+ io.emit(await runEmulatorList(deps2, {
1431
+ ...targetOptionsOf(opts2),
1432
+ ...opts2.json === void 0 ? {} : { json: opts2.json }
1433
+ }));
1434
+ });
1435
+ withEmulatorTargets(
1436
+ emulator.command("start").description("start an emulator instance and wait until it has booted").argument("<name>", "emulator instance name").option("--timeout <seconds>", "how long to wait for the boot, in seconds").option("--json", "print the result as JSON")
1437
+ ).action(async (name, opts2) => {
1438
+ const { timeout, json: json2 } = opts2;
1439
+ let timeoutMs;
1440
+ if (timeout !== void 0) {
1441
+ try {
1442
+ timeoutMs = parseDurationSeconds(timeout);
1443
+ } catch (err) {
1444
+ const reason = safeMessage(err).replace(/^invalid --duration [^:]*: /, "");
1445
+ const message2 = reason.startsWith("expected a positive number of seconds") ? "--timeout must be greater than 0 (a positive number of seconds, e.g. 30)" : reason;
1446
+ io.emit({
1447
+ stdout: "",
1448
+ stderr: `invalid --timeout ${JSON.stringify(timeout)}: ${message2}
1449
+ `,
1450
+ exitCode: 1
1451
+ });
1452
+ return;
1453
+ }
1454
+ }
1455
+ io.emit(await runEmulatorStart(deps2, name, {
1456
+ ...targetOptionsOf(opts2),
1457
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
1458
+ ...json2 === void 0 ? {} : { json: json2 }
1459
+ }));
1460
+ });
1461
+ withEmulatorTargets(
1462
+ emulator.command("stop").description("stop an emulator instance").argument("<name>", "emulator instance name").option("--json", "print the result as JSON")
1463
+ ).action(async (name, opts2) => {
1464
+ io.emit(await runEmulatorStop(deps2, name, {
1465
+ ...targetOptionsOf(opts2),
1466
+ ...opts2.json === void 0 ? {} : { json: opts2.json }
1467
+ }));
1468
+ });
1469
+ withEmulatorTargets(
1470
+ emulator.command("create").description("create an emulator instance from an already-downloaded image").argument("<name>", "instance name; it becomes a directory under the instance root").option("--device-type <type>", "image device type, e.g. phone or foldable").option("--os-version <version>", 'image OS version, e.g. "HarmonyOS 6.1.1(24)"').option("--screen-profile <model>", "screen profile name").option("--memory <GB>", "RAM size in GB").option("--storage <GB>", "data partition size in GB").option("--json", "print the created instance as JSON")
1471
+ ).action(async (name, opts2) => {
1472
+ if (opts2.deviceType === void 0 || opts2.osVersion === void 0) {
1473
+ io.emit({
1474
+ stdout: "",
1475
+ stderr: "--device-type and --os-version are required\n",
1476
+ exitCode: 1
1477
+ });
1478
+ return;
1479
+ }
1480
+ const number = (flag, raw) => {
1481
+ if (raw === void 0) return void 0;
1482
+ const value = Number(raw);
1483
+ if (!Number.isInteger(value)) {
1484
+ throw new Error(`invalid ${flag}: expected a whole number, got ${JSON.stringify(raw)}`);
1485
+ }
1486
+ return value;
1487
+ };
1488
+ let memoryGb;
1489
+ let storageGb;
1490
+ try {
1491
+ memoryGb = number("--memory", opts2.memory);
1492
+ storageGb = number("--storage", opts2.storage);
1493
+ } catch (err) {
1494
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1495
+ `, exitCode: 1 });
1496
+ return;
1497
+ }
1498
+ io.emit(await runEmulatorCreate(deps2, {
1499
+ name,
1500
+ deviceType: opts2.deviceType,
1501
+ osVersion: opts2.osVersion,
1502
+ ...opts2.screenProfile === void 0 ? {} : { screenProfile: opts2.screenProfile },
1503
+ ...memoryGb === void 0 ? {} : { memoryGb },
1504
+ ...storageGb === void 0 ? {} : { storageGb },
1505
+ ...targetOptionsOf(opts2)
1506
+ }, { json: opts2.json }));
1507
+ });
1508
+ const gestureGroup = program2.command("gesture").description("inject a UI gesture on the attached device");
1509
+ const withGestureTargets = (cmd) => cmd.option("--target <id>", "inject on this hdc target instead of the first connected one").option("--json", "print the result as JSON");
1510
+ const sendGesture = async (build, opts2) => {
1511
+ let gesture;
1512
+ try {
1513
+ gesture = build();
1514
+ } catch (err) {
1515
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1516
+ `, exitCode: 1 });
1517
+ return;
1518
+ }
1519
+ io.emit(await runGesture(deps2, {
1520
+ gesture,
1521
+ ...opts2.target === void 0 ? {} : { target: opts2.target }
1522
+ }, { json: opts2.json }));
1523
+ };
1524
+ withGestureTargets(
1525
+ gestureGroup.command("click").description("tap at <x>,<y>").argument("<x>").argument("<y>")
1526
+ ).action(async (x, y, opts2) => {
1527
+ await sendGesture(
1528
+ () => ({ action: "click", x: parseCoordinate(x, "<x>"), y: parseCoordinate(y, "<y>") }),
1529
+ opts2
1530
+ );
1531
+ });
1532
+ withGestureTargets(
1533
+ gestureGroup.command("swipe").description("swipe from <from-x>,<from-y> to <to-x>,<to-y>").argument("<from-x>").argument("<from-y>").argument("<to-x>").argument("<to-y>").option("--velocity <n>", "swipe velocity, 200 to 40000 (device default 600)")
1534
+ ).action(async (fromX, fromY, toX, toY, opts2) => {
1535
+ await sendGesture(
1536
+ () => ({
1537
+ action: "swipe",
1538
+ fromX: parseCoordinate(fromX, "<from-x>"),
1539
+ fromY: parseCoordinate(fromY, "<from-y>"),
1540
+ toX: parseCoordinate(toX, "<to-x>"),
1541
+ toY: parseCoordinate(toY, "<to-y>"),
1542
+ ...opts2.velocity === void 0 ? {} : { velocity: parseVelocity(opts2.velocity) }
1543
+ }),
1544
+ opts2
1545
+ );
1546
+ });
1547
+ withGestureTargets(
1548
+ gestureGroup.command("key").description("inject a key event").argument("<key>", "Back, Home, Power or a positive key code")
1549
+ ).action(async (key, opts2) => {
1550
+ await sendGesture(() => ({ action: "key", key: parseKey(key) }), opts2);
1551
+ });
1552
+ withGestureTargets(
1553
+ gestureGroup.command("input").description("type text at <x>,<y>").argument("<x>").argument("<y>").argument("<text>", "text to type; quote it when it contains spaces")
1554
+ ).action(async (x, y, text, opts2) => {
1555
+ await sendGesture(
1556
+ () => ({
1557
+ action: "inputText",
1558
+ x: parseCoordinate(x, "<x>"),
1559
+ y: parseCoordinate(y, "<y>"),
1560
+ text: parseText(text)
1561
+ }),
1562
+ opts2
1563
+ );
1564
+ });
1565
+ withGestureTargets(
1566
+ gestureGroup.command("text").description("type text at the focused field").argument("<text>", "text to type; quote it when it contains spaces")
1567
+ ).action(async (text, opts2) => {
1568
+ await sendGesture(() => ({ action: "text", text: parseText(text) }), opts2);
1569
+ });
736
1570
  return program2;
737
1571
  }
738
1572
 
@@ -750,7 +1584,7 @@ function emit(result) {
750
1584
  function ignoreEpipe(stream) {
751
1585
  stream.on("error", (err) => {
752
1586
  if (err.code === "EPIPE") return;
753
- process.stderr.write(`${safeMessage(err)}
1587
+ process.stderr.write(`${failureLine(err)}
754
1588
  `);
755
1589
  process.exitCode = 1;
756
1590
  });
@@ -763,7 +1597,7 @@ var program = buildProgram(deps, {
763
1597
  emit
764
1598
  });
765
1599
  program.parseAsync(process.argv).catch((err) => {
766
- process.stderr.write(`${safeMessage(err)}
1600
+ process.stderr.write(`${failureLine(err)}
767
1601
  `);
768
1602
  process.exitCode = 1;
769
1603
  });