@oniroproject/oniro-app 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bin/oniro-app.ts","../src/commands/sdk.ts","../src/adapters/logger.ts","../src/adapters/progress.ts","../src/adapters/config.ts","../src/lib/runtime.ts","../src/commands/cmdtools.ts","../src/commands/emulator.ts","../src/commands/build.ts","../src/commands/sign.ts","../src/commands/auth.ts","../src/commands/app.ts","../src/commands/create.ts","../src/lib/templateRoot.ts","../src/commands/templates.ts","../src/commands/reboot.ts","../src/commands/wait.ts","../src/lib/target.ts","../src/lib/logSince.ts","../src/commands/watch.ts","../src/commands/screenshot.ts","../src/lib/screenshotImage.ts","../src/commands/dump.ts","../src/lib/layoutText.ts","../src/commands/devices.ts","../src/commands/file.ts","../src/commands/lint.ts","../src/commands/input.ts","../src/commands/logs.ts","../src/lib/logBundle.ts","../src/commands/hdc.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { OniroError } from '@oniroproject/core';\nimport { registerSdkCommand } from '../commands/sdk.js';\nimport { registerCmdToolsCommand } from '../commands/cmdtools.js';\nimport { registerEmulatorCommand } from '../commands/emulator.js';\nimport { registerBuildCommand } from '../commands/build.js';\nimport { registerSignCommand } from '../commands/sign.js';\nimport { registerAuthCommand } from '../commands/auth.js';\nimport { registerAppCommand } from '../commands/app.js';\nimport { registerCreateCommand } from '../commands/create.js';\nimport { registerTemplatesCommand } from '../commands/templates.js';\nimport { registerRebootCommand } from '../commands/reboot.js';\nimport { registerWaitCommand } from '../commands/wait.js';\nimport { registerWatchCommand } from '../commands/watch.js';\nimport { registerScreenshotCommand } from '../commands/screenshot.js';\nimport { registerDumpCommand } from '../commands/dump.js';\nimport { registerDevicesCommand } from '../commands/devices.js';\nimport { registerFileCommand } from '../commands/file.js';\nimport { registerLintCommand } from '../commands/lint.js';\nimport { registerInputCommand } from '../commands/input.js';\nimport { registerLogsCommand } from '../commands/logs.js';\nimport { registerHdcCommand } from '../commands/hdc.js';\n\ndeclare const __CLI_VERSION__: string;\nconst CLI_VERSION = __CLI_VERSION__;\n\nfunction buildProgram(): Command {\n const program = new Command()\n .name('oniro-app')\n .description(\n 'Cross-platform CLI for Oniro/OpenHarmony app development.\\n\\n' +\n 'Designed for non-interactive use (CI, scripts, agents): every command\\n' +\n 'takes explicit flags, results go to stdout, progress/logs go to stderr,\\n' +\n 'and a non-zero exit code indicates failure.',\n )\n .version(CLI_VERSION)\n .showHelpAfterError()\n // Lets `hdc` pass its arguments through untouched; global options go before the command.\n .enablePositionalOptions();\n\n registerSdkCommand(program);\n registerCmdToolsCommand(program);\n registerEmulatorCommand(program);\n registerBuildCommand(program);\n registerSignCommand(program);\n registerAuthCommand(program);\n registerAppCommand(program);\n registerCreateCommand(program);\n registerTemplatesCommand(program);\n registerRebootCommand(program);\n registerWaitCommand(program);\n registerWatchCommand(program);\n registerScreenshotCommand(program);\n registerDumpCommand(program);\n registerDevicesCommand(program);\n registerFileCommand(program);\n registerLintCommand(program);\n registerInputCommand(program);\n registerLogsCommand(program);\n registerHdcCommand(program);\n\n return program;\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n const message = err instanceof OniroError ? err.message : err instanceof Error ? err.message : String(err);\n process.stderr.write(`[error] ${message}\\n`);\n if (process.env.ONIRO_DEBUG === '1' && err instanceof Error && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n process.exit(1);\n }\n}\n\nvoid main();\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n ALL_SDKS,\n OHOS_DAILY_BUILDS_URL,\n downloadAndInstallSdk,\n getOsFolder,\n getSdkRootDir,\n getSupportedSdksForUi,\n installSdkFromArchive,\n removeSdk,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nconst FULL_SDK_TIP =\n 'Tip: the full SDK (with system APIs) is not on the release mirror. Download an ohos-sdk-full archive ' +\n `from the OpenHarmony daily builds, ${OHOS_DAILY_BUILDS_URL}, and install it with ` +\n '`oniro-app sdk install --from-archive <archive>`.';\n\nexport function registerSdkCommand(program: Command): void {\n const sdk = program.command('sdk').description('Manage OpenHarmony SDK installs.');\n\n sdk\n .command('install [version]')\n .description(\n 'Download and install an OpenHarmony SDK (skips if already installed), or install one from a local ' +\n 'archive with --from-archive.',\n )\n .option(\n '--from-archive <path>',\n 'Install from a local SDK .tar.gz instead of downloading, e.g. the full SDK. The API level is read ' +\n 'from the archive.',\n )\n .option('--force', 'Reinstall even if the SDK is already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for download/extract temporaries (default: ONIRO_TMP_DIR, else .oniro-tmp next to ' +\n 'the install target). Use this when that filesystem is short on space.',\n )\n .addHelpText('after', `\\n${FULL_SDK_TIP}`)\n .action(async (version: string | undefined, opts: { fromArchive?: string; force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n if (opts.fromArchive) {\n if (version) throw new Error('Pass either a version or --from-archive, not both.');\n const archivePath = path.resolve(opts.fromArchive);\n logger.info(`Installing OpenHarmony SDK from ${archivePath}...`);\n const installed = await installSdkFromArchive({\n config,\n archivePath,\n force: opts.force,\n progress,\n logger,\n tmpDir: opts.tmpDir,\n });\n const label = installed.version ? `SDK ${installed.version} (api ${installed.api})` : `SDK api ${installed.api}`;\n logger.info(`${label} installed at ${installed.dir}.`);\n return;\n }\n if (!version) {\n throw new Error(\n `Name an SDK version (${ALL_SDKS.map((s) => s.version).join(', ')}) or pass --from-archive <path>.\\n` +\n FULL_SDK_TIP,\n );\n }\n const release = ALL_SDKS.find((s) => s.version === version);\n if (!release) {\n throw new Error(\n `Unknown SDK version \"${version}\". Known: ${ALL_SDKS.map((s) => s.version).join(', ')}`,\n );\n }\n const sdkInstallDir = path.join(getSdkRootDir(config), getOsFolder(), release.api);\n if (fs.existsSync(sdkInstallDir) && !opts.force) {\n logger.info(\n `SDK ${release.version} (api ${release.api}) already installed at ${sdkInstallDir}; pass --force to reinstall.`,\n );\n return;\n }\n logger.info(`Installing OpenHarmony SDK ${release.version} (api ${release.api})...`);\n await downloadAndInstallSdk({\n config,\n version: release.version,\n api: release.api,\n progress,\n logger,\n tmpDir: opts.tmpDir,\n });\n logger.info('SDK installed.');\n });\n\n sdk\n .command('list')\n .description('List known SDK versions and whether they are installed on this machine.')\n .option('--json', 'Emit machine-readable JSON instead of a table.')\n .action((opts: { json?: boolean }) => {\n const { config } = getRuntime();\n const sdks = getSupportedSdksForUi(config);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(sdks, null, 2)}\\n`);\n return;\n }\n const rows = sdks.map((s) => `${s.installed ? '*' : ' '} ${s.version.padEnd(8)} api ${s.api}`);\n process.stdout.write(`${rows.join('\\n')}\\n`);\n });\n\n sdk\n .command('remove <api>')\n .description('Remove an installed SDK by API level (e.g. 18, 20).')\n .action((api: string) => {\n const { config, logger } = getRuntime();\n const removed = removeSdk(config, api);\n if (!removed) {\n logger.warn(`No SDK with api ${api} found under the configured SDK root.`);\n process.exit(1);\n }\n logger.info(`Removed SDK api ${api}.`);\n });\n}\n","import type { Logger } from '@oniroproject/core';\n\n/**\n * Stderr-only logger. All diagnostic output goes to stderr so command stdout\n * stays clean for machine consumers (json results, paths, etc.).\n *\n * Debug lines are suppressed unless `ONIRO_DEBUG=1`.\n */\nexport function createCliLogger(): Logger {\n const debugEnabled = process.env.ONIRO_DEBUG === '1' || process.env.ONIRO_DEBUG === 'true';\n return {\n debug(m) {\n if (debugEnabled) process.stderr.write(`[debug] ${m}\\n`);\n },\n info(m) {\n process.stderr.write(`${m}\\n`);\n },\n warn(m) {\n process.stderr.write(`[warn] ${m}\\n`);\n },\n error(m) {\n process.stderr.write(`[error] ${m}\\n`);\n },\n };\n}\n","import type { ProgressReporter } from '@oniroproject/core';\n\n/**\n * Line-per-update progress reporter, designed for machine consumers and log scrapers.\n * Format: `[progress NN%] message` (or `[progress] message` if no percent is known).\n * Updates that don't change the percent and don't carry a message are suppressed\n * to keep output volume reasonable on chatty downloads.\n */\nexport function createCliProgress(): ProgressReporter {\n let total = 0;\n let lastEmitted = -1;\n let lastMessage = '';\n return {\n report({ message, increment }) {\n if (typeof increment === 'number') total = Math.min(100, total + increment);\n const pct = total > 0 ? Math.round(total) : null;\n const msg = message ?? lastMessage;\n // Drop redundant updates: same message, same percent.\n if (pct === lastEmitted && msg === lastMessage) return;\n const prefix = pct === null ? '[progress]' : `[progress ${pct}%]`;\n process.stderr.write(`${prefix} ${msg}\\n`);\n lastEmitted = pct ?? lastEmitted;\n if (message) lastMessage = message;\n },\n };\n}\n","import * as os from 'node:os';\nimport type { ConfigKey, ConfigProvider } from '@oniroproject/core';\n\n/**\n * Maps a core ConfigKey to its environment variable name.\n * Convention: ONIRO_<UPPER_SNAKE>.\n */\nconst ENV_VAR_BY_KEY: Record<ConfigKey, string> = {\n sdkRootDir: 'ONIRO_SDK_ROOT_DIR',\n cmdToolsPath: 'ONIRO_CMD_TOOLS_PATH',\n hdcPath: 'ONIRO_HDC',\n emulatorDir: 'ONIRO_EMULATOR_DIR',\n hapPath: 'ONIRO_HAP_PATH',\n cmdToolsUrlLinux: 'ONIRO_CMD_TOOLS_URL_LINUX',\n cmdToolsUrlWindows: 'ONIRO_CMD_TOOLS_URL_WINDOWS',\n cmdToolsUrlMac: 'ONIRO_CMD_TOOLS_URL_MAC',\n emulatorUrl: 'ONIRO_EMULATOR_URL',\n tmpDir: 'ONIRO_TMP_DIR',\n sdkUrlBase: 'ONIRO_SDK_URL_BASE',\n applicationCertPath: 'ONIRO_APPLICATION_CERT_PATH',\n harmonyosSdkPath: 'ONIRO_HARMONYOS_SDK_PATH',\n harmonyosAuthDir: 'ONIRO_HARMONYOS_AUTH_DIR',\n harmonyosSigningDir: 'ONIRO_HARMONYOS_SIGNING_DIR',\n};\n\n/**\n * Reads configuration from environment variables (ONIRO_*). Returns the fallback\n * when the variable is unset or empty. Expands `${userHome}` to the user's home\n * directory for parity with the VS Code extension's `${userHome}` expansion.\n */\nexport function createEnvConfig(env: NodeJS.ProcessEnv = process.env): ConfigProvider {\n return {\n get<T extends string | number | boolean>(key: ConfigKey, fallback: T): T {\n const envName = ENV_VAR_BY_KEY[key];\n const raw = env[envName];\n if (raw === undefined || raw === '') return fallback;\n const expanded = raw.includes('${userHome}')\n ? raw.replace(/\\$\\{userHome\\}/g, os.homedir())\n : raw;\n return expanded as unknown as T;\n },\n };\n}\n","import type { ConfigProvider, Logger, ProgressReporter } from '@oniroproject/core';\nimport { createCliLogger } from '../adapters/logger.js';\nimport { createCliProgress } from '../adapters/progress.js';\nimport { createEnvConfig } from '../adapters/config.js';\n\nexport interface CliRuntime {\n logger: Logger;\n config: ConfigProvider;\n progress: ProgressReporter;\n}\n\nlet cached: CliRuntime | null = null;\n\n/**\n * Build (and cache) the per-process runtime used by every command. Tests can\n * override the cached runtime via `setRuntime` to inject mocks.\n */\nexport function getRuntime(): CliRuntime {\n if (!cached) {\n cached = {\n logger: createCliLogger(),\n config: createEnvConfig(),\n progress: createCliProgress(),\n };\n }\n return cached;\n}\n\nexport function setRuntime(runtime: CliRuntime | null): void {\n cached = runtime;\n}\n","import { Command } from 'commander';\nimport { getCmdToolsStatus, installCmdTools, isCmdToolsInstalled, removeCmdTools } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerCmdToolsCommand(program: Command): void {\n const cmdtools = program.command('cmdtools').description('Manage OpenHarmony command-line tools.');\n\n cmdtools\n .command('install')\n .description('Install the OpenHarmony command-line tools (hvigorw, ohpm, hdc). Skips if already installed.')\n .option('--from-zip <path>', 'Install from a local ZIP instead of downloading.')\n .option('--force', 'Reinstall even if the tools are already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for download/extract temporaries (default: ONIRO_TMP_DIR, else .oniro-tmp next to ' +\n 'the install target). Use this when that filesystem is short on space.',\n )\n .action(async (opts: { fromZip?: string; force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n if (isCmdToolsInstalled(config) && !opts.force) {\n logger.info('Command-line tools already installed; pass --force to reinstall.');\n return;\n }\n logger.info('Installing OpenHarmony command-line tools...');\n await installCmdTools({ config, progress, logger, localZipPath: opts.fromZip, tmpDir: opts.tmpDir });\n logger.info('Command-line tools installed.');\n });\n\n cmdtools\n .command('status')\n .description(\n 'Report whether the command-line tools are installed, their version and flavour (HarmonyOS or ' +\n 'OpenHarmony), and the hdc binary every device command uses.',\n )\n .option('--json', 'Emit machine-readable JSON.')\n .action((opts: { json?: boolean }) => {\n const { config } = getRuntime();\n const status = getCmdToolsStatus(config);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n return;\n }\n process.stdout.write(`${status.status}\\n`);\n process.stdout.write(`path: ${status.path}\\n`);\n if (status.flavour) process.stdout.write(`flavour: ${status.flavour}\\n`);\n process.stdout.write(`hdc: ${status.hdc.path}${status.hdc.exists ? '' : ' (missing)'}\\n`);\n if (!status.installed) process.exit(1);\n });\n\n cmdtools\n .command('remove')\n .description('Delete the configured command-line tools directory.')\n .action(() => {\n const { config, logger } = getRuntime();\n removeCmdTools(config);\n logger.info('Command-line tools removed.');\n });\n}\n","import { Command } from 'commander';\nimport {\n attemptHdcConnection,\n getEmulatorStatus,\n installEmulator,\n isEmulatorInstalled,\n removeEmulator,\n startEmulator,\n stopEmulator,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerEmulatorCommand(program: Command): void {\n const emu = program.command('emulator').description('Manage the Oniro emulator.');\n\n emu\n .command('install')\n .description('Download and install the Oniro emulator (QEMU-based). Skips if already installed.')\n .option('--force', 'Reinstall even if the emulator is already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for the downloaded ZIP (default: ONIRO_TMP_DIR, else .oniro-tmp next to the ' +\n 'install target). Use this when that filesystem is short on space.',\n )\n .action(async (opts: { force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n if (isEmulatorInstalled(config) && !opts.force) {\n logger.info('Emulator already installed; pass --force to reinstall.');\n return;\n }\n logger.info('Installing Oniro emulator...');\n await installEmulator({ config, progress, logger, tmpDir: opts.tmpDir });\n logger.info('Emulator installed.');\n });\n\n emu\n .command('start')\n .description('Start the Oniro emulator via the bundled launcher (run.sh / run.bat). Detaches so the CLI can exit while the emulator keeps running.')\n .option('--headless', 'Launch headless (VNC + telnet serial, no local window). Required in CI.')\n .option('--log <path>', 'Redirect launcher stdout/stderr to this file. Defaults to discarding output.')\n .option('--wait-for-hdc <seconds>', 'Wait up to N seconds for hdc to connect. 0 = do not wait.', (v) => parseInt(v, 10), 0)\n .option('--connect <host:port>', 'Override the launcher\\'s hdc port-forward bind address. Pass 0.0.0.0:55555 on hosts where QEMU refuses to bind 127.0.0.1 (some CI runners).')\n .action(async (opts: { headless?: boolean; log?: string; waitForHdc: number; connect?: string }) => {\n const { config, logger } = getRuntime();\n await startEmulator({\n config,\n logger,\n headless: opts.headless === true,\n logFile: opts.log,\n waitForHdcSeconds: opts.waitForHdc,\n connect: opts.connect,\n });\n logger.info('Emulator start command complete.');\n });\n\n emu\n .command('status')\n .description(\n 'Report whether the Oniro emulator is installed, running, and connected to hdc, without starting it. ' +\n 'Exits 1 when it is not installed.',\n )\n .option('--address <addr>', 'hdc address the emulator listens on', '127.0.0.1:55555')\n .option('--json', 'Emit machine-readable JSON.')\n .action(async (opts: { address: string; json?: boolean }) => {\n const { config, logger } = getRuntime();\n const status = await getEmulatorStatus(config, { address: opts.address, logger });\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n } else {\n process.stdout.write(\n `installed: ${status.installed ? 'yes' : 'no'} (${status.dir})\\n` +\n `running: ${status.running ? 'yes' : 'no'}\\n` +\n `connected: ${status.connected ? 'yes' : 'no'} (${status.address})\\n`,\n );\n }\n if (!status.installed) process.exitCode = 1;\n });\n\n emu\n .command('stop')\n .description('Kill running emulator processes.')\n .action(async () => {\n const { logger } = getRuntime();\n await stopEmulator(logger);\n logger.info('Emulator stopped.');\n });\n\n emu\n .command('connect')\n .description('Attempt to connect hdc to the emulator.')\n .option('--address <addr>', 'hdc address to connect to', '127.0.0.1:55555')\n .action(async (opts: { address: string }) => {\n const { config, logger } = getRuntime();\n const ok = await attemptHdcConnection(config, opts.address, logger);\n if (!ok) {\n logger.error(`Could not connect hdc to ${opts.address}.`);\n process.exit(1);\n }\n logger.info(`hdc connected to ${opts.address}.`);\n });\n\n emu\n .command('remove')\n .description('Delete the configured emulator directory.')\n .action(() => {\n const { config, logger } = getRuntime();\n removeEmulator(config);\n logger.info('Emulator removed.');\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport { SdkNotInstalledError, buildHap, downloadAndInstallSdk } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\ninterface BuildOpts {\n product: string;\n module?: string;\n mode?: string;\n task: string;\n deps: boolean;\n parallel: boolean;\n installSdk?: boolean;\n json?: boolean;\n}\n\nexport function registerBuildCommand(program: Command): void {\n program\n .command('build [project-dir]')\n .description(\n 'Build an OpenHarmony or HarmonyOS app via hvigorw. Defaults to the current directory. ' +\n 'Projects declaring runtimeOS \"HarmonyOS\" build against the HarmonyOS SDK (ONIRO_HARMONYOS_SDK_PATH or an installed DevEco Studio). ' +\n 'An OpenHarmony project fails early, naming the release to install, when the SDK for its compileSdkVersion is missing.',\n )\n .option('--product <product>', 'hvigor product name', 'default')\n .option('--module <module>', 'restrict the build to a specific module')\n .option('--mode <mode>', 'hvigor build mode (e.g. release, debug)')\n .option('--task <task>', 'hvigor task to run', 'assembleHap')\n .option('--no-deps', 'skip the automatic `ohpm install --all` when oh_modules/ is missing')\n .option('--no-parallel', 'build modules serially (default: parallel)')\n .option('--install-sdk', 'install the OpenHarmony SDK the project compiles against when it is missing, then build')\n .option('--json', 'emit the build result (discovered HAPs, warnings) as JSON')\n .action(async (projectDir: string | undefined, opts: BuildOpts) => {\n const { config, logger, progress } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n logger.info(`Building project at ${dir}...`);\n const build = () =>\n buildHap({\n config,\n projectDir: dir,\n product: opts.product,\n module: opts.module,\n mode: opts.mode,\n task: opts.task,\n autoInstallDeps: opts.deps,\n parallel: opts.parallel,\n logger,\n // The logger already echoes spawn output; this hook is for streaming to other UIs.\n onOutput: () => {},\n });\n let result;\n try {\n result = await build();\n } catch (err) {\n if (!(err instanceof SdkNotInstalledError && err.version && opts.installSdk)) throw err;\n logger.info(`Installing OpenHarmony SDK ${err.version} (api ${err.api}), which the project compiles against...`);\n await downloadAndInstallSdk({ config, version: err.version, api: err.api, progress, logger });\n result = await build();\n }\n for (const w of result.warnings) logger.warn(w);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }\n logger.info('Build complete.');\n });\n}\n","import { Command, Option } from 'commander';\nimport * as path from 'node:path';\nimport {\n APL_VALUES,\n APP_FEATURE_VALUES,\n OniroError,\n createHarmonyOsSession,\n detectRuntimeOs,\n generateSigningConfigs,\n harmonyOsAutoSign,\n harmonyOsSignHap,\n signOpenHarmonyHap,\n prepareSigning,\n getOhosBaseSdkHome,\n type Apl,\n type AppFeature,\n type SigningPasswords,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nfunction parseAclsList(value: string): string[] {\n return value\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\nexport function registerSignCommand(program: Command): void {\n program\n .command('sign [project-dir]')\n .description(\n [\n 'Generate signing keys, certificates, and signingConfigs for an OpenHarmony project.',\n 'Requires java on PATH. The generated profile uses the SDK\\'s built-in development',\n 'cert (issuer=pki_internal) and its bundled validity window — dev/local builds only.',\n 'Overwrites the `signingConfigs` block in build-profile.json5 (other keys preserved).',\n 'HarmonyOS projects need --harmonyos instead, which has AppGallery Connect issue the',\n 'certificate and profile for a signed-in Huawei account (`oniro-app auth login`).',\n 'With --hap <file>, signs a prebuilt HAP instead of a project (with --harmonyos, for HarmonyOS).',\n ].join(' '),\n )\n .addOption(\n new Option(\n '--apl <level>',\n 'Ability Privilege Level written into the profile. Apps that request permissions above `normal` (e.g. ohos.permission.GET_WIFI_INFO_INTERNAL) need system_basic or system_core, which also switches the HAP-signing key to \"OpenHarmony Application Release\".',\n )\n .choices([...APL_VALUES])\n .default('normal'),\n )\n .addOption(\n new Option(\n '--app-feature <feature>',\n 'App feature written into the profile. Defaults: hos_normal_app for apl=normal; hos_system_app for apl=system_basic/system_core.',\n ).choices([...APP_FEATURE_VALUES]),\n )\n .addOption(\n new Option(\n '--acls <list>',\n 'Comma-separated permission names to write into the profile\\'s acls.allowed-acls. Required for apps that request permissions above their apl (e.g. a system_basic app requesting ohos.permission.CAPTURE_SCREEN). Example: --acls ohos.permission.REBOOT,ohos.permission.INJECT_INPUT_EVENT',\n ).argParser(parseAclsList),\n )\n .addOption(\n new Option(\n '--app-privilege-capabilities <list>',\n 'Comma-separated privileges to write into the profile\\'s app-privilege-capabilities. An app that declares a privileged extension ability (e.g. an AccessibilityExtensionAbility) needs AllowAppUsePrivilegeExtension, else install fails with 9568344 \"not allow use privilege extension\". Others include AllowAppMultiProcess and AllowAppDesktopIconHide.',\n ).argParser(parseAclsList),\n )\n .option(\n '--harmonyos',\n 'Sign a HarmonyOS project through AppGallery Connect. Needs `oniro-app auth login`, and a device registered to the team: a connected device is registered if it reports a UDID (`hdc shell bm get -u`).',\n )\n .option(\n '--hap <file>',\n 'Sign this prebuilt .hap (unsigned, or signed with other material) instead of a project, and write a signed copy (see --out). The bundle name is read from the HAP. For OpenHarmony, --apl, --app-feature, --acls and --app-privilege-capabilities apply as for a project; with --harmonyos, the ACL permissions are read from the HAP too.',\n )\n .option(\n '--out <file>',\n 'With --hap: where to write the signed HAP. Default: next to the input, `<name>-unsigned.hap` → `<name>-signed.hap`, `<name>.hap` → `<name>-signed.hap`, `<name>-signed.hap` → `<name>-resigned.hap`. Name the input itself to re-sign it in place.',\n )\n .option('--team-id <id>', 'With --harmonyos: the AGC team to sign under. Default: the account\\'s own (`oniro-app auth team list`).')\n .option('--product <name>', 'With --harmonyos: the product to sign. Default `default`.')\n .option('--force', 'With --harmonyos: regenerate the certificate and profile even when they are still valid.')\n .option('--bootstrap', 'No-op if signing material is already present; otherwise generate it.')\n .option('--store-password <pwd>', 'Keystore store password (default 123456 — the SDK keystore password).')\n .option('--key-password <pwd>', 'Keystore key password (default 123456 — the SDK keystore password).')\n .action(\n async (\n projectDir: string | undefined,\n opts: {\n apl: Apl;\n appFeature?: AppFeature;\n acls?: string[];\n appPrivilegeCapabilities?: string[];\n bootstrap?: boolean;\n storePassword?: string;\n keyPassword?: string;\n harmonyos?: boolean;\n teamId?: string;\n product?: string;\n force?: boolean;\n hap?: string;\n out?: string;\n },\n ) => {\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n const passwords: SigningPasswords | undefined =\n opts.storePassword || opts.keyPassword\n ? { store: opts.storePassword ?? '123456', key: opts.keyPassword ?? '123456' }\n : undefined;\n\n if (opts.out && !opts.hap) throw new OniroError('--out names where `--hap` writes the signed HAP; pass --hap too.');\n if (opts.hap) {\n if (projectDir) throw new OniroError('Pass either a project directory or --hap, not both.');\n if (opts.product || opts.bootstrap) {\n throw new OniroError(`--${opts.product ? 'product' : 'bootstrap'} applies to a project, not to --hap.`);\n }\n // Each signing path honours only its own flags; say so rather than drop one.\n const ignored = opts.harmonyos\n ? [\n opts.apl !== 'normal' && '--apl',\n opts.appFeature && '--app-feature',\n opts.acls && '--acls (the ACLs are read from the HAP)',\n opts.appPrivilegeCapabilities && '--app-privilege-capabilities',\n (opts.storePassword || opts.keyPassword) && '--store-password/--key-password',\n ]\n : [opts.teamId && '--team-id', opts.force && '--force'];\n const unsupported = ignored.filter((flag): flag is string => typeof flag === 'string');\n if (unsupported.length > 0) {\n throw new OniroError(\n `${unsupported.join(', ')} ${unsupported.length > 1 ? 'do' : 'does'} not apply to ${opts.harmonyos ? '--harmonyos --hap' : '--hap without --harmonyos'}.`,\n );\n }\n if (!opts.harmonyos) {\n const result = await signOpenHarmonyHap({\n hapPath: opts.hap,\n outPath: opts.out,\n sdkHome: getOhosBaseSdkHome(config),\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n applicationCertPath: config.get('applicationCertPath', '') || undefined,\n logger,\n });\n logger.info(`Signed ${result.bundleName} into ${result.outPath}.`);\n return;\n }\n const result = await harmonyOsSignHap({\n config,\n session: createHarmonyOsSession({ config, logger }),\n hapPath: opts.hap,\n outPath: opts.out,\n teamId: opts.teamId,\n force: opts.force,\n logger,\n });\n logger.info(`Signed ${result.bundleName} into ${result.outPath} (profile names ${result.deviceIds.length} device(s)).`);\n return;\n }\n\n if (opts.harmonyos) {\n const result = await harmonyOsAutoSign({\n config,\n session: createHarmonyOsSession({ config, logger }),\n projectDir: dir,\n productName: opts.product,\n teamId: opts.teamId,\n force: opts.force,\n logger,\n });\n logger.info(`Signing configs ready for ${result.bundleName} (profile names ${result.deviceIds.length} device(s)).`);\n return;\n }\n // The OpenHarmony development certificate cannot sign for a HarmonyOS device.\n if (detectRuntimeOs(dir, opts.product) === 'HarmonyOS') {\n throw new OniroError(\n `${dir} targets HarmonyOS, which needs a certificate from AppGallery Connect: run \\`oniro-app auth login\\` once, then \\`oniro-app sign --harmonyos\\`.`,\n );\n }\n\n if (opts.bootstrap) {\n const result = prepareSigning({\n config,\n projectDir: dir,\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n logger,\n });\n logger.info(result.source === 'present' ? 'Signing material already present.' : 'Signing configs generated.');\n return;\n }\n\n const sdkHome = getOhosBaseSdkHome(config);\n logger.info(`Generating signing configs in ${dir} using SDK at ${sdkHome}...`);\n generateSigningConfigs({\n projectDir: dir,\n sdkHome,\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n logger,\n });\n logger.info('Signing configs generated.');\n },\n );\n}\n","import { Command } from 'commander';\nimport { HUAWEI_SITES, createHarmonyOsSession, type HarmonyOsSession } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** A session bound to the CLI runtime. The sign-in URL goes to stderr for headless hosts. */\nfunction session(): HarmonyOsSession {\n const { config, logger } = getRuntime();\n return createHarmonyOsSession({\n config,\n logger,\n onLoginUrl: (url) => process.stderr.write(`Opening the Huawei sign-in page. If no browser opens, visit:\\n ${url}\\n`),\n });\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program\n .command('auth')\n .description(\n 'Sign in to a Huawei developer account, which HarmonyOS signing (`oniro-app sign --harmonyos`) needs. ' +\n 'OpenHarmony signing needs no account. The token is stored encrypted under ONIRO_HARMONYOS_AUTH_DIR ' +\n '(default ~/.oniro/harmonyos).',\n );\n\n auth\n .command('login')\n .description('Sign in through the browser, which redirects back to a loopback port on this machine.')\n .option('--timeout <seconds>', 'How long to wait for the browser sign-in. Default 600.', (v) => Number(v))\n .action(async (opts: { timeout?: number }) => {\n const user = await session().login(opts.timeout ? { timeoutMs: Math.max(1, opts.timeout) * 1000 } : undefined);\n process.stdout.write(`${user.userName || user.userId}\\n`);\n });\n\n auth\n .command('logout')\n .description('Sign out and delete the stored token.')\n .action(async () => {\n const signedOut = await session().logout();\n getRuntime().logger.info(signedOut ? 'Signed out.' : 'Not signed in; nothing to do.');\n });\n\n auth\n .command('status')\n .description('Show the signed-in account. Exits non-zero when not signed in.')\n .option('--json', 'Emit the account details as JSON.')\n .action(async (opts: { json?: boolean }) => {\n const s = session();\n // Refreshed: a stale access token makes the agreement check fail.\n const user = await s.getUserInfo({ refresh: true });\n if (!user) {\n process.stderr.write('Not signed in. Run `oniro-app auth login`.\\n');\n process.exitCode = 1;\n return;\n }\n // Without real-name verification, the developer agreement is what allows signing.\n const agreement = user.isRealName ? null : await s.getDeveloperAgreement(user);\n if (opts.json) {\n const { userId, userName, countryCode, siteCode, isRealName } = user;\n const agcBaseUrl = HUAWEI_SITES[siteCode].agcBaseUrl;\n const status = { userId, userName, countryCode, site: siteCode, agcBaseUrl, isRealName, developerAgreement: agreement, tokenPath: s.tokenPath };\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n return;\n }\n process.stdout.write(`${user.userName || user.userId} (${user.userId}) [${user.siteCode}]\\n`);\n if (agreement && !(agreement.signed && agreement.latest)) {\n process.stderr.write(\n '[warn] This account has neither real-name verification nor the current HUAWEI Developer Basic Service Agreement accepted, so AppGallery Connect will not issue signing material. Accept the agreement in AppGallery Connect or DevEco Studio.\\n',\n );\n }\n });\n\n auth\n .command('team')\n .description('AGC teams this account belongs to.')\n .command('list')\n .description('List the AGC teams this account belongs to, for `oniro-app sign --harmonyos --team-id <id>`.')\n .option('--json', 'Emit the team list as JSON.')\n .action(async (opts: { json?: boolean }) => {\n const teams = await session().listTeams();\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(teams, null, 2)}\\n`);\n return;\n }\n for (const t of teams) process.stdout.write(`${t.id}\\t${t.name}\\n`);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n installApp,\n launchApp,\n uninstallApp,\n forceStop,\n applyChanges,\n existingHapOrUnsigned,\n getBundleName,\n readHapBundleName,\n OniroError,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\ninterface ApplyOpts {\n bundle?: string;\n module?: string;\n hap?: string;\n installedHap?: string;\n system?: boolean;\n allowUninstall?: boolean;\n device?: string;\n json?: boolean;\n}\n\nexport function registerAppCommand(program: Command): void {\n const app = program.command('app').description('Install, launch, and manage built apps on a connected device/emulator.');\n\n app\n .command('install [project-dir-or-hap]')\n .description(\n 'Install a built .hap on the connected device/emulator via hdc. Takes a project dir (default: the ' +\n 'current one), whose newest signed HAP is installed, else its unsigned one, or a .hap file. Fails ' +\n 'when the bundle manager rejects the HAP, and says how to sign when a target refuses an unsigned one.',\n )\n .option('--hap <path>', 'Override the .hap path (relative to project-dir or absolute).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (target: string | undefined, opts: { hap?: string; device?: string }) => {\n const { config, logger } = getRuntime();\n const isHap = target !== undefined && /\\.hap$/i.test(target);\n const dir = isHap ? process.cwd() : path.resolve(target ?? process.cwd());\n const hapPath = isHap ? path.resolve(target) : opts.hap;\n logger.info(`Installing ${hapPath ?? `app from ${dir}`}...`);\n const result = await installApp({ config, projectDir: dir, hapPath, deviceSerial: opts.device, logger });\n logger.info(`Installed ${result.hapPath}.`);\n });\n\n app\n .command('launch [project-dir]')\n .description(\n 'Launch an app on the connected device/emulator. Project mode (default): resolves ' +\n 'bundle + main ability from the project. Bundle mode (--bundle): launch an ' +\n 'already-installed app by bundle name, no project needed.',\n )\n .option('--bundle <bundle>', 'Launch an already-installed app by bundle name (no project needed).')\n .option('--module <module>', 'Module folder name (project mode).', 'entry')\n .option('--ability <name>', 'Explicit ability to launch (defaults to the module mainElement in project mode, or the installed bundle main ability in --bundle mode).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (projectDir: string | undefined, opts: { bundle?: string; module: string; ability?: string; device?: string }) => {\n const { config, logger } = getRuntime();\n if (opts.bundle) {\n logger.info(`Launching installed bundle ${opts.bundle}...`);\n await launchApp({ config, bundleName: opts.bundle, abilityName: opts.ability, deviceSerial: opts.device, logger });\n } else {\n const dir = path.resolve(projectDir ?? process.cwd());\n logger.info(`Launching app from ${dir}...`);\n await launchApp({ config, projectDir: dir, moduleName: opts.module, abilityName: opts.ability, deviceSerial: opts.device, logger });\n }\n logger.info('App launched.');\n });\n\n app\n .command('apply [project-dir-or-hap]')\n .description(\n 'Install a HAP (a project dir, default the current one, or a .hap file) and verify the running process ' +\n 'took the change. Refuses a HAP of another bundle. Handles sign-info mismatch, asset-cache invalidation, ' +\n 'and persistent-bundle restart.',\n )\n .option(\n '--bundle <bundle>',\n 'Bundle name to apply changes to. Defaults to the bundleName in the .hap file, else in the project AppScope/app.json5.',\n )\n .option('--module <module>', 'Module to resolve the HAP from (multi-module projects).')\n .option('--hap <path>', 'Explicit .hap path (relative to project-dir or absolute).')\n .option('--installed-hap <path>', 'Local path to the currently-installed HAP, to enable the asset-cache reboot.')\n .option('--system', 'Treat as a persistent/system bundle (refuses uninstall on sign-info mismatch).')\n .option('--allow-uninstall', 'Permit uninstalling a system bundle on sign-info mismatch (dangerous).')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Emit the result as JSON.')\n .action(async (target: string | undefined, opts: ApplyOpts) => {\n const { config, logger } = getRuntime();\n const isHap = target !== undefined && /\\.hap$/i.test(target);\n if (isHap && opts.hap) throw new OniroError('Pass the HAP either as the argument or with --hap, not both.');\n const dir = isHap ? process.cwd() : path.resolve(target ?? process.cwd());\n const hapPath = isHap ? path.resolve(target) : opts.hap;\n let bundle = opts.bundle;\n if (!bundle && isHap) {\n // The same signed-to-unsigned fallback applyChanges applies when it installs.\n const hap = existingHapOrUnsigned(hapPath!);\n if (!hap) throw new OniroError(`HAP not found at ${hapPath}.`);\n bundle = (await readHapBundleName(hap.path).catch(() => null)) ?? undefined;\n if (!bundle) throw new OniroError(`Could not read the bundle name from ${hap.path}. Pass --bundle.`);\n }\n bundle ??= getBundleName(dir);\n const result = await applyChanges({\n config,\n bundle,\n hapPath,\n projectDir: dir,\n module: opts.module,\n installedHapPath: opts.installedHap,\n isSystemBundle: opts.system,\n allowUninstall: opts.allowUninstall,\n deviceSerial: opts.device,\n logger,\n });\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n } else {\n logger.info(\n `apply: method=${result.method} pid ${result.preInstallPid ?? '-'} -> ${result.postInstallPid ?? '-'}` +\n `${result.cacheCleared ? ' (cache cleared)' : ''}`,\n );\n }\n });\n\n app\n .command('uninstall <bundle>')\n .description('Uninstall an app by bundle name.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (bundle: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await uninstallApp({ config, bundle, deviceSerial: opts.device, logger });\n logger.info(`Uninstalled ${bundle}.`);\n });\n\n app\n .command('stop <bundle>')\n .description('Force-stop an app by bundle name.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (bundle: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await forceStop({ config, bundle, deviceSerial: opts.device, logger });\n logger.info(`Stopped ${bundle}.`);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n ALL_SDKS,\n createScaffold,\n isValidBundleName,\n isValidProjectName,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { getBundledTemplateRoot } from '../lib/templateRoot.js';\n\ninterface CreateOpts {\n name: string;\n bundle: string;\n location: string;\n sdk: string;\n template: string;\n module?: string;\n overwrite?: boolean;\n}\n\nexport function registerCreateCommand(program: Command): void {\n program\n .command('create')\n .description('Scaffold a new Oniro/OpenHarmony or HarmonyOS app from a template. All flags are required (non-interactive).')\n .requiredOption('--name <name>', 'Project folder name (letters, digits, ._- only)')\n .requiredOption('--bundle <bundleName>', 'Bundle name in reverse-DNS form, e.g. com.example.myapp')\n .requiredOption('--location <dir>', 'Parent directory where the new project folder will be created')\n .requiredOption('--sdk <api>', 'Target SDK API level (e.g. 18, 20)')\n .option('--template <id>', 'Template id', 'EmptyAbility')\n .option('--module <name>', 'Module folder name (defaults to the template default, usually `entry`)')\n .option('--overwrite', 'Replace the destination if it already exists')\n .action(async (opts: CreateOpts) => {\n const { config, logger } = getRuntime();\n\n if (!isValidProjectName(opts.name)) {\n throw new Error(`Invalid --name '${opts.name}'. Use letters/numbers/._- and no slashes.`);\n }\n if (!isValidBundleName(opts.bundle)) {\n throw new Error(`Invalid --bundle '${opts.bundle}'. Example: com.example.myapp`);\n }\n const sdkApi = Number(opts.sdk);\n if (!Number.isFinite(sdkApi)) {\n throw new Error(`--sdk must be a numeric api level. Known: ${ALL_SDKS.map((s) => s.api).join(', ')}`);\n }\n\n const templateRoot = getBundledTemplateRoot();\n const result = await createScaffold({\n config,\n templateId: opts.template,\n projectName: opts.name,\n bundleName: opts.bundle,\n location: path.resolve(opts.location),\n sdkApi,\n moduleName: opts.module,\n templateRoot,\n overwrite: opts.overwrite,\n logger,\n });\n\n logger.info(`Project created at ${result.projectDir}`);\n process.stdout.write(`${result.projectDir}\\n`);\n });\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Resolve the bundled `templates/` directory shipped inside this CLI package.\n *\n * The CLI's `dist/oniro-app.js` lives at `<pkg>/dist/oniro-app.js` after build\n * and the templates ship at `<pkg>/templates/`. During development the entrypoint\n * lives at `<pkg>/src/bin/oniro-app.ts` so we also try `../../templates` from there.\n */\nexport function getBundledTemplateRoot(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n path.resolve(here, '../templates'), // dist/oniro-app.js → ../templates\n path.resolve(here, '../../templates'), // src/bin/oniro-app.ts → ../../templates\n ];\n for (const c of candidates) {\n if (fs.existsSync(c)) return c;\n }\n // Return the most likely path even if it doesn't exist yet; createScaffold will\n // surface a clear error from there.\n return candidates[0]!;\n}\n","import { Command } from 'commander';\nimport { listTemplates } from '@oniroproject/core';\nimport { getBundledTemplateRoot } from '../lib/templateRoot.js';\n\nexport function registerTemplatesCommand(program: Command): void {\n const templates = program.command('templates').description('Inspect the templates bundled with this CLI.');\n\n templates\n .command('list')\n .description('List available project templates.')\n .option('--json', 'Emit machine-readable JSON.')\n .action((opts: { json?: boolean }) => {\n const root = getBundledTemplateRoot();\n const list = listTemplates(root);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(list, null, 2)}\\n`);\n return;\n }\n if (list.length === 0) {\n process.stdout.write('No templates available.\\n');\n return;\n }\n const rows = list.map((t) => `${t.id.padEnd(20)} ${t.label.padEnd(24)} ${t.description}`);\n process.stdout.write(`${rows.join('\\n')}\\n`);\n });\n}\n","import { Command, Option } from 'commander';\nimport { reboot } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerRebootCommand(program: Command): void {\n program\n .command('reboot')\n .description('Reboot the connected device/emulator.')\n .addOption(\n new Option('--mode <mode>', 'Reboot target.').choices(['system', 'bootloader', 'recovery']).default('system'),\n )\n .option('--wait-bundle <bundle>', 'After a system reboot, wait until this bundle is running again.')\n .option('--timeout <ms>', 'Max time to wait for the bundle, ms.', '180000')\n .option('--device <serial>', 'Target device serial.')\n .action(\n async (opts: {\n mode: 'system' | 'bootloader' | 'recovery';\n waitBundle?: string;\n timeout: string;\n device?: string;\n }) => {\n const { config, logger } = getRuntime();\n logger.info(`Rebooting device (${opts.mode})...`);\n await reboot({\n config,\n mode: opts.mode,\n waitForBundle: opts.waitBundle,\n timeoutMs: Number(opts.timeout),\n deviceSerial: opts.device,\n logger,\n });\n logger.info('Reboot complete.');\n },\n );\n}\n","import { Command } from 'commander';\nimport { waitForLog, waitForBoot, waitForBundle, waitForTarget, describeLayoutNode } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { addTargetOptions, selectorFrom, type TargetOpts } from '../lib/target.js';\nimport { parseSince } from '../lib/logSince.js';\n\ninterface WaitOpts extends TargetOpts {\n log?: string;\n since?: string;\n boot?: boolean;\n bundle?: string;\n pidOf?: string;\n domain?: string;\n gone?: boolean;\n interval: string;\n timeout: string;\n device?: string;\n json?: boolean;\n}\n\nexport function registerWaitCommand(program: Command): void {\n const wait = program\n .command('wait')\n .description(\n 'Wait for a device condition: a log line (--log), boot (--boot), a bundle to start (--bundle), ' +\n 'or an on-screen element (--target / --target-id / --target-type).',\n )\n .option('--log <pattern>', 'Resolve when a hilog line (tag: message) logged after the command starts matches this regex.')\n .option(\n '--since <seconds>',\n 'With --log: also match lines logged up to N seconds before the command started, ' +\n 'measured on the device clock; \"all\" matches everything still in the device log buffer.',\n )\n .option('--boot', 'Resolve when the device is reachable (optionally also --pid-of).')\n .option('--bundle <bundle>', 'With --log: filter to this bundle. Alone: wait until this bundle is running.')\n .option('--pid-of <name>', 'With --boot: also require this process to have a pid.')\n .option('--domain <domain>', 'With --log: hilog domain filter (e.g. 0xD003900).');\n addTargetOptions(wait, 'Resolve when', { index: false });\n wait\n .option('--gone', 'With --target*: resolve when no uncovered element matches any more.')\n .option('--interval <ms>', 'With --target*: poll interval, ms (each poll is a layout dump).', '500')\n .option('--timeout <ms>', 'Max wait, ms.', '30000')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'With --log or --target*: emit the matched entry/element as JSON.')\n .action(async (opts: WaitOpts) => {\n const { config, logger } = getRuntime();\n const timeoutMs = Number(opts.timeout);\n const selector = selectorFrom(opts);\n if (opts.since !== undefined && !opts.log) throw new Error('--since applies only to --log.');\n\n if (opts.log) {\n const entry = await waitForLog({\n config,\n pattern: new RegExp(opts.log),\n timeoutMs,\n bundle: opts.bundle,\n domain: opts.domain,\n deviceSerial: opts.device,\n lookbackMs: parseSince(opts.since),\n logger,\n });\n if (opts.json) process.stdout.write(`${JSON.stringify(entry, null, 2)}\\n`);\n else logger.info(`matched: ${entry.time} ${entry.tag}: ${entry.message}`);\n return;\n }\n if (opts.boot) {\n await waitForBoot({ config, untilPidOf: opts.pidOf, timeoutMs, deviceSerial: opts.device, logger });\n logger.info('Device booted.');\n return;\n }\n if (selector) {\n const node = await waitForTarget({\n config,\n selector,\n gone: opts.gone,\n timeoutMs,\n pollMs: Number(opts.interval) || 500,\n deviceSerial: opts.device,\n logger,\n });\n if (!node) {\n logger.info('Element is gone.');\n return;\n }\n if (opts.json) process.stdout.write(`${JSON.stringify(node, null, 2)}\\n`);\n else logger.info(`found: ${describeLayoutNode(node)}`);\n return;\n }\n if (opts.bundle) {\n await waitForBundle({ config, bundle: opts.bundle, timeoutMs, deviceSerial: opts.device, logger });\n logger.info(`Bundle ${opts.bundle} is running.`);\n return;\n }\n throw new Error('Specify one of --log <pattern>, --boot, --bundle <bundle>, or --target <text> (or --target-id / --target-type).');\n });\n}\n","import type { Command } from 'commander';\nimport type { LayoutSelector } from '@oniroproject/core';\n\n/** The shared element-selector flags, as commander parses them. */\nexport interface TargetOpts {\n target?: string;\n targetId?: string;\n targetType?: string;\n targetIndex?: string;\n}\n\n/**\n * Add the element-selector flags shared by `input`, `wait`, and `screenshot`.\n * `verb` completes the `--target` help text (e.g. \"Tap\" → \"Tap the element …\").\n */\nexport function addTargetOptions(cmd: Command, verb: string, opts: { index?: boolean } = {}): Command {\n cmd\n .option(\n '--target <text>',\n `${verb} the element whose text, description, or placeholder matches ` +\n '(case-insensitive; exact matches win, else substring). Covered elements are skipped.',\n )\n .option('--target-id <id>', 'Match the element by its id or key.')\n .option('--target-type <type>', 'Restrict the match to a component type (e.g. Button, TextInput).');\n if (opts.index !== false) {\n cmd.option('--target-index <n>', 'Pick the n-th (0-based) of several matching elements.');\n }\n return cmd;\n}\n\n/** The selector built from the flags, or undefined when none was given. */\nexport function selectorFrom(opts: TargetOpts): LayoutSelector | undefined {\n if (opts.target === undefined && opts.targetId === undefined && opts.targetType === undefined) return undefined;\n return { text: opts.target, id: opts.targetId, type: opts.targetType };\n}\n\nexport function targetIndexFrom(opts: TargetOpts): number | undefined {\n if (opts.targetIndex === undefined) return undefined;\n const n = Number(opts.targetIndex);\n if (!Number.isInteger(n) || n < 0) throw new Error(`--target-index must be a non-negative integer; got ${opts.targetIndex}.`);\n return n;\n}\n","/**\n * Parse a `--since` value for `wait --log` and `watch`: how many seconds before\n * the command started a log line may be from and still count, or `all` for\n * everything still in the device buffer. Returns ms; undefined when not given.\n */\nexport function parseSince(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (value === 'all') return Infinity;\n const seconds = Number(value);\n if (value.trim() === '' || !Number.isFinite(seconds) || seconds < 0) {\n throw new Error(`--since takes a number of seconds or \"all\", not \"${value}\".`);\n }\n return seconds * 1000;\n}\n","import { Command } from 'commander';\nimport { watchLog } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { parseSince } from '../lib/logSince.js';\n\ninterface WatchOpts {\n log?: string;\n for: string;\n since?: string;\n bundle?: string;\n domain?: string;\n dedup: boolean;\n device?: string;\n json?: boolean;\n}\n\nexport function registerWatchCommand(program: Command): void {\n program\n .command('watch')\n .description('Collect the hilog lines matching a pattern that are logged during a fixed duration.')\n .option('--log <pattern>', 'Regex tested against each line (tag: message).')\n .option('--for <ms>', 'Duration to watch, ms.', '10000')\n .option(\n '--since <seconds>',\n 'Also collect lines logged up to N seconds before the command started, measured on the device clock; ' +\n '\"all\" adds everything still in the device log buffer.',\n )\n .option('--bundle <bundle>', 'Filter to this bundle.')\n .option('--domain <domain>', 'hilog domain filter (e.g. 0xD003900).')\n .option('--no-dedup', 'Do not collapse consecutive duplicate lines.')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Emit the entries as JSON.')\n .action(async (opts: WatchOpts) => {\n const { config, logger } = getRuntime();\n if (!opts.log) throw new Error('watch requires --log <pattern>.');\n const entries = await watchLog({\n config,\n pattern: new RegExp(opts.log),\n durationMs: Number(opts.for),\n bundle: opts.bundle,\n domain: opts.domain,\n dedup: opts.dedup,\n deviceSerial: opts.device,\n lookbackMs: parseSince(opts.since),\n logger,\n });\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(entries, null, 2)}\\n`);\n } else {\n for (const e of entries) process.stdout.write(`${e.time} ${e.level} ${e.tag}: ${e.message}\\n`);\n }\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { takeScreenshot, captureBurst, locateTarget, describeLayoutNode } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport {\n renderWithGrid,\n buildContactSheet,\n frameDiffs,\n cropImage,\n parseCropRect,\n padCropRect,\n type CropRect,\n} from '../lib/screenshotImage.js';\nimport { addTargetOptions, selectorFrom, targetIndexFrom, type TargetOpts } from '../lib/target.js';\n\ninterface ScreenshotOpts extends TargetOpts {\n output: string;\n grid?: boolean;\n maxDim: string;\n crop?: string;\n contactSheet?: boolean;\n burst?: string;\n interval: string;\n json?: boolean;\n device?: string;\n}\n\nconst DEFAULT_CONTACT_SHEET_FRAMES = 8;\n// Margin kept around a --target element when cropping to it, as a fraction of the display.\nconst TARGET_CROP_PAD = 0.02;\n\nfunction clampMaxDim(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n)) return 1024;\n return Math.max(256, Math.min(4096, Math.round(n)));\n}\n\nexport function registerScreenshotCommand(program: Command): void {\n const screenshot = program\n .command('screenshot')\n .description(\n 'Capture the screen. Default: full-resolution raw JPEG. ' +\n '--grid: downscaled JPEG with a 10x10 grid (axes 0.0-1.0) for picking tap coordinates. ' +\n '--crop / --target: a full-resolution crop of one region or element, for checking detail cheaply. ' +\n '--contact-sheet: capture a burst and tile it into one image with per-frame change diffs.',\n )\n .option('-o, --output <file>', 'Output file path.', 'screenshot.jpeg')\n .option('--grid', 'Downscale (to --max-dim) and overlay a 10x10 coordinate grid.')\n .option('--max-dim <px>', 'Longest-side cap for --grid / --crop / --target / --contact-sheet (256-4096).', '1024')\n .option('--crop <x1,y1,x2,y2>', 'Crop to this region, given as 0-1 fractions of the screen.');\n addTargetOptions(screenshot, 'Crop to');\n screenshot\n .option('--contact-sheet', 'Capture a burst and composite it into one tiled contact sheet.')\n .option('--burst <count>', 'Capture N frames; writes <base>-<i><ext> (or feeds --contact-sheet).')\n .option('--interval <ms>', 'Delay between burst frames, ms.', '50')\n .option('--json', 'Emit the full result object as JSON on stdout (with --contact-sheet).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: ScreenshotOpts, command: Command) => {\n const { config, logger } = getRuntime();\n const maxDim = clampMaxDim(opts.maxDim);\n const intervalMs = Number(opts.interval) || 50;\n\n // --- Crop: one region (or element) at full resolution ---\n const selector = selectorFrom(opts);\n if (opts.crop !== undefined || selector) {\n if (opts.crop !== undefined && selector) throw new Error('Use either --crop or --target*, not both.');\n if (opts.grid || opts.contactSheet || opts.burst) {\n throw new Error('--crop / --target cannot be combined with --grid, --contact-sheet, or --burst.');\n }\n let rect: CropRect;\n let label: string;\n if (selector) {\n // Leave the keyboard alone: dismissing it would change what we are capturing.\n const located = await locateTarget({\n config,\n selector,\n index: targetIndexFrom(opts),\n hideKeyboard: false,\n deviceSerial: opts.device,\n logger,\n });\n if (!located.node.b) throw new Error(`${describeLayoutNode(located.node)} has no bounds to crop to.`);\n rect = padCropRect(located.node.b, TARGET_CROP_PAD);\n label = describeLayoutNode(located.node);\n } else {\n rect = parseCropRect(opts.crop!);\n label = rect.map((n) => n.toFixed(3)).join(',');\n }\n const shot = await takeScreenshot({ config, deviceSerial: opts.device, logger });\n const cropped = await cropImage(shot.pixels, rect, { maxDim });\n fs.writeFileSync(opts.output, cropped.buf);\n logger.info(\n `Wrote ${opts.output} (${cropped.width}x${cropped.height} from a ${cropped.cropWidth}x${cropped.cropHeight} ` +\n `crop at ${cropped.left},${cropped.top}: ${label}).`,\n );\n return;\n }\n\n // --- Contact sheet: burst -> one tiled image + per-frame diffs ---\n if (opts.contactSheet) {\n const count = opts.burst ? Math.max(1, Number(opts.burst)) : DEFAULT_CONTACT_SHEET_FRAMES;\n const frames = await captureBurst({ config, count, intervalMs, deviceSerial: opts.device, logger });\n const diffs = await frameDiffs(frames);\n const sheet = await buildContactSheet(frames, { maxDim, diffs });\n fs.writeFileSync(opts.output, sheet.buf);\n\n // Only fan out the individual raw frames when --burst was also requested.\n if (opts.burst) {\n const ext = path.extname(opts.output) || '.jpeg';\n const base = opts.output.slice(0, opts.output.length - ext.length);\n frames.forEach((frame, i) => fs.writeFileSync(`${base}-${i}${ext}`, frame));\n }\n\n const perFrame = frames.map((_, i) => ({ idx: i, t_ms: i * intervalMs, diffVsPrev: diffs[i] ?? 0 }));\n if (opts.json) {\n process.stdout.write(\n `${JSON.stringify(\n {\n sheet: opts.output,\n frameCount: frames.length,\n cols: sheet.cols,\n rows: sheet.rows,\n intervalMs,\n note: 't_ms is nominal (idx*interval); diffVsPrev is 0..1 mean greyscale diff vs the previous frame.',\n frames: perFrame,\n },\n null,\n 2,\n )}\\n`,\n );\n } else {\n process.stdout.write(`${JSON.stringify(perFrame)}\\n`);\n }\n\n let peak = 0;\n for (let i = 1; i < diffs.length; i++) if ((diffs[i] ?? 0) > (diffs[peak] ?? 0)) peak = i;\n logger.info(\n `Wrote contact sheet ${opts.output} (${sheet.cols}x${sheet.rows}, ${frames.length} frames). ` +\n `Biggest change at frame ${peak} (Δ${(diffs[peak] ?? 0).toFixed(2)}).`,\n );\n return;\n }\n\n // --- Burst (raw frames) — unchanged behaviour ---\n if (opts.burst) {\n const frames = await captureBurst({\n config,\n count: Number(opts.burst),\n intervalMs,\n deviceSerial: opts.device,\n logger,\n });\n const ext = path.extname(opts.output) || '.jpeg';\n const base = opts.output.slice(0, opts.output.length - ext.length);\n frames.forEach((frame, i) => fs.writeFileSync(`${base}-${i}${ext}`, frame));\n logger.info(`Wrote ${frames.length} frames to ${base}-<0..${frames.length - 1}>${ext}.`);\n return;\n }\n\n // --- Single shot ---\n const shot = await takeScreenshot({ config, deviceSerial: opts.device, logger });\n const maxDimProvided = command.getOptionValueSource('maxDim') === 'cli';\n if (opts.grid || maxDimProvided) {\n const rendered = await renderWithGrid(shot.pixels, { maxDim, grid: !!opts.grid });\n fs.writeFileSync(opts.output, rendered.buf);\n logger.info(\n `Wrote ${opts.output} (${rendered.width}x${rendered.height} from ` +\n `${rendered.originalWidth}x${rendered.originalHeight}${opts.grid ? ', 10x10 grid' : ''}).`,\n );\n return;\n }\n fs.writeFileSync(opts.output, shot.pixels);\n logger.info(`Wrote ${opts.output} (${shot.width}x${shot.height}).`);\n });\n}\n","import sharp from 'sharp';\n\n/**\n * Agent-facing screenshot image processing for the CLI.\n *\n * `@oniroproject/core` deliberately ships no image dependency — it returns raw\n * JPEG buffers. The grid overlay / downscale and the burst contact-sheet live\n * here (the CLI is the affordance layer), so `oniro-app screenshot` can produce\n * exactly what the ohos-hdc MCP used to. The grid drawing is ported verbatim\n * from that MCP so the output is equivalent.\n */\n\nexport interface RenderResult {\n /** Encoded JPEG. */\n buf: Buffer;\n /** Rendered (post-downscale) dimensions. */\n width: number;\n height: number;\n /** Source dimensions, before downscale. */\n originalWidth: number;\n originalHeight: number;\n}\n\nexport interface RenderWithGridOptions {\n /** Longest-side cap in pixels. The image is downscaled (never upscaled) to fit. */\n maxDim: number;\n /** Overlay the 10x10 grid with 0.0–1.0 axis labels after downscaling. */\n grid?: boolean;\n}\n\n/**\n * Build an SVG overlay: a 10x10 grid with X/Y axis labels (0.0–1.0) sized to the\n * given image dimensions. Ported verbatim from the ohos-hdc MCP so the gridded\n * output matches what agents are used to.\n */\nexport function buildGridSvg(width: number, height: number): string {\n const lineColor = 'rgba(255,80,80,0.55)';\n const labelBg = 'rgba(0,0,0,0.7)';\n const labelFg = '#fff';\n const fontSize = Math.max(10, Math.round(Math.min(width, height) / 60));\n const padding = Math.round(fontSize * 0.4);\n const labels: string[] = [];\n const lines: string[] = [];\n for (let i = 0; i <= 10; i++) {\n const f = i / 10;\n const x = Math.round(f * (width - 1));\n const y = Math.round(f * (height - 1));\n // grid lines (skip 0 and 10 — those are the image edges)\n if (i > 0 && i < 10) {\n lines.push(`<line x1=\"${x}\" y1=\"0\" x2=\"${x}\" y2=\"${height}\" stroke=\"${lineColor}\" stroke-width=\"1\"/>`);\n lines.push(`<line x1=\"0\" y1=\"${y}\" x2=\"${width}\" y2=\"${y}\" stroke=\"${lineColor}\" stroke-width=\"1\"/>`);\n }\n const tag = f.toFixed(1);\n // X-axis labels along the top\n const tx = i === 0 ? padding : i === 10 ? width - padding : x;\n const anchorX = i === 0 ? 'start' : i === 10 ? 'end' : 'middle';\n labels.push(\n `<text x=\"${tx}\" y=\"${fontSize + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"${anchorX}\">${tag}</text>`,\n );\n // Y-axis labels along the left\n const ty = i === 0 ? fontSize + padding : i === 10 ? height - padding : y + fontSize / 3;\n labels.push(\n `<text x=\"${padding}\" y=\"${ty}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">${tag}</text>`,\n );\n }\n // Axis title markers in the corners\n labels.push(\n `<text x=\"${width / 2}\" y=\"${fontSize * 2.4 + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"middle\">X →</text>`,\n );\n labels.push(\n `<text x=\"${padding}\" y=\"${fontSize * 2.6 + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">Y ↓</text>`,\n );\n return `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">${lines.join('')}${labels.join('')}</svg>`;\n}\n\n/**\n * Downscale a JPEG so its longest side is <= `maxDim` (never upscaling) and,\n * when `grid` is set, overlay the coordinate grid. Returns the encoded JPEG plus\n * rendered and original dimensions.\n */\nexport async function renderWithGrid(jpeg: Buffer, opts: RenderWithGridOptions): Promise<RenderResult> {\n const meta = await sharp(jpeg).metadata();\n const originalWidth = meta.width ?? 0;\n const originalHeight = meta.height ?? 0;\n const longest = Math.max(originalWidth, originalHeight) || 1;\n const scale = Math.min(1, opts.maxDim / longest);\n const width = Math.max(1, Math.round(originalWidth * scale));\n const height = Math.max(1, Math.round(originalHeight * scale));\n const resized = await sharp(jpeg).resize(width, height).jpeg({ quality: 80 }).toBuffer();\n if (!opts.grid) {\n return { buf: resized, width, height, originalWidth, originalHeight };\n }\n const svg = buildGridSvg(width, height);\n const buf = await sharp(resized)\n .composite([{ input: Buffer.from(svg) }])\n .jpeg({ quality: 80 })\n .toBuffer();\n return { buf, width, height, originalWidth, originalHeight };\n}\n\n/** A region as [x1, y1, x2, y2] fractions (0–1) of the image. */\nexport type CropRect = [number, number, number, number];\n\n/** Parse `\"x1,y1,x2,y2\"` (0–1 fractions, x1<x2, y1<y2) into a {@link CropRect}. */\nexport function parseCropRect(spec: string): CropRect {\n const parts = spec.split(',').map((s) => Number(s.trim()));\n if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0 || n > 1)) {\n throw new Error(`--crop expects four 0-1 fractions \"x1,y1,x2,y2\"; got \"${spec}\".`);\n }\n const [x1, y1, x2, y2] = parts as CropRect;\n if (!(x2 > x1 && y2 > y1)) throw new Error(`--crop needs x1 < x2 and y1 < y2; got \"${spec}\".`);\n return [x1, y1, x2, y2];\n}\n\n/** Grow a rect by `pad` (a fraction) on every side, clamped to 0–1. */\nexport function padCropRect(r: CropRect, pad: number): CropRect {\n return [Math.max(0, r[0] - pad), Math.max(0, r[1] - pad), Math.min(1, r[2] + pad), Math.min(1, r[3] + pad)];\n}\n\nexport interface CropResult {\n /** Encoded JPEG. */\n buf: Buffer;\n /** Rendered (post-downscale) dimensions. */\n width: number;\n height: number;\n /** The cropped region in source pixels. */\n left: number;\n top: number;\n cropWidth: number;\n cropHeight: number;\n}\n\n/**\n * Crop a JPEG to a 0–1 region at full resolution, then downscale so the longest\n * side is <= `maxDim` (never upscaling). Detail where it is needed, at a\n * fraction of a full-resolution screenshot's size.\n */\nexport async function cropImage(jpeg: Buffer, rect: CropRect, opts: { maxDim: number }): Promise<CropResult> {\n const meta = await sharp(jpeg).metadata();\n const w = meta.width ?? 1;\n const h = meta.height ?? 1;\n const left = Math.min(w - 1, Math.floor(rect[0] * w));\n const top = Math.min(h - 1, Math.floor(rect[1] * h));\n const cropWidth = Math.max(1, Math.min(w, Math.ceil(rect[2] * w)) - left);\n const cropHeight = Math.max(1, Math.min(h, Math.ceil(rect[3] * h)) - top);\n const scale = Math.min(1, opts.maxDim / Math.max(cropWidth, cropHeight));\n const width = Math.max(1, Math.round(cropWidth * scale));\n const height = Math.max(1, Math.round(cropHeight * scale));\n const buf = await sharp(jpeg)\n .extract({ left, top, width: cropWidth, height: cropHeight })\n .resize(width, height)\n .jpeg({ quality: 85 })\n .toBuffer();\n return { buf, width, height, left, top, cropWidth, cropHeight };\n}\n\nexport interface ContactSheetOptions {\n /** Longest-side cap for the whole sheet; per-tile size derives from this. */\n maxDim: number;\n /** Tiles per row. Defaults to ceil(sqrt(N)). */\n cols?: number;\n /** Per-frame diff (0..1), index-aligned with `frames`; printed on each tile. */\n diffs?: number[];\n /** Gap between tiles, px. */\n gap?: number;\n}\n\nexport interface ContactSheetResult {\n buf: Buffer;\n width: number;\n height: number;\n cols: number;\n rows: number;\n tileWidth: number;\n tileHeight: number;\n count: number;\n}\n\nfunction buildTileLabelSvg(width: number, height: number, idx: number, diff?: number): string {\n const fontSize = Math.max(12, Math.round(Math.min(width, height) / 16));\n const pad = Math.round(fontSize * 0.4);\n let label = `#${idx}`;\n if (typeof diff === 'number') label += ` Δ${diff.toFixed(2)}`;\n const boxW = Math.round(label.length * fontSize * 0.62) + pad * 2;\n const boxH = fontSize + pad * 2;\n return (\n `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">` +\n `<rect x=\"0\" y=\"0\" width=\"${boxW}\" height=\"${boxH}\" fill=\"rgba(0,0,0,0.6)\"/>` +\n `<text x=\"${pad}\" y=\"${fontSize + pad - 1}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"#fff\" stroke=\"rgba(0,0,0,0.85)\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">${label}</text>` +\n `</svg>`\n );\n}\n\n/**\n * Composite a burst of JPEG frames into a single tiled contact sheet, each tile\n * labelled with its frame index (and per-frame diff when provided). One image\n * replaces N — a large token saving when verifying transient UI.\n */\nexport async function buildContactSheet(frames: Buffer[], opts: ContactSheetOptions): Promise<ContactSheetResult> {\n if (frames.length === 0) throw new Error('buildContactSheet: no frames');\n const count = frames.length;\n const cols = Math.max(1, opts.cols ?? Math.ceil(Math.sqrt(count)));\n const rows = Math.ceil(count / cols);\n const gap = opts.gap ?? 8;\n\n const meta0 = await sharp(frames[0]).metadata();\n const fw = meta0.width ?? 1;\n const fh = meta0.height ?? 1;\n const longest = Math.max(fw, fh) || 1;\n const tileScale = Math.min(1, opts.maxDim / cols / longest);\n const tileWidth = Math.max(1, Math.round(fw * tileScale));\n const tileHeight = Math.max(1, Math.round(fh * tileScale));\n\n const tiles = await Promise.all(\n frames.map((frame, i) => {\n const label = Buffer.from(buildTileLabelSvg(tileWidth, tileHeight, i, opts.diffs?.[i]));\n return sharp(frame)\n .resize(tileWidth, tileHeight, { fit: 'fill' })\n .composite([{ input: label, top: 0, left: 0 }])\n .png()\n .toBuffer();\n }),\n );\n\n const width = cols * tileWidth + (cols + 1) * gap;\n const height = rows * tileHeight + (rows + 1) * gap;\n const placements = tiles.map((input, i) => {\n const r = Math.floor(i / cols);\n const c = i % cols;\n return { input, left: gap + c * (tileWidth + gap), top: gap + r * (tileHeight + gap) };\n });\n\n const buf = await sharp({\n create: { width, height, channels: 3, background: { r: 20, g: 20, b: 20 } },\n })\n .composite(placements)\n .jpeg({ quality: 80 })\n .toBuffer();\n\n return { buf, width, height, cols, rows, tileWidth, tileHeight, count };\n}\n\n/**\n * Per-frame change metric: mean absolute difference of a downscaled greyscale\n * thumbnail vs. the previous frame, normalised to 0..1. Frame 0 is 0 (no\n * predecessor). Cheap, deterministic, and device-free.\n */\nexport async function frameDiffs(frames: Buffer[], opts: { sample?: number } = {}): Promise<number[]> {\n if (frames.length === 0) return [];\n const sample = opts.sample ?? 32;\n const thumbs = await Promise.all(\n frames.map((f) => sharp(f).greyscale().resize(sample, sample, { fit: 'fill' }).raw().toBuffer()),\n );\n const out: number[] = [0];\n for (let i = 1; i < thumbs.length; i++) {\n const a = thumbs[i - 1];\n const b = thumbs[i];\n if (!a || !b) {\n out.push(0);\n continue;\n }\n const n = Math.min(a.length, b.length) || 1;\n let s = 0;\n for (let k = 0; k < n; k++) s += Math.abs((a[k] ?? 0) - (b[k] ?? 0));\n out.push(+(s / n / 255).toFixed(4));\n }\n return out;\n}\n","import { Command } from 'commander';\nimport { dumpLayout } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { formatFlatLayout } from '../lib/layoutText.js';\n\ninterface DumpOpts {\n bundle?: string;\n raw?: boolean;\n flat?: boolean;\n device?: string;\n}\n\nexport function registerDumpCommand(program: Command): void {\n program\n .command('dump [target]')\n .description(\n 'Dump device state. Currently supports `dump layout` (the default target): JSON by default, ' +\n 'or one line per element with --flat.',\n )\n .option('--bundle <bundle>', 'Filter the layout to a single window/bundle.')\n .option('--raw', 'Return the unpruned layout tree.')\n .option('--flat', 'One line per element (type, label, center as 0-1 fractions, flags) instead of a JSON tree.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (target: string | undefined, opts: DumpOpts) => {\n const { config, logger } = getRuntime();\n const what = target ?? 'layout';\n if (what !== 'layout') throw new Error(`Unknown dump target \"${what}\". Supported: layout.`);\n if (opts.raw && opts.flat) throw new Error('--raw and --flat cannot be combined.');\n const result = await dumpLayout({\n config,\n bundleName: opts.bundle,\n prune: !opts.raw,\n detectKeyboard: !opts.raw,\n deviceSerial: opts.device,\n logger,\n });\n process.stdout.write(opts.flat ? formatFlatLayout(result) : `${JSON.stringify(result, null, 2)}\\n`);\n });\n}\n","import { flattenLayout, type DumpLayoutResult, type FlatLayoutNode } from '@oniroproject/core';\n\nconst MAX_TEXT = 80;\n\nfunction quote(s: string): string {\n return JSON.stringify(s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT - 1)}…` : s);\n}\n\nfunction flags(n: FlatLayoutNode): string[] {\n const out: string[] = [];\n if (n.click) out.push('click');\n if (n.longClick) out.push('longClick');\n if (n.scroll) out.push('scroll');\n if (n.checked) out.push('checked');\n else if (n.check) out.push('checkable');\n if (n.sel) out.push('selected');\n if (n.focus) out.push('focus');\n if (n.disabled) out.push('disabled');\n if (n.covered) out.push('covered');\n return out;\n}\n\n/** One line per element: type, label, center (0–1 fractions), and state flags. */\nexport function formatLayoutLine(n: FlatLayoutNode): string {\n const parts: string[] = [n.type ?? 'node'];\n if (n.text !== undefined) parts.push(quote(n.text));\n if (n.desc !== undefined) parts.push(`desc=${quote(n.desc)}`);\n if (n.hint !== undefined) parts.push(`hint=${quote(n.hint)}`);\n if (n.id !== undefined) parts.push(`#${n.id}`);\n if (n.key !== undefined) parts.push(`key=${n.key}`);\n if (n.c) parts.push(`c=${n.c[0].toFixed(3)},${n.c[1].toFixed(3)}`);\n parts.push(...flags(n));\n return parts.join(' ');\n}\n\n/** Worth a line: it has a label to read or match, or it can be interacted with. */\nfunction isListed(n: FlatLayoutNode): boolean {\n const labelled = n.text !== undefined || n.desc !== undefined || n.hint !== undefined;\n return labelled || !!(n.click || n.longClick || n.scroll || n.check || n.focus);\n}\n\n/**\n * Render a pruned layout as compact text for agents: a `[window <bundle>]`\n * header per window, then one line per labelled or interactive element in\n * paint order (decorative images and id-only wrappers are left to the JSON\n * output). The soft keyboard collapses to a single `[keyboard <bundle>]` line\n * instead of listing every key.\n */\nexport function formatFlatLayout(result: DumpLayoutResult): string {\n const lines: string[] = [];\n const d = result.display;\n lines.push(\n `# display ${d ? `${d.width}x${d.height}` : 'unknown'}; c = element center as 0-1 fractions ` +\n '(input --fx/--fy), or act by label with input --target \"<text>\"',\n );\n const keyboardBundle = result.keyboard?.shown ? result.keyboard.bundle : undefined;\n let window: string | undefined;\n for (const n of flattenLayout(result.tree)) {\n if (n.window !== window) {\n window = n.window;\n if (window !== undefined && window === keyboardBundle) {\n lines.push(`[keyboard ${window}] up — dismiss with input --type hideKeyboard`);\n } else if (window !== undefined) {\n lines.push(`[window ${window}]`);\n }\n }\n if (window !== undefined && window === keyboardBundle) continue;\n if (n.bundle !== undefined && n.text === undefined && !n.click) continue; // the window root itself\n if (isListed(n)) lines.push(formatLayoutLine(n));\n }\n return `${lines.join('\\n')}\\n`;\n}\n","import { Command } from 'commander';\nimport { getDeviceInfo, listDevices, type DeviceFullInfo, type DeviceInfo } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** One `devices --long` line: the target-list columns, then what the device reports about itself. */\nexport function formatLongDevice(d: DeviceInfo, info: DeviceFullInfo | undefined): string {\n const head = `${d.serial}\\t${d.connection ?? ''}\\t${d.status}`;\n if (!info) return head;\n const os = [info.osFamily, info.osFamily === 'HarmonyOS' ? info.osDistVersion : undefined].filter(Boolean).join(' ');\n const fields: Array<[string, string | undefined]> = [\n ['os', os || undefined],\n ['api', info.sdkApiVersion],\n ['abi', info.abi],\n ['type', info.deviceType],\n ['model', info.model],\n ['fullname', info.osFullName],\n ];\n const rest = fields.filter(([, v]) => v).map(([k, v]) => `${k}=${/\\s/.test(v!) ? JSON.stringify(v) : v}`);\n return [head, ...rest].join('\\t');\n}\n\nexport function registerDevicesCommand(program: Command): void {\n program\n .command('devices')\n .description('List connected hdc devices.')\n .option(\n '--long',\n 'Also ask each connected device for its OS family (HarmonyOS / OpenHarmony), version, API level, ' +\n 'CPU ABI, device type and model.',\n )\n .option('--json', 'Emit machine-readable JSON.')\n .action(async (opts: { long?: boolean; json?: boolean }) => {\n const { config, logger } = getRuntime();\n const devices = await listDevices(config);\n const infos = new Map<string, DeviceFullInfo>();\n if (opts.long) {\n for (const d of devices.filter((x) => x.status === 'Connected')) {\n try {\n infos.set(d.serial, await getDeviceInfo({ config, deviceSerial: d.serial, logger }));\n } catch (err) {\n logger.warn(`Could not query ${d.serial}: ${(err as Error).message}`);\n }\n }\n }\n if (opts.json) {\n const out = opts.long ? devices.map((d) => ({ ...d, info: infos.get(d.serial) ?? null })) : devices;\n process.stdout.write(`${JSON.stringify(out, null, 2)}\\n`);\n return;\n }\n if (devices.length === 0) {\n process.stdout.write('(no devices)\\n');\n return;\n }\n for (const d of devices) {\n process.stdout.write(`${opts.long ? formatLongDevice(d, infos.get(d.serial)) : `${d.serial}\\t${d.connection ?? ''}\\t${d.status}`}\\n`);\n }\n });\n}\n","import { Command } from 'commander';\nimport { sendFile, recvFile } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('Transfer files to/from the device (hdc file send/recv).');\n\n file\n .command('send <local> <remote>')\n .description(\n 'Push a local file to the device. With --bundle, <remote> may be relative to that app\\'s sandbox ' +\n '(files/x is its filesDir, haps/entry/files/x the entry module\\'s), and the file is chowned to the app ' +\n 'so it can read it. Prints the device path.',\n )\n .option('--bundle <bundle>', 'Push into this app\\'s sandbox and give the file to the app\\'s user.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (local: string, remote: string, opts: { bundle?: string; device?: string }) => {\n const { config, logger } = getRuntime();\n const written = await sendFile({ config, local, remote, bundle: opts.bundle, deviceSerial: opts.device, logger });\n logger.info(`Sent ${local} -> ${written}${opts.bundle ? ` (owned by ${opts.bundle})` : ''}.`);\n process.stdout.write(`${written}\\n`);\n });\n\n file\n .command('recv <remote> <local>')\n .description('Pull a file from the device.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (remote: string, local: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await recvFile({ config, remote, local, deviceSerial: opts.device, logger });\n logger.info(`Received ${remote} -> ${local}.`);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n detectCmdToolsFlavour,\n detectRuntimeOs,\n getCmdToolsPath,\n missingProjectRootFiles,\n runCodelinter,\n type CodelinterResult,\n type CodelinterSummary,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\ninterface LintOpts {\n files?: string[];\n json?: boolean;\n}\n\n/** codelinter's totals, or totals counted from the findings when it printed none. */\nexport function lintTotals(result: Pick<CodelinterResult, 'findings' | 'summary'>): CodelinterSummary {\n if (result.summary) return result.summary;\n const count = (s: string): number => result.findings.filter((f) => f.severity === s).length;\n return {\n defects: result.findings.length,\n errors: count('error'),\n warnings: count('warning'),\n suggestions: count('suggestion'),\n };\n}\n\n/**\n * The exit code for a lint run: 1 when there is an error-severity finding, or when\n * codelinter exited non-zero without printing a report (so it did not really run).\n * Warnings and suggestions alone exit 0, although codelinter itself exits 1 for them.\n */\nexport function lintExitCode(result: Pick<CodelinterResult, 'code' | 'findings' | 'summary'>): number {\n if (lintTotals(result).errors > 0) return 1;\n return lintFailed(result) ? result.code : 0;\n}\n\n/** True when codelinter exited non-zero without printing a report, so it did not really run. */\nexport function lintFailed(result: Pick<CodelinterResult, 'code' | 'findings' | 'summary'>): boolean {\n return result.summary === null && result.findings.length === 0 && result.code !== 0;\n}\n\nexport function registerLintCommand(program: Command): void {\n program\n .command('lint [project-dir]')\n .description(\n 'Run the OpenHarmony codelinter on a project. Defaults to the current directory. ' +\n 'Exits 1 on error-severity findings or when codelinter fails to run; warnings alone exit 0.',\n )\n .option('--files <globs...>', 'Specific files/globs to lint (default: the whole project).')\n .option('--json', 'Emit the report (findings, summary, notices, incomplete) as JSON.')\n .action(async (projectDir: string | undefined, opts: LintOpts) => {\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n const result = await runCodelinter({ config, projectDir: dir, files: opts.files, logger });\n const totals = lintTotals(result);\n const failed = lintFailed(result);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n } else if (!failed) {\n for (const f of result.findings) {\n const at = `${f.file}:${f.line}${f.column ? `:${f.column}` : ''}`;\n process.stdout.write(`${at} ${f.severity} ${f.message}${f.code ? ` [${f.code}]` : ''}\\n`);\n }\n process.stdout.write(\n totals.defects === 0\n ? 'No defects found.\\n'\n : `${totals.defects} defects: ${totals.errors} errors, ${totals.warnings} warnings, ` +\n `${totals.suggestions} suggestions.\\n`,\n );\n }\n\n if (failed) {\n const missing = missingProjectRootFiles(dir);\n const why = missing.length ? ` It needs a DevEco project root, and ${dir} has no ${missing.join(', ')}.` : '';\n logger.error(\n `codelinter exited ${result.code} without a report, so nothing was linted.${why}\\n` +\n result.raw.trim().split('\\n').slice(-15).join('\\n'),\n );\n }\n if (result.incomplete) {\n for (const n of result.notices) logger.warn(`codelinter: ${n}`);\n const cmdToolsPath = getCmdToolsPath(config);\n const flavour = detectCmdToolsFlavour(cmdToolsPath);\n const projectOs = detectRuntimeOs(dir);\n if (flavour !== projectOs) {\n logger.warn(\n `The command-line tools at ${cmdToolsPath} are the ${flavour} flavour, but the project targets ` +\n `${projectOs} (runtimeOS in build-profile.json5), so codelinter skipped part of its checks: treat the ` +\n `counts as a lower bound. For a complete report, point ONIRO_CMD_TOOLS_PATH at ${projectOs} ` +\n \"command-line tools. The build's ArkTS compiler checks are not affected.\",\n );\n }\n }\n // Let output flush before exiting non-zero.\n process.exitCode = lintExitCode(result);\n });\n}\n","import { Command, Option } from 'commander';\nimport {\n performInput,\n sendGesture,\n getDisplaySize,\n describeLayoutNode,\n type UiInputType,\n type Waypoint,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { addTargetOptions, selectorFrom, targetIndexFrom, type TargetOpts } from '../lib/target.js';\n\nconst INPUT_TYPES: UiInputType[] = [\n 'click',\n 'doubleClick',\n 'longClick',\n 'swipe',\n 'drag',\n 'fling',\n 'keyEvent',\n 'inputText',\n 'clearText',\n 'hideKeyboard',\n];\n\nconst num = (v: string | undefined): number | undefined => (v === undefined ? undefined : Number(v));\n\ninterface InputOpts extends TargetOpts {\n type: UiInputType;\n x?: string;\n y?: string;\n x2?: string;\n y2?: string;\n fx?: string;\n fy?: string;\n fx2?: string;\n fy2?: string;\n speed?: string;\n key?: string;\n text?: string;\n clear?: boolean;\n hideKeyboard?: boolean;\n device?: string;\n}\n\ninterface GestureOpts {\n waypoints: string;\n fractions?: boolean;\n holdStart?: string;\n holdEnd?: string;\n device?: string;\n}\n\nexport function registerInputCommand(program: Command): void {\n const input = program\n .command('input')\n .description(\n 'Inject a UI input event via uitest uiInput. Position it with --target (an on-screen element), ' +\n '--fx/--fy (0-1 fractions of the display, as in `dump layout` and the screenshot grid), or --x/--y (pixels).',\n )\n .addOption(new Option('--type <type>', 'Input type.').choices(INPUT_TYPES).makeOptionMandatory());\n addTargetOptions(input, 'Act on');\n input\n .option('--fx <fraction>', 'Start X as a 0-1 fraction of the display width.')\n .option('--fy <fraction>', 'Start Y as a 0-1 fraction of the display height.')\n .option('--fx2 <fraction>', 'End X fraction (swipe/drag/fling).')\n .option('--fy2 <fraction>', 'End Y fraction (swipe/drag/fling).')\n .option('--x <px>', 'X pixel (click/swipe start).')\n .option('--y <px>', 'Y pixel (click/swipe start).')\n .option('--x2 <px>', 'End X pixel (swipe/drag/fling).')\n .option('--y2 <px>', 'End Y pixel (swipe/drag/fling).')\n .option('--speed <px-per-s>', 'Velocity for swipe/drag/fling.')\n .option(\n '--key <key>',\n 'Key for keyEvent: Back/Home/Power, a name (Delete, Enter, Tab, Escape, MoveHome, MoveEnd, …), ' +\n 'a letter, a KeyCode id, or a combo like Ctrl+A.',\n )\n .option('--text <text>', 'Text for inputText.')\n .option('--clear', 'inputText: clear the field (Ctrl+A, Delete) before typing.')\n .option('--hide-keyboard', 'Dismiss the soft keyboard afterwards, if it is up.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: InputOpts) => {\n const { config, logger } = getRuntime();\n const result = await performInput({\n config,\n type: opts.type,\n target: selectorFrom(opts),\n targetIndex: targetIndexFrom(opts),\n fx: num(opts.fx),\n fy: num(opts.fy),\n fx2: num(opts.fx2),\n fy2: num(opts.fy2),\n pxX: num(opts.x),\n pxY: num(opts.y),\n pxX2: num(opts.x2),\n pxY2: num(opts.y2),\n speed: num(opts.speed),\n key: opts.key,\n text: opts.text,\n clear: opts.clear,\n hideKeyboard: opts.hideKeyboard,\n deviceSerial: opts.device,\n logger,\n });\n if (opts.type === 'hideKeyboard') {\n logger.info(result.keyboardHidden ? 'Dismissed the keyboard.' : 'The keyboard was not shown.');\n return;\n }\n const at = result.x !== undefined ? ` at ${result.x},${result.y}` : '';\n const on = result.target ? ` on ${describeLayoutNode(result.target)}` : '';\n const kb = result.keyboardHidden ? ' (dismissed the keyboard)' : '';\n logger.info(`Sent ${opts.type}${at}${on}${kb}.`);\n });\n\n program\n .command('gesture')\n .description('Inject a multi-waypoint gesture. Waypoints are JSON: [{\"x\":..,\"y\":..,\"t\":..}] in pixels (or fractions with --fractions).')\n .requiredOption('--waypoints <json>', 'JSON array of {x,y,t} waypoints (t = ms from start).')\n .option('--fractions', 'Waypoint x/y are 0-1 fractions of the display instead of pixels.')\n .option('--hold-start <ms>', 'Leading press-hold before moving (best-effort: uses `uitest drag`).')\n .option('--hold-end <ms>', 'Trailing hold before lifting (no uitest equivalent; ignored).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: GestureOpts) => {\n const { config, logger } = getRuntime();\n let waypoints = JSON.parse(opts.waypoints) as Waypoint[];\n if (opts.fractions) {\n const bad = waypoints.find((w) => !(w.x >= 0 && w.x <= 1 && w.y >= 0 && w.y <= 1));\n if (bad) throw new Error(`With --fractions, waypoint x and y must be 0-1; got ${bad.x},${bad.y}.`);\n const display = await getDisplaySize(config, { deviceSerial: opts.device, logger });\n if (!display) throw new Error('Could not read the display size to convert fractions to pixels.');\n // 1.0 maps to the last pixel, not one past the edge.\n const px = (f: number, size: number): number => Math.min(size - 1, Math.round(f * size));\n waypoints = waypoints.map((w) => ({ ...w, x: px(w.x, display.width), y: px(w.y, display.height) }));\n }\n await sendGesture({\n config,\n waypoints,\n holdStartMs: num(opts.holdStart),\n holdEndMs: num(opts.holdEnd),\n deviceSerial: opts.device,\n logger,\n });\n logger.info('Gesture sent.');\n });\n}\n","import { Command } from 'commander';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { captureLog } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { collectLogBundle } from '../lib/logBundle.js';\n\ninterface LogsOpts {\n output?: string;\n for?: string;\n grep?: string;\n clear?: boolean;\n domain?: string;\n device?: string;\n}\n\ninterface CollectOptions {\n output: string;\n device?: string;\n package?: string;\n pid?: string;\n tag?: string;\n level?: string;\n duration: string;\n redact: boolean;\n json?: boolean;\n}\n\nexport function registerLogsCommand(program: Command): void {\n const logs = program\n .command('logs')\n .description(\n 'Capture hilog to a file for a whole session: the device\\'s small log buffer wraps within ' +\n 'seconds under chatty components, so a dump at the end loses lines. Runs until --for elapses ' +\n 'or the process is interrupted; start it in the background, e.g. `oniro-app logs --clear -o ' +\n 'hilog_full.txt &`. Every line is flushed as it arrives and the stream reconnects after a reboot.',\n )\n // Not requiredOption: commander checks a parent's mandatory options for its\n // subcommands too, so `logs collect` would demand it.\n .option('-o, --output <file>', 'File to append the lines to (required).')\n .option('--for <ms>', 'Stop after this many ms (default: run until interrupted).')\n .option('--grep <regex>', 'Keep only lines matching this regex (default: all).')\n .option('--clear', 'Clear the device log buffer first (hilog -r), so the file covers only this session.')\n .option('--domain <domain>', 'hilog domain filter (e.g. 0xD003900).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: LogsOpts) => {\n if (!opts.output) logs.error(\"error: required option '-o, --output <file>' not specified\");\n const { config, logger } = getRuntime();\n const file = path.resolve(opts.output!);\n const abort = new AbortController();\n const stop = (): void => abort.abort();\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n logger.info(`Capturing hilog to ${file}${opts.for ? ` for ${opts.for} ms` : ' until interrupted'}...`);\n const result = await captureLog({\n config,\n file,\n durationMs: opts.for !== undefined ? Number(opts.for) : undefined,\n pattern: opts.grep ? new RegExp(opts.grep) : undefined,\n clear: opts.clear,\n domain: opts.domain,\n deviceSerial: opts.device,\n abortSignal: abort.signal,\n logger,\n });\n logger.info(`Wrote ${result.lines} lines to ${result.file} (${result.reconnects} reconnects).`);\n process.stdout.write(`${result.file}\\n`);\n });\n\n logs\n .command('collect')\n .description('Create a diagnostic bundle from a connected device.')\n .allowExcessArguments(false)\n .option('-o, --output <directory>', 'Parent directory for incident bundles.', path.join(os.homedir(), '.oniro', 'incident-bundles'))\n .option('--device <serial>', 'Target device serial.')\n .option('--package <bundle>', 'Collect faultlog entries for this application bundle.')\n .option('--pid <pid>', 'Create a filtered HiLog view for this process.')\n .option('--tag <tag>', 'Create a filtered HiLog view for this tag.')\n .option('--level <level>', 'Create a filtered HiLog view for this level (V/D/I/W/E/F).')\n .option('--duration <seconds>', 'Keep HiLog records from the last N seconds (default 600).', '600')\n .option('--redact', 'Redact sensitive values and archive only the redacted bundle.')\n .option('--json', 'Emit bundle paths and status as JSON.')\n .action(async (opts: CollectOptions) => {\n const { config } = getRuntime();\n const result = await collectLogBundle({\n config,\n outputDirectory: opts.output,\n deviceSerial: opts.device,\n packageName: opts.package,\n pid: opts.pid,\n tag: opts.tag,\n level: opts.level,\n durationSeconds: Number(opts.duration),\n redact: Boolean(opts.redact),\n });\n const output = opts.json\n ? `${JSON.stringify({ ...result, status: result.complete ? 'complete' : 'partial' }, null, 2)}\\n`\n : `${result.archivePath ?? result.bundleDirectory}\\n`;\n process.stdout.write(output);\n if (!result.complete) {\n throw new Error(`Bundle is partial; inspect manifest.json. ${result.error ?? 'One or more collectors failed.'}`);\n }\n });\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { deflateRawSync } from 'node:zlib';\nimport {\n VERSION, hdcExec, parseDeviceList, resolveDeviceSerial, shellChecked, type ConfigProvider, type HdcExecResult,\n} from '@oniroproject/core';\n\nexport interface CollectLogBundleOptions {\n config: ConfigProvider;\n outputDirectory: string;\n deviceSerial?: string;\n packageName?: string;\n pid?: string;\n tag?: string;\n level?: string;\n durationSeconds?: number;\n redact: boolean;\n execute?: (args: readonly string[], deviceSerial?: string) => Promise<HdcExecResult>;\n}\n\nexport interface LogBundleResult {\n bundleDirectory: string;\n archivePath: string | null;\n redactedDirectory: string | null;\n complete: boolean;\n error?: string;\n}\n\ninterface CommandRecord {\n name: string;\n status: 'success' | 'failed';\n output: string | null;\n stderr: string | null;\n exitCode: number | null;\n error: string | null;\n}\n\nconst LEVELS: Record<string, string> = {\n V: 'V', VERBOSE: 'V', D: 'D', DEBUG: 'D', I: 'I', INFO: 'I',\n W: 'W', WARN: 'W', WARNING: 'W', E: 'E', ERROR: 'E', F: 'F', FATAL: 'F',\n};\nconst HILOG_RECORD = /^(?<date>\\d{2}-\\d{2})[ \\t]+(?<time>\\d{2}:\\d{2}:\\d{2}\\.\\d{3})[ \\t]+(?<pid>\\d+)[ \\t]+\\d+[ \\t]+(?<level>[VDIWEF])[ \\t]+(?<tag>\\S+?)(?:[ \\t]+[NH](?::(?:[ \\t]+.*)?|[ \\t]+.*)?|:(?:[ \\t]+.*)?)$/;\nconst FAILURE_TEXT = /^(?:\\s*(?:\\[(?:fail|error)\\]|(?:error|failed|failure):|permission denied\\b|no devices? connected\\b|too many arguments\\b|unknown option\\b|invalid option\\b|command not found\\b)|\\s*(?:hdc|device)\\b.*\\b(?:error|failed|no device|not connected|offline)\\b)/im;\n\nfunction validateDate(date: string, time: string): boolean {\n const [, monthText, dayText] = /^(\\d{2})-(\\d{2})$/.exec(date) ?? [];\n const [, hourText, minuteText, secondText, millisecondText] = /^(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})$/.exec(time) ?? [];\n if (!monthText || !dayText || !hourText || !minuteText || !secondText || !millisecondText) return false;\n const value = new Date(Date.UTC(2000, Number(monthText) - 1, Number(dayText), Number(hourText), Number(minuteText), Number(secondText), Number(millisecondText)));\n return value.getUTCMonth() === Number(monthText) - 1 && value.getUTCDate() === Number(dayText) &&\n Number(hourText) < 24 && Number(minuteText) < 60 && Number(secondText) < 60;\n}\n\nexport function filterHilog(\n input: string,\n filters: { pid?: string; tag?: string; level?: string },\n): { text: string; applied: string[] } | null {\n const criteria: Record<string, string> = {};\n if (filters.pid) criteria.pid = filters.pid.replace(/^0+(?=\\d)/, '');\n if (filters.tag) criteria.tag = filters.tag;\n if (filters.level) criteria.level = LEVELS[filters.level.toUpperCase()] ?? filters.level.toUpperCase();\n if (Object.keys(criteria).length === 0) return null;\n\n let sawRecord = false;\n let keep = false;\n let output = '';\n for (const line of input.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n const content = line.replace(/[\\r\\n]+$/, '');\n const match = HILOG_RECORD.exec(content);\n if (match?.groups) {\n if (!validateDate(match.groups.date!, match.groups.time!)) return null;\n sawRecord = true;\n keep = Object.entries(criteria).every(([key, value]) => {\n const field = key === 'tag'\n ? match.groups!.tag!.slice(match.groups!.tag!.lastIndexOf('/') + 1)\n : match.groups![key];\n return key === 'pid' ? field?.replace(/^0+(?=\\d)/, '') === value : field === value;\n });\n } else if (/^\\s*\\[?\\d{1,4}[-/]/.test(content) || (!sawRecord && content.trim())) {\n return null;\n }\n if (keep) output += line;\n }\n return sawRecord ? { text: output, applied: Object.keys(criteria) } : null;\n}\n\nexport function redactLogText(value: string, deviceSerials: readonly string[] = []): string {\n let result = value\n .replace(/(\\bBearer\\s+)[A-Za-z0-9._~+/=-]+/gi, '$1[REDACTED]')\n .replace(/(\\bBasic\\s+)[A-Za-z0-9+/=]+/gi, '$1[REDACTED]')\n .replace(/((?:token|password|passwd|secret|api[_-]?key)\\s*[=:]\\s*)[^\\s,;]+/gi, '$1[REDACTED]')\n .replace(/(cookie\\s*[=:]\\s*)[^\\r\\n]+/gi, '$1[REDACTED]')\n .replace(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi, '[REDACTED_EMAIL]')\n .replace(/((?:phone|mobile|telephone|tel)(?:number)?\\s*[=:]\\s*)\\+?[\\d ()-]{8,}\\d/gi, '$1[REDACTED_PHONE]')\n .replace(/(?<![\\w.])(?:\\+\\d{1,3}[ -]?)?\\(?\\d{2,4}\\)?[ -]\\d{3,4}[ -]\\d{3,4}(?![\\w.])/g, '[REDACTED_PHONE]')\n .replace(/\\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\\b/g, '[REDACTED_MAC]')\n .replace(/([A-Z]:\\\\Users\\\\)[^\\\\\\r\\n \"']+/gi, '$1[REDACTED_USER]')\n .replace(/(\\/(?:Users|home)\\/)[^/\\r\\n \"']+/gi, '$1[REDACTED_USER]')\n .replace(/(\"(?:target|deviceSerial)\"\\s*:\\s*\")[^\"]+(\")/gi, '$1[REDACTED_DEVICE]$2')\n .replace(/(--device\\s+|-t\\s+)([A-Za-z0-9._:-]+)/gi, '$1[REDACTED_DEVICE]');\n\n for (const serial of deviceSerials) {\n if (serial) result = result.split(serial).join('[REDACTED_DEVICE]');\n }\n\n const ipv4 = /\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b/g;\n result = result.replace(ipv4, (address, offset: number, whole: string) => {\n const prefix = whole.slice(Math.max(0, offset - 48), offset);\n const suffix = whole.slice(offset + address.length);\n const contextual = /(?:ip|addr(?:ess)?|host|peer|remote|local|endpoint|server|client|target|device(?:id)?|serial)[^\\r\\n]{0,24}$/i.test(prefix);\n const hasPort = /^:\\d{1,5}(?!\\d)/.test(suffix);\n const octets = address.split('.').map(Number);\n return octets.every((part: number) => part <= 255) && (contextual || hasPort) ? '[REDACTED_IP]' : address;\n });\n return result;\n}\n\nfunction decodeText(data: Buffer, relativePath: string): string {\n let text: string;\n if (data.subarray(0, 2).equals(Buffer.from([0xff, 0xfe]))) text = data.toString('utf16le').slice(1);\n else if (data.subarray(0, 2).equals(Buffer.from([0xfe, 0xff]))) {\n const swapped = Buffer.from(data.subarray(2));\n for (let i = 0; i + 1 < swapped.length; i += 2) [swapped[i], swapped[i + 1]] = [swapped[i + 1]!, swapped[i]!];\n text = swapped.toString('utf16le');\n } else {\n const utf8 = data.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) ? data.subarray(3) : data;\n if (utf8.includes(0)) throw new Error(`Binary data cannot be safely redacted: ${relativePath}`);\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(utf8);\n } catch {\n throw new Error(`Non-UTF-8 data cannot be safely redacted: ${relativePath}`);\n }\n }\n if (text.includes('\\u0000')) throw new Error(`Binary data cannot be safely redacted: ${relativePath}`);\n return text;\n}\n\nasync function redactTree(\n source: string,\n destination: string,\n serials: readonly string[],\n boundedHilog: string | null,\n): Promise<void> {\n await fs.mkdir(destination, { recursive: false, mode: 0o700 });\n try {\n const visit = async (directory: string): Promise<void> => {\n for (const entry of await fs.readdir(directory, { withFileTypes: true })) {\n const sourcePath = path.join(directory, entry.name);\n const relative = path.relative(source, sourcePath);\n const portableRelative = relative.split(path.sep).join('/');\n const destinationPath = path.join(destination, relative);\n if (entry.isDirectory()) {\n await fs.mkdir(destinationPath, { recursive: true, mode: 0o700 });\n await visit(sourcePath);\n } else if (entry.isFile()) {\n if (portableRelative === 'logs/hilog.txt') {\n const text = boundedHilog ?? 'HiLog omitted from this archive because the requested duration could not be reliably applied.\\n';\n await fs.mkdir(path.dirname(destinationPath), { recursive: true, mode: 0o700 });\n await fs.writeFile(destinationPath, redactLogText(text, serials), { encoding: 'utf8', mode: 0o600 });\n continue;\n }\n if (portableRelative === 'logs/hilog-filtered.txt' && boundedHilog === null) continue;\n const text = decodeText(await fs.readFile(sourcePath), relative);\n await fs.mkdir(path.dirname(destinationPath), { recursive: true, mode: 0o700 });\n await fs.writeFile(destinationPath, redactLogText(text, serials), { encoding: 'utf8', mode: 0o600 });\n }\n }\n };\n await visit(source);\n } catch (error) {\n await fs.rm(destination, { recursive: true, force: true });\n throw error;\n }\n}\n\nconst CRC_TABLE = new Uint32Array(256);\nfor (let i = 0; i < CRC_TABLE.length; i++) {\n let value = i;\n for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;\n CRC_TABLE[i] = value >>> 0;\n}\n\nfunction crc32(data: Buffer): number {\n let crc = 0xffffffff;\n for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nfunction dosDateTime(date: Date): { date: number; time: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2),\n };\n}\n\nasync function writeZip(source: string, archivePath: string): Promise<void> {\n const files: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n for (const entry of await fs.readdir(directory, { withFileTypes: true })) {\n const filePath = path.join(directory, entry.name);\n if (entry.isDirectory()) await visit(filePath);\n else if (entry.isFile()) files.push(filePath);\n }\n };\n await visit(source);\n const localParts: Buffer[] = [];\n const centralParts: Buffer[] = [];\n let offset = 0;\n const stamp = dosDateTime(new Date());\n\n for (const filePath of files) {\n const name = Buffer.from(path.relative(source, filePath).split(path.sep).join('/'), 'utf8');\n const data = await fs.readFile(filePath);\n const compressed = deflateRawSync(data);\n const checksum = crc32(data);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6);\n local.writeUInt16LE(8, 8); local.writeUInt16LE(stamp.time, 10); local.writeUInt16LE(stamp.date, 12);\n local.writeUInt32LE(checksum, 14); local.writeUInt32LE(compressed.length, 18); local.writeUInt32LE(data.length, 22);\n local.writeUInt16LE(name.length, 26); local.writeUInt16LE(0, 28);\n localParts.push(local, name, compressed);\n\n const central = Buffer.alloc(46);\n central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6);\n central.writeUInt16LE(0x0800, 8); central.writeUInt16LE(8, 10); central.writeUInt16LE(stamp.time, 12);\n central.writeUInt16LE(stamp.date, 14); central.writeUInt32LE(checksum, 16);\n central.writeUInt32LE(compressed.length, 20); central.writeUInt32LE(data.length, 24);\n central.writeUInt16LE(name.length, 28); central.writeUInt16LE(0, 30); central.writeUInt16LE(0, 32);\n central.writeUInt16LE(0, 34); central.writeUInt16LE(0, 36); central.writeUInt32LE(0, 38);\n central.writeUInt32LE(offset, 42);\n centralParts.push(central, name);\n offset += local.length + name.length + compressed.length;\n }\n\n const centralDirectory = Buffer.concat(centralParts);\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(0, 4); end.writeUInt16LE(0, 6);\n end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);\n end.writeUInt32LE(centralDirectory.length, 12); end.writeUInt32LE(offset, 16); end.writeUInt16LE(0, 20);\n await fs.writeFile(archivePath, Buffer.concat([...localParts, centralDirectory, end]), { flag: 'wx', mode: 0o600 });\n}\n\nfunction commandFailure(result: HdcExecResult): string | null {\n if (result.code !== 0) return `hdc exited with code ${result.code}`;\n if (result.stderr.trim()) return 'hdc wrote to stderr';\n const contentError = result.stdout.split(/\\r?\\n/).find((line) => FAILURE_TEXT.test(line))?.trim() ?? null;\n return contentError ? `command output indicates failure: ${contentError}` : null;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function uniqueBundleDirectory(outputDirectory: string, stamp: string): Promise<string> {\n await fs.mkdir(outputDirectory, { recursive: true, mode: 0o700 });\n for (let suffix = 0; ; suffix++) {\n const name = `incident-${stamp}${suffix ? `-${suffix}` : ''}`;\n const directory = path.join(outputDirectory, name);\n try {\n await fs.mkdir(directory, { mode: 0o700 });\n return directory;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n}\n\nexport async function collectLogBundle(options: CollectLogBundleOptions): Promise<LogBundleResult> {\n if (options.packageName && !/^[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)+$/.test(options.packageName)) {\n throw new Error('packageName must be a reverse-DNS bundle name.');\n }\n if (options.pid && !/^[1-9]\\d*$/.test(options.pid)) throw new Error('pid must be a positive integer.');\n if (options.tag && !/^[^\\s/\\x00-\\x1f\\x7f]+$/.test(options.tag)) throw new Error('tag must be a single HiLog tag.');\n if (options.level && !LEVELS[options.level.toUpperCase()]) throw new Error('level is not a recognized HiLog level.');\n const durationSeconds = options.durationSeconds ?? 600;\n if (!Number.isSafeInteger(durationSeconds) || durationSeconds < 1 || durationSeconds > 31_536_000) {\n throw new Error('durationSeconds must be an integer between 1 and 31536000.');\n }\n\n const started = new Date();\n const stamp = started.toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z');\n const bundleDirectory = await uniqueBundleDirectory(path.resolve(options.outputDirectory), stamp);\n const records: CommandRecord[] = [];\n const serials: string[] = [];\n let replacementWarning = false;\n const execute = options.execute ?? ((args, deviceSerial) => args[0] === 'shell'\n ? shellChecked({ config: options.config, command: args.slice(1).join(' '), deviceSerial })\n : hdcExec({ config: options.config, args, deviceSerial }));\n const manifest: Record<string, unknown> = {\n schemaVersion: '1.0',\n collectorVersion: VERSION,\n collectionStartUtc: started.toISOString(),\n collectionEndUtc: null,\n host: { os: process.platform },\n target: null,\n packageName: options.packageName ?? null,\n pid: options.pid ?? null,\n filters: {\n tag: options.tag ?? null,\n level: options.level ?? null,\n pid: options.pid ?? null,\n packageName: options.packageName ?? null,\n durationSeconds,\n },\n filterStatus: {\n duration: 'not-applied',\n packageName: options.packageName ? 'failed' : 'not-requested',\n pid: options.pid ? 'not-applied' : 'not-requested',\n tag: options.tag ? 'not-applied' : 'not-requested',\n level: options.level ? 'not-applied' : 'not-requested',\n },\n hilogWindowApplied: false,\n redactionRequested: options.redact,\n redactionStatus: options.redact ? 'pending' : 'not-requested',\n archiveStatus: { status: 'pending', path: null },\n commands: records,\n files: [],\n notes: [\n 'Collection is read-only on the target device.',\n 'hilog -x captures the current device buffer; duration is applied locally against device time when log timestamps are recognized.',\n 'Redaction is heuristic and does not guarantee that a bundle is safe to publish.',\n ],\n };\n\n const run = async (name: string, relativeOutput: string, args: readonly string[], deviceSerial?: string): Promise<CommandRecord> => {\n const outputPath = path.join(bundleDirectory, relativeOutput);\n await fs.mkdir(path.dirname(outputPath), { recursive: true, mode: 0o700 });\n let result: HdcExecResult | null = null;\n let failure: string | null = null;\n try {\n result = await execute(args, deviceSerial);\n await fs.writeFile(outputPath, result.stdout, { encoding: 'utf8', mode: 0o600 });\n if (result.stderr) await fs.writeFile(`${outputPath}.stderr.txt`, result.stderr, { encoding: 'utf8', mode: 0o600 });\n if (result.stdout.includes('\\ufffd') || result.stderr.includes('\\ufffd')) {\n replacementWarning = true;\n (manifest.notes as string[]).push(`${name} output contains Unicode replacement characters; review the redacted evidence before sharing.`);\n }\n failure = commandFailure(result);\n } catch (error) {\n failure = errorMessage(error);\n await fs.writeFile(outputPath, '', { encoding: 'utf8', mode: 0o600 });\n }\n const record: CommandRecord = {\n name,\n status: failure ? 'failed' : 'success',\n output: relativeOutput,\n stderr: result?.stderr ? `${relativeOutput}.stderr.txt` : null,\n exitCode: result?.code ?? null,\n error: failure,\n };\n records.push(record);\n return record;\n };\n\n const targetRecord = await run('list-targets', 'device/targets.txt', ['list', 'targets', '-v']);\n const targetOutput = await fs.readFile(path.join(bundleDirectory, 'device/targets.txt'), 'utf8').catch(() => '');\n const targets = parseDeviceList(targetOutput).filter((target) => target.status === 'Connected' || target.status === 'Unknown');\n serials.push(...parseDeviceList(targetOutput).map((target) => target.serial));\n const requestedDevice = resolveDeviceSerial(options.deviceSerial);\n let selectedDevice: string | null = null;\n let targetError: string | null = null;\n if (targetRecord.status !== 'success') targetError = targetRecord.error ?? 'hdc target discovery failed';\n else if (requestedDevice) {\n selectedDevice = targets.find((target) => target.serial === requestedDevice)?.serial ?? null;\n if (!selectedDevice) targetError = 'selected device was not discovered as connected';\n } else if (targets.length === 0) targetError = 'hdc did not discover a connected device';\n else if (targets.length > 1) targetError = 'multiple devices are connected; specify --device';\n else selectedDevice = targets[0]!.serial;\n\n let boundedHilog: string | null = null;\n let durationApplied = false;\n let durationFailureReason = 'device clock or HiLog collection failed';\n if (targetError) {\n targetRecord.status = 'failed';\n targetRecord.error = targetError;\n (manifest.notes as string[]).push('Device collection stopped because target discovery did not identify exactly one selected connected device.');\n } else {\n manifest.target = selectedDevice;\n const shell = (args: readonly string[]) => run(args[0]!, args[1]!, args.slice(2), selectedDevice!);\n const captureStartedHostMs = Date.now();\n const deviceTimeBefore = await shell([\n 'device-time-before', 'device/device-time-before.txt', 'shell', 'date', '+%Y-%m-%dT%H:%M:%S',\n ]);\n const hilog = await shell(['hilog-snapshot', 'logs/hilog.txt', 'shell', 'hilog', '-x']);\n const deviceTimeAfter = await shell([\n 'device-time-after', 'device/device-time-after.txt', 'shell', 'date', '+%Y-%m-%dT%H:%M:%S',\n ]);\n const hostElapsedMs = Date.now() - captureStartedHostMs;\n if (deviceTimeBefore.status === 'success' && hilog.status === 'success' && deviceTimeAfter.status === 'success') {\n const [beforeText, afterText, fullHilog] = await Promise.all([\n fs.readFile(path.join(bundleDirectory, 'device/device-time-before.txt'), 'utf8'),\n fs.readFile(path.join(bundleDirectory, 'device/device-time-after.txt'), 'utf8'),\n fs.readFile(path.join(bundleDirectory, 'logs/hilog.txt'), 'utf8'),\n ]);\n const window = filterHilogWindow(fullHilog, beforeText, afterText, durationSeconds, hostElapsedMs);\n if (window.text === null) durationFailureReason = window.reason;\n else boundedHilog = window.text;\n } else if (deviceTimeBefore.status !== 'success' || deviceTimeAfter.status !== 'success') {\n durationFailureReason = 'device clock could not be read';\n } else if (hilog.status !== 'success') {\n durationFailureReason = 'HiLog snapshot collection failed';\n }\n durationApplied = boundedHilog !== null;\n manifest.hilogWindowApplied = durationApplied;\n const faultArgs = options.packageName\n ? ['faultlog', 'logs/faultlog.txt', 'shell', 'hidumper', '-e', '--print', options.packageName, '-n', '5']\n : ['faultlog', 'logs/faultlog.txt', 'shell', 'hidumper', '-e', '--list', '-n', '20'];\n const faultlog = await shell(faultArgs);\n manifest.filterStatus = {\n duration: durationApplied ? 'applied' : 'not-applied',\n packageName: options.packageName ? (faultlog.status === 'success' ? 'applied' : 'failed') : 'not-requested',\n pid: options.pid ? 'not-applied' : 'not-requested',\n tag: options.tag ? 'not-applied' : 'not-requested',\n level: options.level ? 'not-applied' : 'not-requested',\n };\n if (!durationApplied) {\n (manifest.notes as string[]).push(\n `HiLog duration was not applied (${durationFailureReason}); the full snapshot is kept only in the local raw bundle and omitted from the redacted archive.`,\n );\n } else if (boundedHilog !== null && (options.pid || options.tag || options.level)) {\n const filtered = filterHilog(boundedHilog, { pid: options.pid, tag: options.tag, level: options.level });\n if (filtered) {\n await fs.writeFile(path.join(bundleDirectory, 'logs/hilog-filtered.txt'), filtered.text, { encoding: 'utf8', mode: 0o600 });\n const status = manifest.filterStatus as Record<string, string>;\n for (const key of filtered.applied) status[key] = 'applied';\n } else {\n (manifest.notes as string[]).push('Requested HiLog PID/tag/level filters were not applied because the windowed snapshot format could not be parsed reliably.');\n }\n }\n await shell(['device-name', 'device/device-info.txt', 'shell', 'param', 'get', 'const.product.name']);\n await shell(['process-list', 'device/process-list.txt', 'shell', 'ps', '-ef']);\n await shell(['memory', 'device/memory.txt', 'shell', 'hidumper', '--mem']);\n await shell(['threads', 'device/threads.txt', 'shell', 'hidumper', '-p']);\n }\n\n const ended = new Date();\n manifest.collectionEndUtc = ended.toISOString();\n const files = records.flatMap((record) => [record.output, record.stderr].filter((file): file is string => Boolean(file)));\n files.push('manifest.json', 'notes.txt');\n if (await fs.access(path.join(bundleDirectory, 'logs/hilog-filtered.txt')).then(() => true, () => false)) {\n files.push('logs/hilog-filtered.txt');\n }\n manifest.files = files;\n await fs.writeFile(path.join(bundleDirectory, 'notes.txt'), 'Add reproduction steps and precise event timestamps here.\\n', { encoding: 'utf8', mode: 0o600 });\n\n const durationFailure = !durationApplied;\n const criticalFailure = Boolean(targetError) || records.some((record) => record.name === 'hilog-snapshot' && record.status !== 'success');\n const anyCommandFailure = records.some((record) => record.status !== 'success');\n let redactedDirectory: string | null = null;\n let archivePath: string | null = null;\n let bundleError: string | undefined;\n\n try {\n if (options.redact) {\n redactedDirectory = `${bundleDirectory}-redacted`;\n manifest.redactionStatus = replacementWarning ? 'review-required' : 'success';\n manifest.archiveStatus = { status: 'success', path: `${path.basename(redactedDirectory)}.zip` };\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n await redactTree(bundleDirectory, redactedDirectory, serials, boundedHilog);\n archivePath = `${redactedDirectory}.zip`;\n await writeZip(redactedDirectory, archivePath);\n } else {\n archivePath = `${bundleDirectory}.zip`;\n manifest.archiveStatus = { status: 'success', path: path.basename(archivePath) };\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n await writeZip(bundleDirectory, archivePath);\n }\n } catch (error) {\n bundleError = options.redact ? `redaction or archive creation failed: ${errorMessage(error)}` : `archive creation failed: ${errorMessage(error)}`;\n archivePath = null;\n manifest.redactionStatus = options.redact ? 'failed' : 'not-requested';\n manifest.archiveStatus = { status: 'failed', path: null };\n (manifest.notes as string[]).push(bundleError);\n await fs.rm(`${redactedDirectory ?? bundleDirectory}.zip`, { force: true }).catch(() => undefined);\n if (redactedDirectory) await fs.rm(redactedDirectory, { recursive: true, force: true }).catch(() => undefined);\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n redactedDirectory = null;\n }\n\n return {\n bundleDirectory,\n archivePath,\n redactedDirectory,\n complete: !criticalFailure && !anyCommandFailure && !bundleError && !replacementWarning && !durationFailure,\n error: bundleError ?? (criticalFailure ? targetError ?? 'HiLog collection failed' : replacementWarning\n ? 'Captured output contains Unicode replacement characters; review the manifest before sharing.'\n : durationFailure ? `HiLog duration was not applied (${durationFailureReason}); the redacted archive omits the full snapshot.`\n : undefined),\n };\n}\n\nfunction parseDeviceClock(value: string): number | null {\n const match = /^\\s*(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\s*$/.exec(value);\n if (!match) return null;\n const [, year, month, day, hour, minute, second] = match;\n const timestamp = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second));\n const date = new Date(timestamp);\n return date.getUTCFullYear() === Number(year) && date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day) && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60\n ? timestamp\n : null;\n}\n\nfunction parseHilogTimestamp(datePart: string, timePart: string, referenceMs: number): number | null {\n if (!validateDate(datePart, timePart)) return null;\n const [month, day] = datePart.split('-').map(Number);\n const [hour, minute, second, millisecond] = timePart.split(/[:.]/).map(Number);\n const referenceYear = new Date(referenceMs).getUTCFullYear();\n const candidates = [referenceYear - 1, referenceYear, referenceYear + 1]\n .map((year) => Date.UTC(year, month! - 1, day!, hour!, minute!, second!, millisecond!))\n .filter((timestamp) => {\n const candidate = new Date(timestamp);\n return candidate.getUTCMonth() === month! - 1 && candidate.getUTCDate() === day;\n })\n .sort((left, right) => Math.abs(left - referenceMs) - Math.abs(right - referenceMs));\n const closest = candidates[0];\n return closest !== undefined && closest <= referenceMs + 2_000 ? closest : null;\n}\n\nexport type HilogWindowResult = { text: string; reason?: undefined } | { text: null; reason: string };\n\nexport function filterHilogWindow(\n input: string,\n deviceClockBefore: string,\n deviceClockAfter: string,\n durationSeconds: number,\n hostElapsedMs: number,\n): HilogWindowResult {\n if (!Number.isSafeInteger(durationSeconds) || durationSeconds < 1 || durationSeconds > 31_536_000) {\n return { text: null, reason: 'requested duration is invalid' };\n }\n const beforeMs = parseDeviceClock(deviceClockBefore);\n const afterMs = parseDeviceClock(deviceClockAfter);\n if (beforeMs === null || afterMs === null) return { text: null, reason: 'device clock output was not recognized' };\n const deviceElapsedMs = afterMs - beforeMs;\n if (deviceElapsedMs < -1_000 || deviceElapsedMs > Math.max(0, hostElapsedMs) + 5_000) {\n return { text: null, reason: 'device clock changed inconsistently during capture' };\n }\n\n const windowEnd = afterMs + 999;\n const windowStart = windowEnd - durationSeconds * 1_000;\n let sawRecord = false;\n let keep = false;\n let output = '';\n for (const line of input.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n const content = line.replace(/[\\r\\n]+$/, '');\n const match = HILOG_RECORD.exec(content);\n if (match?.groups) {\n if (!validateDate(match.groups.date!, match.groups.time!)) {\n return { text: null, reason: 'HiLog contains an invalid timestamp' };\n }\n const timestamp = parseHilogTimestamp(match.groups.date!, match.groups.time!, afterMs);\n if (timestamp === null || timestamp > windowEnd) {\n return { text: null, reason: 'HiLog timestamps do not agree with the device clock' };\n }\n sawRecord = true;\n keep = timestamp >= windowStart;\n } else if (/^-{3,}\\s*beginning of\\b/i.test(content.trim())) {\n continue;\n } else if (/^\\s*\\[?\\d{1,4}[-/]/.test(content) || /^\\s*\\d{2}:\\d{2}:\\d{2}/.test(content)) {\n return { text: null, reason: 'HiLog contains timestamped lines in an unrecognized format' };\n } else if (!sawRecord && content.trim()) {\n return { text: null, reason: 'HiLog contains unclassified lines before the first record' };\n }\n if (keep) output += line;\n }\n return sawRecord ? { text: output } : { text: null, reason: 'no recognized timestamped HiLog records were found' };\n}\n","import { Command } from 'commander';\nimport { getHdcPath, hdcTargetArgsFor, spawnCompat } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** The argv for the passthrough: verbatim when the caller already picked a target with `-t`. */\nexport function hdcPassthroughArgv(args: readonly string[], device?: string): string[] {\n return args[0] === '-t' ? [...args] : [...hdcTargetArgsFor(args, device), ...args];\n}\n\nexport function registerHdcCommand(program: Command): void {\n program\n .command('hdc')\n .description(\n 'Run the hdc binary oniro-app itself uses (see `cmdtools status`), addressed at --device or ' +\n 'ONIRO_DEVICE_SERIAL, with stdio passed through. Exits with hdc\\'s own code, which is 0 even for ' +\n 'a `[Fail]` line. Example: oniro-app hdc shell param get const.ohos.apiversion',\n )\n .argument('[args...]', 'hdc arguments, passed through verbatim')\n .option('--device <serial>', 'Target device serial.')\n .option('--path', 'Print the hdc binary path and exit.')\n .passThroughOptions()\n .allowUnknownOption()\n .action(async (args: string[], opts: { device?: string; path?: boolean }) => {\n const { config } = getRuntime();\n const hdc = getHdcPath(config);\n if (opts.path) {\n process.stdout.write(`${hdc}\\n`);\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const child = spawnCompat(hdc, hdcPassthroughArgv(args, opts.device), { stdio: 'inherit' });\n child.on('error', (err) => reject(new Error(`Failed to run ${hdc}: ${err.message}`)));\n child.on('close', (code) => {\n process.exitCode = code ?? 1;\n resolve();\n });\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,gBAAe;AACxB,SAAS,cAAAC,mBAAkB;;;ACA3B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACJA,SAAS,kBAA0B;AACxC,QAAM,eAAe,QAAQ,IAAI,gBAAgB,OAAO,QAAQ,IAAI,gBAAgB;AACpF,SAAO;AAAA,IACL,MAAM,GAAG;AACP,UAAI,aAAc,SAAQ,OAAO,MAAM,WAAW,CAAC;AAAA,CAAI;AAAA,IACzD;AAAA,IACA,KAAK,GAAG;AACN,cAAQ,OAAO,MAAM,GAAG,CAAC;AAAA,CAAI;AAAA,IAC/B;AAAA,IACA,KAAK,GAAG;AACN,cAAQ,OAAO,MAAM,UAAU,CAAC;AAAA,CAAI;AAAA,IACtC;AAAA,IACA,MAAM,GAAG;AACP,cAAQ,OAAO,MAAM,WAAW,CAAC;AAAA,CAAI;AAAA,IACvC;AAAA,EACF;AACF;;;AChBO,SAAS,oBAAsC;AACpD,MAAI,QAAQ;AACZ,MAAI,cAAc;AAClB,MAAI,cAAc;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,SAAS,UAAU,GAAG;AAC7B,UAAI,OAAO,cAAc,SAAU,SAAQ,KAAK,IAAI,KAAK,QAAQ,SAAS;AAC1E,YAAM,MAAM,QAAQ,IAAI,KAAK,MAAM,KAAK,IAAI;AAC5C,YAAM,MAAM,WAAW;AAEvB,UAAI,QAAQ,eAAe,QAAQ,YAAa;AAChD,YAAM,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","result","createHarmonyOsSession","createHarmonyOsSession","path","OniroError","OniroError","path","ALL_SDKS","fs","path","ALL_SDKS","Option","Option","fs","path","describeLayoutNode","describeLayoutNode","shot","os","path","detectRuntimeOs","detectRuntimeOs","Option","describeLayoutNode","Option","describeLayoutNode","os","path","fs","path","relative","text","resolve","Command","OniroError"]}
1
+ {"version":3,"sources":["../src/bin/oniro-app.ts","../src/commands/sdk.ts","../src/adapters/logger.ts","../src/adapters/progress.ts","../src/adapters/config.ts","../src/lib/runtime.ts","../src/commands/cmdtools.ts","../src/commands/emulator.ts","../src/commands/build.ts","../src/commands/sign.ts","../src/commands/auth.ts","../src/commands/app.ts","../src/lib/screenshotImage.ts","../src/commands/appVerify.ts","../src/commands/create.ts","../src/lib/templateRoot.ts","../src/commands/templates.ts","../src/commands/reboot.ts","../src/commands/wait.ts","../src/lib/target.ts","../src/lib/logSince.ts","../src/commands/watch.ts","../src/commands/screenshot.ts","../src/commands/dump.ts","../src/lib/layoutText.ts","../src/commands/devices.ts","../src/commands/file.ts","../src/commands/lint.ts","../src/commands/check.ts","../src/commands/test.ts","../src/commands/doctor.ts","../src/commands/screens.ts","../src/commands/input.ts","../src/commands/logs.ts","../src/lib/logBundle.ts","../src/lib/crashReport.ts","../src/commands/hdc.ts","../src/commands/api.ts","../src/commands/serve.ts","../src/mcp/protocol.ts","../src/mcp/schema.ts","../src/mcp/tools.ts","../src/commands/perf.ts","../src/lib/interrupt.ts","../src/mcp/target.ts","../src/commands/record.ts","../src/commands/replay.ts"],"sourcesContent":["import { Command, CommanderError } from 'commander';\nimport { OniroError } from '@oniroproject/core';\nimport { registerSdkCommand } from '../commands/sdk.js';\nimport { registerCmdToolsCommand } from '../commands/cmdtools.js';\nimport { registerEmulatorCommand } from '../commands/emulator.js';\nimport { registerBuildCommand } from '../commands/build.js';\nimport { registerSignCommand } from '../commands/sign.js';\nimport { registerAuthCommand } from '../commands/auth.js';\nimport { registerAppCommand } from '../commands/app.js';\nimport { registerCreateCommand } from '../commands/create.js';\nimport { registerTemplatesCommand } from '../commands/templates.js';\nimport { registerRebootCommand } from '../commands/reboot.js';\nimport { registerWaitCommand } from '../commands/wait.js';\nimport { registerWatchCommand } from '../commands/watch.js';\nimport { registerScreenshotCommand } from '../commands/screenshot.js';\nimport { registerDumpCommand } from '../commands/dump.js';\nimport { registerDevicesCommand } from '../commands/devices.js';\nimport { registerFileCommand } from '../commands/file.js';\nimport { registerLintCommand } from '../commands/lint.js';\nimport { registerTestCommand } from '../commands/test.js';\nimport { registerCheckCommand } from '../commands/check.js';\nimport { registerDoctorCommand } from '../commands/doctor.js';\nimport { registerScreensCommand } from '../commands/screens.js';\nimport { registerInputCommand } from '../commands/input.js';\nimport { registerLogsCommand } from '../commands/logs.js';\nimport { registerHdcCommand } from '../commands/hdc.js';\nimport { registerApiCommand } from '../commands/api.js';\nimport { registerServeCommand } from '../commands/serve.js';\nimport { registerRecordCommand } from '../commands/record.js';\nimport { registerReplayCommand } from '../commands/replay.js';\nimport { registerPerfCommand } from '../commands/perf.js';\n\ndeclare const __CLI_VERSION__: string;\nconst CLI_VERSION = __CLI_VERSION__;\n\nfunction buildProgram(): Command {\n const program = new Command()\n .name('oniro-app')\n .description(\n 'Cross-platform CLI for Oniro/OpenHarmony app development.\\n\\n' +\n 'Designed for non-interactive use (CI, scripts, agents): every command\\n' +\n 'takes explicit flags, results go to stdout, progress/logs go to stderr,\\n' +\n 'and a non-zero exit code indicates failure.',\n )\n .version(CLI_VERSION)\n .showHelpAfterError()\n // Lets `hdc` pass its arguments through untouched; global options go before the command.\n .enablePositionalOptions()\n // Commander would process.exit() right after printing help, the version or a usage\n // error. Writes to a pipe are asynchronous on macOS, so that cut `--help | …` at 8 KB.\n // Throw instead (subcommands inherit this) and let main() set the exit code.\n .exitOverride();\n\n registerSdkCommand(program);\n registerCmdToolsCommand(program);\n registerEmulatorCommand(program);\n registerBuildCommand(program);\n registerSignCommand(program);\n registerAuthCommand(program);\n registerAppCommand(program);\n registerCreateCommand(program);\n registerTemplatesCommand(program);\n registerRebootCommand(program);\n registerWaitCommand(program);\n registerWatchCommand(program);\n registerScreenshotCommand(program);\n registerDumpCommand(program);\n registerDevicesCommand(program);\n registerFileCommand(program);\n registerLintCommand(program);\n registerCheckCommand(program);\n registerDoctorCommand(program);\n registerScreensCommand(program);\n registerApiCommand(program);\n registerTestCommand(program);\n registerInputCommand(program);\n registerRecordCommand(program);\n registerReplayCommand(program);\n registerPerfCommand(program);\n registerLogsCommand(program);\n registerHdcCommand(program);\n registerServeCommand(program);\n\n return program;\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n if (err instanceof CommanderError) {\n // Commander has already printed the help, version or usage error; exit once stdout drains.\n process.exitCode = err.exitCode;\n return;\n }\n const message = err instanceof OniroError ? err.message : err instanceof Error ? err.message : String(err);\n const stack = process.env.ONIRO_DEBUG === '1' && err instanceof Error && err.stack ? `${err.stack}\\n` : '';\n // Exit only once stderr has drained (asynchronous for pipes on macOS), even if a\n // device process or timer the failed command started is still holding the loop.\n process.stderr.write(`[error] ${message}\\n${stack}`, () => process.exit(1));\n }\n}\n\nvoid main();\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n ALL_SDKS,\n OHOS_DAILY_BUILDS_URL,\n downloadAndInstallSdk,\n getOsFolder,\n getHarmonyOsSdkListing,\n getSdkRootDir,\n getSupportedSdksForUi,\n installSdkFromArchive,\n removeSdk,\n type HarmonyOsSdkListing,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nconst HARMONYOS_SOURCE: Record<NonNullable<HarmonyOsSdkListing['source']>, string> = {\n cmdtools: 'from the command-line tools',\n 'deveco-studio': 'from DevEco Studio',\n configured: 'from ONIRO_HARMONYOS_SDK_PATH',\n};\n\n/** What `sdk list` prints after the OpenHarmony table: the HarmonyOS SDK, which it does not manage. */\nexport function formatHarmonyOsSdkNote(listing: HarmonyOsSdkListing | null): string {\n const note =\n 'HarmonyOS SDKs are not managed by `sdk`: they ship inside the HarmonyOS command-line tools ' +\n '(`oniro-app cmdtools`) or DevEco Studio.';\n if (!listing) return `${note}\\nNo HarmonyOS SDK found; \\`oniro-app cmdtools install\\` installs one.`;\n const name = listing.displayName ?? `HarmonyOS ${listing.version ?? ''}`.trim();\n const from = listing.source ? `, ${HARMONYOS_SOURCE[listing.source]}` : '';\n return `${note}\\n* ${name.padEnd(17)} api ${listing.api ?? '?'} ${listing.path}${from}`;\n}\n\nconst FULL_SDK_TIP =\n 'Tip: the full SDK (with system APIs) is not on the release mirror. Download an ohos-sdk-full archive ' +\n `from the OpenHarmony daily builds, ${OHOS_DAILY_BUILDS_URL}, and install it with ` +\n '`oniro-app sdk install --from-archive <archive>`.';\n\nexport function registerSdkCommand(program: Command): void {\n const sdk = program\n .command('sdk')\n .description('Manage OpenHarmony SDK installs. HarmonyOS SDKs come with the command-line tools (`cmdtools`).');\n\n sdk\n .command('install [version]')\n .description(\n 'Download and install an OpenHarmony SDK (skips if already installed), or install one from a local ' +\n 'archive with --from-archive.',\n )\n .option(\n '--from-archive <path>',\n 'Install from a local SDK .tar.gz instead of downloading, e.g. the full SDK. The API level is read ' +\n 'from the archive.',\n )\n .option('--force', 'Reinstall even if the SDK is already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for download/extract temporaries (default: ONIRO_TMP_DIR, else .oniro-tmp next to ' +\n 'the install target). Use this when that filesystem is short on space.',\n )\n .addHelpText('after', `\\n${FULL_SDK_TIP}`)\n .action(async (version: string | undefined, opts: { fromArchive?: string; force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n if (opts.fromArchive) {\n if (version) throw new Error('Pass either a version or --from-archive, not both.');\n const archivePath = path.resolve(opts.fromArchive);\n logger.info(`Installing OpenHarmony SDK from ${archivePath}...`);\n const installed = await installSdkFromArchive({\n config,\n archivePath,\n force: opts.force,\n progress,\n logger,\n tmpDir: opts.tmpDir,\n });\n const label = installed.version ? `SDK ${installed.version} (api ${installed.api})` : `SDK api ${installed.api}`;\n logger.info(`${label} installed at ${installed.dir}.`);\n return;\n }\n if (!version) {\n throw new Error(\n `Name an SDK version (${ALL_SDKS.map((s) => s.version).join(', ')}) or pass --from-archive <path>.\\n` +\n FULL_SDK_TIP,\n );\n }\n const release = ALL_SDKS.find((s) => s.version === version);\n if (!release) {\n throw new Error(\n `Unknown SDK version \"${version}\". Known: ${ALL_SDKS.map((s) => s.version).join(', ')}`,\n );\n }\n const sdkInstallDir = path.join(getSdkRootDir(config), getOsFolder(), release.api);\n if (fs.existsSync(sdkInstallDir) && !opts.force) {\n logger.info(\n `SDK ${release.version} (api ${release.api}) already installed at ${sdkInstallDir}; pass --force to reinstall.`,\n );\n return;\n }\n logger.info(`Installing OpenHarmony SDK ${release.version} (api ${release.api})...`);\n await downloadAndInstallSdk({\n config,\n version: release.version,\n api: release.api,\n progress,\n logger,\n tmpDir: opts.tmpDir,\n });\n logger.info('SDK installed.');\n });\n\n sdk\n .command('list')\n .description(\n 'List known OpenHarmony SDK versions and whether they are installed on this machine, then the HarmonyOS ' +\n 'SDK, which comes with the command-line tools (`cmdtools`) or DevEco Studio, if one is found.',\n )\n .option('--json', 'Emit machine-readable JSON instead of a table.')\n .action((opts: { json?: boolean }) => {\n const { config } = getRuntime();\n const sdks = getSupportedSdksForUi(config);\n const harmonyOs = getHarmonyOsSdkListing(config);\n if (opts.json) {\n const rows = [...sdks.map((s) => ({ ...s, flavour: 'OpenHarmony' })), ...(harmonyOs ? [harmonyOs] : [])];\n process.stdout.write(`${JSON.stringify(rows, null, 2)}\\n`);\n return;\n }\n const rows = sdks.map((s) => `${s.installed ? '*' : ' '} ${s.version.padEnd(8)} api ${s.api}`);\n process.stdout.write(`${rows.join('\\n')}\\n\\n${formatHarmonyOsSdkNote(harmonyOs)}\\n`);\n });\n\n sdk\n .command('remove <api>')\n .description('Remove an installed SDK by API level (e.g. 18, 20).')\n .action((api: string) => {\n const { config, logger } = getRuntime();\n const removed = removeSdk(config, api);\n if (!removed) {\n logger.warn(`No SDK with api ${api} found under the configured SDK root.`);\n process.exit(1);\n }\n logger.info(`Removed SDK api ${api}.`);\n });\n}\n","import type { Logger } from '@oniroproject/core';\n\n/**\n * Stderr-only logger. All diagnostic output goes to stderr so command stdout\n * stays clean for machine consumers (json results, paths, etc.).\n *\n * Debug lines are suppressed unless `ONIRO_DEBUG=1`.\n */\nexport function createCliLogger(): Logger {\n const debugEnabled = process.env.ONIRO_DEBUG === '1' || process.env.ONIRO_DEBUG === 'true';\n return {\n debug(m) {\n if (debugEnabled) process.stderr.write(`[debug] ${m}\\n`);\n },\n info(m) {\n process.stderr.write(`${m}\\n`);\n },\n warn(m) {\n process.stderr.write(`[warn] ${m}\\n`);\n },\n error(m) {\n process.stderr.write(`[error] ${m}\\n`);\n },\n };\n}\n","import type { ProgressReporter } from '@oniroproject/core';\n\n/**\n * Line-per-update progress reporter, designed for machine consumers and log scrapers.\n * Format: `[progress NN%] message` (or `[progress] message` if no percent is known).\n * Updates that don't change the percent and don't carry a message are suppressed\n * to keep output volume reasonable on chatty downloads.\n */\nexport function createCliProgress(): ProgressReporter {\n let total = 0;\n let lastEmitted = -1;\n let lastMessage = '';\n return {\n report({ message, increment }) {\n if (typeof increment === 'number') total = Math.min(100, total + increment);\n const pct = total > 0 ? Math.round(total) : null;\n const msg = message ?? lastMessage;\n // Drop redundant updates: same message, same percent.\n if (pct === lastEmitted && msg === lastMessage) return;\n const prefix = pct === null ? '[progress]' : `[progress ${pct}%]`;\n process.stderr.write(`${prefix} ${msg}\\n`);\n lastEmitted = pct ?? lastEmitted;\n if (message) lastMessage = message;\n },\n };\n}\n","import * as os from 'node:os';\nimport type { ConfigKey, ConfigProvider } from '@oniroproject/core';\n\n/**\n * Maps a core ConfigKey to its environment variable name.\n * Convention: ONIRO_<UPPER_SNAKE>.\n */\nconst ENV_VAR_BY_KEY: Record<ConfigKey, string> = {\n sdkRootDir: 'ONIRO_SDK_ROOT_DIR',\n cmdToolsPath: 'ONIRO_CMD_TOOLS_PATH',\n hdcPath: 'ONIRO_HDC',\n emulatorDir: 'ONIRO_EMULATOR_DIR',\n hapPath: 'ONIRO_HAP_PATH',\n cmdToolsUrlLinux: 'ONIRO_CMD_TOOLS_URL_LINUX',\n cmdToolsUrlWindows: 'ONIRO_CMD_TOOLS_URL_WINDOWS',\n cmdToolsUrlMac: 'ONIRO_CMD_TOOLS_URL_MAC',\n emulatorUrl: 'ONIRO_EMULATOR_URL',\n tmpDir: 'ONIRO_TMP_DIR',\n sdkUrlBase: 'ONIRO_SDK_URL_BASE',\n applicationCertPath: 'ONIRO_APPLICATION_CERT_PATH',\n harmonyosSdkPath: 'ONIRO_HARMONYOS_SDK_PATH',\n harmonyosAuthDir: 'ONIRO_HARMONYOS_AUTH_DIR',\n harmonyosSigningDir: 'ONIRO_HARMONYOS_SIGNING_DIR',\n cacheDir: 'ONIRO_CACHE_DIR',\n};\n\n/**\n * Reads configuration from environment variables (ONIRO_*). Returns the fallback\n * when the variable is unset or empty. Expands `${userHome}` to the user's home\n * directory for parity with the VS Code extension's `${userHome}` expansion.\n */\nexport function createEnvConfig(env: NodeJS.ProcessEnv = process.env): ConfigProvider {\n return {\n get<T extends string | number | boolean>(key: ConfigKey, fallback: T): T {\n const envName = ENV_VAR_BY_KEY[key];\n const raw = env[envName];\n if (raw === undefined || raw === '') return fallback;\n const expanded = raw.includes('${userHome}')\n ? raw.replace(/\\$\\{userHome\\}/g, os.homedir())\n : raw;\n return expanded as unknown as T;\n },\n };\n}\n","import type { ConfigProvider, Logger, ProgressReporter } from '@oniroproject/core';\nimport { createCliLogger } from '../adapters/logger.js';\nimport { createCliProgress } from '../adapters/progress.js';\nimport { createEnvConfig } from '../adapters/config.js';\n\nexport interface CliRuntime {\n logger: Logger;\n config: ConfigProvider;\n progress: ProgressReporter;\n}\n\nlet cached: CliRuntime | null = null;\n\n/**\n * Build (and cache) the per-process runtime used by every command. Tests can\n * override the cached runtime via `setRuntime` to inject mocks.\n */\nexport function getRuntime(): CliRuntime {\n if (!cached) {\n cached = {\n logger: createCliLogger(),\n config: createEnvConfig(),\n progress: createCliProgress(),\n };\n }\n return cached;\n}\n\nexport function setRuntime(runtime: CliRuntime | null): void {\n cached = runtime;\n}\n","import { Command } from 'commander';\nimport {\n describeCmdTools,\n getCmdToolsStatus,\n installCmdTools,\n removeCmdTools,\n type CmdToolsSdk,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** `HarmonyOS 6.1.1, API 24 (6.1.1.125) at <path>`, leaving out what is unknown. */\nexport function formatCmdToolsSdk(sdk: CmdToolsSdk): string {\n const name = [sdk.displayName, sdk.apiVersion ? `API ${sdk.apiVersion}` : undefined].filter(Boolean).join(', ');\n return `${name || 'SDK'}${sdk.build ? ` (${sdk.build})` : ''} at ${sdk.path}`;\n}\n\nexport function registerCmdToolsCommand(program: Command): void {\n const cmdtools = program\n .command('cmdtools')\n .description(\n 'Manage the command-line tools (hvigorw, ohpm, codelinter, hdc). Their HarmonyOS edition also supplies ' +\n 'the HarmonyOS SDK, which `sdk` does not manage.',\n );\n\n cmdtools\n .command('install')\n .description(\n 'Install the command-line tools (hvigorw, ohpm, codelinter, hdc and, in the HarmonyOS edition, the ' +\n 'HarmonyOS SDK). Skips if already installed.',\n )\n .option('--from-zip <path>', 'Install from a local ZIP instead of downloading.')\n .option('--force', 'Reinstall even if the tools are already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for download/extract temporaries (default: ONIRO_TMP_DIR, else .oniro-tmp next to ' +\n 'the install target). Use this when that filesystem is short on space.',\n )\n .action(async (opts: { fromZip?: string; force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n const current = getCmdToolsStatus(config);\n if (current.installed && !opts.force) {\n logger.info(\n `Command-line tools ${describeCmdTools(current)} already installed at ${current.path}; ` +\n 'pass --force to replace them.',\n );\n return;\n }\n logger.info('Installing command-line tools...');\n const result = await installCmdTools({ config, progress, logger, localZipPath: opts.fromZip, tmpDir: opts.tmpDir });\n logger.info(`Command-line tools ${describeCmdTools(result.installed)} installed at ${result.path}.`);\n });\n\n cmdtools\n .command('status')\n .description(\n 'Report whether the command-line tools are installed, their version, flavour (HarmonyOS or ' +\n 'OpenHarmony), the SDK they bundle (name, API level), their tools\\' versions (hvigor, ohpm, ...), ' +\n 'and the hdc binary every device command uses.',\n )\n .option('--json', 'Emit machine-readable JSON.')\n .action((opts: { json?: boolean }) => {\n const { config } = getRuntime();\n const status = getCmdToolsStatus(config);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n return;\n }\n process.stdout.write(`${status.version ? `Installed ${describeCmdTools(status)}` : status.status}\\n`);\n process.stdout.write(`path: ${status.path}\\n`);\n if (status.flavour) process.stdout.write(`flavour: ${status.flavour}\\n`);\n if (status.sdk) process.stdout.write(`sdk: ${formatCmdToolsSdk(status.sdk)}\\n`);\n if (status.tools?.hvigor) process.stdout.write(`hvigor: ${status.tools.hvigor}\\n`);\n process.stdout.write(`hdc: ${status.hdc.path}${status.hdc.exists ? '' : ' (missing)'}\\n`);\n if (!status.installed) process.exit(1);\n });\n\n cmdtools\n .command('remove')\n .description('Delete the configured command-line tools directory.')\n .action(() => {\n const { config, logger } = getRuntime();\n removeCmdTools(config);\n logger.info('Command-line tools removed.');\n });\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport {\n MAX_POOL_INSTANCE,\n POOL_DEFAULT_MEMORY,\n POOL_DEFAULT_RESOLUTION,\n POOL_DEFAULT_SMP,\n DEFAULT_BOOT_TIMEOUT_SECONDS,\n attemptHdcConnection,\n getEmulatorStatus,\n getPoolInstanceStatus,\n installEmulator,\n isEmulatorInstalled,\n removeEmulator,\n startEmulator,\n startPoolInstance,\n stopEmulator,\n stopPoolInstance,\n type EmulatorAccel,\n type EmulatorInstanceStatus,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nfunction parseInstance(v: string): number {\n const n = Number(v);\n if (!/^\\d+$/.test(v) || n > MAX_POOL_INSTANCE) {\n throw new InvalidArgumentError(`expected an integer from 0 to ${MAX_POOL_INSTANCE}.`);\n }\n return n;\n}\n\nfunction parseSeconds(v: string): number {\n if (!/^\\d+$/.test(v)) throw new InvalidArgumentError('expected a whole number of seconds.');\n return Number(v);\n}\n\nfunction parseSmp(v: string): number {\n if (!/^\\d+$/.test(v) || Number(v) < 1) throw new InvalidArgumentError('expected a positive integer.');\n return Number(v);\n}\n\nconst ACCELS: readonly EmulatorAccel[] = ['auto', 'kvm', 'hvf', 'whpx', 'tcg'];\n\nfunction parseAccel(v: string): EmulatorAccel {\n if (!(ACCELS as readonly string[]).includes(v)) throw new InvalidArgumentError(`expected one of ${ACCELS.join(', ')}.`);\n return v as EmulatorAccel;\n}\n\n/** One `emulator status` line: instance, health, ports, then what is known about the process. */\nexport function formatInstanceRow(i: EmulatorInstanceStatus): string {\n const fields = [String(i.instance), i.state, `hdc=${i.address}`];\n if (i.vncPort) fields.push(`vnc=127.0.0.1:${i.vncPort}`);\n if (i.instance > 0 && i.serialPort) fields.push(`serial=127.0.0.1:${i.serialPort}`);\n if (i.pid) fields.push(`pid=${i.pid}`);\n if (i.smp) fields.push(`cpus=${i.smp}`);\n if (i.memory) fields.push(`mem=${i.memory}`);\n if (i.bootSeconds !== undefined) fields.push(`boot=${i.bootSeconds}s`);\n return fields.join('\\t');\n}\n\n/** Options `emulator start` accepts only for a pool instance (keys as commander names them). */\nconst POOL_ONLY_OPTIONS = ['memory', 'smp', 'resolution', 'window', 'fresh', 'bootTimeout', 'qemu', 'accel', 'json'] as const;\n\ninterface StartOpts {\n headless?: boolean;\n log?: string;\n waitForHdc: number;\n connect?: string;\n instance?: number;\n memory?: string;\n smp?: number;\n resolution?: string;\n window?: boolean;\n fresh?: boolean;\n waitReady?: number;\n bootTimeout?: number;\n qemu?: string;\n accel?: EmulatorAccel;\n json?: boolean;\n}\n\nconst flagName = (key: string): string => `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;\n\nexport function registerEmulatorCommand(program: Command): void {\n const emu = program.command('emulator').description('Manage the Oniro emulator.');\n\n emu\n .command('install')\n .description('Download and install the Oniro emulator (QEMU-based). Skips if already installed.')\n .option('--force', 'Reinstall even if the emulator is already present.')\n .option(\n '--tmp-dir <path>',\n 'Directory for the downloaded ZIP (default: ONIRO_TMP_DIR, else .oniro-tmp next to the ' +\n 'install target). Use this when that filesystem is short on space.',\n )\n .action(async (opts: { force?: boolean; tmpDir?: string }) => {\n const { config, logger, progress } = getRuntime();\n if (isEmulatorInstalled(config) && !opts.force) {\n logger.info('Emulator already installed; pass --force to reinstall.');\n return;\n }\n logger.info('Installing Oniro emulator...');\n await installEmulator({ config, progress, logger, tmpDir: opts.tmpDir });\n logger.info('Emulator installed.');\n });\n\n emu\n .command('start')\n .description(\n 'Start the Oniro emulator and detach, so the CLI can exit while it keeps running. Without --instance (or ' +\n 'with --instance 0) it runs the bundled launcher (run.sh / run.bat). --instance <n> (1..99) starts pool ' +\n 'instance n instead: its own QEMU on copy-on-write overlays of the images, hdc on 127.0.0.1:55555+n, ' +\n 'headless VNC on 127.0.0.1:5900+n, serial console on telnet 127.0.0.1:4444+n.',\n )\n .option('--instance <n>', 'Pool instance number (1..99). 0 or unset: the default emulator via run.sh.', parseInstance)\n .option('--headless', 'Launch headless (VNC + telnet serial, no local window). Required in CI. Pool instances are headless unless --window.')\n .option('--log <path>', 'Redirect launcher stdout/stderr to this file. Defaults to discarding output (pool instances: <instance dir>/qemu.log).')\n .option('--wait-for-hdc <seconds>', 'Default emulator: wait up to N seconds for hdc to connect (restarts the hdc server). 0 = do not wait.', (v) => parseInt(v, 10), 0)\n .option('--wait-ready <seconds>', 'Wait up to N seconds until the guest reports bootevent.boot.completed=true. Connects with hdc tconn only, never restarting the hdc server.', parseSeconds)\n .option('--connect <host:port>', 'Default emulator: override the launcher\\'s hdc port-forward bind address. Pass 0.0.0.0:55555 on hosts where QEMU refuses to bind 127.0.0.1 (some CI runners).')\n .option('--memory <size>', `Pool: guest RAM in QEMU syntax (default ${POOL_DEFAULT_MEMORY}).`)\n .option('--smp <n>', `Pool: virtual CPUs (default ${POOL_DEFAULT_SMP}).`, parseSmp)\n .option('--resolution <WxH>', `Pool: display resolution (default ${POOL_DEFAULT_RESOLUTION}).`)\n .option('--window', 'Pool: show a local SDL window instead of VNC.')\n .option('--fresh', 'Pool: discard the instance\\'s overlays first (factory reset).')\n .option('--boot-timeout <seconds>', `Pool: seconds after launch past which a boot that has not completed is reported stuck (default ${DEFAULT_BOOT_TIMEOUT_SECONDS}).`, parseSeconds)\n .option('--qemu <path>', 'Pool: qemu-system-x86_64 binary (default QEMU_BIN, else PATH); qemu-img is looked up next to it.')\n .option('--accel <kind>', `Pool: accelerator, one of ${ACCELS.join(', ')} (default auto: KVM on Linux, as run.sh).`, parseAccel)\n .option('--json', 'Pool: print the instance\\'s status as JSON when done.')\n .action(async (opts: StartOpts) => {\n const { config, logger } = getRuntime();\n if (opts.instance === undefined || opts.instance === 0) {\n const poolOnly = POOL_ONLY_OPTIONS.filter((k) => opts[k] !== undefined);\n if (poolOnly.length > 0) {\n throw new InvalidArgumentError(\n `${poolOnly.map(flagName).join(', ')} ${poolOnly.length > 1 ? 'apply' : 'applies'} only to pool instances ` +\n `(--instance 1..${MAX_POOL_INSTANCE}).`,\n );\n }\n await startEmulator({\n config,\n logger,\n headless: opts.headless === true,\n logFile: opts.log,\n waitForHdcSeconds: opts.waitForHdc,\n waitReadySeconds: opts.waitReady,\n connect: opts.connect,\n });\n logger.info('Emulator start command complete.');\n return;\n }\n if (opts.connect || opts.waitForHdc > 0) {\n throw new InvalidArgumentError(\n '--connect and --wait-for-hdc apply to the default emulator only; a pool instance listens on 127.0.0.1:55555+n, wait with --wait-ready.',\n );\n }\n const status = await startPoolInstance({\n config,\n logger,\n instance: opts.instance,\n memory: opts.memory,\n smp: opts.smp,\n resolution: opts.resolution,\n headless: opts.window !== true,\n fresh: opts.fresh === true,\n waitReadySeconds: opts.waitReady,\n bootTimeoutSeconds: opts.bootTimeout,\n qemuBin: opts.qemu,\n accel: opts.accel,\n logFile: opts.log,\n });\n if (opts.json) process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n else logger.info(`Instance ${status.instance}: ${status.state} (${status.address}).`);\n });\n\n emu\n .command('status')\n .description(\n 'Report whether the Oniro emulator is installed, running, and connected to hdc, without starting it, and ' +\n 'list every instance (the default emulator as 0, then each pool instance) with its health: stopped, ' +\n 'booting, ready, hdc-lost or stuck. Exits 1 when the emulator is not installed.',\n )\n .option('--address <addr>', 'hdc address the default emulator listens on', '127.0.0.1:55555')\n .option('--instance <n>', 'Report only this instance (0 = the default emulator).', parseInstance)\n .option('--json', 'Emit machine-readable JSON: `instances` lists every instance; with --instance, that instance alone.')\n .action(async (opts: { address: string; json?: boolean; instance?: number }) => {\n const { config, logger } = getRuntime();\n const print = (one: EmulatorInstanceStatus): void => {\n process.stdout.write(opts.json ? `${JSON.stringify(one, null, 2)}\\n` : `${formatInstanceRow(one)}\\n`);\n };\n if (opts.instance !== undefined && opts.instance > 0) {\n print(await getPoolInstanceStatus(config, opts.instance, { logger }));\n if (!isEmulatorInstalled(config)) process.exitCode = 1;\n return;\n }\n const status = await getEmulatorStatus(config, { address: opts.address, logger });\n if (opts.instance === 0) {\n print(status.instances[0]!);\n } else if (opts.json) {\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n } else {\n process.stdout.write(\n `installed: ${status.installed ? 'yes' : 'no'} (${status.dir})\\n` +\n `running: ${status.running ? 'yes' : 'no'}\\n` +\n `connected: ${status.connected ? 'yes' : 'no'} (${status.address})\\n`,\n );\n if (status.instances.length > 1) {\n process.stdout.write(`instances:\\n${status.instances.map((i) => ` ${formatInstanceRow(i)}`).join('\\n')}\\n`);\n }\n }\n if (!status.installed) process.exitCode = 1;\n });\n\n emu\n .command('stop')\n .description(\n 'Without --instance: kill running emulator processes (every qemu-system-x86_64, pool instances included). ' +\n 'With --instance <n>: stop only that pool instance\\'s QEMU and drop its target from hdc.',\n )\n .option('--instance <n>', 'Pool instance to stop (1..99).', parseInstance)\n .option('--discard', 'With --instance: also delete the instance\\'s overlays, log and state.')\n .action(async (opts: { instance?: number; discard?: boolean }) => {\n const { config, logger } = getRuntime();\n if (opts.instance === undefined || opts.instance === 0) {\n if (opts.discard) throw new InvalidArgumentError(`--discard needs --instance <n> (1..${MAX_POOL_INSTANCE}).`);\n await stopEmulator(logger);\n logger.info('Emulator stopped.');\n return;\n }\n const stopped = await stopPoolInstance({ config, instance: opts.instance, discard: opts.discard === true, logger });\n if (!stopped) logger.info(`Instance ${opts.instance} was not running.`);\n });\n\n emu\n .command('connect')\n .description('Attempt to connect hdc to the emulator.')\n .option('--address <addr>', 'hdc address to connect to', '127.0.0.1:55555')\n .action(async (opts: { address: string }) => {\n const { config, logger } = getRuntime();\n const ok = await attemptHdcConnection(config, opts.address, logger);\n if (!ok) {\n logger.error(`Could not connect hdc to ${opts.address}.`);\n process.exit(1);\n }\n logger.info(`hdc connected to ${opts.address}.`);\n });\n\n emu\n .command('remove')\n .description('Delete the configured emulator directory.')\n .action(() => {\n const { config, logger } = getRuntime();\n removeEmulator(config);\n logger.info('Emulator removed.');\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n OniroError,\n buildWithDiagnostics,\n downloadAndInstallSdk,\n type BuildDiagnostic,\n type BuildReport,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport interface BuildOpts {\n product: string;\n module?: string;\n mode?: string;\n task: string;\n deps: boolean;\n parallel: boolean;\n installSdk?: boolean;\n json?: boolean;\n}\n\n/**\n * Build, and with `installSdk` install a missing SDK and build again. Throws\n * only when the build could not run at all (no command-line tools, not a\n * project). Shared with `serve mcp`.\n */\nexport async function runBuild(projectDir: string | undefined, opts: Omit<BuildOpts, 'json'>): Promise<BuildReport> {\n const { config, logger, progress } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n logger.info(`Building project at ${dir}...`);\n const build = () =>\n buildWithDiagnostics({\n config,\n projectDir: dir,\n product: opts.product,\n module: opts.module,\n mode: opts.mode,\n task: opts.task,\n autoInstallDeps: opts.deps,\n parallel: opts.parallel,\n logger,\n // The logger already echoes spawn output; this hook is for streaming to other UIs.\n onOutput: () => {},\n });\n let report = await build();\n if (!report.ok && report.missingSdk?.version && opts.installSdk) {\n const { version, api } = report.missingSdk;\n logger.info(`Installing OpenHarmony SDK ${version} (api ${api}), which the project compiles against...`);\n await downloadAndInstallSdk({ config, version, api, progress, logger });\n report = await build();\n }\n return report;\n}\n\nexport function registerBuildCommand(program: Command): void {\n program\n .command('build [project-dir]')\n .description(\n 'Build an OpenHarmony or HarmonyOS app via hvigorw. Defaults to the current directory. ' +\n 'Projects declaring runtimeOS \"HarmonyOS\" build against the HarmonyOS SDK (ONIRO_HARMONYOS_SDK_PATH or an installed DevEco Studio). ' +\n 'An OpenHarmony project fails early, naming the release to install, when the SDK for its compileSdkVersion is missing. ' +\n 'With --json, one result object is printed whether the build passes or fails; a failed build exits 1.',\n )\n .option('--product <product>', 'hvigor product name', 'default')\n .option('--module <module>', 'restrict the build to a specific module')\n .option('--mode <mode>', 'hvigor build mode (e.g. release, debug)')\n .option('--task <task>', 'hvigor task to run', 'assembleHap')\n .option('--no-deps', 'skip the automatic `ohpm install --all` when oh_modules/ is missing')\n .option('--no-parallel', 'build modules serially (default: parallel)')\n .option('--install-sdk', 'install the OpenHarmony SDK the project compiles against when it is missing, then build')\n .option(\n '--json',\n 'print the result as JSON: ok, diagnostics (file, line, column, code, rule, message), summary, failedTask, discoveredHaps, warnings',\n )\n .action(async (projectDir: string | undefined, opts: BuildOpts) => {\n const { logger } = getRuntime();\n let report: BuildReport;\n try {\n report = await runBuild(projectDir, opts);\n } catch (err) {\n // The build could not run at all (no command-line tools, not a project):\n // still one object on stdout for a caller that parses it.\n if (opts.json) {\n const error = err instanceof Error ? err.message : String(err);\n process.stdout.write(`${JSON.stringify({ ok: false, exitCode: 1, error, diagnostics: [] }, null, 2)}\\n`);\n }\n throw err;\n }\n for (const w of report.warnings) logger.warn(w);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n }\n if (!report.ok) {\n const listed = formatDiagnostics(report.diagnostics);\n if (listed) logger.error(`Build failed${report.failedTask ? ` in ${report.failedTask}` : ''}:\\n${listed}`);\n throw new OniroError(report.error ?? 'Build failed.');\n }\n logger.info('Build complete.');\n });\n}\n\n/** Diagnostics one per line, `file:line:col severity [code] message (rule)`, errors first, at most `max`. */\nexport function formatDiagnostics(diagnostics: readonly BuildDiagnostic[], max = 20): string {\n const sorted = [...diagnostics].sort((a, b) => (a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1));\n const lines = sorted.slice(0, max).map((d) => {\n const at = d.file ? `${d.file}${d.line ? `:${d.line}${d.column ? `:${d.column}` : ''}` : ''} ` : '';\n return ` ${at}${d.severity} ${d.source}${d.code ? ` ${d.code}` : ''}: ${d.message}${d.rule ? ` (${d.rule})` : ''}`;\n });\n if (sorted.length > max) lines.push(` … and ${sorted.length - max} more`);\n return lines.join('\\n');\n}\n","import { Command, Option } from 'commander';\nimport * as path from 'node:path';\nimport {\n APL_VALUES,\n APP_FEATURE_VALUES,\n OniroError,\n createHarmonyOsSession,\n detectRuntimeOs,\n generateSigningConfigs,\n harmonyOsAutoSign,\n harmonyOsSignHap,\n signOpenHarmonyHap,\n prepareSigning,\n getOhosBaseSdkHome,\n describeProfileValidity,\n describeSigningMaterial,\n type Apl,\n type AppFeature,\n type HarmonyOsSigningResult,\n type SigningMaterialSummary,\n type SigningPasswords,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** `profile names 6 device(s), debug, valid until 2026-10-01 11:50 UTC`. */\nfunction profileSummary(result: HarmonyOsSigningResult): string {\n const validity = describeProfileValidity({ type: result.profileType, notAfter: result.notAfter });\n return [`profile names ${result.deviceIds.length} device(s)`, validity].filter(Boolean).join(', ');\n}\n\n/** ` (release profile, apl normal; certificate valid until …)`, or nothing when nothing is known. */\nfunction materialSuffix(summary: SigningMaterialSummary): string {\n const text = describeSigningMaterial(summary);\n return text ? ` (${text})` : '';\n}\n\nfunction parseAclsList(value: string): string[] {\n return value\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\nexport function registerSignCommand(program: Command): void {\n program\n .command('sign [project-dir]')\n .description(\n [\n 'Generate signing keys, certificates, and signingConfigs for an OpenHarmony project.',\n 'Requires java on PATH. The generated profile uses the SDK\\'s built-in development',\n 'cert (issuer=pki_internal) and its bundled validity window — dev/local builds only.',\n 'Overwrites the `signingConfigs` block in build-profile.json5 (other keys preserved).',\n 'HarmonyOS projects need --harmonyos instead, which has AppGallery Connect issue the',\n 'certificate and profile for a signed-in Huawei account (`oniro-app auth login`).',\n 'With --hap <file>, signs a prebuilt HAP instead of a project (with --harmonyos, for HarmonyOS).',\n 'Ends by naming the profile type and expiry; `oniro-app app verify <hap>` checks what signed a built HAP.',\n ].join(' '),\n )\n .addOption(\n new Option(\n '--apl <level>',\n 'Ability Privilege Level written into the profile. Apps that request permissions above `normal` (e.g. ohos.permission.GET_WIFI_INFO_INTERNAL) need system_basic or system_core, which also switches the HAP-signing key to \"OpenHarmony Application Release\".',\n )\n .choices([...APL_VALUES])\n .default('normal'),\n )\n .addOption(\n new Option(\n '--app-feature <feature>',\n 'App feature written into the profile. Defaults: hos_normal_app for apl=normal; hos_system_app for apl=system_basic/system_core.',\n ).choices([...APP_FEATURE_VALUES]),\n )\n .addOption(\n new Option(\n '--acls <list>',\n 'Comma-separated permission names to write into the profile\\'s acls.allowed-acls. Required for apps that request permissions above their apl (e.g. a system_basic app requesting ohos.permission.CAPTURE_SCREEN). Example: --acls ohos.permission.REBOOT,ohos.permission.INJECT_INPUT_EVENT',\n ).argParser(parseAclsList),\n )\n .addOption(\n new Option(\n '--app-privilege-capabilities <list>',\n 'Comma-separated privileges to write into the profile\\'s app-privilege-capabilities. An app that declares a privileged extension ability (e.g. an AccessibilityExtensionAbility) needs AllowAppUsePrivilegeExtension, else install fails with 9568344 \"not allow use privilege extension\". Others include AllowAppMultiProcess and AllowAppDesktopIconHide.',\n ).argParser(parseAclsList),\n )\n .option(\n '--harmonyos',\n 'Sign a HarmonyOS project through AppGallery Connect. Needs `oniro-app auth login`, and a device registered to the team: a connected device is registered if it reports a UDID (`hdc shell bm get -u`).',\n )\n .option(\n '--hap <file>',\n 'Sign this prebuilt .hap (unsigned, or signed with other material) instead of a project, and write a signed copy (see --out). The bundle name is read from the HAP. For OpenHarmony, --apl, --app-feature, --acls and --app-privilege-capabilities apply as for a project; with --harmonyos, the ACL permissions are read from the HAP too.',\n )\n .option(\n '--out <file>',\n 'With --hap: where to write the signed HAP. Default: next to the input, `<name>-unsigned.hap` → `<name>-signed.hap`, `<name>.hap` → `<name>-signed.hap`, `<name>-signed.hap` → `<name>-resigned.hap`. Name the input itself to re-sign it in place.',\n )\n .option('--team-id <id>', 'With --harmonyos: the AGC team to sign under. Default: the account\\'s own (`oniro-app auth team list`).')\n .option('--product <name>', 'With --harmonyos: the product to sign. Default `default`.')\n .option('--force', 'With --harmonyos: regenerate the certificate and profile even when they are still valid.')\n .option('--bootstrap', 'No-op if signing material is already present; otherwise generate it.')\n .option('--store-password <pwd>', 'Keystore store password (default 123456 — the SDK keystore password).')\n .option('--key-password <pwd>', 'Keystore key password (default 123456 — the SDK keystore password).')\n .action(\n async (\n projectDir: string | undefined,\n opts: {\n apl: Apl;\n appFeature?: AppFeature;\n acls?: string[];\n appPrivilegeCapabilities?: string[];\n bootstrap?: boolean;\n storePassword?: string;\n keyPassword?: string;\n harmonyos?: boolean;\n teamId?: string;\n product?: string;\n force?: boolean;\n hap?: string;\n out?: string;\n },\n ) => {\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n const passwords: SigningPasswords | undefined =\n opts.storePassword || opts.keyPassword\n ? { store: opts.storePassword ?? '123456', key: opts.keyPassword ?? '123456' }\n : undefined;\n\n if (opts.out && !opts.hap) throw new OniroError('--out names where `--hap` writes the signed HAP; pass --hap too.');\n if (opts.hap) {\n if (projectDir) throw new OniroError('Pass either a project directory or --hap, not both.');\n if (opts.product || opts.bootstrap) {\n throw new OniroError(`--${opts.product ? 'product' : 'bootstrap'} applies to a project, not to --hap.`);\n }\n // Each signing path honours only its own flags; say so rather than drop one.\n const ignored = opts.harmonyos\n ? [\n opts.apl !== 'normal' && '--apl',\n opts.appFeature && '--app-feature',\n opts.acls && '--acls (the ACLs are read from the HAP)',\n opts.appPrivilegeCapabilities && '--app-privilege-capabilities',\n (opts.storePassword || opts.keyPassword) && '--store-password/--key-password',\n ]\n : [opts.teamId && '--team-id', opts.force && '--force'];\n const unsupported = ignored.filter((flag): flag is string => typeof flag === 'string');\n if (unsupported.length > 0) {\n throw new OniroError(\n `${unsupported.join(', ')} ${unsupported.length > 1 ? 'do' : 'does'} not apply to ${opts.harmonyos ? '--harmonyos --hap' : '--hap without --harmonyos'}.`,\n );\n }\n if (!opts.harmonyos) {\n const result = await signOpenHarmonyHap({\n hapPath: opts.hap,\n outPath: opts.out,\n sdkHome: getOhosBaseSdkHome(config),\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n applicationCertPath: config.get('applicationCertPath', '') || undefined,\n logger,\n });\n logger.info(`Signed ${result.bundleName} into ${result.outPath}${materialSuffix(result.material)}.`);\n return;\n }\n const result = await harmonyOsSignHap({\n config,\n session: createHarmonyOsSession({ config, logger }),\n hapPath: opts.hap,\n outPath: opts.out,\n teamId: opts.teamId,\n force: opts.force,\n logger,\n });\n logger.info(`Signed ${result.bundleName} into ${result.outPath} (${profileSummary(result)}).`);\n return;\n }\n\n if (opts.harmonyos) {\n const result = await harmonyOsAutoSign({\n config,\n session: createHarmonyOsSession({ config, logger }),\n projectDir: dir,\n productName: opts.product,\n teamId: opts.teamId,\n force: opts.force,\n logger,\n });\n logger.info(`Signing configs ready for ${result.bundleName} (${profileSummary(result)}).`);\n return;\n }\n // The OpenHarmony development certificate cannot sign for a HarmonyOS device.\n if (detectRuntimeOs(dir, opts.product) === 'HarmonyOS') {\n throw new OniroError(\n `${dir} targets HarmonyOS, which needs a certificate from AppGallery Connect: run \\`oniro-app auth login\\` once, then \\`oniro-app sign --harmonyos\\`.`,\n );\n }\n\n if (opts.bootstrap) {\n const result = prepareSigning({\n config,\n projectDir: dir,\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n logger,\n });\n logger.info(result.source === 'present' ? 'Signing material already present.' : 'Signing configs generated.');\n return;\n }\n\n const sdkHome = getOhosBaseSdkHome(config);\n logger.info(`Generating signing configs in ${dir} using SDK at ${sdkHome}...`);\n const generated = generateSigningConfigs({\n projectDir: dir,\n sdkHome,\n apl: opts.apl,\n appFeature: opts.appFeature,\n acls: opts.acls,\n appPrivilegeCapabilities: opts.appPrivilegeCapabilities,\n passwords,\n logger,\n });\n logger.info(`Signing configs generated${materialSuffix(generated)}.`);\n },\n );\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as readline from 'node:readline';\nimport { HUAWEI_SITES, createHarmonyOsSession, type HarmonyOsSession } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** A session bound to the CLI runtime. */\nfunction session(): HarmonyOsSession {\n const { config, logger } = getRuntime();\n return createHarmonyOsSession({ config, logger });\n}\n\nfunction parsePort(value: string): number {\n const port = Number(value);\n if (!/^\\d+$/.test(value) || port < 1 || port > 65_535) {\n throw new InvalidArgumentError('expected a port number from 1 to 65535.');\n }\n return port;\n}\n\n/** Stderr text for a login that opens the browser here. The URL is repeated for headless hosts. */\nfunction browserInstructions(url: string): string {\n return `Opening the Huawei sign-in page. If no browser opens, visit:\\n ${url}\\n`;\n}\n\n/** Stderr text for a login whose browser may be on another machine. */\nfunction manualInstructions(url: string, callbackUrl: string, port: number): string {\n return [\n 'Open this address in a browser, on this machine or any other, and sign in:',\n ` ${url}`,\n `The browser is then sent to ${callbackUrl}?... If that page does not load (the browser is not on`,\n 'this machine), copy the whole address from its address bar, paste it here and press Enter.',\n `(Or forward the port first, from the machine with the browser: ssh -L ${port}:127.0.0.1:${port} <this-host>.)`,\n '',\n ].join('\\n');\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program\n .command('auth')\n .description(\n 'Sign in to a Huawei developer account, which HarmonyOS signing (`oniro-app sign --harmonyos`) needs. ' +\n 'OpenHarmony signing needs no account. The token is stored encrypted under ONIRO_HARMONYOS_AUTH_DIR ' +\n '(default ~/.oniro/harmonyos).',\n );\n\n auth\n .command('login')\n .description(\n 'Sign in through the browser, which redirects back to a loopback port on this machine. ' +\n 'With the browser on another machine, either pass --manual and paste the address the browser ' +\n 'ends up on, or fix the port with --port and forward it with `ssh -L <port>:127.0.0.1:<port>`.',\n )\n .option('--timeout <seconds>', 'How long to wait for the browser sign-in. Default 600.', (v) => Number(v))\n .option(\n '--port <n>',\n 'Loopback port the sign-in page redirects to, instead of a random one, so an ssh tunnel can be set up ' +\n 'beforehand: `ssh -L <n>:127.0.0.1:<n> <this-host>` from the machine with the browser (same port both ends).',\n parsePort,\n )\n .option(\n '--no-browser',\n 'Do not open a browser. Print the sign-in URL, then finish the sign-in from the callback address ' +\n '(`http://127.0.0.1:<port>/callback?...`, or just its query) pasted on stdin, or from the loopback ' +\n 'port itself, whichever comes first.',\n )\n .option('--manual', 'Same as --no-browser.')\n .option('--print-url', 'Also write the sign-in URL to stdout, alone on its line, before waiting.')\n .option(\n '--json',\n 'Write JSON lines to stdout: {\"loginUrl\",\"port\",\"callbackUrl\"} before waiting, then the account ' +\n '({\"userId\",\"userName\",\"site\",\"tokenPath\"}) once signed in.',\n )\n .action(\n async (opts: {\n timeout?: number;\n port?: number;\n browser: boolean;\n manual?: boolean;\n printUrl?: boolean;\n json?: boolean;\n }) => {\n const { config, logger } = getRuntime();\n const manual = opts.manual || !opts.browser;\n const s = createHarmonyOsSession({\n config,\n logger,\n onLoginUrl: (url, { port }) => {\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n if (opts.json) process.stdout.write(`${JSON.stringify({ loginUrl: url, port, callbackUrl })}\\n`);\n else if (opts.printUrl) process.stdout.write(`${url}\\n`);\n process.stderr.write(manual ? manualInstructions(url, callbackUrl, port) : browserInstructions(url));\n },\n });\n // Read pasted callbacks only when asked: a plain login must not hold stdin.\n const stdin = manual ? readline.createInterface({ input: process.stdin, terminal: false }) : undefined;\n let user;\n try {\n user = await s.login({\n timeoutMs: opts.timeout ? Math.max(1, opts.timeout) * 1000 : undefined,\n port: opts.port,\n openBrowser: !manual,\n pastedCallbacks: stdin,\n });\n } finally {\n stdin?.close();\n // A pending read keeps a TTY or pipe open, and with it the process.\n if (stdin) process.stdin.destroy();\n }\n if (opts.json) {\n const status = { userId: user.userId, userName: user.userName, site: user.siteCode, tokenPath: s.tokenPath };\n process.stdout.write(`${JSON.stringify(status)}\\n`);\n return;\n }\n process.stdout.write(`${user.userName || user.userId}\\n`);\n },\n );\n\n auth\n .command('logout')\n .description('Sign out and delete the stored token.')\n .action(async () => {\n const signedOut = await session().logout();\n getRuntime().logger.info(signedOut ? 'Signed out.' : 'Not signed in; nothing to do.');\n });\n\n auth\n .command('status')\n .description('Show the signed-in account. Exits non-zero when not signed in.')\n .option('--json', 'Emit the account details as JSON.')\n .action(async (opts: { json?: boolean }) => {\n const s = session();\n // Refreshed: a stale access token makes the agreement check fail.\n const user = await s.getUserInfo({ refresh: true });\n if (!user) {\n process.stderr.write('Not signed in. Run `oniro-app auth login`.\\n');\n process.exitCode = 1;\n return;\n }\n // Without real-name verification, the developer agreement is what allows signing.\n const agreement = user.isRealName ? null : await s.getDeveloperAgreement(user);\n if (opts.json) {\n const { userId, userName, countryCode, siteCode, isRealName } = user;\n const agcBaseUrl = HUAWEI_SITES[siteCode].agcBaseUrl;\n const status = { userId, userName, countryCode, site: siteCode, agcBaseUrl, isRealName, developerAgreement: agreement, tokenPath: s.tokenPath };\n process.stdout.write(`${JSON.stringify(status, null, 2)}\\n`);\n return;\n }\n process.stdout.write(`${user.userName || user.userId} (${user.userId}) [${user.siteCode}]\\n`);\n if (agreement && !(agreement.signed && agreement.latest)) {\n process.stderr.write(\n '[warn] This account has neither real-name verification nor the current HUAWEI Developer Basic Service Agreement accepted, so AppGallery Connect will not issue signing material. Accept the agreement in AppGallery Connect or DevEco Studio.\\n',\n );\n }\n });\n\n auth\n .command('team')\n .description('AGC teams this account belongs to.')\n .command('list')\n .description('List the AGC teams this account belongs to, for `oniro-app sign --harmonyos --team-id <id>`.')\n .option('--json', 'Emit the team list as JSON.')\n .action(async (opts: { json?: boolean }) => {\n const teams = await session().listTeams();\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(teams, null, 2)}\\n`);\n return;\n }\n for (const t of teams) process.stdout.write(`${t.id}\\t${t.name}\\n`);\n });\n}\n","import { Command } from 'commander';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport {\n installApp,\n launchApp,\n uninstallApp,\n forceStop,\n applyChanges,\n existingHapOrUnsigned,\n getBundleName,\n readHapBundleName,\n smokeCheck,\n latestCrash,\n wakeAndUnlock,\n DEFAULT_SMOKE_DELAY_MS,\n OniroError,\n type ConfigProvider,\n type Logger,\n type ApplyChangesResult,\n type CrashVerdict,\n type SmokeResult,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { decodeGreyscale } from '../lib/screenshotImage.js';\nimport { registerAppVerifyCommand } from './appVerify.js';\n\nexport interface SmokeOpts {\n smoke?: boolean;\n /** Milliseconds, as the flag's string or a number. */\n smokeDelay: string | number;\n smokeScreenshot?: string;\n}\n\nfunction addSmokeOptions(cmd: Command): Command {\n return cmd\n .option(\n '--smoke',\n 'After launch, wait for the process, take a screenshot after --smoke-delay, and fail (exit 1) when the ' +\n 'process died or the screen is blank.',\n )\n .option('--smoke-delay <ms>', 'With --smoke: wait between the process appearing and the screenshot.', String(DEFAULT_SMOKE_DELAY_MS))\n .option('--smoke-screenshot <file>', 'With --smoke: where to write the screenshot (default: a file in the system temp dir).');\n}\n\nfunction smokeDelayFrom(raw: string | number): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n < 0) throw new OniroError(`--smoke-delay expects a number of milliseconds; got \"${raw}\".`);\n return Math.round(n);\n}\n\n/**\n * A dark screen would read as a blank app, and `aa start` refuses to launch\n * over a lock screen, so turn the screen on and swipe the lock away first.\n */\nasync function wakeForSmoke(config: ConfigProvider, logger: Logger, device?: string): Promise<void> {\n const screen = await wakeAndUnlock({ config, deviceSerial: device, logger }).catch((err: Error) => {\n logger.warn(`Could not wake the screen: ${err.message}`);\n return null;\n });\n if (screen?.locked) logger.warn('The lock screen asks for a credential; the smoke screenshot will show it.');\n}\n\n/** Extra seconds before the launch to look back for its crash (the device clock reads whole seconds). */\nconst CRASH_CLOCK_SLACK_MS = 2_000;\n/** How long to wait for the faultlog of an app that died after launch. */\nconst CRASH_WAIT_MS = 15_000;\n\n/** The launch smoke check, with sharp decoding the screenshot and the faultlog reader for crashes. */\nfunction runSmoke(\n config: ConfigProvider,\n logger: Logger,\n bundle: string,\n since: Date,\n opts: SmokeOpts & { device?: string },\n): Promise<SmokeResult<CrashVerdict>> {\n const screenshotPath = opts.smokeScreenshot\n ? path.resolve(opts.smokeScreenshot)\n : path.join(os.tmpdir(), `oniro-smoke-${bundle}-${since.getTime()}.jpeg`);\n return smokeCheck({\n config,\n bundle,\n since,\n delayMs: smokeDelayFrom(opts.smokeDelay),\n screenshotPath,\n decodeGreyscale: (jpeg) => decodeGreyscale(jpeg),\n crashProbe: (probe) =>\n latestCrash({\n config: probe.config,\n bundle: probe.bundle,\n // Faultlog times are the device's clock, which need not agree with the host's:\n // ask for \"as long ago as the launch\" on the device's clock, plus a little slack.\n since: (Date.now() - probe.since.getTime() + CRASH_CLOCK_SLACK_MS) / 1000,\n // hiview writes the faultlog seconds after a death; a live app is looked up once.\n waitMs: probe.alive ? 0 : CRASH_WAIT_MS,\n deviceSerial: probe.deviceSerial,\n logger: probe.logger,\n }),\n deviceSerial: opts.device,\n logger,\n });\n}\n\n/** One line for the smoke verdict. */\nexport function formatSmoke(s: SmokeResult<CrashVerdict>): string {\n const parts = [\n s.pid === null ? 'no process' : `pid ${s.pid} ${s.alive ? 'alive' : 'died'}`,\n s.blankScreen === null ? 'blank check skipped' : `${s.blankScreen ? 'blank' : 'not blank'} (score ${s.blankScore})`,\n ];\n if (s.crash) {\n const where = s.crash.file ? ` at ${s.crash.file}:${s.crash.line ?? '?'}` : '';\n parts.push(`${s.crash.kind ?? 'crash'}${s.crash.reason ? ` (${s.crash.reason})` : ''}${where}`);\n }\n if (s.screenshot) parts.push(`screenshot ${s.screenshot}`);\n return `smoke: ${s.passed ? 'passed' : `FAILED (${s.failures.join('; ')})`}: ${parts.join(', ')}`;\n}\n\ninterface LaunchOpts extends SmokeOpts {\n bundle?: string;\n module: string;\n ability?: string;\n device?: string;\n json?: boolean;\n}\n\ninterface ApplyOpts extends SmokeOpts {\n bundle?: string;\n module?: string;\n hap?: string;\n installedHap?: string;\n system?: boolean;\n allowUninstall?: boolean;\n device?: string;\n json?: boolean;\n}\n\n/** What `app launch` and `app apply` need from the runtime. */\nexport interface AppRuntime {\n config: ConfigProvider;\n logger: Logger;\n}\n\nexport interface LaunchParams extends Partial<SmokeOpts> {\n /** Project mode: the project to launch (default: the current directory). */\n projectDir?: string;\n /** Bundle mode: launch this installed bundle instead. */\n bundle?: string;\n module?: string;\n ability?: string;\n device?: string;\n}\n\n/** The `app launch --smoke --json` object; `smoke` is absent without `smoke`. */\nexport interface LaunchReport {\n bundle: string;\n smoke?: SmokeResult<CrashVerdict>;\n}\n\n/** `app launch`: start the app and, with `smoke`, judge it. Shared with `serve mcp`. */\nexport async function launchWithSmoke(rt: AppRuntime, p: LaunchParams): Promise<LaunchReport> {\n const { config, logger } = rt;\n const smokeDelay = p.smokeDelay ?? DEFAULT_SMOKE_DELAY_MS;\n if (p.smoke) {\n smokeDelayFrom(smokeDelay); // validate before launching\n await wakeForSmoke(config, logger, p.device);\n }\n const since = new Date();\n let bundle: string;\n if (p.bundle) {\n bundle = p.bundle;\n logger.info(`Launching installed bundle ${p.bundle}...`);\n await launchApp({ config, bundleName: p.bundle, abilityName: p.ability, deviceSerial: p.device, logger });\n } else {\n const dir = path.resolve(p.projectDir ?? process.cwd());\n bundle = getBundleName(dir);\n logger.info(`Launching app from ${dir}...`);\n await launchApp({\n config,\n projectDir: dir,\n moduleName: p.module ?? 'entry',\n abilityName: p.ability,\n deviceSerial: p.device,\n logger,\n });\n }\n logger.info('App launched.');\n if (!p.smoke) return { bundle };\n const smoke = await runSmoke(config, logger, bundle, since, { ...p, smokeDelay });\n return { bundle, smoke };\n}\n\nexport interface ApplyParams extends Partial<SmokeOpts> {\n /** A project directory or a .hap file (default: the current directory). */\n target?: string;\n bundle?: string;\n module?: string;\n hap?: string;\n installedHap?: string;\n system?: boolean;\n allowUninstall?: boolean;\n device?: string;\n}\n\n/** The `app apply --json` object: the install result, plus `smoke` with `smoke`. */\nexport type ApplyReport = ApplyChangesResult & { smoke?: SmokeResult<CrashVerdict> };\n\n/** `app apply`: install, check the process took the change and, with `smoke`, relaunch and judge it. Shared with `serve mcp`. */\nexport async function applyWithSmoke(rt: AppRuntime, p: ApplyParams): Promise<ApplyReport> {\n const { config, logger } = rt;\n const smokeDelay = p.smokeDelay ?? DEFAULT_SMOKE_DELAY_MS;\n if (p.smoke) smokeDelayFrom(smokeDelay); // validate before installing\n const target = p.target;\n const isHap = target !== undefined && /\\.hap$/i.test(target);\n if (isHap && p.hap) throw new OniroError('Pass the HAP either as the argument or with --hap, not both.');\n const dir = isHap ? process.cwd() : path.resolve(target ?? process.cwd());\n const hapPath = isHap ? path.resolve(target) : p.hap;\n let bundle = p.bundle;\n if (!bundle && isHap) {\n // The same signed-to-unsigned fallback applyChanges applies when it installs.\n const hap = existingHapOrUnsigned(hapPath!);\n if (!hap) throw new OniroError(`HAP not found at ${hapPath}.`);\n bundle = (await readHapBundleName(hap.path).catch(() => null)) ?? undefined;\n if (!bundle) throw new OniroError(`Could not read the bundle name from ${hap.path}. Pass --bundle.`);\n }\n bundle ??= getBundleName(dir);\n const result = await applyChanges({\n config,\n bundle,\n hapPath,\n projectDir: dir,\n module: p.module,\n installedHapPath: p.installedHap,\n isSystemBundle: p.system,\n allowUninstall: p.allowUninstall,\n deviceSerial: p.device,\n logger,\n });\n if (!p.smoke) return result;\n // A replace install stops the app, so launch it again before judging it.\n await wakeForSmoke(config, logger, p.device);\n const since = new Date();\n logger.info(`Launching ${bundle} for the smoke check...`);\n await launchApp({ config, bundleName: bundle, deviceSerial: p.device, logger });\n const smoke = await runSmoke(config, logger, bundle, since, { ...p, smokeDelay });\n return { ...result, smoke };\n}\n\nexport function registerAppCommand(program: Command): void {\n const app = program.command('app').description('Install, launch, and manage built apps on a connected device/emulator.');\n\n app\n .command('install [project-dir-or-hap]')\n .description(\n 'Install a built .hap on the connected device/emulator via hdc. Takes a project dir (default: the ' +\n 'current one), whose newest signed HAP is installed, else its unsigned one, or a .hap file. Fails ' +\n 'when the bundle manager rejects the HAP, and says how to sign when a target refuses an unsigned one.',\n )\n .option('--hap <path>', 'Override the .hap path (relative to project-dir or absolute).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (target: string | undefined, opts: { hap?: string; device?: string }) => {\n const { config, logger } = getRuntime();\n const isHap = target !== undefined && /\\.hap$/i.test(target);\n const dir = isHap ? process.cwd() : path.resolve(target ?? process.cwd());\n const hapPath = isHap ? path.resolve(target) : opts.hap;\n logger.info(`Installing ${hapPath ?? `app from ${dir}`}...`);\n const result = await installApp({ config, projectDir: dir, hapPath, deviceSerial: opts.device, logger });\n logger.info(`Installed ${result.hapPath}.`);\n });\n\n const launch = app\n .command('launch [project-dir]')\n .description(\n 'Launch an app on the connected device/emulator. Project mode (default): resolves ' +\n 'bundle + main ability from the project. Bundle mode (--bundle): launch an ' +\n 'already-installed app by bundle name, no project needed.',\n )\n .option('--bundle <bundle>', 'Launch an already-installed app by bundle name (no project needed).')\n .option('--module <module>', 'Module folder name (project mode).', 'entry')\n .option('--ability <name>', 'Explicit ability to launch (defaults to the module mainElement in project mode, or the installed bundle main ability in --bundle mode).')\n .option('--device <serial>', 'Target device serial.');\n addSmokeOptions(launch)\n .option('--json', 'With --smoke: emit `{ bundle, smoke }` as JSON.')\n .action(async (projectDir: string | undefined, opts: LaunchOpts) => {\n const { config, logger } = getRuntime();\n const { bundle, smoke } = await launchWithSmoke({ config, logger }, { ...opts, projectDir });\n if (!smoke) return;\n if (opts.json) process.stdout.write(`${JSON.stringify({ bundle, smoke }, null, 2)}\\n`);\n else process.stdout.write(`${formatSmoke(smoke)}\\n`);\n if (!smoke.passed) process.exitCode = 1;\n });\n\n const apply = app\n .command('apply [project-dir-or-hap]')\n .description(\n 'Install a HAP (a project dir, default the current one, or a .hap file) and verify the running process ' +\n 'took the change. Refuses a HAP of another bundle. Handles sign-info mismatch, asset-cache invalidation, ' +\n 'and persistent-bundle restart.',\n )\n .option(\n '--bundle <bundle>',\n 'Bundle name to apply changes to. Defaults to the bundleName in the .hap file, else in the project AppScope/app.json5.',\n )\n .option('--module <module>', 'Module to resolve the HAP from (multi-module projects).')\n .option('--hap <path>', 'Explicit .hap path (relative to project-dir or absolute).')\n .option('--installed-hap <path>', 'Local path to the currently-installed HAP, to enable the asset-cache reboot.')\n .option('--system', 'Treat as a persistent/system bundle (refuses uninstall on sign-info mismatch).')\n .option('--allow-uninstall', 'Permit uninstalling a system bundle on sign-info mismatch (dangerous).')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Emit the result as JSON (with --smoke, plus a `smoke` object).');\n addSmokeOptions(apply)\n .action(async (target: string | undefined, opts: ApplyOpts) => {\n const { config, logger } = getRuntime();\n const report = await applyWithSmoke({ config, logger }, { ...opts, target });\n const { smoke, ...result } = report;\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else {\n logger.info(\n `apply: method=${result.method} pid ${result.preInstallPid ?? '-'} -> ${result.postInstallPid ?? '-'}` +\n `${result.cacheCleared ? ' (cache cleared)' : ''}`,\n );\n if (smoke) process.stdout.write(`${formatSmoke(smoke)}\\n`);\n }\n if (smoke && !smoke.passed) process.exitCode = 1;\n });\n\n app\n .command('uninstall <bundle>')\n .description('Uninstall an app by bundle name.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (bundle: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await uninstallApp({ config, bundle, deviceSerial: opts.device, logger });\n logger.info(`Uninstalled ${bundle}.`);\n });\n\n app\n .command('stop <bundle>')\n .description('Force-stop an app by bundle name.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (bundle: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await forceStop({ config, bundle, deviceSerial: opts.device, logger });\n logger.info(`Stopped ${bundle}.`);\n });\n\n registerAppVerifyCommand(app);\n}\n","import sharp from 'sharp';\nimport { compareImages, type GreyImage, type ImageComparison } from '@oniroproject/core';\n\n/**\n * Agent-facing screenshot image processing for the CLI.\n *\n * `@oniroproject/core` deliberately ships no image dependency — it returns raw\n * JPEG buffers. The grid overlay / downscale and the burst contact-sheet live\n * here (the CLI is the affordance layer), so `oniro-app screenshot` can produce\n * exactly what the ohos-hdc MCP used to. The grid drawing is ported verbatim\n * from that MCP so the output is equivalent.\n */\n\nexport interface RenderResult {\n /** Encoded JPEG. */\n buf: Buffer;\n /** Rendered (post-downscale) dimensions. */\n width: number;\n height: number;\n /** Source dimensions, before downscale. */\n originalWidth: number;\n originalHeight: number;\n}\n\nexport interface RenderWithGridOptions {\n /** Longest-side cap in pixels. The image is downscaled (never upscaled) to fit. */\n maxDim: number;\n /** Overlay the 10x10 grid with 0.0–1.0 axis labels after downscaling. */\n grid?: boolean;\n}\n\n/**\n * Build an SVG overlay: a 10x10 grid with X/Y axis labels (0.0–1.0) sized to the\n * given image dimensions. Ported verbatim from the ohos-hdc MCP so the gridded\n * output matches what agents are used to.\n */\nexport function buildGridSvg(width: number, height: number): string {\n const lineColor = 'rgba(255,80,80,0.55)';\n const labelBg = 'rgba(0,0,0,0.7)';\n const labelFg = '#fff';\n const fontSize = Math.max(10, Math.round(Math.min(width, height) / 60));\n const padding = Math.round(fontSize * 0.4);\n const labels: string[] = [];\n const lines: string[] = [];\n for (let i = 0; i <= 10; i++) {\n const f = i / 10;\n const x = Math.round(f * (width - 1));\n const y = Math.round(f * (height - 1));\n // grid lines (skip 0 and 10 — those are the image edges)\n if (i > 0 && i < 10) {\n lines.push(`<line x1=\"${x}\" y1=\"0\" x2=\"${x}\" y2=\"${height}\" stroke=\"${lineColor}\" stroke-width=\"1\"/>`);\n lines.push(`<line x1=\"0\" y1=\"${y}\" x2=\"${width}\" y2=\"${y}\" stroke=\"${lineColor}\" stroke-width=\"1\"/>`);\n }\n const tag = f.toFixed(1);\n // X-axis labels along the top\n const tx = i === 0 ? padding : i === 10 ? width - padding : x;\n const anchorX = i === 0 ? 'start' : i === 10 ? 'end' : 'middle';\n labels.push(\n `<text x=\"${tx}\" y=\"${fontSize + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"${anchorX}\">${tag}</text>`,\n );\n // Y-axis labels along the left\n const ty = i === 0 ? fontSize + padding : i === 10 ? height - padding : y + fontSize / 3;\n labels.push(\n `<text x=\"${padding}\" y=\"${ty}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">${tag}</text>`,\n );\n }\n // Axis title markers in the corners\n labels.push(\n `<text x=\"${width / 2}\" y=\"${fontSize * 2.4 + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"middle\">X →</text>`,\n );\n labels.push(\n `<text x=\"${padding}\" y=\"${fontSize * 2.6 + padding}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"${labelFg}\" stroke=\"${labelBg}\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">Y ↓</text>`,\n );\n return `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">${lines.join('')}${labels.join('')}</svg>`;\n}\n\n/**\n * Downscale a JPEG so its longest side is <= `maxDim` (never upscaling) and,\n * when `grid` is set, overlay the coordinate grid. Returns the encoded JPEG plus\n * rendered and original dimensions.\n */\nexport async function renderWithGrid(jpeg: Buffer, opts: RenderWithGridOptions): Promise<RenderResult> {\n const meta = await sharp(jpeg).metadata();\n const originalWidth = meta.width ?? 0;\n const originalHeight = meta.height ?? 0;\n const longest = Math.max(originalWidth, originalHeight) || 1;\n const scale = Math.min(1, opts.maxDim / longest);\n const width = Math.max(1, Math.round(originalWidth * scale));\n const height = Math.max(1, Math.round(originalHeight * scale));\n const resized = await sharp(jpeg).resize(width, height).jpeg({ quality: 80 }).toBuffer();\n if (!opts.grid) {\n return { buf: resized, width, height, originalWidth, originalHeight };\n }\n const svg = buildGridSvg(width, height);\n const buf = await sharp(resized)\n .composite([{ input: Buffer.from(svg) }])\n .jpeg({ quality: 80 })\n .toBuffer();\n return { buf, width, height, originalWidth, originalHeight };\n}\n\n/** A region as [x1, y1, x2, y2] fractions (0–1) of the image. */\nexport type CropRect = [number, number, number, number];\n\n/** Parse `\"x1,y1,x2,y2\"` (0–1 fractions, x1<x2, y1<y2) into a {@link CropRect}. */\nexport function parseCropRect(spec: string): CropRect {\n const parts = spec.split(',').map((s) => Number(s.trim()));\n if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0 || n > 1)) {\n throw new Error(`--crop expects four 0-1 fractions \"x1,y1,x2,y2\"; got \"${spec}\".`);\n }\n const [x1, y1, x2, y2] = parts as CropRect;\n if (!(x2 > x1 && y2 > y1)) throw new Error(`--crop needs x1 < x2 and y1 < y2; got \"${spec}\".`);\n return [x1, y1, x2, y2];\n}\n\n/** Grow a rect by `pad` (a fraction) on every side, clamped to 0–1. */\nexport function padCropRect(r: CropRect, pad: number): CropRect {\n return [Math.max(0, r[0] - pad), Math.max(0, r[1] - pad), Math.min(1, r[2] + pad), Math.min(1, r[3] + pad)];\n}\n\nexport interface CropResult {\n /** Encoded JPEG. */\n buf: Buffer;\n /** Rendered (post-downscale) dimensions. */\n width: number;\n height: number;\n /** The cropped region in source pixels. */\n left: number;\n top: number;\n cropWidth: number;\n cropHeight: number;\n}\n\n/**\n * Crop a JPEG to a 0–1 region at full resolution, then downscale so the longest\n * side is <= `maxDim` (never upscaling). Detail where it is needed, at a\n * fraction of a full-resolution screenshot's size.\n */\nexport async function cropImage(jpeg: Buffer, rect: CropRect, opts: { maxDim: number }): Promise<CropResult> {\n const meta = await sharp(jpeg).metadata();\n const w = meta.width ?? 1;\n const h = meta.height ?? 1;\n const left = Math.min(w - 1, Math.floor(rect[0] * w));\n const top = Math.min(h - 1, Math.floor(rect[1] * h));\n const cropWidth = Math.max(1, Math.min(w, Math.ceil(rect[2] * w)) - left);\n const cropHeight = Math.max(1, Math.min(h, Math.ceil(rect[3] * h)) - top);\n const scale = Math.min(1, opts.maxDim / Math.max(cropWidth, cropHeight));\n const width = Math.max(1, Math.round(cropWidth * scale));\n const height = Math.max(1, Math.round(cropHeight * scale));\n const buf = await sharp(jpeg)\n .extract({ left, top, width: cropWidth, height: cropHeight })\n .resize(width, height)\n .jpeg({ quality: 85 })\n .toBuffer();\n return { buf, width, height, left, top, cropWidth, cropHeight };\n}\n\nexport interface ContactSheetOptions {\n /** Longest-side cap for the whole sheet; per-tile size derives from this. */\n maxDim: number;\n /** Tiles per row. Defaults to ceil(sqrt(N)). */\n cols?: number;\n /** Per-frame diff (0..1), index-aligned with `frames`; printed on each tile. */\n diffs?: number[];\n /** Gap between tiles, px. */\n gap?: number;\n}\n\nexport interface ContactSheetResult {\n buf: Buffer;\n width: number;\n height: number;\n cols: number;\n rows: number;\n tileWidth: number;\n tileHeight: number;\n count: number;\n}\n\nfunction buildTileLabelSvg(width: number, height: number, idx: number, diff?: number): string {\n const fontSize = Math.max(12, Math.round(Math.min(width, height) / 16));\n const pad = Math.round(fontSize * 0.4);\n let label = `#${idx}`;\n if (typeof diff === 'number') label += ` Δ${diff.toFixed(2)}`;\n const boxW = Math.round(label.length * fontSize * 0.62) + pad * 2;\n const boxH = fontSize + pad * 2;\n return (\n `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">` +\n `<rect x=\"0\" y=\"0\" width=\"${boxW}\" height=\"${boxH}\" fill=\"rgba(0,0,0,0.6)\"/>` +\n `<text x=\"${pad}\" y=\"${fontSize + pad - 1}\" font-family=\"monospace\" font-size=\"${fontSize}\" font-weight=\"bold\" fill=\"#fff\" stroke=\"rgba(0,0,0,0.85)\" stroke-width=\"3\" paint-order=\"stroke\" text-anchor=\"start\">${label}</text>` +\n `</svg>`\n );\n}\n\n/**\n * Composite a burst of JPEG frames into a single tiled contact sheet, each tile\n * labelled with its frame index (and per-frame diff when provided). One image\n * replaces N — a large token saving when verifying transient UI.\n */\nexport async function buildContactSheet(frames: Buffer[], opts: ContactSheetOptions): Promise<ContactSheetResult> {\n if (frames.length === 0) throw new Error('buildContactSheet: no frames');\n const count = frames.length;\n const cols = Math.max(1, opts.cols ?? Math.ceil(Math.sqrt(count)));\n const rows = Math.ceil(count / cols);\n const gap = opts.gap ?? 8;\n\n const meta0 = await sharp(frames[0]).metadata();\n const fw = meta0.width ?? 1;\n const fh = meta0.height ?? 1;\n const longest = Math.max(fw, fh) || 1;\n const tileScale = Math.min(1, opts.maxDim / cols / longest);\n const tileWidth = Math.max(1, Math.round(fw * tileScale));\n const tileHeight = Math.max(1, Math.round(fh * tileScale));\n\n const tiles = await Promise.all(\n frames.map((frame, i) => {\n const label = Buffer.from(buildTileLabelSvg(tileWidth, tileHeight, i, opts.diffs?.[i]));\n return sharp(frame)\n .resize(tileWidth, tileHeight, { fit: 'fill' })\n .composite([{ input: label, top: 0, left: 0 }])\n .png()\n .toBuffer();\n }),\n );\n\n const width = cols * tileWidth + (cols + 1) * gap;\n const height = rows * tileHeight + (rows + 1) * gap;\n const placements = tiles.map((input, i) => {\n const r = Math.floor(i / cols);\n const c = i % cols;\n return { input, left: gap + c * (tileWidth + gap), top: gap + r * (tileHeight + gap) };\n });\n\n const buf = await sharp({\n create: { width, height, channels: 3, background: { r: 20, g: 20, b: 20 } },\n })\n .composite(placements)\n .jpeg({ quality: 80 })\n .toBuffer();\n\n return { buf, width, height, cols, rows, tileWidth, tileHeight, count };\n}\n\n/**\n * Per-frame change metric: mean absolute difference of a downscaled greyscale\n * thumbnail vs. the previous frame, normalised to 0..1. Frame 0 is 0 (no\n * predecessor). Cheap, deterministic, and device-free.\n */\nexport async function frameDiffs(frames: Buffer[], opts: { sample?: number } = {}): Promise<number[]> {\n if (frames.length === 0) return [];\n const sample = opts.sample ?? 32;\n const thumbs = await Promise.all(\n frames.map((f) => sharp(f).greyscale().resize(sample, sample, { fit: 'fill' }).raw().toBuffer()),\n );\n const out: number[] = [0];\n for (let i = 1; i < thumbs.length; i++) {\n const a = thumbs[i - 1];\n const b = thumbs[i];\n if (!a || !b) {\n out.push(0);\n continue;\n }\n const n = Math.min(a.length, b.length) || 1;\n let s = 0;\n for (let k = 0; k < n; k++) s += Math.abs((a[k] ?? 0) - (b[k] ?? 0));\n out.push(+(s / n / 255).toFixed(4));\n }\n return out;\n}\n\n/**\n * Decode a JPEG to 8-bit greyscale, downscaled (never upscaled) so its longest\n * side is at most `maxDim` — the input core's image hashes and blank check\n * expect ({@link GreyImage}).\n */\nexport async function decodeGreyscale(jpeg: Buffer, maxDim = 512): Promise<GreyImage> {\n const { data, info } = await sharp(jpeg)\n .greyscale()\n .resize(maxDim, maxDim, { fit: 'inside', withoutEnlargement: true })\n .raw()\n .toBuffer({ resolveWithObject: true });\n const n = info.width * info.height;\n const grey = new Uint8Array(n);\n // One channel for an opaque JPEG; an alpha channel, if any, rides along after the grey one.\n for (let i = 0; i < n; i++) grey[i] = data[i * info.channels]!;\n return { width: info.width, height: info.height, data: grey };\n}\n\nexport interface ScreenshotDiff extends ImageComparison {\n /** Mean absolute greyscale difference, 0-1 (the `--contact-sheet` per-frame change metric). */\n meanDiff: number;\n}\n\n/** Compare a baseline screenshot with a current one: pHash/dHash distances, pixel-change ratio, mean change. */\nexport async function diffScreenshots(baseline: Buffer, current: Buffer): Promise<ScreenshotDiff> {\n const [a, b] = await Promise.all([decodeGreyscale(baseline), decodeGreyscale(current)]);\n const [, meanDiff] = await frameDiffs([baseline, current]);\n return { ...compareImages(a, b), meanDiff: meanDiff ?? 0 };\n}\n","import type { Command } from 'commander';\nimport { formatHapVerification, verifyHap, verifyHapExitCode } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** `app verify <hap>`: what signed a HAP, and whether a device will accept it. */\nexport function registerAppVerifyCommand(app: Command): void {\n app\n .command('verify <hap>')\n .description(\n \"Verify a HAP's signature with the SDK's hap-sign-tool (`verify-app`), then report what signed it: the \" +\n 'certificate chain and its root, whether it is OpenHarmony development material or a HarmonyOS ' +\n 'certificate from AppGallery Connect (root Huawei CBG Root CA G2), and the provisioning profile: type, ' +\n 'bundle name, apl, app-feature, devices, validity and days left. Exits 0 when valid, 1 when unsigned, ' +\n 'invalid, expired or mismatched, 2 when it could not verify (no java or hap-sign-tool.jar). Needs java.',\n )\n .option('--json', 'Emit the result as JSON.')\n .action(async (hap: string, opts: { json?: boolean }) => {\n const { config, logger } = getRuntime();\n const result = await verifyHap({ hapPath: hap, config, logger });\n process.stdout.write(opts.json ? `${JSON.stringify(result, null, 2)}\\n` : formatHapVerification(result));\n process.exitCode = verifyHapExitCode(result);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n ALL_SDKS,\n createScaffold,\n isValidBundleName,\n isValidProjectName,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { getBundledTemplateRoot } from '../lib/templateRoot.js';\n\ninterface CreateOpts {\n name: string;\n bundle: string;\n location: string;\n sdk: string;\n template: string;\n module?: string;\n overwrite?: boolean;\n}\n\nexport function registerCreateCommand(program: Command): void {\n program\n .command('create')\n .description('Scaffold a new Oniro/OpenHarmony or HarmonyOS app from a template. All flags are required (non-interactive).')\n .requiredOption('--name <name>', 'Project folder name (letters, digits, ._- only)')\n .requiredOption('--bundle <bundleName>', 'Bundle name in reverse-DNS form, e.g. com.example.myapp')\n .requiredOption('--location <dir>', 'Parent directory where the new project folder will be created')\n .requiredOption('--sdk <api>', 'Target SDK API level (e.g. 18, 20)')\n .option('--template <id>', 'Template id', 'EmptyAbility')\n .option('--module <name>', 'Module folder name (defaults to the template default, usually `entry`)')\n .option('--overwrite', 'Replace the destination if it already exists')\n .action(async (opts: CreateOpts) => {\n const { config, logger } = getRuntime();\n\n if (!isValidProjectName(opts.name)) {\n throw new Error(`Invalid --name '${opts.name}'. Use letters/numbers/._- and no slashes.`);\n }\n if (!isValidBundleName(opts.bundle)) {\n throw new Error(`Invalid --bundle '${opts.bundle}'. Example: com.example.myapp`);\n }\n const sdkApi = Number(opts.sdk);\n if (!Number.isFinite(sdkApi)) {\n throw new Error(`--sdk must be a numeric api level. Known: ${ALL_SDKS.map((s) => s.api).join(', ')}`);\n }\n\n const templateRoot = getBundledTemplateRoot();\n const result = await createScaffold({\n config,\n templateId: opts.template,\n projectName: opts.name,\n bundleName: opts.bundle,\n location: path.resolve(opts.location),\n sdkApi,\n moduleName: opts.module,\n templateRoot,\n overwrite: opts.overwrite,\n logger,\n });\n\n logger.info(`Project created at ${result.projectDir}`);\n process.stdout.write(`${result.projectDir}\\n`);\n });\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Resolve the bundled `templates/` directory shipped inside this CLI package.\n *\n * The CLI's `dist/oniro-app.js` lives at `<pkg>/dist/oniro-app.js` after build\n * and the templates ship at `<pkg>/templates/`. During development the entrypoint\n * lives at `<pkg>/src/bin/oniro-app.ts` so we also try `../../templates` from there.\n */\nexport function getBundledTemplateRoot(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n path.resolve(here, '../templates'), // dist/oniro-app.js → ../templates\n path.resolve(here, '../../templates'), // src/bin/oniro-app.ts → ../../templates\n ];\n for (const c of candidates) {\n if (fs.existsSync(c)) return c;\n }\n // Return the most likely path even if it doesn't exist yet; createScaffold will\n // surface a clear error from there.\n return candidates[0]!;\n}\n","import { Command } from 'commander';\nimport { listTemplates } from '@oniroproject/core';\nimport { getBundledTemplateRoot } from '../lib/templateRoot.js';\n\nexport function registerTemplatesCommand(program: Command): void {\n const templates = program.command('templates').description('Inspect the templates bundled with this CLI.');\n\n templates\n .command('list')\n .description('List available project templates.')\n .option('--json', 'Emit machine-readable JSON.')\n .action((opts: { json?: boolean }) => {\n const root = getBundledTemplateRoot();\n const list = listTemplates(root);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(list, null, 2)}\\n`);\n return;\n }\n if (list.length === 0) {\n process.stdout.write('No templates available.\\n');\n return;\n }\n const rows = list.map((t) => `${t.id.padEnd(20)} ${t.label.padEnd(24)} ${t.description}`);\n process.stdout.write(`${rows.join('\\n')}\\n`);\n });\n}\n","import { Command, Option } from 'commander';\nimport { reboot } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerRebootCommand(program: Command): void {\n program\n .command('reboot')\n .description('Reboot the connected device/emulator.')\n .addOption(\n new Option('--mode <mode>', 'Reboot target.').choices(['system', 'bootloader', 'recovery']).default('system'),\n )\n .option('--wait-bundle <bundle>', 'After a system reboot, wait until this bundle is running again.')\n .option('--timeout <ms>', 'Max time to wait for the bundle, ms.', '180000')\n .option('--device <serial>', 'Target device serial.')\n .action(\n async (opts: {\n mode: 'system' | 'bootloader' | 'recovery';\n waitBundle?: string;\n timeout: string;\n device?: string;\n }) => {\n const { config, logger } = getRuntime();\n logger.info(`Rebooting device (${opts.mode})...`);\n await reboot({\n config,\n mode: opts.mode,\n waitForBundle: opts.waitBundle,\n timeoutMs: Number(opts.timeout),\n deviceSerial: opts.device,\n logger,\n });\n logger.info('Reboot complete.');\n },\n );\n}\n","import { Command } from 'commander';\nimport { waitForLog, waitForBoot, waitForBundle, waitForTarget, describeLayoutNode } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { addTargetOptions, selectorFrom, windowIdFrom, type TargetOpts } from '../lib/target.js';\nimport { parseSince } from '../lib/logSince.js';\n\ninterface WaitOpts extends TargetOpts {\n log?: string;\n since?: string;\n boot?: boolean;\n bundle?: string;\n pidOf?: string;\n domain?: string;\n gone?: boolean;\n interval: string;\n timeout: string;\n device?: string;\n json?: boolean;\n}\n\nexport function registerWaitCommand(program: Command): void {\n const wait = program\n .command('wait')\n .description(\n 'Wait for a device condition: a log line (--log), boot (--boot), a bundle to start (--bundle), ' +\n 'or an on-screen element (--target / --target-id / --target-type, or --selector).',\n )\n .option('--log <pattern>', 'Resolve when a hilog line (tag: message) logged after the command starts matches this regex.')\n .option(\n '--since <seconds>',\n 'With --log: also match lines logged up to N seconds before the command started, ' +\n 'measured on the device clock; \"all\" matches everything still in the device log buffer.',\n )\n .option('--boot', 'Resolve when the device is reachable (optionally also --pid-of).')\n .option('--bundle <bundle>', 'With --log: filter to this bundle. Alone: wait until this bundle is running.')\n .option('--pid-of <name>', 'With --boot: also require this process to have a pid.')\n .option('--domain <domain>', 'With --log: hilog domain filter (e.g. 0xD003900).');\n addTargetOptions(wait, 'Resolve when', { index: false });\n wait\n .option('--gone', 'With --target* or --selector: resolve when no uncovered element matches any more.')\n .option('--interval <ms>', 'With --target* or --selector: poll interval, ms (each poll is a layout dump).', '500')\n .option('--timeout <ms>', 'Max wait, ms.', '30000')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'With --log, --target* or --selector: emit the matched entry/element as JSON.')\n .action(async (opts: WaitOpts) => {\n const { config, logger } = getRuntime();\n const timeoutMs = Number(opts.timeout);\n const selector = selectorFrom(opts);\n const windowId = windowIdFrom(opts);\n if (opts.since !== undefined && !opts.log) throw new Error('--since applies only to --log.');\n if (windowId !== undefined && !selector) throw new Error('--window applies only to --target* and --selector.');\n\n if (opts.log) {\n const entry = await waitForLog({\n config,\n pattern: new RegExp(opts.log),\n timeoutMs,\n bundle: opts.bundle,\n domain: opts.domain,\n deviceSerial: opts.device,\n lookbackMs: parseSince(opts.since),\n logger,\n });\n if (opts.json) process.stdout.write(`${JSON.stringify(entry, null, 2)}\\n`);\n else logger.info(`matched: ${entry.time} ${entry.tag}: ${entry.message}`);\n return;\n }\n if (opts.boot) {\n await waitForBoot({ config, untilPidOf: opts.pidOf, timeoutMs, deviceSerial: opts.device, logger });\n logger.info('Device booted.');\n return;\n }\n if (selector) {\n const node = await waitForTarget({\n config,\n selector,\n gone: opts.gone,\n windowId,\n timeoutMs,\n pollMs: Number(opts.interval) || 500,\n deviceSerial: opts.device,\n logger,\n });\n if (!node) {\n logger.info('Element is gone.');\n return;\n }\n if (opts.json) process.stdout.write(`${JSON.stringify(node, null, 2)}\\n`);\n else logger.info(`found: ${describeLayoutNode(node)}`);\n return;\n }\n if (opts.bundle) {\n await waitForBundle({ config, bundle: opts.bundle, timeoutMs, deviceSerial: opts.device, logger });\n logger.info(`Bundle ${opts.bundle} is running.`);\n return;\n }\n throw new Error(\n 'Specify one of --log <pattern>, --boot, --bundle <bundle>, --target <text> (or --target-id / --target-type), or --selector <expr>.',\n );\n });\n}\n","import type { Command } from 'commander';\nimport { parseSelector, type ElementQuery, type ElementSelector } from '@oniroproject/core';\n\n/** The shared element-selector flags, as commander parses them. */\nexport interface TargetOpts {\n target?: string;\n targetId?: string;\n targetType?: string;\n targetIndex?: string;\n selector?: string;\n window?: string;\n}\n\n/** Help text for `--selector`, shared by every command that takes it. */\nexport const SELECTOR_HELP =\n 'An attribute selector such as \"type=Button,text*=Sign\" (keys text, desc, hint, id, key, type, enabled, focused, ' +\n 'checked, selected, visible, clickable, longClickable, checkable, scrollable; operators = *= ^= $= /=regex; ' +\n 'a [n] suffix picks the n-th match, 0-based, [-1] or [last] the last), or \"xpath=//Button[@text=\\'OK\\']\".';\n\nexport const WINDOW_HELP =\n 'Restrict to one window: a window id from `dump layout --flat` ([window <id> …]) or `dump windows`.';\n\n/**\n * Add the element-selector flags shared by `input`, `wait`, and `screenshot`.\n * `verb` completes the `--target` help text (e.g. \"Tap\" → \"Tap the element …\").\n */\nexport function addTargetOptions(cmd: Command, verb: string, opts: { index?: boolean } = {}): Command {\n cmd\n .option(\n '--target <text>',\n `${verb} the element whose text, description, or placeholder matches ` +\n '(case-insensitive; exact matches win, else substring). Covered elements are skipped.',\n )\n .option('--target-id <id>', 'Match the element by its id or key.')\n .option('--target-type <type>', 'Restrict the match to a component type (e.g. Button, TextInput).');\n if (opts.index !== false) {\n cmd.option('--target-index <n>', 'Pick the n-th (0-based) of several matching elements.');\n }\n cmd.option('--selector <expr>', `Instead of --target*: ${SELECTOR_HELP}`).option('--window <id>', WINDOW_HELP);\n return cmd;\n}\n\n/** Parse `--selector` text; undefined when the flag is absent. */\nexport function parseSelectorOption(raw: string | undefined): ElementSelector | undefined {\n return raw === undefined ? undefined : parseSelector(raw);\n}\n\n/** The selector built from the flags, or undefined when none was given. */\nexport function selectorFrom(opts: TargetOpts): ElementQuery | undefined {\n const plain = opts.target !== undefined || opts.targetId !== undefined || opts.targetType !== undefined;\n if (opts.selector !== undefined) {\n if (plain) throw new Error('Use either --selector or --target / --target-id / --target-type, not both.');\n if (opts.targetIndex !== undefined) throw new Error('--target-index does not apply to --selector; append [n] to the selector.');\n return parseSelector(opts.selector);\n }\n if (!plain) return undefined;\n return { text: opts.target, id: opts.targetId, type: opts.targetType };\n}\n\nexport function targetIndexFrom(opts: TargetOpts): number | undefined {\n if (opts.targetIndex === undefined) return undefined;\n const n = Number(opts.targetIndex);\n if (!Number.isInteger(n) || n < 0) throw new Error(`--target-index must be a non-negative integer; got ${opts.targetIndex}.`);\n return n;\n}\n\n/** The `--window` id, or undefined when the flag is absent. */\nexport function windowIdFrom(opts: { window?: string }): number | undefined {\n if (opts.window === undefined) return undefined;\n const n = Number(opts.window);\n if (!Number.isInteger(n) || n < 0) throw new Error(`--window must be a window id (a non-negative integer); got ${opts.window}.`);\n return n;\n}\n","/**\n * Parse a `--since` value for `wait --log` and `watch`: how many seconds before\n * the command started a log line may be from and still count, or `all` for\n * everything still in the device buffer. Returns ms; undefined when not given.\n */\nexport function parseSince(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (value === 'all') return Infinity;\n const seconds = Number(value);\n if (value.trim() === '' || !Number.isFinite(seconds) || seconds < 0) {\n throw new Error(`--since takes a number of seconds or \"all\", not \"${value}\".`);\n }\n return seconds * 1000;\n}\n","import { Command } from 'commander';\nimport { watchLog } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { parseSince } from '../lib/logSince.js';\n\ninterface WatchOpts {\n log?: string;\n for: string;\n since?: string;\n bundle?: string;\n domain?: string;\n dedup: boolean;\n device?: string;\n json?: boolean;\n}\n\nexport function registerWatchCommand(program: Command): void {\n program\n .command('watch')\n .description('Collect the hilog lines matching a pattern that are logged during a fixed duration.')\n .option('--log <pattern>', 'Regex tested against each line (tag: message).')\n .option('--for <ms>', 'Duration to watch, ms.', '10000')\n .option(\n '--since <seconds>',\n 'Also collect lines logged up to N seconds before the command started, measured on the device clock; ' +\n '\"all\" adds everything still in the device log buffer.',\n )\n .option('--bundle <bundle>', 'Filter to this bundle.')\n .option('--domain <domain>', 'hilog domain filter (e.g. 0xD003900).')\n .option('--no-dedup', 'Do not collapse consecutive duplicate lines.')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Emit the entries as JSON.')\n .action(async (opts: WatchOpts) => {\n const { config, logger } = getRuntime();\n if (!opts.log) throw new Error('watch requires --log <pattern>.');\n const entries = await watchLog({\n config,\n pattern: new RegExp(opts.log),\n durationMs: Number(opts.for),\n bundle: opts.bundle,\n domain: opts.domain,\n dedup: opts.dedup,\n deviceSerial: opts.device,\n lookbackMs: parseSince(opts.since),\n logger,\n });\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(entries, null, 2)}\\n`);\n } else {\n for (const e of entries) process.stdout.write(`${e.time} ${e.level} ${e.tag}: ${e.message}\\n`);\n }\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { takeScreenshot, captureBurst, locateTarget, describeLayoutNode, dumpLayout, listLayoutWindows } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport {\n renderWithGrid,\n buildContactSheet,\n frameDiffs,\n cropImage,\n diffScreenshots,\n parseCropRect,\n padCropRect,\n type CropRect,\n} from '../lib/screenshotImage.js';\nimport { addTargetOptions, selectorFrom, targetIndexFrom, windowIdFrom, type TargetOpts } from '../lib/target.js';\n\ninterface ScreenshotOpts extends TargetOpts {\n output: string;\n grid?: boolean;\n maxDim: string;\n crop?: string;\n contactSheet?: boolean;\n burst?: string;\n interval: string;\n json?: boolean;\n diff?: string;\n device?: string;\n}\n\nconst DEFAULT_CONTACT_SHEET_FRAMES = 8;\n// Margin kept around a --target element when cropping to it, as a fraction of the display.\nconst TARGET_CROP_PAD = 0.02;\n\nfunction clampMaxDim(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n)) return 1024;\n return Math.max(256, Math.min(4096, Math.round(n)));\n}\n\nexport function registerScreenshotCommand(program: Command): void {\n const screenshot = program\n .command('screenshot')\n .description(\n 'Capture the screen. Default: full-resolution raw JPEG. ' +\n '--grid: downscaled JPEG with a 10x10 grid (axes 0.0-1.0) for picking tap coordinates. ' +\n '--crop / --target / --selector / --window: a full-resolution crop of one region, element or window, ' +\n 'for checking detail cheaply. ' +\n '--contact-sheet: capture a burst and tile it into one image with per-frame change diffs. ' +\n '--diff: compare the screen with a baseline JPEG (perceptual-hash distance, pixel-change ratio).',\n )\n .option('-o, --output <file>', 'Output file path.', 'screenshot.jpeg')\n .option('--grid', 'Downscale (to --max-dim) and overlay a 10x10 coordinate grid.')\n .option('--max-dim <px>', 'Longest-side cap for --grid / --crop / --target / --contact-sheet (256-4096).', '1024')\n .option('--crop <x1,y1,x2,y2>', 'Crop to this region, given as 0-1 fractions of the screen.');\n addTargetOptions(screenshot, 'Crop to');\n screenshot\n .option('--contact-sheet', 'Capture a burst and composite it into one tiled contact sheet.')\n .option('--burst <count>', 'Capture N frames; writes <base>-<i><ext> (or feeds --contact-sheet).')\n .option('--interval <ms>', 'Delay between burst frames, ms.', '50')\n .option(\n '--diff <baseline.jpeg>',\n 'Capture the screen (written to --output) and compare it with this baseline: pHash and dHash distance, ' +\n 'pixel-change ratio, mean change.',\n )\n .option('--json', 'Emit the full result object as JSON on stdout (with --contact-sheet or --diff).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: ScreenshotOpts, command: Command) => {\n const { config, logger } = getRuntime();\n const maxDim = clampMaxDim(opts.maxDim);\n const intervalMs = Number(opts.interval) || 50;\n\n const selector = selectorFrom(opts);\n const windowId = windowIdFrom(opts);\n\n // --- Diff: the screen now against a baseline ---\n if (opts.diff !== undefined) {\n if (opts.crop !== undefined || selector || windowId !== undefined || opts.grid || opts.contactSheet || opts.burst) {\n throw new Error(\n '--diff cannot be combined with --crop, --target* / --selector / --window, --grid, --contact-sheet, or --burst.',\n );\n }\n let baseline: Buffer;\n try {\n baseline = fs.readFileSync(opts.diff);\n } catch (err) {\n throw new Error(`Cannot read the baseline ${opts.diff}: ${(err as Error).message}`);\n }\n const shot = await takeScreenshot({ config, deviceSerial: opts.device, logger });\n fs.writeFileSync(opts.output, shot.pixels);\n const diff = await diffScreenshots(baseline, shot.pixels);\n const result = { baseline: opts.diff, current: opts.output, ...diff };\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n } else {\n process.stdout.write(\n `${diff.same ? 'same' : 'different'}: pHash ${diff.phashDistance}/64, dHash ${diff.dhashDistance}/64, ` +\n `${(diff.pixelChangeRatio * 100).toFixed(2)}% of pixels changed, mean change ${diff.meanDiff.toFixed(4)}` +\n `${diff.sizeMismatch ? ' (sizes differ)' : ''}\\n`,\n );\n }\n logger.info(`Wrote ${opts.output} (${shot.width}x${shot.height}).`);\n return;\n }\n\n // --- Crop: one region, element or window at full resolution ---\n if (opts.crop !== undefined || selector || windowId !== undefined) {\n if (opts.crop !== undefined && (selector || windowId !== undefined)) {\n throw new Error('Use either --crop or --target* / --selector / --window, not both.');\n }\n if (opts.grid || opts.contactSheet || opts.burst) {\n throw new Error('--crop / --target / --selector / --window cannot be combined with --grid, --contact-sheet, or --burst.');\n }\n let rect: CropRect;\n let label: string;\n if (selector) {\n // Leave the keyboard alone: dismissing it would change what we are capturing.\n const located = await locateTarget({\n config,\n selector,\n index: targetIndexFrom(opts),\n windowId,\n hideKeyboard: false,\n deviceSerial: opts.device,\n logger,\n });\n if (!located.node.b) throw new Error(`${describeLayoutNode(located.node)} has no bounds to crop to.`);\n rect = padCropRect(located.node.b, TARGET_CROP_PAD);\n label = describeLayoutNode(located.node);\n } else if (windowId !== undefined) {\n const { tree } = await dumpLayout({ config, windowId, deviceSerial: opts.device, logger });\n const win = listLayoutWindows(tree).find((w) => w.windowId === windowId);\n if (!win?.b) throw new Error(`Window ${windowId} has no bounds to crop to.`);\n rect = win.b;\n label = `window ${windowId}${win.bundle ? ` (${win.bundle})` : ''}`;\n } else {\n rect = parseCropRect(opts.crop!);\n label = rect.map((n) => n.toFixed(3)).join(',');\n }\n const shot = await takeScreenshot({ config, deviceSerial: opts.device, logger });\n const cropped = await cropImage(shot.pixels, rect, { maxDim });\n fs.writeFileSync(opts.output, cropped.buf);\n logger.info(\n `Wrote ${opts.output} (${cropped.width}x${cropped.height} from a ${cropped.cropWidth}x${cropped.cropHeight} ` +\n `crop at ${cropped.left},${cropped.top}: ${label}).`,\n );\n return;\n }\n\n // --- Contact sheet: burst -> one tiled image + per-frame diffs ---\n if (opts.contactSheet) {\n const count = opts.burst ? Math.max(1, Number(opts.burst)) : DEFAULT_CONTACT_SHEET_FRAMES;\n const frames = await captureBurst({ config, count, intervalMs, deviceSerial: opts.device, logger });\n const diffs = await frameDiffs(frames);\n const sheet = await buildContactSheet(frames, { maxDim, diffs });\n fs.writeFileSync(opts.output, sheet.buf);\n\n // Only fan out the individual raw frames when --burst was also requested.\n if (opts.burst) {\n const ext = path.extname(opts.output) || '.jpeg';\n const base = opts.output.slice(0, opts.output.length - ext.length);\n frames.forEach((frame, i) => fs.writeFileSync(`${base}-${i}${ext}`, frame));\n }\n\n const perFrame = frames.map((_, i) => ({ idx: i, t_ms: i * intervalMs, diffVsPrev: diffs[i] ?? 0 }));\n if (opts.json) {\n process.stdout.write(\n `${JSON.stringify(\n {\n sheet: opts.output,\n frameCount: frames.length,\n cols: sheet.cols,\n rows: sheet.rows,\n intervalMs,\n note: 't_ms is nominal (idx*interval); diffVsPrev is 0..1 mean greyscale diff vs the previous frame.',\n frames: perFrame,\n },\n null,\n 2,\n )}\\n`,\n );\n } else {\n process.stdout.write(`${JSON.stringify(perFrame)}\\n`);\n }\n\n let peak = 0;\n for (let i = 1; i < diffs.length; i++) if ((diffs[i] ?? 0) > (diffs[peak] ?? 0)) peak = i;\n logger.info(\n `Wrote contact sheet ${opts.output} (${sheet.cols}x${sheet.rows}, ${frames.length} frames). ` +\n `Biggest change at frame ${peak} (Δ${(diffs[peak] ?? 0).toFixed(2)}).`,\n );\n return;\n }\n\n // --- Burst (raw frames) — unchanged behaviour ---\n if (opts.burst) {\n const frames = await captureBurst({\n config,\n count: Number(opts.burst),\n intervalMs,\n deviceSerial: opts.device,\n logger,\n });\n const ext = path.extname(opts.output) || '.jpeg';\n const base = opts.output.slice(0, opts.output.length - ext.length);\n frames.forEach((frame, i) => fs.writeFileSync(`${base}-${i}${ext}`, frame));\n logger.info(`Wrote ${frames.length} frames to ${base}-<0..${frames.length - 1}>${ext}.`);\n return;\n }\n\n // --- Single shot ---\n const shot = await takeScreenshot({ config, deviceSerial: opts.device, logger });\n const maxDimProvided = command.getOptionValueSource('maxDim') === 'cli';\n if (opts.grid || maxDimProvided) {\n const rendered = await renderWithGrid(shot.pixels, { maxDim, grid: !!opts.grid });\n fs.writeFileSync(opts.output, rendered.buf);\n logger.info(\n `Wrote ${opts.output} (${rendered.width}x${rendered.height} from ` +\n `${rendered.originalWidth}x${rendered.originalHeight}${opts.grid ? ', 10x10 grid' : ''}).`,\n );\n return;\n }\n fs.writeFileSync(opts.output, shot.pixels);\n logger.info(`Wrote ${opts.output} (${shot.width}x${shot.height}).`);\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport {\n diffLayouts,\n dumpLayout,\n findLayoutNodes,\n listWindows,\n parseLayoutBaseline,\n selectableTree,\n summarizeLayout,\n type WindowInfo,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { formatFlatLayout, formatSelectorMatches } from '../lib/layoutText.js';\nimport { SELECTOR_HELP, WINDOW_HELP, parseSelectorOption, windowIdFrom } from '../lib/target.js';\n\ninterface DumpOpts {\n bundle?: string;\n raw?: boolean;\n flat?: boolean;\n summary?: boolean;\n diff?: string;\n selector?: string;\n window?: string;\n json?: boolean;\n device?: string;\n}\n\n/** Read a `dump layout` JSON file saved earlier. */\nfunction readBaseline(file: string): ReturnType<typeof parseLayoutBaseline> {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch (err) {\n throw new Error(`Cannot read the layout baseline ${file}: ${(err as Error).message}`);\n }\n try {\n return parseLayoutBaseline(JSON.parse(text));\n } catch (err) {\n throw new Error(`${file} is not a saved \\`dump layout\\` JSON: ${(err as Error).message}`);\n }\n}\n\nfunction formatWindows(windows: WindowInfo[]): string {\n const lines = ['# id name pid type z-order [x y w h]; z-order -1 = not shown; `--window <id>` restricts dump/input/wait/screenshot'];\n for (const w of windows) {\n const rect = w.rect ? ` [${w.rect.join(' ')}]` : '';\n lines.push(`${w.id} ${w.name} pid=${w.pid} type=${w.type} z=${w.zOrder}${rect}${w.focused ? ' focused' : ''}`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nexport function registerDumpCommand(program: Command): void {\n program\n .command('dump [target]')\n .description(\n 'Dump device state. `dump layout` (the default target): JSON by default, or one line per element with --flat; ' +\n '--selector lists only the matching elements, --summary counts elements per window, --diff compares the live ' +\n 'layout with one saved earlier. `dump windows`: the window list (ids for --window).',\n )\n .option('--bundle <bundle>', 'Filter the layout to a single window/bundle.')\n .option('--raw', 'Return the unpruned layout tree.')\n .option('--flat', 'One line per element (type, label, center as 0-1 fractions, flags) instead of a JSON tree.')\n .option('--summary', 'Per window: element, content, clickable and text-node counts (JSON).')\n .option(\n '--diff <baseline.json>',\n 'Compare with a saved `dump layout` JSON: matched elements with IoU, missing, extra, and a 0-1 similarity (JSON).',\n )\n .option('--selector <expr>', `List only the elements matching this expression, numbered for its [n] suffix. ${SELECTOR_HELP}`)\n .option('--window <id>', WINDOW_HELP)\n .option('--json', 'dump windows: print JSON instead of one line per window.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (target: string | undefined, opts: DumpOpts) => {\n const { config, logger } = getRuntime();\n const what = target ?? 'layout';\n if (what === 'windows') {\n const windows = await listWindows({ config, deviceSerial: opts.device, logger });\n process.stdout.write(opts.json ? `${JSON.stringify(windows, null, 2)}\\n` : formatWindows(windows));\n return;\n }\n if (what !== 'layout') throw new Error(`Unknown dump target \"${what}\". Supported: layout, windows.`);\n if (opts.raw && opts.flat) throw new Error('--raw and --flat cannot be combined.');\n const selector = parseSelectorOption(opts.selector);\n if (selector && opts.raw) throw new Error('--selector matches the pruned layout; it cannot be combined with --raw.');\n const modes = [opts.flat && '--flat', opts.summary && '--summary', opts.diff !== undefined && '--diff'].filter(Boolean);\n if (modes.length > 1) throw new Error(`${modes.join(' and ')} cannot be combined.`);\n if (opts.raw && modes.length > 0) throw new Error(`--raw cannot be combined with ${modes[0]}.`);\n if (selector && (opts.summary || opts.diff !== undefined)) {\n throw new Error(`--selector cannot be combined with ${opts.summary ? '--summary' : '--diff'}.`);\n }\n // Read the baseline before touching the device, so a bad path fails fast.\n const baseline = opts.diff !== undefined ? readBaseline(opts.diff) : undefined;\n const result = await dumpLayout({\n config,\n bundleName: opts.bundle,\n windowId: windowIdFrom(opts),\n prune: !opts.raw,\n detectKeyboard: !opts.raw,\n deviceSerial: opts.device,\n logger,\n });\n if (selector) {\n const matches = findLayoutNodes(selectableTree(result, windowIdFrom(opts)), selector);\n process.stdout.write(\n opts.flat\n ? formatSelectorMatches(result.display, selector.raw, matches)\n : `${JSON.stringify({ display: result.display, selector: selector.raw, matches }, null, 2)}\\n`,\n );\n return;\n }\n let out: string;\n if (opts.flat) out = formatFlatLayout(result);\n else if (opts.summary) out = `${JSON.stringify(summarizeLayout(result), null, 2)}\\n`;\n else if (baseline) {\n const diff = diffLayouts(baseline, result);\n logger.info(\n `layout similarity ${diff.similarity.toFixed(3)}: ${diff.matched.length} matched ` +\n `(${diff.moved} moved, ${diff.changed} changed), ${diff.missing.length} missing, ${diff.extra.length} extra.`,\n );\n out = `${JSON.stringify(diff, null, 2)}\\n`;\n } else out = `${JSON.stringify(result, null, 2)}\\n`;\n process.stdout.write(out);\n });\n}\n","import { flattenLayout, type DumpLayoutResult, type FlatLayoutNode } from '@oniroproject/core';\n\nconst MAX_TEXT = 80;\n\nfunction quote(s: string): string {\n return JSON.stringify(s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT - 1)}…` : s);\n}\n\nfunction flags(n: FlatLayoutNode): string[] {\n const out: string[] = [];\n if (n.click) out.push('click');\n if (n.longClick) out.push('longClick');\n if (n.scroll) out.push('scroll');\n if (n.checked) out.push('checked');\n else if (n.check) out.push('checkable');\n if (n.sel) out.push('selected');\n if (n.focus) out.push('focus');\n if (n.disabled) out.push('disabled');\n if (n.hidden) out.push('hidden');\n if (n.covered) out.push('covered');\n return out;\n}\n\n/** One line per element: type, label, center (0–1 fractions), and state flags. */\nexport function formatLayoutLine(n: FlatLayoutNode): string {\n const parts: string[] = [n.type ?? 'node'];\n if (n.text !== undefined) parts.push(quote(n.text));\n if (n.desc !== undefined) parts.push(`desc=${quote(n.desc)}`);\n if (n.hint !== undefined) parts.push(`hint=${quote(n.hint)}`);\n if (n.id !== undefined) parts.push(`#${n.id}`);\n if (n.key !== undefined) parts.push(`key=${n.key}`);\n if (n.c) parts.push(`c=${n.c[0].toFixed(3)},${n.c[1].toFixed(3)}`);\n parts.push(...flags(n));\n return parts.join(' ');\n}\n\n/** Worth a line: it has a label to read or match, or it can be interacted with. */\nfunction isListed(n: FlatLayoutNode): boolean {\n const labelled = n.text !== undefined || n.desc !== undefined || n.hint !== undefined;\n return labelled || !!(n.click || n.longClick || n.scroll || n.check || n.focus);\n}\n\n/** `<id> <bundle>`, or whichever of the two is known. */\nfunction windowLabel(windowId: number | undefined, bundle: string | undefined): string {\n return [windowId, bundle].filter((x) => x !== undefined).join(' ');\n}\n\n/**\n * Render a pruned layout as compact text for agents: a `[window <id> <bundle>]`\n * header per window (the id is what `--window` takes), then one line per labelled or interactive element in\n * paint order (decorative images and id-only wrappers are left to the JSON\n * output). The soft keyboard collapses to a single `[keyboard <bundle>]` line\n * instead of listing every key.\n */\nexport function formatFlatLayout(result: DumpLayoutResult): string {\n const lines: string[] = [];\n const d = result.display;\n lines.push(\n `# display ${d ? `${d.width}x${d.height}` : 'unknown'}; c = element center as 0-1 fractions ` +\n '(input --fx/--fy), or act by label with input --target \"<text>\"',\n );\n const keyboardBundle = result.keyboard?.shown ? result.keyboard.bundle : undefined;\n let window: string | undefined;\n let windowId: number | undefined;\n for (const n of flattenLayout(result.tree)) {\n if (n.window !== window || n.windowId !== windowId) {\n window = n.window;\n windowId = n.windowId;\n if (window !== undefined && window === keyboardBundle) {\n lines.push(`[keyboard ${windowLabel(windowId, window)}] up — dismiss with input --type hideKeyboard`);\n } else if (window !== undefined || windowId !== undefined) {\n lines.push(`[window ${windowLabel(windowId, window)}]`);\n }\n }\n if (window !== undefined && window === keyboardBundle) continue;\n if (n.bundle !== undefined && n.text === undefined && !n.click) continue; // the window root itself\n if (isListed(n)) lines.push(formatLayoutLine(n));\n }\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * Render the matches of `dump layout --selector`: one line per match, numbered\n * with the index a `[n]` suffix on the selector picks, and the window it is in.\n */\nexport function formatSelectorMatches(display: DumpLayoutResult['display'], selector: string, matches: FlatLayoutNode[]): string {\n const lines = [\n `# display ${display ? `${display.width}x${display.height}` : 'unknown'}; ${matches.length} element(s) match ` +\n `${JSON.stringify(selector)}${matches.length > 1 ? '; append [n] to the selector to act on one' : ''}`,\n ];\n matches.forEach((n, i) => {\n const win = windowLabel(n.windowId, n.window);\n lines.push(`[${i}] ${formatLayoutLine(n)}${win ? ` (window ${win})` : ''}`);\n });\n return `${lines.join('\\n')}\\n`;\n}\n","import { Command } from 'commander';\nimport { getDeviceInfo, listDevices, type DeviceFullInfo, type DeviceInfo } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** One `devices --long` line: the target-list columns, then what the device reports about itself. */\nexport function formatLongDevice(d: DeviceInfo, info: DeviceFullInfo | undefined): string {\n const head = `${d.serial}\\t${d.connection ?? ''}\\t${d.status}`;\n if (!info) return head;\n const os = [info.osFamily, info.osFamily === 'HarmonyOS' ? info.osDistVersion : undefined].filter(Boolean).join(' ');\n const fields: Array<[string, string | undefined]> = [\n ['os', os || undefined],\n ['api', info.sdkApiVersion],\n ['abi', info.abi],\n ['type', info.deviceType],\n ['model', info.model],\n ['fullname', info.osFullName],\n ];\n const rest = fields.filter(([, v]) => v).map(([k, v]) => `${k}=${/\\s/.test(v!) ? JSON.stringify(v) : v}`);\n return [head, ...rest].join('\\t');\n}\n\n/** The hdc targets and, with `long`, what each connected one reports about itself. */\nexport async function queryDevices(\n long: boolean,\n): Promise<{ devices: DeviceInfo[]; infos: Map<string, DeviceFullInfo> }> {\n const { config, logger } = getRuntime();\n const devices = await listDevices(config);\n const infos = new Map<string, DeviceFullInfo>();\n if (long) {\n for (const d of devices.filter((x) => x.status === 'Connected')) {\n try {\n infos.set(d.serial, await getDeviceInfo({ config, deviceSerial: d.serial, logger }));\n } catch (err) {\n logger.warn(`Could not query ${d.serial}: ${(err as Error).message}`);\n }\n }\n }\n return { devices, infos };\n}\n\n/** What `devices --json` prints (with `--long`, each device gains `info`). */\nexport function devicesJson(\n devices: DeviceInfo[],\n infos: Map<string, DeviceFullInfo>,\n long: boolean,\n): Array<DeviceInfo | (DeviceInfo & { info: DeviceFullInfo | null })> {\n return long ? devices.map((d) => ({ ...d, info: infos.get(d.serial) ?? null })) : devices;\n}\n\nexport function registerDevicesCommand(program: Command): void {\n program\n .command('devices')\n .description('List connected hdc devices.')\n .option(\n '--long',\n 'Also ask each connected device for its OS family (HarmonyOS / OpenHarmony), version, API level, ' +\n 'CPU ABI, device type and model.',\n )\n .option('--json', 'Emit machine-readable JSON.')\n .action(async (opts: { long?: boolean; json?: boolean }) => {\n const { devices, infos } = await queryDevices(!!opts.long);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(devicesJson(devices, infos, !!opts.long), null, 2)}\\n`);\n return;\n }\n if (devices.length === 0) {\n process.stdout.write('(no devices)\\n');\n return;\n }\n for (const d of devices) {\n process.stdout.write(`${opts.long ? formatLongDevice(d, infos.get(d.serial)) : `${d.serial}\\t${d.connection ?? ''}\\t${d.status}`}\\n`);\n }\n });\n}\n","import { Command } from 'commander';\nimport { sendFile, recvFile } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('Transfer files to/from the device (hdc file send/recv).');\n\n file\n .command('send <local> <remote>')\n .description(\n 'Push a local file to the device. With --bundle, <remote> may be relative to that app\\'s sandbox ' +\n '(files/x is its filesDir, haps/entry/files/x the entry module\\'s), and the file is chowned to the app ' +\n 'so it can read it. Prints the device path.',\n )\n .option('--bundle <bundle>', 'Push into this app\\'s sandbox and give the file to the app\\'s user.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (local: string, remote: string, opts: { bundle?: string; device?: string }) => {\n const { config, logger } = getRuntime();\n const written = await sendFile({ config, local, remote, bundle: opts.bundle, deviceSerial: opts.device, logger });\n logger.info(`Sent ${local} -> ${written}${opts.bundle ? ` (owned by ${opts.bundle})` : ''}.`);\n process.stdout.write(`${written}\\n`);\n });\n\n file\n .command('recv <remote> <local>')\n .description('Pull a file from the device.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (remote: string, local: string, opts: { device?: string }) => {\n const { config, logger } = getRuntime();\n await recvFile({ config, remote, local, deviceSerial: opts.device, logger });\n logger.info(`Received ${remote} -> ${local}.`);\n });\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as path from 'node:path';\nimport {\n detectCmdToolsFlavour,\n detectRuntimeOs,\n getCmdToolsPath,\n missingProjectRootFiles,\n runCodelinter,\n type CodelinterResult,\n type CodelinterSummary,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { runArktsCheckCommand } from './check.js';\n\ninterface LintOpts {\n files?: string[];\n json?: boolean;\n engine: string;\n allowIncomplete?: boolean;\n}\n\n/** codelinter's totals, or totals counted from the findings when it printed none. */\nexport function lintTotals(result: Pick<CodelinterResult, 'findings' | 'summary'>): CodelinterSummary {\n if (result.summary) return result.summary;\n const count = (s: string): number => result.findings.filter((f) => f.severity === s).length;\n return {\n defects: result.findings.length,\n errors: count('error'),\n warnings: count('warning'),\n suggestions: count('suggestion'),\n };\n}\n\n/**\n * The exit code for a lint run: 1 when there is an error-severity finding, or when\n * codelinter exited non-zero without printing a report (so it did not really run);\n * 2 when codelinter said its report is incomplete (it skipped checks, so a clean\n * report means nothing), unless `allowIncomplete`. Warnings and suggestions alone\n * exit 0, although codelinter itself exits 1 for them.\n */\nexport function lintExitCode(\n result: Pick<CodelinterResult, 'code' | 'findings' | 'summary' | 'incomplete'>,\n allowIncomplete = false,\n): number {\n if (lintTotals(result).errors > 0) return 1;\n if (lintFailed(result)) return result.code;\n return result.incomplete && !allowIncomplete ? 2 : 0;\n}\n\n/** True when codelinter exited non-zero without printing a report, so it did not really run. */\nexport function lintFailed(result: Pick<CodelinterResult, 'code' | 'findings' | 'summary'>): boolean {\n return result.summary === null && result.findings.length === 0 && result.code !== 0;\n}\n\nexport function registerLintCommand(program: Command): void {\n program\n .command('lint [project-dir]')\n .description(\n 'Run the OpenHarmony codelinter on a project. Defaults to the current directory. ' +\n 'Exits 1 on error-severity findings or when codelinter fails to run, 2 when codelinter reports that it ' +\n 'skipped checks (incomplete), 0 otherwise; warnings alone exit 0. `--engine arkts` runs `check arkts` instead.',\n )\n .option('--files <globs...>', 'Specific files/globs to lint (default: the whole project).')\n .option('--json', 'Emit the report (findings, summary, notices, incomplete) as JSON.')\n .option(\n '--engine <engine>',\n '`codelinter`, or `arkts` for the ArkTS checker of `check arkts` (same options, report and exit codes).',\n 'codelinter',\n )\n .option(\n '--allow-incomplete',\n 'Exit 0 rather than 2 when codelinter reports that it skipped checks (e.g. the tools flavour differs from runtimeOS).',\n )\n .action(async (projectDir: string | undefined, opts: LintOpts) => {\n if (opts.engine === 'arkts') {\n process.exitCode = await runArktsCheckCommand(projectDir, { files: opts.files, json: opts.json });\n return;\n }\n if (opts.engine !== 'codelinter') {\n throw new InvalidArgumentError(`Unknown --engine ${opts.engine}: use codelinter or arkts.`);\n }\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n const result = await runCodelinter({ config, projectDir: dir, files: opts.files, logger });\n const totals = lintTotals(result);\n const failed = lintFailed(result);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n } else if (!failed) {\n for (const f of result.findings) {\n const at = `${f.file}:${f.line}${f.column ? `:${f.column}` : ''}`;\n process.stdout.write(`${at} ${f.severity} ${f.message}${f.code ? ` [${f.code}]` : ''}\\n`);\n }\n process.stdout.write(\n totals.defects === 0\n ? 'No defects found.\\n'\n : `${totals.defects} defects: ${totals.errors} errors, ${totals.warnings} warnings, ` +\n `${totals.suggestions} suggestions.\\n`,\n );\n }\n\n if (failed) {\n const missing = missingProjectRootFiles(dir);\n const why = missing.length ? ` It needs a DevEco project root, and ${dir} has no ${missing.join(', ')}.` : '';\n logger.error(\n `codelinter exited ${result.code} without a report, so nothing was linted.${why}\\n` +\n result.raw.trim().split('\\n').slice(-15).join('\\n'),\n );\n }\n if (result.incomplete) {\n for (const n of result.notices) logger.warn(`codelinter: ${n}`);\n const cmdToolsPath = getCmdToolsPath(config);\n const flavour = detectCmdToolsFlavour(cmdToolsPath);\n const projectOs = detectRuntimeOs(dir);\n if (flavour !== projectOs) {\n logger.warn(\n `The command-line tools at ${cmdToolsPath} are the ${flavour} flavour, but the project targets ` +\n `${projectOs} (runtimeOS in build-profile.json5), so codelinter skipped part of its checks: treat the ` +\n `counts as a lower bound. For a complete report, point ONIRO_CMD_TOOLS_PATH at ${projectOs} ` +\n \"command-line tools. The build's ArkTS compiler checks are not affected.\",\n );\n }\n }\n // Let output flush before exiting non-zero.\n if (result.incomplete && !opts.allowIncomplete && lintTotals(result).errors === 0 && !failed) {\n logger.error(\n 'codelinter reported an incomplete run, so a clean result is not evidence the code is clean: exiting 2. ' +\n 'Pass --allow-incomplete to exit 0, or use `oniro-app check arkts`, which does not depend on codelinter.',\n );\n }\n process.exitCode = lintExitCode(result, opts.allowIncomplete);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport { checkArkts, type ArktsCheckReport } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { formatDiagnostics } from './build.js';\n\nexport interface ArktsCheckCommandOpts {\n files?: string[];\n fix?: boolean;\n sdk?: string;\n json?: boolean;\n}\n\n/** 0 when the check ran clean, 1 when it found an error, 2 when it could not run, so nothing is known. */\nexport function arktsCheckExitCode(report: Pick<ArktsCheckReport, 'completed' | 'ok'>): number {\n if (!report.completed) return 2;\n return report.ok ? 0 : 1;\n}\n\n/** The closing line of a text report. */\nexport function arktsCheckSummaryLine(report: Pick<ArktsCheckReport, 'summary' | 'durationMs'>): string {\n const s = report.summary;\n const fixed = s.fixed ? `, ${s.fixed} fixed` : '';\n return `${s.errors} errors, ${s.warnings} warnings${fixed} in ${s.files} files (${(report.durationMs / 1000).toFixed(1)} s).`;\n}\n\n/** What `check arkts --json` prints when the check could not start (not a project, SDK not installed). */\nexport interface ArktsCheckNotStarted {\n ok: false;\n completed: false;\n error: string;\n diagnostics: [];\n}\n\n/** The check's report, or the could-not-start object instead of a throw. Shared with `serve mcp`. */\nexport async function arktsCheckOrError(\n projectDir: string | undefined,\n opts: Omit<ArktsCheckCommandOpts, 'json'>,\n): Promise<ArktsCheckReport | ArktsCheckNotStarted> {\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n try {\n return await checkArkts({ config, projectDir: dir, files: opts.files, fix: opts.fix, sdkDir: opts.sdk, logger });\n } catch (err) {\n return { ok: false, completed: false, error: err instanceof Error ? err.message : String(err), diagnostics: [] };\n }\n}\n\n/** Run `check arkts` and print its report; returns the exit code. Shared with `lint --engine arkts`. */\nexport async function runArktsCheckCommand(projectDir: string | undefined, opts: ArktsCheckCommandOpts): Promise<number> {\n const { logger } = getRuntime();\n const report = await arktsCheckOrError(projectDir, opts);\n if (!('summary' in report)) {\n // Still one object on stdout for a caller that parses it, and exit 2 since nothing was checked.\n if (opts.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n logger.error(report.error);\n return 2;\n }\n\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else if (report.completed) {\n if (report.diagnostics.length) process.stdout.write(`${formatDiagnostics(report.diagnostics, Infinity)}\\n`);\n for (const d of report.fixed) {\n process.stdout.write(` fixed ${d.file}:${d.line}:${d.column} ${d.message}\\n`);\n }\n if (report.alsoModified.length) {\n process.stdout.write(`--fix also edited: ${report.alsoModified.join(', ')}\\n`);\n }\n process.stdout.write(`${arktsCheckSummaryLine(report)}\\n`);\n }\n if (!report.completed) logger.error(report.error ?? 'The ArkTS checker did not complete, so nothing was checked.');\n return arktsCheckExitCode(report);\n}\n\nexport function registerCheckCommand(program: Command): void {\n const check = program\n .command('check')\n .description('Static checks that need no build and no device.');\n\n check\n .command('arkts [project-dir]')\n .description(\n \"Type-check and lint ArkTS with the SDK's own ArkTS checker (what the build's CompileArkTS runs), plus the \" +\n 'ArkUI component-model and project-config rules the build enforces later (V1/V2 decorators, @Entry root, ' +\n 'route maps, resources, permissions), in seconds and without a build. Uses the SDK the project compiles ' +\n 'with. Exits 0 when clean, 1 on an error, 2 when the checker could not run (then nothing is known).',\n )\n .option(\n '--files <files...>',\n 'Check only these .ets files (project-wide rules such as main_pages.json and module.json5 are then skipped).',\n )\n .option(\n '--fix',\n \"Apply the fixes the checker can verify (the compiler's `Did you mean` suggestions, import paths, a missing \" +\n '`export`, the @Component/@ComponentV2 decorator), re-check, and revert any fix that adds an error.',\n )\n .option('--sdk <dir>', 'SDK directory to check against (holding ets/), instead of the one compileSdkVersion names.')\n .option(\n '--json',\n 'Print the report as JSON: ok, completed, diagnostics (severity, source, rule, message, file, line, column), ' +\n 'fixed, alsoModified, summary, sdk, durationMs, error.',\n )\n .action(async (projectDir: string | undefined, opts: ArktsCheckCommandOpts) => {\n process.exitCode = await runArktsCheckCommand(projectDir, opts);\n });\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as path from 'node:path';\nimport { runTests, type TestCaseResult, type TestRunReport } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { formatDiagnostics } from './build.js';\n\ninterface TestOpts {\n module: string;\n product: string;\n class?: string;\n timeout: number;\n runTimeout: number;\n build: boolean;\n wake: boolean;\n mode?: string;\n deps: boolean;\n device?: string;\n json?: boolean;\n}\n\nfunction positiveMs(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError('Expected a positive number of milliseconds.');\n return Math.floor(n);\n}\n\n/** 0 when every case passed, 1 when a case failed or threw, 2 when the run itself did not complete. */\nexport function testExitCode(report: Pick<TestRunReport, 'outcome'>): number {\n return report.outcome === 'passed' ? 0 : report.outcome === 'failed' ? 1 : 2;\n}\n\n/** The first stack frame in the project's own code (not Hypium's), e.g. `entry/src/ohosTest/ets/test/A.test.ets:26:17`. */\nexport function projectFrame(stack: string | undefined): string | undefined {\n for (const line of stack?.split('\\n') ?? []) {\n if (/oh_modules|@ohos\\/hypium/.test(line)) continue;\n const m = /\\(([^()]+:\\d+:\\d+)\\)\\s*$/.exec(line.trim());\n if (m) return m[1];\n }\n return undefined;\n}\n\n/** One line per case: `PASS Suite > case (12 ms)`, and for a failure the message and where it was raised. */\nexport function formatTestCase(t: TestCaseResult): string {\n const label = { pass: 'PASS', fail: 'FAIL', error: 'ERROR', ignore: 'SKIP', unknown: `CODE ${t.statusCode}` }[t.status];\n const time = t.durationMs !== undefined ? ` (${t.durationMs} ms)` : '';\n let line = `${label} ${t.suite} > ${t.name}${time}`;\n if (t.status !== 'pass' && t.message) line += `\\n ${t.message}`;\n const at = t.status !== 'pass' ? projectFrame(t.stack) : undefined;\n if (at) line += `\\n at ${at}`;\n return line;\n}\n\nexport function registerTestCommand(program: Command): void {\n program\n .command('test [project-dir]')\n .description(\n \"Build a module's main and ohosTest HAPs, install both on the device, run the suite with `aa test` \" +\n '(Hypium, OpenHarmonyTestRunner) and report each case. Defaults to the current directory. ' +\n 'Exits 0 when every case passed, 1 when a case failed or threw, 2 when the run did not complete ' +\n '(build failed, test module not found, timeout, no device). The test module is left installed.',\n )\n .option('--module <module>', 'Module whose src/ohosTest suite runs.', 'entry')\n .option('--product <product>', 'hvigor product name.', 'default')\n .option('--class <filter>', 'Run only these cases: `Suite`, `Suite#case`, or several joined by commas.')\n .option('--timeout <ms>', 'Per-case timeout passed to the runner.', positiveMs, 15_000)\n .option('--run-timeout <ms>', 'Wall-clock limit for the whole run; aa test can hang when the app dies.', positiveMs, 600_000)\n .option('--no-build', 'Use the HAPs already built instead of building them.')\n .option('--no-wake', 'Leave the screen as it is (by default it is turned on, a lock screen without a credential is swiped away, and it is kept on during the run).')\n .option('--mode <mode>', 'hvigor build mode (e.g. debug).')\n .option('--no-deps', 'Skip the automatic `ohpm install --all` when oh_modules/ is missing.')\n .option('--device <serial>', 'Target device serial.')\n .option(\n '--json',\n 'Print the report as JSON: ok, outcome, tests (suite, name, status, statusCode, durationMs, message, stack), summary, resultCode, haps, log, error.',\n )\n .action(async (projectDir: string | undefined, opts: TestOpts) => {\n const { config, logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n const report = await runTests({\n config,\n projectDir: dir,\n module: opts.module,\n product: opts.product,\n testClass: opts.class,\n caseTimeoutMs: opts.timeout,\n runTimeoutMs: opts.runTimeout,\n build: opts.build,\n wakeScreen: opts.wake,\n mode: opts.mode,\n autoInstallDeps: opts.deps,\n deviceSerial: opts.device,\n logger,\n });\n\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else {\n for (const t of report.tests) process.stdout.write(`${formatTestCase(t)}\\n`);\n const s = report.summary;\n if (report.tests.length || report.outcome !== 'runner-error') {\n process.stdout.write(\n `${s.run} run: ${s.pass} passed, ${s.fail} failed, ${s.error} errors, ${s.ignore} ignored.\\n`,\n );\n }\n }\n for (const w of report.warnings) logger.warn(w);\n if (report.error) {\n const listed = report.diagnostics ? formatDiagnostics(report.diagnostics) : '';\n logger.error(`${report.error}${listed ? `\\n${listed}` : ''}`);\n }\n process.exitCode = testExitCode(report);\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { runDoctor, type DoctorCheck, type DoctorReport } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\ninterface DoctorOpts {\n json?: boolean;\n fix?: boolean;\n device: boolean;\n serial?: string;\n arktsCheck: boolean;\n}\n\n/** One line per check, `fail sdk API 20 is not installed at …`, then its fix indented. */\nexport function formatDoctorCheck(c: DoctorCheck): string {\n const line = `${c.status.padEnd(5)} ${c.id.padEnd(16)} ${c.detail}${c.fixed ? ' (fixed)' : ''}`;\n return c.fix && c.status !== 'ok' && c.status !== 'skip' ? `${line}\\n${' '.repeat(23)}fix: ${c.fix}` : line;\n}\n\nexport function doctorExitCode(report: Pick<DoctorReport, 'ok'>): number {\n return report.ok ? 0 : 1;\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command('doctor [project-dir]')\n .description(\n 'Check that this machine can build, check, sign, install and test: node, java, the SDK the project compiles ' +\n 'with, the command-line tools (complete, their version, their flavour against runtimeOS), a `check arkts` ' +\n \"self-test, hdc and a reachable device at the project's API, signing material, free disk space. Each check is \" +\n 'ok, warn, fail or skip, with a fix. Uses the project in the current directory when there is one. Exits 1 when ' +\n 'any check fails.',\n )\n .option('--json', 'Print the report as JSON: ok, checks (id, status, detail, fix, fixed), project, versions.')\n .option('--fix', \"Install the project's missing OpenHarmony SDK.\")\n .option('--no-device', 'Skip the device check (for a machine that only builds).')\n .option('--serial <serial>', 'The device to check, when several are connected.')\n .option('--no-arkts-check', 'Skip the `check arkts` self-test.')\n .action(async (projectDir: string | undefined, opts: DoctorOpts) => {\n const { config, logger, progress } = getRuntime();\n let dir: string | undefined;\n if (projectDir) {\n dir = path.resolve(projectDir);\n } else if (fs.existsSync(path.join(process.cwd(), 'build-profile.json5'))) {\n dir = process.cwd();\n }\n const report = await runDoctor({\n config,\n projectDir: dir,\n fix: opts.fix,\n device: opts.device,\n deviceSerial: opts.serial,\n arktsSelfTest: opts.arktsCheck,\n logger,\n progress,\n });\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else {\n if (report.project) process.stdout.write(`Project ${report.project.dir} (${report.project.runtimeOS})\\n`);\n for (const c of report.checks) process.stdout.write(`${formatDoctorCheck(c)}\\n`);\n const failed = report.checks.filter((c) => c.status === 'fail').length;\n process.stdout.write(failed ? `${failed} check(s) failed.\\n` : 'No check failed.\\n');\n }\n process.exitCode = doctorExitCode(report);\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport { inventoryScreens, type ScreensInventory } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\ninterface ScreensOpts {\n json?: boolean;\n}\n\n/** Left-aligned columns, two spaces apart, the last one unpadded. */\nexport function formatTable(header: string[], rows: string[][]): string {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));\n const line = (cells: string[]): string =>\n cells\n .map((c, i) => (i === cells.length - 1 ? c : c.padEnd(widths[i] ?? 0)))\n .join(' ')\n .trimEnd();\n return [line(header), ...rows.map(line)].join('\\n');\n}\n\n/** The text report: pages, routes, placeholders and warnings, each as a table or a list. */\nexport function formatScreens(inv: ScreensInventory): string {\n const out: string[] = [];\n const multiModule = inv.modules.length > 1;\n out.push(`Pages (${inv.pages.length})`);\n if (inv.pages.length) {\n out.push(\n formatTable(\n ['NAME', ...(multiModule ? ['MODULE'] : []), 'KIND', 'COMPONENT', 'NODES', 'ROUTES OUT', 'FILE'],\n inv.pages.map((p) => [\n p.registered ? p.name : `${p.name} (unregistered)`,\n ...(multiModule ? [p.module] : []),\n p.kind,\n p.component ?? '-',\n String(p.contentNodes),\n p.routesOut.join(', ') || '-',\n `${p.file}:${p.line}`,\n ]),\n ),\n );\n }\n out.push('', `Routes (${inv.routes.length})`);\n if (inv.routes.length) {\n out.push(\n formatTable(\n ['FROM', 'TO', 'VIA', 'FILE'],\n inv.routes.map((r) => [r.from, r.dynamic ? `${r.to} (dynamic)` : r.to, r.via, `${r.file}:${r.line}`]),\n ),\n );\n }\n out.push('', `Placeholders (${inv.placeholders.length})`);\n if (inv.placeholders.length) {\n out.push(formatTable(['FILE', 'KIND', 'TEXT'], inv.placeholders.map((p) => [`${p.file}:${p.line}`, p.kind, p.text])));\n }\n if (inv.warnings.length) {\n out.push('', `Warnings (${inv.warnings.length})`);\n for (const w of inv.warnings) out.push(w);\n }\n return out.join('\\n');\n}\n\nexport function registerScreensCommand(program: Command): void {\n program\n .command('screens [project-dir]')\n .description(\n 'Static inventory of the pages and routes of a project, from its sources, without a build or a device: ' +\n '@Entry pages (main_pages.json, @Entry({ routeName })), NavDestination pages (route maps and ' +\n '.navDestination() builders that dispatch on the route name), the router.pushUrl/replaceUrl/pushNamedRoute ' +\n 'and NavPathStack.pushPath*/replacePath*/pushDestination* call sites, the content nodes each page renders ' +\n '(component calls through its custom components and @Builders, layout containers excluded), and ' +\n 'placeholder markers (TODO/FIXME, placeholder-like text, empty build()). Reads every module in ' +\n 'build-profile.json5. Exits 0 (it is an inventory, not a gate) unless the project cannot be read.',\n )\n .option(\n '--json',\n 'Print the inventory as JSON: pages (name, module, file, line, component, entry, kind, registered, ' +\n 'contentNodes, routesOut), routes (from, to, file, line, via, dynamic), placeholders (file, line, text, ' +\n 'kind), warnings, modules, projectDir.',\n )\n .action((projectDir: string | undefined, opts: ScreensOpts) => {\n const { logger } = getRuntime();\n const dir = path.resolve(projectDir ?? process.cwd());\n let inv: ScreensInventory;\n try {\n inv = inventoryScreens({ projectDir: dir });\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n if (opts.json) process.stdout.write(`${JSON.stringify({ error }, null, 2)}\\n`);\n logger.error(error);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(opts.json ? `${JSON.stringify(inv, null, 2)}\\n` : `${formatScreens(inv)}\\n`);\n });\n}\n","import { Command, Option } from 'commander';\nimport {\n performInput,\n sendGesture,\n getDisplaySize,\n describeLayoutNode,\n type UiInputType,\n type Waypoint,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { addTargetOptions, selectorFrom, targetIndexFrom, windowIdFrom, type TargetOpts } from '../lib/target.js';\n\nconst INPUT_TYPES: UiInputType[] = [\n 'click',\n 'doubleClick',\n 'longClick',\n 'swipe',\n 'drag',\n 'fling',\n 'keyEvent',\n 'inputText',\n 'clearText',\n 'hideKeyboard',\n];\n\nconst num = (v: string | undefined): number | undefined => (v === undefined ? undefined : Number(v));\n\ninterface InputOpts extends TargetOpts {\n type: UiInputType;\n x?: string;\n y?: string;\n x2?: string;\n y2?: string;\n fx?: string;\n fy?: string;\n fx2?: string;\n fy2?: string;\n speed?: string;\n key?: string;\n text?: string;\n clear?: boolean;\n hideKeyboard?: boolean;\n device?: string;\n}\n\ninterface GestureOpts {\n waypoints: string;\n fractions?: boolean;\n holdStart?: string;\n holdEnd?: string;\n device?: string;\n}\n\nexport function registerInputCommand(program: Command): void {\n const input = program\n .command('input')\n .description(\n 'Inject a UI input event via uitest uiInput. Position it with --target or --selector (an on-screen element), ' +\n '--fx/--fy (0-1 fractions of the display, as in `dump layout` and the screenshot grid), or --x/--y (pixels).',\n )\n .addOption(new Option('--type <type>', 'Input type.').choices(INPUT_TYPES).makeOptionMandatory());\n addTargetOptions(input, 'Act on');\n input\n .option('--fx <fraction>', 'Start X as a 0-1 fraction of the display width.')\n .option('--fy <fraction>', 'Start Y as a 0-1 fraction of the display height.')\n .option('--fx2 <fraction>', 'End X fraction (swipe/drag/fling).')\n .option('--fy2 <fraction>', 'End Y fraction (swipe/drag/fling).')\n .option('--x <px>', 'X pixel (click/swipe start).')\n .option('--y <px>', 'Y pixel (click/swipe start).')\n .option('--x2 <px>', 'End X pixel (swipe/drag/fling).')\n .option('--y2 <px>', 'End Y pixel (swipe/drag/fling).')\n .option('--speed <px-per-s>', 'Velocity for swipe/drag/fling.')\n .option(\n '--key <key>',\n 'Key for keyEvent: Back/Home/Power, a name (Delete, Enter, Tab, Escape, MoveHome, MoveEnd, …), ' +\n 'a letter, a KeyCode id, or a combo like Ctrl+A.',\n )\n .option('--text <text>', 'Text for inputText.')\n .option('--clear', 'inputText: clear the field (Ctrl+A, Delete) before typing.')\n .option('--hide-keyboard', 'Dismiss the soft keyboard afterwards, if it is up.')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: InputOpts) => {\n const { config, logger } = getRuntime();\n const result = await performInput({\n config,\n type: opts.type,\n target: selectorFrom(opts),\n targetIndex: targetIndexFrom(opts),\n windowId: windowIdFrom(opts),\n fx: num(opts.fx),\n fy: num(opts.fy),\n fx2: num(opts.fx2),\n fy2: num(opts.fy2),\n pxX: num(opts.x),\n pxY: num(opts.y),\n pxX2: num(opts.x2),\n pxY2: num(opts.y2),\n speed: num(opts.speed),\n key: opts.key,\n text: opts.text,\n clear: opts.clear,\n hideKeyboard: opts.hideKeyboard,\n deviceSerial: opts.device,\n logger,\n });\n if (opts.type === 'hideKeyboard') {\n logger.info(result.keyboardHidden ? 'Dismissed the keyboard.' : 'The keyboard was not shown.');\n return;\n }\n const at = result.x !== undefined ? ` at ${result.x},${result.y}` : '';\n const on = result.target ? ` on ${describeLayoutNode(result.target)}` : '';\n const kb = result.keyboardHidden ? ' (dismissed the keyboard)' : '';\n logger.info(`Sent ${opts.type}${at}${on}${kb}.`);\n });\n\n program\n .command('gesture')\n .description('Inject a multi-waypoint gesture. Waypoints are JSON: [{\"x\":..,\"y\":..,\"t\":..}] in pixels (or fractions with --fractions).')\n .requiredOption('--waypoints <json>', 'JSON array of {x,y,t} waypoints (t = ms from start).')\n .option('--fractions', 'Waypoint x/y are 0-1 fractions of the display instead of pixels.')\n .option('--hold-start <ms>', 'Leading press-hold before moving (best-effort: uses `uitest drag`).')\n .option('--hold-end <ms>', 'Trailing hold before lifting (no uitest equivalent; ignored).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: GestureOpts) => {\n const { config, logger } = getRuntime();\n let waypoints = JSON.parse(opts.waypoints) as Waypoint[];\n if (opts.fractions) {\n const bad = waypoints.find((w) => !(w.x >= 0 && w.x <= 1 && w.y >= 0 && w.y <= 1));\n if (bad) throw new Error(`With --fractions, waypoint x and y must be 0-1; got ${bad.x},${bad.y}.`);\n const display = await getDisplaySize(config, { deviceSerial: opts.device, logger });\n if (!display) throw new Error('Could not read the display size to convert fractions to pixels.');\n // 1.0 maps to the last pixel, not one past the edge.\n const px = (f: number, size: number): number => Math.min(size - 1, Math.round(f * size));\n waypoints = waypoints.map((w) => ({ ...w, x: px(w.x, display.width), y: px(w.y, display.height) }));\n }\n await sendGesture({\n config,\n waypoints,\n holdStartMs: num(opts.holdStart),\n holdEndMs: num(opts.holdEnd),\n deviceSerial: opts.device,\n logger,\n });\n logger.info('Gesture sent.');\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { analyzeFaultLog, captureLog, latestCrash, type CrashVerdict } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { collectLogBundle } from '../lib/logBundle.js';\nimport { formatCrashVerdict, parseCrashSince, projectBundle } from '../lib/crashReport.js';\n\ninterface LogsOpts {\n output?: string;\n for?: string;\n grep?: string;\n clear?: boolean;\n domain?: string;\n device?: string;\n}\n\ninterface CollectOptions {\n output: string;\n device?: string;\n package?: string;\n pid?: string;\n tag?: string;\n level?: string;\n duration: string;\n redact: boolean;\n json?: boolean;\n}\n\ninterface CrashOptions {\n bundle?: string;\n since?: string;\n wait?: string;\n path?: string;\n output: string;\n device?: string;\n json?: boolean;\n}\n\nexport function registerLogsCommand(program: Command): void {\n const logs = program\n .command('logs')\n .description(\n 'Capture hilog to a file for a whole session: the device\\'s small log buffer wraps within ' +\n 'seconds under chatty components, so a dump at the end loses lines. Runs until --for elapses ' +\n 'or the process is interrupted; start it in the background, e.g. `oniro-app logs --clear -o ' +\n 'hilog_full.txt &`. Every line is flushed as it arrives and the stream reconnects after a reboot.',\n )\n // Not requiredOption: commander checks a parent's mandatory options for its\n // subcommands too, so `logs collect` would demand it.\n .option('-o, --output <file>', 'File to append the lines to (required).')\n .option('--for <ms>', 'Stop after this many ms (default: run until interrupted).')\n .option('--grep <regex>', 'Keep only lines matching this regex (default: all).')\n .option('--clear', 'Clear the device log buffer first (hilog -r), so the file covers only this session.')\n .option('--domain <domain>', 'hilog domain filter (e.g. 0xD003900).')\n .option('--device <serial>', 'Target device serial.')\n .action(async (opts: LogsOpts) => {\n if (!opts.output) logs.error(\"error: required option '-o, --output <file>' not specified\");\n const { config, logger } = getRuntime();\n const file = path.resolve(opts.output!);\n const abort = new AbortController();\n const stop = (): void => abort.abort();\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n logger.info(`Capturing hilog to ${file}${opts.for ? ` for ${opts.for} ms` : ' until interrupted'}...`);\n const result = await captureLog({\n config,\n file,\n durationMs: opts.for !== undefined ? Number(opts.for) : undefined,\n pattern: opts.grep ? new RegExp(opts.grep) : undefined,\n clear: opts.clear,\n domain: opts.domain,\n deviceSerial: opts.device,\n abortSignal: abort.signal,\n logger,\n });\n logger.info(`Wrote ${result.lines} lines to ${result.file} (${result.reconnects} reconnects).`);\n process.stdout.write(`${result.file}\\n`);\n });\n\n logs\n .command('collect')\n .description('Create a diagnostic bundle from a connected device.')\n .allowExcessArguments(false)\n .option('-o, --output <directory>', 'Parent directory for incident bundles.', path.join(os.homedir(), '.oniro', 'incident-bundles'))\n .option('--device <serial>', 'Target device serial.')\n .option('--package <bundle>', 'Collect faultlog entries for this application bundle.')\n .option('--pid <pid>', 'Create a filtered HiLog view for this process.')\n .option('--tag <tag>', 'Create a filtered HiLog view for this tag.')\n .option('--level <level>', 'Create a filtered HiLog view for this level (V/D/I/W/E/F).')\n .option('--duration <seconds>', 'Keep HiLog records from the last N seconds (default 600).', '600')\n .option('--redact', 'Redact sensitive values and archive only the redacted bundle.')\n .option('--json', 'Emit bundle paths and status as JSON.')\n .action(async (opts: CollectOptions) => {\n const { config } = getRuntime();\n const result = await collectLogBundle({\n config,\n outputDirectory: opts.output,\n deviceSerial: opts.device,\n packageName: opts.package,\n pid: opts.pid,\n tag: opts.tag,\n level: opts.level,\n durationSeconds: Number(opts.duration),\n redact: Boolean(opts.redact),\n });\n const output = opts.json\n ? `${JSON.stringify({ ...result, status: result.complete ? 'complete' : 'partial' }, null, 2)}\\n`\n : `${result.archivePath ?? result.bundleDirectory}\\n`;\n process.stdout.write(output);\n if (!result.complete) {\n throw new Error(`Bundle is partial; inspect manifest.json. ${result.error ?? 'One or more collectors failed.'}`);\n }\n });\n\n logs\n .command('crash')\n .description(\n \"Fetch the newest faultlog of an app from the device and say what happened: a native crash (cpp_crash), \" +\n 'an uncaught ArkTS/JS error (js_crash), a freeze (app_freeze), or none. Reports the reason, the top frame, ' +\n 'the first frame in the project\\'s own code with file:line:column, the JS error and its stack, the native ' +\n 'frames and, for a freeze, the binder chain. The bundle defaults to the project in the current directory, ' +\n 'else any app. Lists through `hidumper -s 1201 -a \"-p Faultlogger\"`, and also reads faultloggerd\\'s native ' +\n 'crash records that hiview did not turn into a faultlog. Exits 0 whether or not there was a crash; check `crashed`.',\n )\n .allowExcessArguments(false)\n .option('--bundle <bundle>', 'App to look for (default: the bundleName of the project in the current directory, else any process).')\n .option('--since <s|ISO>', 'Only faults from the last N seconds (device clock), or since an ISO 8601 time.')\n .option('--wait <ms>', 'Keep looking this long when there is no fault yet; hiview writes the faultlog a few seconds after the process dies (default: look once).')\n .option('--path <file>', 'Analyse this local faultlog (or faultloggerd .json crash record) instead of fetching one.')\n .option('-o, --output <directory>', 'Where to save the fetched faultlog.', path.join(os.homedir(), '.oniro', 'faultlogs'))\n .option('--device <serial>', 'Target device serial.')\n .option(\n '--json',\n 'Print the verdict as JSON: crashed, kind, subtype, confidence, bundle, pid, time, reason, topFrame, projectFrame, ' +\n 'file, line, column, jsError {name, message, stack}, stack, nativeFrames, jsFrames, binderChain, deadlocks, notes, name, path, rawPath.',\n )\n .action(async (opts: CrashOptions) => {\n const since = parseCrashSince(opts.since);\n const waitMs = opts.wait !== undefined ? Number(opts.wait) : 0;\n if (!Number.isFinite(waitMs) || waitMs < 0) throw new Error(`--wait takes a number of milliseconds, not \"${opts.wait}\".`);\n let verdict: CrashVerdict | null;\n const bundle = opts.bundle ?? (opts.path ? undefined : projectBundle(process.cwd()));\n if (opts.path) {\n const file = path.resolve(opts.path);\n verdict = analyzeFaultLog(await fs.readFile(file, 'utf8'), { name: path.basename(file), path: file, rawPath: file });\n } else {\n const { config, logger } = getRuntime();\n logger.info(`Looking for the newest fault of ${bundle ?? 'any process'}${opts.since ? ` since ${opts.since}` : ''}...`);\n verdict = await latestCrash({ config, bundle, since, waitMs, deviceSerial: opts.device, saveDir: opts.output, logger });\n }\n if (opts.json) {\n const none = { crashed: false, kind: null, bundle: bundle ?? null, since: since instanceof Date ? since.toISOString() : since ?? null };\n process.stdout.write(`${JSON.stringify(verdict ?? none, null, 2)}\\n`);\n } else {\n process.stdout.write(verdict ? formatCrashVerdict(verdict) : `No fault for ${bundle ?? 'any process'}${opts.since ? ` since ${opts.since}` : ''}.\\n`);\n }\n });\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { deflateRawSync } from 'node:zlib';\nimport {\n VERSION, hdcExec, parseDeviceList, resolveDeviceSerial, shellChecked, type ConfigProvider, type HdcExecResult,\n} from '@oniroproject/core';\n\nexport interface CollectLogBundleOptions {\n config: ConfigProvider;\n outputDirectory: string;\n deviceSerial?: string;\n packageName?: string;\n pid?: string;\n tag?: string;\n level?: string;\n durationSeconds?: number;\n redact: boolean;\n execute?: (args: readonly string[], deviceSerial?: string) => Promise<HdcExecResult>;\n}\n\nexport interface LogBundleResult {\n bundleDirectory: string;\n archivePath: string | null;\n redactedDirectory: string | null;\n complete: boolean;\n error?: string;\n}\n\ninterface CommandRecord {\n name: string;\n status: 'success' | 'failed';\n output: string | null;\n stderr: string | null;\n exitCode: number | null;\n error: string | null;\n}\n\nconst LEVELS: Record<string, string> = {\n V: 'V', VERBOSE: 'V', D: 'D', DEBUG: 'D', I: 'I', INFO: 'I',\n W: 'W', WARN: 'W', WARNING: 'W', E: 'E', ERROR: 'E', F: 'F', FATAL: 'F',\n};\nconst HILOG_RECORD = /^(?<date>\\d{2}-\\d{2})[ \\t]+(?<time>\\d{2}:\\d{2}:\\d{2}\\.\\d{3})[ \\t]+(?<pid>\\d+)[ \\t]+\\d+[ \\t]+(?<level>[VDIWEF])[ \\t]+(?<tag>\\S+?)(?:[ \\t]+[NH](?::(?:[ \\t]+.*)?|[ \\t]+.*)?|:(?:[ \\t]+.*)?)$/;\nconst FAILURE_TEXT = /^(?:\\s*(?:\\[(?:fail|error)\\]|(?:error|failed|failure):|permission denied\\b|no devices? connected\\b|too many arguments\\b|unknown option\\b|invalid option\\b|command not found\\b)|\\s*(?:hdc|device)\\b.*\\b(?:error|failed|no device|not connected|offline)\\b)/im;\n\nfunction validateDate(date: string, time: string): boolean {\n const [, monthText, dayText] = /^(\\d{2})-(\\d{2})$/.exec(date) ?? [];\n const [, hourText, minuteText, secondText, millisecondText] = /^(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})$/.exec(time) ?? [];\n if (!monthText || !dayText || !hourText || !minuteText || !secondText || !millisecondText) return false;\n const value = new Date(Date.UTC(2000, Number(monthText) - 1, Number(dayText), Number(hourText), Number(minuteText), Number(secondText), Number(millisecondText)));\n return value.getUTCMonth() === Number(monthText) - 1 && value.getUTCDate() === Number(dayText) &&\n Number(hourText) < 24 && Number(minuteText) < 60 && Number(secondText) < 60;\n}\n\nexport function filterHilog(\n input: string,\n filters: { pid?: string; tag?: string; level?: string },\n): { text: string; applied: string[] } | null {\n const criteria: Record<string, string> = {};\n if (filters.pid) criteria.pid = filters.pid.replace(/^0+(?=\\d)/, '');\n if (filters.tag) criteria.tag = filters.tag;\n if (filters.level) criteria.level = LEVELS[filters.level.toUpperCase()] ?? filters.level.toUpperCase();\n if (Object.keys(criteria).length === 0) return null;\n\n let sawRecord = false;\n let keep = false;\n let output = '';\n for (const line of input.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n const content = line.replace(/[\\r\\n]+$/, '');\n const match = HILOG_RECORD.exec(content);\n if (match?.groups) {\n if (!validateDate(match.groups.date!, match.groups.time!)) return null;\n sawRecord = true;\n keep = Object.entries(criteria).every(([key, value]) => {\n const field = key === 'tag'\n ? match.groups!.tag!.slice(match.groups!.tag!.lastIndexOf('/') + 1)\n : match.groups![key];\n return key === 'pid' ? field?.replace(/^0+(?=\\d)/, '') === value : field === value;\n });\n } else if (/^\\s*\\[?\\d{1,4}[-/]/.test(content) || (!sawRecord && content.trim())) {\n return null;\n }\n if (keep) output += line;\n }\n return sawRecord ? { text: output, applied: Object.keys(criteria) } : null;\n}\n\nexport function redactLogText(value: string, deviceSerials: readonly string[] = []): string {\n let result = value\n .replace(/(\\bBearer\\s+)[A-Za-z0-9._~+/=-]+/gi, '$1[REDACTED]')\n .replace(/(\\bBasic\\s+)[A-Za-z0-9+/=]+/gi, '$1[REDACTED]')\n .replace(/((?:token|password|passwd|secret|api[_-]?key)\\s*[=:]\\s*)[^\\s,;]+/gi, '$1[REDACTED]')\n .replace(/(cookie\\s*[=:]\\s*)[^\\r\\n]+/gi, '$1[REDACTED]')\n .replace(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi, '[REDACTED_EMAIL]')\n .replace(/((?:phone|mobile|telephone|tel)(?:number)?\\s*[=:]\\s*)\\+?[\\d ()-]{8,}\\d/gi, '$1[REDACTED_PHONE]')\n .replace(/(?<![\\w.])(?:\\+\\d{1,3}[ -]?)?\\(?\\d{2,4}\\)?[ -]\\d{3,4}[ -]\\d{3,4}(?![\\w.])/g, '[REDACTED_PHONE]')\n .replace(/\\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\\b/g, '[REDACTED_MAC]')\n .replace(/([A-Z]:\\\\Users\\\\)[^\\\\\\r\\n \"']+/gi, '$1[REDACTED_USER]')\n .replace(/(\\/(?:Users|home)\\/)[^/\\r\\n \"']+/gi, '$1[REDACTED_USER]')\n .replace(/(\"(?:target|deviceSerial)\"\\s*:\\s*\")[^\"]+(\")/gi, '$1[REDACTED_DEVICE]$2')\n .replace(/(--device\\s+|-t\\s+)([A-Za-z0-9._:-]+)/gi, '$1[REDACTED_DEVICE]');\n\n for (const serial of deviceSerials) {\n if (serial) result = result.split(serial).join('[REDACTED_DEVICE]');\n }\n\n const ipv4 = /\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b/g;\n result = result.replace(ipv4, (address, offset: number, whole: string) => {\n const prefix = whole.slice(Math.max(0, offset - 48), offset);\n const suffix = whole.slice(offset + address.length);\n const contextual = /(?:ip|addr(?:ess)?|host|peer|remote|local|endpoint|server|client|target|device(?:id)?|serial)[^\\r\\n]{0,24}$/i.test(prefix);\n const hasPort = /^:\\d{1,5}(?!\\d)/.test(suffix);\n const octets = address.split('.').map(Number);\n return octets.every((part: number) => part <= 255) && (contextual || hasPort) ? '[REDACTED_IP]' : address;\n });\n return result;\n}\n\nfunction decodeText(data: Buffer, relativePath: string): string {\n let text: string;\n if (data.subarray(0, 2).equals(Buffer.from([0xff, 0xfe]))) text = data.toString('utf16le').slice(1);\n else if (data.subarray(0, 2).equals(Buffer.from([0xfe, 0xff]))) {\n const swapped = Buffer.from(data.subarray(2));\n for (let i = 0; i + 1 < swapped.length; i += 2) [swapped[i], swapped[i + 1]] = [swapped[i + 1]!, swapped[i]!];\n text = swapped.toString('utf16le');\n } else {\n const utf8 = data.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) ? data.subarray(3) : data;\n if (utf8.includes(0)) throw new Error(`Binary data cannot be safely redacted: ${relativePath}`);\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(utf8);\n } catch {\n throw new Error(`Non-UTF-8 data cannot be safely redacted: ${relativePath}`);\n }\n }\n if (text.includes('\\u0000')) throw new Error(`Binary data cannot be safely redacted: ${relativePath}`);\n return text;\n}\n\nasync function redactTree(\n source: string,\n destination: string,\n serials: readonly string[],\n boundedHilog: string | null,\n): Promise<void> {\n await fs.mkdir(destination, { recursive: false, mode: 0o700 });\n try {\n const visit = async (directory: string): Promise<void> => {\n for (const entry of await fs.readdir(directory, { withFileTypes: true })) {\n const sourcePath = path.join(directory, entry.name);\n const relative = path.relative(source, sourcePath);\n const portableRelative = relative.split(path.sep).join('/');\n const destinationPath = path.join(destination, relative);\n if (entry.isDirectory()) {\n await fs.mkdir(destinationPath, { recursive: true, mode: 0o700 });\n await visit(sourcePath);\n } else if (entry.isFile()) {\n if (portableRelative === 'logs/hilog.txt') {\n const text = boundedHilog ?? 'HiLog omitted from this archive because the requested duration could not be reliably applied.\\n';\n await fs.mkdir(path.dirname(destinationPath), { recursive: true, mode: 0o700 });\n await fs.writeFile(destinationPath, redactLogText(text, serials), { encoding: 'utf8', mode: 0o600 });\n continue;\n }\n if (portableRelative === 'logs/hilog-filtered.txt' && boundedHilog === null) continue;\n const text = decodeText(await fs.readFile(sourcePath), relative);\n await fs.mkdir(path.dirname(destinationPath), { recursive: true, mode: 0o700 });\n await fs.writeFile(destinationPath, redactLogText(text, serials), { encoding: 'utf8', mode: 0o600 });\n }\n }\n };\n await visit(source);\n } catch (error) {\n await fs.rm(destination, { recursive: true, force: true });\n throw error;\n }\n}\n\nconst CRC_TABLE = new Uint32Array(256);\nfor (let i = 0; i < CRC_TABLE.length; i++) {\n let value = i;\n for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;\n CRC_TABLE[i] = value >>> 0;\n}\n\nfunction crc32(data: Buffer): number {\n let crc = 0xffffffff;\n for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nfunction dosDateTime(date: Date): { date: number; time: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2),\n };\n}\n\nasync function writeZip(source: string, archivePath: string): Promise<void> {\n const files: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n for (const entry of await fs.readdir(directory, { withFileTypes: true })) {\n const filePath = path.join(directory, entry.name);\n if (entry.isDirectory()) await visit(filePath);\n else if (entry.isFile()) files.push(filePath);\n }\n };\n await visit(source);\n const localParts: Buffer[] = [];\n const centralParts: Buffer[] = [];\n let offset = 0;\n const stamp = dosDateTime(new Date());\n\n for (const filePath of files) {\n const name = Buffer.from(path.relative(source, filePath).split(path.sep).join('/'), 'utf8');\n const data = await fs.readFile(filePath);\n const compressed = deflateRawSync(data);\n const checksum = crc32(data);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6);\n local.writeUInt16LE(8, 8); local.writeUInt16LE(stamp.time, 10); local.writeUInt16LE(stamp.date, 12);\n local.writeUInt32LE(checksum, 14); local.writeUInt32LE(compressed.length, 18); local.writeUInt32LE(data.length, 22);\n local.writeUInt16LE(name.length, 26); local.writeUInt16LE(0, 28);\n localParts.push(local, name, compressed);\n\n const central = Buffer.alloc(46);\n central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6);\n central.writeUInt16LE(0x0800, 8); central.writeUInt16LE(8, 10); central.writeUInt16LE(stamp.time, 12);\n central.writeUInt16LE(stamp.date, 14); central.writeUInt32LE(checksum, 16);\n central.writeUInt32LE(compressed.length, 20); central.writeUInt32LE(data.length, 24);\n central.writeUInt16LE(name.length, 28); central.writeUInt16LE(0, 30); central.writeUInt16LE(0, 32);\n central.writeUInt16LE(0, 34); central.writeUInt16LE(0, 36); central.writeUInt32LE(0, 38);\n central.writeUInt32LE(offset, 42);\n centralParts.push(central, name);\n offset += local.length + name.length + compressed.length;\n }\n\n const centralDirectory = Buffer.concat(centralParts);\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(0, 4); end.writeUInt16LE(0, 6);\n end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);\n end.writeUInt32LE(centralDirectory.length, 12); end.writeUInt32LE(offset, 16); end.writeUInt16LE(0, 20);\n await fs.writeFile(archivePath, Buffer.concat([...localParts, centralDirectory, end]), { flag: 'wx', mode: 0o600 });\n}\n\nfunction commandFailure(result: HdcExecResult): string | null {\n if (result.code !== 0) return `hdc exited with code ${result.code}`;\n if (result.stderr.trim()) return 'hdc wrote to stderr';\n const contentError = result.stdout.split(/\\r?\\n/).find((line) => FAILURE_TEXT.test(line))?.trim() ?? null;\n return contentError ? `command output indicates failure: ${contentError}` : null;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function uniqueBundleDirectory(outputDirectory: string, stamp: string): Promise<string> {\n await fs.mkdir(outputDirectory, { recursive: true, mode: 0o700 });\n for (let suffix = 0; ; suffix++) {\n const name = `incident-${stamp}${suffix ? `-${suffix}` : ''}`;\n const directory = path.join(outputDirectory, name);\n try {\n await fs.mkdir(directory, { mode: 0o700 });\n return directory;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n}\n\nexport async function collectLogBundle(options: CollectLogBundleOptions): Promise<LogBundleResult> {\n if (options.packageName && !/^[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)+$/.test(options.packageName)) {\n throw new Error('packageName must be a reverse-DNS bundle name.');\n }\n if (options.pid && !/^[1-9]\\d*$/.test(options.pid)) throw new Error('pid must be a positive integer.');\n if (options.tag && !/^[^\\s/\\x00-\\x1f\\x7f]+$/.test(options.tag)) throw new Error('tag must be a single HiLog tag.');\n if (options.level && !LEVELS[options.level.toUpperCase()]) throw new Error('level is not a recognized HiLog level.');\n const durationSeconds = options.durationSeconds ?? 600;\n if (!Number.isSafeInteger(durationSeconds) || durationSeconds < 1 || durationSeconds > 31_536_000) {\n throw new Error('durationSeconds must be an integer between 1 and 31536000.');\n }\n\n const started = new Date();\n const stamp = started.toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z');\n const bundleDirectory = await uniqueBundleDirectory(path.resolve(options.outputDirectory), stamp);\n const records: CommandRecord[] = [];\n const serials: string[] = [];\n let replacementWarning = false;\n const execute = options.execute ?? ((args, deviceSerial) => args[0] === 'shell'\n ? shellChecked({ config: options.config, command: args.slice(1).join(' '), deviceSerial })\n : hdcExec({ config: options.config, args, deviceSerial }));\n const manifest: Record<string, unknown> = {\n schemaVersion: '1.0',\n collectorVersion: VERSION,\n collectionStartUtc: started.toISOString(),\n collectionEndUtc: null,\n host: { os: process.platform },\n target: null,\n packageName: options.packageName ?? null,\n pid: options.pid ?? null,\n filters: {\n tag: options.tag ?? null,\n level: options.level ?? null,\n pid: options.pid ?? null,\n packageName: options.packageName ?? null,\n durationSeconds,\n },\n filterStatus: {\n duration: 'not-applied',\n packageName: options.packageName ? 'failed' : 'not-requested',\n pid: options.pid ? 'not-applied' : 'not-requested',\n tag: options.tag ? 'not-applied' : 'not-requested',\n level: options.level ? 'not-applied' : 'not-requested',\n },\n hilogWindowApplied: false,\n redactionRequested: options.redact,\n redactionStatus: options.redact ? 'pending' : 'not-requested',\n archiveStatus: { status: 'pending', path: null },\n commands: records,\n files: [],\n notes: [\n 'Collection is read-only on the target device.',\n 'hilog -x captures the current device buffer; duration is applied locally against device time when log timestamps are recognized.',\n 'Redaction is heuristic and does not guarantee that a bundle is safe to publish.',\n ],\n };\n\n const run = async (name: string, relativeOutput: string, args: readonly string[], deviceSerial?: string): Promise<CommandRecord> => {\n const outputPath = path.join(bundleDirectory, relativeOutput);\n await fs.mkdir(path.dirname(outputPath), { recursive: true, mode: 0o700 });\n let result: HdcExecResult | null = null;\n let failure: string | null = null;\n try {\n result = await execute(args, deviceSerial);\n await fs.writeFile(outputPath, result.stdout, { encoding: 'utf8', mode: 0o600 });\n if (result.stderr) await fs.writeFile(`${outputPath}.stderr.txt`, result.stderr, { encoding: 'utf8', mode: 0o600 });\n if (result.stdout.includes('\\ufffd') || result.stderr.includes('\\ufffd')) {\n replacementWarning = true;\n (manifest.notes as string[]).push(`${name} output contains Unicode replacement characters; review the redacted evidence before sharing.`);\n }\n failure = commandFailure(result);\n } catch (error) {\n failure = errorMessage(error);\n await fs.writeFile(outputPath, '', { encoding: 'utf8', mode: 0o600 });\n }\n const record: CommandRecord = {\n name,\n status: failure ? 'failed' : 'success',\n output: relativeOutput,\n stderr: result?.stderr ? `${relativeOutput}.stderr.txt` : null,\n exitCode: result?.code ?? null,\n error: failure,\n };\n records.push(record);\n return record;\n };\n\n const targetRecord = await run('list-targets', 'device/targets.txt', ['list', 'targets', '-v']);\n const targetOutput = await fs.readFile(path.join(bundleDirectory, 'device/targets.txt'), 'utf8').catch(() => '');\n const targets = parseDeviceList(targetOutput).filter((target) => target.status === 'Connected' || target.status === 'Unknown');\n serials.push(...parseDeviceList(targetOutput).map((target) => target.serial));\n const requestedDevice = resolveDeviceSerial(options.deviceSerial);\n let selectedDevice: string | null = null;\n let targetError: string | null = null;\n if (targetRecord.status !== 'success') targetError = targetRecord.error ?? 'hdc target discovery failed';\n else if (requestedDevice) {\n selectedDevice = targets.find((target) => target.serial === requestedDevice)?.serial ?? null;\n if (!selectedDevice) targetError = 'selected device was not discovered as connected';\n } else if (targets.length === 0) targetError = 'hdc did not discover a connected device';\n else if (targets.length > 1) targetError = 'multiple devices are connected; specify --device';\n else selectedDevice = targets[0]!.serial;\n\n let boundedHilog: string | null = null;\n let durationApplied = false;\n let durationFailureReason = 'device clock or HiLog collection failed';\n if (targetError) {\n targetRecord.status = 'failed';\n targetRecord.error = targetError;\n (manifest.notes as string[]).push('Device collection stopped because target discovery did not identify exactly one selected connected device.');\n } else {\n manifest.target = selectedDevice;\n const shell = (args: readonly string[]) => run(args[0]!, args[1]!, args.slice(2), selectedDevice!);\n const captureStartedHostMs = Date.now();\n const deviceTimeBefore = await shell([\n 'device-time-before', 'device/device-time-before.txt', 'shell', 'date', '+%Y-%m-%dT%H:%M:%S',\n ]);\n const hilog = await shell(['hilog-snapshot', 'logs/hilog.txt', 'shell', 'hilog', '-x']);\n const deviceTimeAfter = await shell([\n 'device-time-after', 'device/device-time-after.txt', 'shell', 'date', '+%Y-%m-%dT%H:%M:%S',\n ]);\n const hostElapsedMs = Date.now() - captureStartedHostMs;\n if (deviceTimeBefore.status === 'success' && hilog.status === 'success' && deviceTimeAfter.status === 'success') {\n const [beforeText, afterText, fullHilog] = await Promise.all([\n fs.readFile(path.join(bundleDirectory, 'device/device-time-before.txt'), 'utf8'),\n fs.readFile(path.join(bundleDirectory, 'device/device-time-after.txt'), 'utf8'),\n fs.readFile(path.join(bundleDirectory, 'logs/hilog.txt'), 'utf8'),\n ]);\n const window = filterHilogWindow(fullHilog, beforeText, afterText, durationSeconds, hostElapsedMs);\n if (window.text === null) durationFailureReason = window.reason;\n else boundedHilog = window.text;\n } else if (deviceTimeBefore.status !== 'success' || deviceTimeAfter.status !== 'success') {\n durationFailureReason = 'device clock could not be read';\n } else if (hilog.status !== 'success') {\n durationFailureReason = 'HiLog snapshot collection failed';\n }\n durationApplied = boundedHilog !== null;\n manifest.hilogWindowApplied = durationApplied;\n const faultArgs = options.packageName\n ? ['faultlog', 'logs/faultlog.txt', 'shell', 'hidumper', '-e', '--print', options.packageName, '-n', '5']\n : ['faultlog', 'logs/faultlog.txt', 'shell', 'hidumper', '-e', '--list', '-n', '20'];\n const faultlog = await shell(faultArgs);\n manifest.filterStatus = {\n duration: durationApplied ? 'applied' : 'not-applied',\n packageName: options.packageName ? (faultlog.status === 'success' ? 'applied' : 'failed') : 'not-requested',\n pid: options.pid ? 'not-applied' : 'not-requested',\n tag: options.tag ? 'not-applied' : 'not-requested',\n level: options.level ? 'not-applied' : 'not-requested',\n };\n if (!durationApplied) {\n (manifest.notes as string[]).push(\n `HiLog duration was not applied (${durationFailureReason}); the full snapshot is kept only in the local raw bundle and omitted from the redacted archive.`,\n );\n } else if (boundedHilog !== null && (options.pid || options.tag || options.level)) {\n const filtered = filterHilog(boundedHilog, { pid: options.pid, tag: options.tag, level: options.level });\n if (filtered) {\n await fs.writeFile(path.join(bundleDirectory, 'logs/hilog-filtered.txt'), filtered.text, { encoding: 'utf8', mode: 0o600 });\n const status = manifest.filterStatus as Record<string, string>;\n for (const key of filtered.applied) status[key] = 'applied';\n } else {\n (manifest.notes as string[]).push('Requested HiLog PID/tag/level filters were not applied because the windowed snapshot format could not be parsed reliably.');\n }\n }\n await shell(['device-name', 'device/device-info.txt', 'shell', 'param', 'get', 'const.product.name']);\n await shell(['process-list', 'device/process-list.txt', 'shell', 'ps', '-ef']);\n await shell(['memory', 'device/memory.txt', 'shell', 'hidumper', '--mem']);\n await shell(['threads', 'device/threads.txt', 'shell', 'hidumper', '-p']);\n }\n\n const ended = new Date();\n manifest.collectionEndUtc = ended.toISOString();\n const files = records.flatMap((record) => [record.output, record.stderr].filter((file): file is string => Boolean(file)));\n files.push('manifest.json', 'notes.txt');\n if (await fs.access(path.join(bundleDirectory, 'logs/hilog-filtered.txt')).then(() => true, () => false)) {\n files.push('logs/hilog-filtered.txt');\n }\n manifest.files = files;\n await fs.writeFile(path.join(bundleDirectory, 'notes.txt'), 'Add reproduction steps and precise event timestamps here.\\n', { encoding: 'utf8', mode: 0o600 });\n\n const durationFailure = !durationApplied;\n const criticalFailure = Boolean(targetError) || records.some((record) => record.name === 'hilog-snapshot' && record.status !== 'success');\n const anyCommandFailure = records.some((record) => record.status !== 'success');\n let redactedDirectory: string | null = null;\n let archivePath: string | null = null;\n let bundleError: string | undefined;\n\n try {\n if (options.redact) {\n redactedDirectory = `${bundleDirectory}-redacted`;\n manifest.redactionStatus = replacementWarning ? 'review-required' : 'success';\n manifest.archiveStatus = { status: 'success', path: `${path.basename(redactedDirectory)}.zip` };\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n await redactTree(bundleDirectory, redactedDirectory, serials, boundedHilog);\n archivePath = `${redactedDirectory}.zip`;\n await writeZip(redactedDirectory, archivePath);\n } else {\n archivePath = `${bundleDirectory}.zip`;\n manifest.archiveStatus = { status: 'success', path: path.basename(archivePath) };\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n await writeZip(bundleDirectory, archivePath);\n }\n } catch (error) {\n bundleError = options.redact ? `redaction or archive creation failed: ${errorMessage(error)}` : `archive creation failed: ${errorMessage(error)}`;\n archivePath = null;\n manifest.redactionStatus = options.redact ? 'failed' : 'not-requested';\n manifest.archiveStatus = { status: 'failed', path: null };\n (manifest.notes as string[]).push(bundleError);\n await fs.rm(`${redactedDirectory ?? bundleDirectory}.zip`, { force: true }).catch(() => undefined);\n if (redactedDirectory) await fs.rm(redactedDirectory, { recursive: true, force: true }).catch(() => undefined);\n await fs.writeFile(path.join(bundleDirectory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n redactedDirectory = null;\n }\n\n return {\n bundleDirectory,\n archivePath,\n redactedDirectory,\n complete: !criticalFailure && !anyCommandFailure && !bundleError && !replacementWarning && !durationFailure,\n error: bundleError ?? (criticalFailure ? targetError ?? 'HiLog collection failed' : replacementWarning\n ? 'Captured output contains Unicode replacement characters; review the manifest before sharing.'\n : durationFailure ? `HiLog duration was not applied (${durationFailureReason}); the redacted archive omits the full snapshot.`\n : undefined),\n };\n}\n\nfunction parseDeviceClock(value: string): number | null {\n const match = /^\\s*(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\s*$/.exec(value);\n if (!match) return null;\n const [, year, month, day, hour, minute, second] = match;\n const timestamp = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second));\n const date = new Date(timestamp);\n return date.getUTCFullYear() === Number(year) && date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day) && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60\n ? timestamp\n : null;\n}\n\nfunction parseHilogTimestamp(datePart: string, timePart: string, referenceMs: number): number | null {\n if (!validateDate(datePart, timePart)) return null;\n const [month, day] = datePart.split('-').map(Number);\n const [hour, minute, second, millisecond] = timePart.split(/[:.]/).map(Number);\n const referenceYear = new Date(referenceMs).getUTCFullYear();\n const candidates = [referenceYear - 1, referenceYear, referenceYear + 1]\n .map((year) => Date.UTC(year, month! - 1, day!, hour!, minute!, second!, millisecond!))\n .filter((timestamp) => {\n const candidate = new Date(timestamp);\n return candidate.getUTCMonth() === month! - 1 && candidate.getUTCDate() === day;\n })\n .sort((left, right) => Math.abs(left - referenceMs) - Math.abs(right - referenceMs));\n const closest = candidates[0];\n return closest !== undefined && closest <= referenceMs + 2_000 ? closest : null;\n}\n\nexport type HilogWindowResult = { text: string; reason?: undefined } | { text: null; reason: string };\n\nexport function filterHilogWindow(\n input: string,\n deviceClockBefore: string,\n deviceClockAfter: string,\n durationSeconds: number,\n hostElapsedMs: number,\n): HilogWindowResult {\n if (!Number.isSafeInteger(durationSeconds) || durationSeconds < 1 || durationSeconds > 31_536_000) {\n return { text: null, reason: 'requested duration is invalid' };\n }\n const beforeMs = parseDeviceClock(deviceClockBefore);\n const afterMs = parseDeviceClock(deviceClockAfter);\n if (beforeMs === null || afterMs === null) return { text: null, reason: 'device clock output was not recognized' };\n const deviceElapsedMs = afterMs - beforeMs;\n if (deviceElapsedMs < -1_000 || deviceElapsedMs > Math.max(0, hostElapsedMs) + 5_000) {\n return { text: null, reason: 'device clock changed inconsistently during capture' };\n }\n\n const windowEnd = afterMs + 999;\n const windowStart = windowEnd - durationSeconds * 1_000;\n let sawRecord = false;\n let keep = false;\n let output = '';\n for (const line of input.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n const content = line.replace(/[\\r\\n]+$/, '');\n const match = HILOG_RECORD.exec(content);\n if (match?.groups) {\n if (!validateDate(match.groups.date!, match.groups.time!)) {\n return { text: null, reason: 'HiLog contains an invalid timestamp' };\n }\n const timestamp = parseHilogTimestamp(match.groups.date!, match.groups.time!, afterMs);\n if (timestamp === null || timestamp > windowEnd) {\n return { text: null, reason: 'HiLog timestamps do not agree with the device clock' };\n }\n sawRecord = true;\n keep = timestamp >= windowStart;\n } else if (/^-{3,}\\s*beginning of\\b/i.test(content.trim())) {\n continue;\n } else if (/^\\s*\\[?\\d{1,4}[-/]/.test(content) || /^\\s*\\d{2}:\\d{2}:\\d{2}/.test(content)) {\n return { text: null, reason: 'HiLog contains timestamped lines in an unrecognized format' };\n } else if (!sawRecord && content.trim()) {\n return { text: null, reason: 'HiLog contains unclassified lines before the first record' };\n }\n if (keep) output += line;\n }\n return sawRecord ? { text: output } : { text: null, reason: 'no recognized timestamped HiLog records were found' };\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { getBundleName, type CrashVerdict } from '@oniroproject/core';\n\n/**\n * `--since` for `logs crash`: a number of seconds before the device's clock\n * now, or an ISO 8601 instant. Undefined when not given.\n */\nexport function parseCrashSince(value: string | undefined): number | Date | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (/^\\d+(?:\\.\\d+)?$/.test(trimmed)) return Number(trimmed);\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(trimmed)) {\n const date = new Date(trimmed);\n if (!Number.isNaN(date.getTime())) return date;\n }\n throw new Error(`--since takes a number of seconds or an ISO 8601 time (2026-11-05T12:30:00+01:00), not \"${value}\".`);\n}\n\n/** The bundle of the project in `dir`, or undefined when `dir` is not a project. */\nexport function projectBundle(dir: string): string | undefined {\n if (!fs.existsSync(path.join(dir, 'AppScope', 'app.json5'))) return undefined;\n try {\n return getBundleName(dir);\n } catch {\n return undefined;\n }\n}\n\n/** A few lines a person reads: kind, process, reason, the JS error, where it happened, and the log. */\nexport function formatCrashVerdict(v: CrashVerdict): string {\n const lines: string[] = [];\n const kind = v.subtype ? `${v.kind} (${v.subtype})` : v.kind;\n const who = [v.bundle ?? v.process, v.pid !== null ? `pid ${v.pid}` : null].filter(Boolean).join(' ');\n lines.push(`${v.crashed ? 'CRASH' : 'NO CRASH'} ${kind}, ${v.confidence} confidence${who ? `: ${who}` : ''}${v.time ? ` at ${v.time}` : ''}`);\n if (v.jsError) lines.push(`${v.jsError.name}: ${v.jsError.message}`);\n else if (v.reason) lines.push(`Reason: ${v.reason}`);\n if (v.lastFatalMessage) lines.push(`Last fatal message: ${v.lastFatalMessage}`);\n if (v.file) lines.push(`At ${v.file}:${v.line}:${v.column}`);\n if (v.topFrame) lines.push(`Top frame: ${v.topFrame}`);\n if (v.projectFrame && v.projectFrame !== v.topFrame) lines.push(`Project frame: ${v.projectFrame}`);\n const shown = v.stack.slice(0, 12);\n if (shown.length > 0) lines.push('Stack:', ...shown.map((f) => ` ${f}`));\n if (v.stack.length > shown.length) lines.push(` … ${v.stack.length - shown.length} more`);\n for (const edge of v.binderChain) {\n lines.push(`Binder: ${edge.from} -> ${edge.to} waits ${edge.waitSeconds.toFixed(2)} s${edge.frzState ? ` frz_state:${edge.frzState}` : ''}`);\n }\n for (const cycle of v.deadlocks) lines.push(`Binder deadlock: ${cycle}`);\n for (const note of v.notes) lines.push(`Note: ${note}`);\n if (v.path) lines.push(`Faultlog: ${v.path}`);\n if (v.rawPath && v.rawPath !== v.path) lines.push(`Saved to: ${v.rawPath}`);\n return `${lines.join('\\n')}\\n`;\n}\n","import { Command } from 'commander';\nimport { getHdcPath, hdcTargetArgsFor, spawnCompat } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\n/** The argv for the passthrough: verbatim when the caller already picked a target with `-t`. */\nexport function hdcPassthroughArgv(args: readonly string[], device?: string): string[] {\n return args[0] === '-t' ? [...args] : [...hdcTargetArgsFor(args, device), ...args];\n}\n\nexport function registerHdcCommand(program: Command): void {\n program\n .command('hdc')\n .description(\n 'Run the hdc binary oniro-app itself uses (see `cmdtools status`), addressed at --device or ' +\n 'ONIRO_DEVICE_SERIAL, with stdio passed through. Exits with hdc\\'s own code, which is 0 even for ' +\n 'a `[Fail]` line. Example: oniro-app hdc shell param get const.ohos.apiversion',\n )\n .argument('[args...]', 'hdc arguments, passed through verbatim')\n .option('--device <serial>', 'Target device serial.')\n .option('--path', 'Print the hdc binary path and exit.')\n .passThroughOptions()\n .allowUnknownOption()\n .action(async (args: string[], opts: { device?: string; path?: boolean }) => {\n const { config } = getRuntime();\n const hdc = getHdcPath(config);\n if (opts.path) {\n process.stdout.write(`${hdc}\\n`);\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const child = spawnCompat(hdc, hdcPassthroughArgv(args, opts.device), { stdio: 'inherit' });\n child.on('error', (err) => reject(new Error(`Failed to run ${hdc}: ${err.message}`)));\n child.on('close', (code) => {\n process.exitCode = code ?? 1;\n resolve();\n });\n });\n });\n}\n","import { Command } from 'commander';\nimport * as path from 'node:path';\nimport {\n findApiInOtherSdks,\n getApiIndexCacheDir,\n loadApiIndex,\n resolveApiSdk,\n searchApi,\n showApi,\n suggestApiSymbols,\n OniroError,\n type ApiElsewhere,\n type ApiEntry,\n type ApiIndex,\n type ApiSdkSelection,\n type ApiSearchHit,\n type ApiSymbolKind,\n type LoadedApiIndex,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\n\nexport interface SdkOpts {\n api?: string;\n sdk?: string;\n project?: string;\n rebuild?: boolean;\n json?: boolean;\n}\n\nexport interface SearchOpts extends SdkOpts {\n kit?: string;\n kind?: string[];\n lang?: string;\n limit?: string;\n deprecated?: boolean;\n systemapi?: boolean;\n}\n\nexport interface ShowOpts extends SdkOpts {\n kit?: string;\n otherSdks?: boolean;\n}\n\nconst KINDS: readonly ApiSymbolKind[] = [\n 'namespace',\n 'class',\n 'interface',\n 'enum',\n 'enumMember',\n 'type',\n 'function',\n 'method',\n 'constructor',\n 'property',\n 'variable',\n 'component',\n 'decorator',\n 'macro',\n 'typedef',\n 'struct',\n];\n\nfunction parseApi(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isInteger(n) || n <= 0) throw new OniroError(`--api expects an API level such as 20, got \"${value}\".`);\n return n;\n}\n\nfunction parseKinds(values: string[] | undefined): ApiSymbolKind[] | undefined {\n if (!values?.length) return undefined;\n const out: ApiSymbolKind[] = [];\n for (const v of values.flatMap((x) => x.split(','))) {\n const k = KINDS.find((kind) => kind.toLowerCase() === v.trim().toLowerCase());\n if (!k) throw new OniroError(`Unknown --kind \"${v}\". Kinds: ${KINDS.join(', ')}.`);\n out.push(k);\n }\n return out;\n}\n\nfunction selectSdk(opts: SdkOpts): ApiSdkSelection {\n const { config, logger } = getRuntime();\n const selection = resolveApiSdk(config, {\n sdkDir: opts.sdk,\n api: parseApi(opts.api),\n projectDir: opts.project ? path.resolve(opts.project) : process.cwd(),\n });\n if (selection.note) logger.warn(selection.note);\n return selection;\n}\n\nfunction openIndex(sdkDir: string, rebuild?: boolean): LoadedApiIndex {\n const { config, logger } = getRuntime();\n return loadApiIndex(sdkDir, { cacheDir: getApiIndexCacheDir(config), rebuild, logger });\n}\n\n/** `API 20 (6.0.0.47)`. */\nexport function describeIndex(index: Pick<ApiIndex, 'api' | 'sdkVersion' | 'sdkDir'>): string {\n const api = index.api !== undefined ? `API ${index.api}` : index.sdkDir;\n return index.sdkVersion ? `${api} (${index.sdkVersion})` : api;\n}\n\n/** The facts line of an entry: `method @kit.ArkUI since 10 deprecated since 18, use X systemapi`. */\nexport function apiEntryFacts(e: ApiEntry): string {\n const parts: string[] = [e.kind];\n if (e.kit) parts.push(e.kit);\n if (e.since !== undefined) parts.push(`since ${e.sinceText ?? e.since}`);\n if (e.deprecated !== undefined) {\n const dep = e.deprecated ? `deprecated ${e.deprecated}` : 'deprecated';\n parts.push(e.useInstead ? `${dep}, use ${e.useInstead}` : dep);\n }\n if (e.systemApi) parts.push('systemapi');\n return parts.join(' ');\n}\n\n/** One hit or entry as text: name and facts, the signature, the doc line, then where. */\nexport function formatApiEntry(e: ApiEntry & { overloads?: number }, sdkDir: string): string {\n const lines = [`${e.qualifiedName} ${apiEntryFacts(e)}`];\n lines.push(` ${e.signature}${e.overloads ? ` (+${e.overloads} overload${e.overloads > 1 ? 's' : ''})` : ''}`);\n if (e.doc) lines.push(` ${e.doc}`);\n const where = [`${path.join(sdkDir, e.file)}:${e.line}`, e.module];\n if (e.import) where.push(e.import);\n else if (e.global) where.push('global, no import');\n if (e.syscap) where.push(e.syscap);\n lines.push(` ${where.join(' ')}`);\n return lines.join('\\n');\n}\n\n/** An entry for `--json`: the fields as indexed, plus the absolute `path`. */\nfunction jsonEntry<T extends ApiEntry>(e: T, sdkDir: string): T & { path: string } {\n return { ...e, path: path.join(sdkDir, e.file) };\n}\n\nfunction sdkJson(index: ApiIndex, sel: ApiSdkSelection): Record<string, unknown> {\n return { dir: index.sdkDir, api: index.api, version: index.sdkVersion, source: sel.source };\n}\n\nexport interface ApiSearchRun {\n /** What `api search --json` prints. */\n json: Record<string, unknown>;\n index: ApiIndex;\n hits: ApiSearchHit[];\n total: number;\n}\n\n/** `api search`: select the SDK, open its index and search it. Shared with `serve mcp`. */\nexport function runApiSearch(query: string, opts: SearchOpts): ApiSearchRun {\n const sel = selectSdk(opts);\n const { index } = openIndex(sel.sdkDir, opts.rebuild);\n const lang = opts.lang?.toLowerCase();\n if (lang && lang !== 'arkts' && lang !== 'c') throw new OniroError(`--lang expects arkts or c, got \"${opts.lang}\".`);\n const limit = Number(opts.limit ?? 20);\n if (!Number.isInteger(limit) || limit <= 0) throw new OniroError(`--limit expects a positive number, got \"${opts.limit}\".`);\n const result = searchApi(index, query, {\n kit: opts.kit,\n kinds: parseKinds(opts.kind),\n language: lang as 'arkts' | 'c' | undefined,\n noDeprecated: opts.deprecated === false,\n noSystemApi: opts.systemapi === false,\n limit,\n });\n const json = {\n sdk: sdkJson(index, sel),\n query: result.query,\n total: result.total,\n hits: result.hits.map((h: ApiSearchHit) => jsonEntry(h, index.sdkDir)),\n };\n return { json, index, hits: result.hits, total: result.total };\n}\n\nexport interface ApiShowRun {\n /** What `api show --json` prints. */\n json: Record<string, unknown>;\n index: ApiIndex;\n found: boolean;\n entries: ApiEntry[];\n alsoIn: ApiElsewhere[];\n suggestions: string[];\n}\n\n/** `api show`: the exact lookup, and on a miss the other SDKs and close names. Shared with `serve mcp`. */\nexport function runApiShow(symbol: string, opts: ShowOpts): ApiShowRun {\n const sel = selectSdk(opts);\n const { index } = openIndex(sel.sdkDir, opts.rebuild);\n const r = showApi(index, symbol, { kit: opts.kit });\n let alsoIn: ApiElsewhere[] = [];\n let suggestions: string[] = [];\n if (!r.found) {\n const { config, logger } = getRuntime();\n if (opts.otherSdks !== false) {\n alsoIn = findApiInOtherSdks(config, symbol, index.sdkDir, {\n cacheDir: getApiIndexCacheDir(config),\n kit: opts.kit,\n logger,\n });\n }\n suggestions = suggestApiSymbols(index, symbol);\n }\n const json: Record<string, unknown> = {\n sdk: sdkJson(index, sel),\n symbol,\n found: r.found,\n entries: r.entries.map((e) => jsonEntry(e, index.sdkDir)),\n };\n if (!r.found) {\n json.alsoIn = alsoIn;\n json.suggestions = suggestions;\n }\n return { json, index, found: r.found, entries: r.entries, alsoIn, suggestions };\n}\n\nexport function registerApiCommand(program: Command): void {\n const api = program\n .command('api')\n .description(\n \"Look up the SDK's declarations: the ArkTS API (`ets/api`, `ets/arkts`, the ArkUI components in `ets/component`, \" +\n 'with the kit that exports each symbol) and the Node-API C headers, at one API level. The index is built on first ' +\n 'use (a few seconds) and cached under ~/.oniro/cache (ONIRO_CACHE_DIR).',\n );\n\n const sdkOptions = (cmd: Command): Command =>\n cmd\n .option(\n '--api <level>',\n \"The SDK API level to read. Default: the project's compileSdkVersion (from the current directory or \" +\n '--project), else the newest installed SDK.',\n )\n .option('--sdk <dir>', 'An SDK API directory (holding ets/) to read instead.')\n .option('--project <dir>', 'The project whose compileSdkVersion picks the SDK (default: the current directory).')\n .option('--rebuild', 'Rebuild the index even if the cached one is current.');\n\n sdkOptions(\n api\n .command('search <query...>')\n .description(\n 'Ranked search: every word must match a symbol name (exact name > prefix > camelCase part > substring) or its ' +\n 'doc line. A dotted word matches qualified names (`router.pushUrl`); a leading @ is ignored (`@Local`).',\n ),\n )\n .option('--kit <name>', 'Only symbols this kit exports (`ArkUI` or `@kit.ArkUI`).')\n .option('--kind <kinds...>', `Only these kinds: ${KINDS.join(', ')}.`)\n .option('--lang <lang>', 'Only `arkts` declarations or `c` (Node-API headers).')\n .option('--limit <n>', 'At most n hits.', '20')\n .option('--no-deprecated', 'Leave out @deprecated symbols.')\n .option('--no-systemapi', 'Leave out @systemapi symbols (system apps only).')\n .option(\n '--json',\n 'Print JSON: sdk (dir, api, version, source), query, total, hits (name, qualifiedName, kind, kit, import, module, ' +\n 'since, deprecated, deprecatedSince, useInstead, syscap, systemApi, file, path, line, signature, doc, overloads, score).',\n )\n .action((words: string[], opts: SearchOpts) => {\n const { json, index, hits, total } = runApiSearch(words.join(' '), opts);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(json, null, 2)}\\n`);\n } else {\n for (const h of hits) process.stdout.write(`${formatApiEntry(h, index.sdkDir)}\\n\\n`);\n const shown = hits.length < total ? `${hits.length} of ${total}` : `${total}`;\n process.stdout.write(`${shown} match${total === 1 ? '' : 'es'} in ${describeIndex(index)}.\\n`);\n }\n process.exitCode = total ? 0 : 1;\n });\n\n sdkOptions(\n api\n .command('show <symbol>')\n .description(\n 'Exact lookup: is `symbol` declared at this API level? Takes a qualified name (`NavPathStack.pushPathByName`, ' +\n '`router.pushUrl`, `Column`, `@Local`, `napi_create_threadsafe_function`); when none matches, names that end ' +\n 'with it (`Preferences.get`). Prints every declaration (overloads included). Exits 1 when it is not declared, ' +\n 'naming the other installed SDKs that declare it and close matches.',\n ),\n )\n .option('--kit <name>', 'Only declarations this kit exports.')\n .option('--no-other-sdks', 'On a miss, do not look in the other installed SDKs.')\n .option(\n '--json',\n 'Print JSON: sdk, symbol, found, entries (the `search` hit fields), and on a miss alsoIn ([{api, since}]) and ' +\n 'suggestions (qualified names).',\n )\n .action((symbol: string, opts: ShowOpts) => {\n const { json, index, found, entries, alsoIn, suggestions } = runApiShow(symbol, opts);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(json, null, 2)}\\n`);\n } else if (found) {\n for (const e of entries) process.stdout.write(`${formatApiEntry(e, index.sdkDir)}\\n\\n`);\n process.stdout.write(\n `${symbol} is declared in ${describeIndex(index)} (${entries.length} declaration${entries.length === 1 ? '' : 's'}).\\n`,\n );\n } else {\n process.stdout.write(`${symbol} is not declared in ${describeIndex(index)}.\\n`);\n for (const a of alsoIn) {\n process.stdout.write(` declared in the installed API ${a.api} SDK${a.since !== undefined ? ` (@since ${a.since})` : ''}\\n`);\n }\n if (suggestions.length) process.stdout.write(` close matches: ${suggestions.join(', ')}\\n`);\n }\n process.exitCode = found ? 0 : 1;\n });\n\n sdkOptions(\n api.command('index').description('Build (or refresh) the index of one SDK and print its size, for warming a cache.'),\n )\n .option('--json', 'Print JSON: sdk, entries, files, buildMs, cached, cachePath, loadMs.')\n .action((opts: SdkOpts) => {\n const sel = selectSdk(opts);\n const loaded = openIndex(sel.sdkDir, opts.rebuild);\n const { index } = loaded;\n if (opts.json) {\n const out = {\n sdk: { dir: index.sdkDir, api: index.api, version: index.sdkVersion, source: sel.source },\n entries: index.entries.length,\n files: index.files,\n buildMs: index.buildMs,\n builtAt: index.builtAt,\n cached: loaded.cached,\n cachePath: loaded.cachePath,\n loadMs: loaded.loadMs,\n };\n process.stdout.write(`${JSON.stringify(out, null, 2)}\\n`);\n } else {\n process.stdout.write(\n `${describeIndex(index)}: ${index.entries.length} declarations from ${index.files} files, ` +\n `${loaded.cached ? `cached (built ${index.builtAt})` : `built in ${index.buildMs} ms`}, ${loaded.cachePath}\\n`,\n );\n }\n });\n}\n","import { Command } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { OniroError } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { McpServer, serveStdio } from '../mcp/protocol.js';\nimport { TOOL_NAMES, selectTools, type ToolContext } from '../mcp/tools.js';\n\ninterface ServeMcpOpts {\n project?: string;\n device?: string;\n tools?: string;\n readOnly?: boolean;\n}\n\n/** The comma list of `--tools`, trimmed, without empties; undefined when not given. */\nexport function parseToolList(raw: string | undefined): string[] | undefined {\n if (raw === undefined) return undefined;\n const names = raw\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (!names.length) throw new OniroError('--tools needs at least one tool name.');\n return names;\n}\n\nfunction instructions(ctx: ToolContext, toolCount: number): string {\n return (\n `oniro-app: build, check, test, deploy and inspect the OpenHarmony/HarmonyOS app in ${ctx.projectDir}` +\n `${ctx.deviceSerial ? ` on device ${ctx.deviceSerial}` : ''} (${toolCount} tools). Each tool runs the matching ` +\n '`oniro-app` command and returns its `--json` object, as structured content and as JSON text; isError is true ' +\n 'when the command would exit non-zero (a failed build, check, test or smoke check, a missing symbol) or could not ' +\n 'run. Relative paths resolve against the project. A typical round: check_arkts on the changed files, build, ' +\n 'apply with smoke, then screenshot and dump_layout (flat) to see the result, input to drive it, logs_crash when it died.'\n );\n}\n\nexport function registerServeCommand(program: Command): void {\n const serve = program.command('serve').description('Serve oniro-app to other programs.');\n\n serve\n .command('mcp')\n .description(\n 'A Model Context Protocol server on stdio (newline-delimited JSON-RPC 2.0) exposing the gate commands as typed ' +\n `tools for agents: ${TOOL_NAMES.join(', ')}. Each tool returns the JSON the command's --json prints. ` +\n 'stdout carries only the protocol; logs go to stderr. Register it with Claude Code: ' +\n '`claude mcp add oniro-app -- oniro-app serve mcp --project <dir>`.',\n )\n .allowExcessArguments(false)\n .option('--project <dir>', 'Project the tools work on unless a call names another (default: the current directory).')\n .option('--device <serial>', 'Device the tools target unless a call names another (default: the only connected one).')\n .option('--tools <list>', `Expose only these tools, comma-separated (of ${TOOL_NAMES.join(', ')}).`)\n .option('--read-only', 'Leave out the tools that change the device: apply, launch, input, test.')\n .action(async (opts: ServeMcpOpts) => {\n const { logger } = getRuntime();\n const projectDir = path.resolve(opts.project ?? process.cwd());\n if (!fs.existsSync(projectDir)) throw new OniroError(`--project ${projectDir} does not exist.`);\n const tools = selectTools(parseToolList(opts.tools), !!opts.readOnly);\n if (!tools.length) throw new OniroError('No tool left to serve: --read-only removed every tool --tools named.');\n const context: ToolContext = { projectDir, deviceSerial: opts.device };\n const server = new McpServer({\n name: 'oniro-app',\n version: program.version() ?? '0.0.0',\n tools,\n context,\n instructions: instructions(context, tools.length),\n logger,\n });\n\n // stdout is the protocol. Anything else that writes to it (a stray\n // console.log in a dependency) goes to stderr instead of corrupting it.\n const protocolWrite = process.stdout.write.bind(process.stdout);\n process.stdout.write = ((chunk: unknown, ...rest: unknown[]) =>\n (process.stderr.write as (...a: unknown[]) => boolean)(chunk, ...rest)) as typeof process.stdout.write;\n // The client went away: nothing left to answer.\n process.stdout.on('error', () => process.exit(0));\n\n logger.info(`oniro-app MCP server on stdio: project ${projectDir}, tools ${tools.map((t) => t.name).join(', ')}`);\n await serveStdio(server, { write: (line) => void protocolWrite(line) });\n logger.info('stdin closed; MCP server exiting.');\n // A device helper left running (an hdc child, a timer) must not keep the\n // process alive; exit once the last response is flushed.\n protocolWrite('', () => process.exit(0));\n });\n}\n","import * as readline from 'node:readline';\nimport type { Logger } from '@oniroproject/core';\nimport { applyDefaults, validateArgs, type JsonSchema } from './schema.js';\n\n/**\n * A Model Context Protocol server over newline-delimited JSON-RPC 2.0 on\n * stdio: `initialize` (with protocol version negotiation),\n * `notifications/initialized`, `ping`, `tools/list` and `tools/call`. That is\n * the whole surface a tools-only server needs, so it is written here instead\n * of pulling in the SDK and its dependency tree.\n */\n\n/** Newest first; the first is offered when the client asks for one we do not speak. */\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'] as const;\n\n/** `structuredContent` in tool results exists from this protocol version on. */\nconst STRUCTURED_CONTENT_SINCE = '2025-06-18';\n\nexport type ToolContent = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string };\n\nexport interface ToolResult {\n content: ToolContent[];\n structuredContent?: Record<string, unknown>;\n isError?: boolean;\n}\n\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\nexport interface McpTool<Ctx> {\n name: string;\n title?: string;\n description: string;\n inputSchema: JsonSchema & { type: 'object' };\n annotations?: ToolAnnotations;\n /** The tool installs, launches or drives the UI on the device; `--read-only` drops it. */\n changesDevice: boolean;\n /** `args` has been validated against `inputSchema` and its defaults filled in. */\n call(args: Record<string, unknown>, ctx: Ctx): Promise<ToolResult>;\n}\n\nexport interface McpServerOptions<Ctx> {\n name: string;\n version: string;\n tools: McpTool<Ctx>[];\n context: Ctx;\n instructions?: string;\n logger: Logger;\n}\n\ntype JsonRpcId = string | number | null;\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nexport const RPC_PARSE_ERROR = -32700;\nexport const RPC_INVALID_REQUEST = -32600;\nexport const RPC_METHOD_NOT_FOUND = -32601;\nexport const RPC_INVALID_PARAMS = -32602;\nexport const RPC_INTERNAL_ERROR = -32603;\n\nfunction rpcError(id: JsonRpcId, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: '2.0', id, error: { code, message } };\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** A tool result carrying one error message, for a tool that threw or got bad arguments. */\nexport function errorResult(message: string, structured?: Record<string, unknown>): ToolResult {\n return {\n content: [{ type: 'text', text: message }],\n ...(structured ? { structuredContent: structured } : {}),\n isError: true,\n };\n}\n\nexport class McpServer<Ctx> {\n private readonly tools = new Map<string, McpTool<Ctx>>();\n private protocolVersion: string | undefined;\n\n constructor(private readonly opts: McpServerOptions<Ctx>) {\n for (const t of opts.tools) this.tools.set(t.name, t);\n }\n\n /** The version agreed in `initialize`, or undefined before it. */\n get negotiatedVersion(): string | undefined {\n return this.protocolVersion;\n }\n\n /**\n * Handle one parsed JSON-RPC message (or a batch, which the 2025-03-26\n * revision allows). Returns the response to send, or undefined for a\n * notification.\n */\n async handle(message: unknown): Promise<JsonRpcResponse | JsonRpcResponse[] | undefined> {\n if (Array.isArray(message)) {\n if (message.length === 0) return rpcError(null, RPC_INVALID_REQUEST, 'Empty batch.');\n const out = (await Promise.all(message.map((m) => this.handleOne(m)))).filter(\n (r): r is JsonRpcResponse => r !== undefined,\n );\n return out.length ? out : undefined;\n }\n return this.handleOne(message);\n }\n\n private async handleOne(msg: unknown): Promise<JsonRpcResponse | undefined> {\n if (!isObject(msg) || msg.jsonrpc !== '2.0') {\n return rpcError(isObject(msg) && isId(msg.id) ? msg.id : null, RPC_INVALID_REQUEST, 'Not a JSON-RPC 2.0 message.');\n }\n const hasId = 'id' in msg;\n if (typeof msg.method !== 'string') {\n // A response to a request we never send (we make none), or garbage.\n if (hasId && ('result' in msg || 'error' in msg)) return undefined;\n return rpcError(isId(msg.id) ? msg.id : null, RPC_INVALID_REQUEST, 'Missing method.');\n }\n if (!hasId) {\n this.onNotification(msg.method);\n return undefined;\n }\n if (!isId(msg.id) || msg.id === null) return rpcError(null, RPC_INVALID_REQUEST, 'The id must be a string or a number.');\n const id = msg.id;\n const params = msg.params === undefined ? {} : msg.params;\n if (!isObject(params)) return rpcError(id, RPC_INVALID_PARAMS, 'params must be an object.');\n try {\n return await this.dispatch(id, msg.method, params);\n } catch (err) {\n this.opts.logger.error(`mcp: ${msg.method} failed: ${(err as Error).stack ?? String(err)}`);\n return rpcError(id, RPC_INTERNAL_ERROR, err instanceof Error ? err.message : String(err));\n }\n }\n\n private onNotification(method: string): void {\n if (method === 'notifications/initialized') this.opts.logger.debug('mcp: client initialized');\n // notifications/cancelled and others: nothing to do; a cancelled call's result is simply ignored by the client.\n }\n\n private async dispatch(id: string | number, method: string, params: Record<string, unknown>): Promise<JsonRpcResponse> {\n const ok = (result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\n if (method === 'initialize') return ok(this.initialize(params));\n if (method === 'ping') return ok({});\n if (this.protocolVersion === undefined) {\n return rpcError(id, RPC_INVALID_REQUEST, `Received ${method} before initialize.`);\n }\n if (method === 'tools/list') {\n return ok({\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n }\n if (method === 'tools/call') {\n const name = params.name;\n if (typeof name !== 'string') return rpcError(id, RPC_INVALID_PARAMS, 'tools/call needs a tool name.');\n const tool = this.tools.get(name);\n if (!tool) return rpcError(id, RPC_INVALID_PARAMS, `Unknown tool: ${name}. Tools: ${[...this.tools.keys()].join(', ')}.`);\n return ok(this.shape(await this.callTool(tool, params.arguments)));\n }\n return rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${method}`);\n }\n\n private initialize(params: Record<string, unknown>): Record<string, unknown> {\n const asked = typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined;\n const version =\n asked && (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(asked) ? asked : SUPPORTED_PROTOCOL_VERSIONS[0];\n this.protocolVersion = version;\n const client = isObject(params.clientInfo) ? `${params.clientInfo.name ?? '?'} ${params.clientInfo.version ?? ''}` : 'client';\n this.opts.logger.info(`mcp: ${client.trim()} connected (protocol ${version}, asked ${asked ?? 'none'})`);\n return {\n protocolVersion: version,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.opts.name, version: this.opts.version },\n ...(this.opts.instructions ? { instructions: this.opts.instructions } : {}),\n };\n }\n\n /** Validate, fill defaults, run. A tool that throws or gets bad arguments yields an `isError` result, not an RPC error. */\n private async callTool(tool: McpTool<Ctx>, rawArgs: unknown): Promise<ToolResult> {\n const args = rawArgs === undefined || rawArgs === null ? {} : rawArgs;\n if (!isObject(args)) return errorResult(`Invalid arguments for ${tool.name}: arguments must be an object.`);\n const problems = validateArgs(tool.inputSchema, args);\n if (problems.length) return errorResult(`Invalid arguments for ${tool.name}: ${problems.join('; ')}.`);\n const started = Date.now();\n this.opts.logger.info(`mcp: ${tool.name} ${JSON.stringify(args)}`);\n try {\n const result = await tool.call(applyDefaults(tool.inputSchema, args), this.opts.context);\n this.opts.logger.info(`mcp: ${tool.name} ${result.isError ? 'failed' : 'done'} in ${Date.now() - started} ms`);\n return result;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n this.opts.logger.info(`mcp: ${tool.name} threw in ${Date.now() - started} ms: ${message}`);\n if (process.env.ONIRO_DEBUG === '1' && err instanceof Error && err.stack) this.opts.logger.debug(err.stack);\n return errorResult(message, { error: message });\n }\n }\n\n /** Clients before 2025-06-18 know no `structuredContent`; the text block carries the same JSON. */\n private shape(result: ToolResult): ToolResult {\n if (result.structuredContent && (this.protocolVersion ?? '') < STRUCTURED_CONTENT_SINCE) {\n const { structuredContent: _dropped, ...rest } = result;\n return rest;\n }\n return result;\n }\n}\n\nfunction isId(v: unknown): v is JsonRpcId {\n return typeof v === 'string' || typeof v === 'number' || v === null;\n}\n\nexport interface StdioOptions {\n input?: NodeJS.ReadableStream;\n /** Where protocol messages go; default the real stdout. */\n write?: (line: string) => void;\n}\n\n/**\n * Serve `server` on newline-delimited JSON over stdin/stdout until stdin\n * closes and every call in flight has answered. Requests run concurrently;\n * responses go out as they finish.\n */\nexport async function serveStdio<Ctx>(server: McpServer<Ctx>, opts: StdioOptions = {}): Promise<void> {\n const input = opts.input ?? process.stdin;\n const write = opts.write ?? ((line: string) => void process.stdout.write(line));\n const send = (msg: unknown): void => write(`${JSON.stringify(msg)}\\n`);\n const pending = new Set<Promise<void>>();\n const rl = readline.createInterface({ input, crlfDelay: Infinity, terminal: false });\n for await (const line of rl) {\n const text = line.trim();\n if (!text) continue;\n let message: unknown;\n try {\n message = JSON.parse(text);\n } catch {\n send(rpcError(null, RPC_PARSE_ERROR, 'Parse error: each line must be one JSON-RPC message.'));\n continue;\n }\n const p: Promise<void> = server.handle(message).then(\n (response) => {\n if (response !== undefined) send(response);\n },\n () => {},\n );\n pending.add(p);\n void p.finally(() => pending.delete(p));\n }\n await Promise.all(pending);\n}\n","/**\n * The JSON Schema subset the tool input schemas use, and a validator for it:\n * enough to turn a wrong argument into a clear tool error the model can fix,\n * without a schema library.\n */\nexport interface JsonSchema {\n type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array';\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchema;\n enum?: readonly (string | number)[];\n minimum?: number;\n maximum?: number;\n minItems?: number;\n default?: unknown;\n}\n\nfunction typeOk(type: JsonSchema['type'], v: unknown): boolean {\n switch (type) {\n case undefined:\n return true;\n case 'object':\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n case 'array':\n return Array.isArray(v);\n case 'integer':\n return typeof v === 'number' && Number.isInteger(v);\n case 'number':\n return typeof v === 'number' && Number.isFinite(v);\n default:\n return typeof v === type;\n }\n}\n\n/** Every way `value` breaks `schema`, as `path: problem` strings; empty when it conforms. */\nexport function validateArgs(schema: JsonSchema, value: unknown, at = ''): string[] {\n const where = at || 'arguments';\n if (!typeOk(schema.type, value)) return [`${where} must be ${schema.type === 'integer' ? 'an integer' : `a ${schema.type}`}`];\n const out: string[] = [];\n if (schema.enum && !schema.enum.includes(value as string | number)) {\n out.push(`${where} must be one of ${schema.enum.map((e) => JSON.stringify(e)).join(', ')}`);\n }\n if (typeof value === 'number') {\n if (schema.minimum !== undefined && value < schema.minimum) out.push(`${where} must be >= ${schema.minimum}`);\n if (schema.maximum !== undefined && value > schema.maximum) out.push(`${where} must be <= ${schema.maximum}`);\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) {\n out.push(`${where} needs at least ${schema.minItems} item${schema.minItems === 1 ? '' : 's'}`);\n }\n if (schema.items) value.forEach((item, i) => out.push(...validateArgs(schema.items!, item, `${where}[${i}]`)));\n }\n if (schema.type === 'object' && typeof value === 'object' && value !== null) {\n const obj = value as Record<string, unknown>;\n const props = schema.properties ?? {};\n for (const key of schema.required ?? []) {\n // null means \"not given\" (below), so it does not satisfy a required property either.\n if (obj[key] === undefined || obj[key] === null) out.push(`${at ? `${at}.` : ''}${key} is required`);\n }\n for (const [key, v] of Object.entries(obj)) {\n const prop = props[key];\n if (!prop) {\n if (schema.additionalProperties === false) {\n out.push(`unknown property ${at ? `${at}.` : ''}${key} (expected: ${Object.keys(props).join(', ') || 'none'})`);\n }\n continue;\n }\n if (v === undefined || v === null) continue; // null means \"not given\", like an omitted flag\n out.push(...validateArgs(prop, v, `${at ? `${at}.` : ''}${key}`));\n }\n }\n return out;\n}\n\n/** `args` with each omitted (or null) top-level property set to its schema default, and nulls dropped. */\nexport function applyDefaults(schema: JsonSchema, args: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(args)) if (v !== null && v !== undefined) out[key] = v;\n for (const [key, prop] of Object.entries(schema.properties ?? {})) {\n if (out[key] === undefined && prop.default !== undefined) out[key] = prop.default;\n }\n return out;\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport {\n analyzeFaultLog,\n captureBurst,\n describeLayoutNode,\n findLayoutNodes,\n listLayoutWindows,\n selectableTree,\n diffLayouts,\n dumpLayout,\n inventoryScreens,\n latestCrash,\n locateTarget,\n parseLayoutBaseline,\n parseSelector,\n performInput,\n runDoctor,\n runTests,\n summarizeLayout,\n takeScreenshot,\n waitForBoot,\n waitForBundle,\n waitForLog,\n waitForTarget,\n DEFAULT_SMOKE_DELAY_MS,\n DEFAULT_TRACE_BUFFER_KB,\n DEFAULT_TRACE_CATEGORIES,\n evaluatePerfGate,\n perfTrace,\n readFlowFile,\n type CrashVerdict,\n type DumpLayoutResult,\n type UiInputType,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { runBuild } from '../commands/build.js';\nimport { arktsCheckExitCode, arktsCheckOrError } from '../commands/check.js';\nimport { testExitCode } from '../commands/test.js';\nimport { applyWithSmoke, launchWithSmoke } from '../commands/app.js';\nimport { runApiSearch, runApiShow } from '../commands/api.js';\nimport { doctorExitCode } from '../commands/doctor.js';\nimport { devicesJson, queryDevices } from '../commands/devices.js';\nimport { perfExitCode } from '../commands/perf.js';\nimport { formatFlatLayout } from '../lib/layoutText.js';\nimport { parseCrashSince, projectBundle } from '../lib/crashReport.js';\nimport { parseSince } from '../lib/logSince.js';\nimport {\n buildContactSheet,\n cropImage,\n diffScreenshots,\n frameDiffs,\n padCropRect,\n parseCropRect,\n renderWithGrid,\n type CropRect,\n} from '../lib/screenshotImage.js';\nimport type { McpTool, ToolContent, ToolResult } from './protocol.js';\nimport type { JsonSchema } from './schema.js';\nimport { selectorFromArgs, targetIndexFromArgs, targetProperties, windowFromArgs, windowProperty } from './target.js';\n\n/** What every tool call knows besides its arguments: the server's `--project` and `--device`. */\nexport interface ToolContext {\n projectDir: string;\n deviceSerial?: string;\n}\n\ntype Args = Record<string, unknown>;\ntype Tool = McpTool<ToolContext>;\n\n// ---- schema helpers -------------------------------------------------------\n\nconst str = (description: string, extra: JsonSchema = {}): JsonSchema => ({ type: 'string', description, ...extra });\nconst bool = (description: string, dflt?: boolean): JsonSchema => ({\n type: 'boolean',\n description,\n ...(dflt !== undefined ? { default: dflt } : {}),\n});\nconst num = (description: string, extra: JsonSchema = {}): JsonSchema => ({ type: 'number', description, ...extra });\nconst int = (description: string, extra: JsonSchema = {}): JsonSchema => ({ type: 'integer', description, ...extra });\n\nconst PROJECT: Record<string, JsonSchema> = {\n project: str(\"Project directory; a relative path resolves against the server's --project (default: the server's --project).\"),\n};\nconst DEVICE: Record<string, JsonSchema> = {\n device: str(\"Target device serial (default: the server's --device, else the only connected device).\"),\n};\n\nfunction object(properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema & { type: 'object' } {\n return { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false };\n}\n\n// ---- argument helpers ------------------------------------------------------\n\nfunction projectOf(a: Args, ctx: ToolContext): string {\n return typeof a.project === 'string' ? path.resolve(ctx.projectDir, a.project) : ctx.projectDir;\n}\n\nfunction deviceOf(a: Args, ctx: ToolContext): string | undefined {\n return (a.device as string | undefined) ?? ctx.deviceSerial;\n}\n\n/** A path argument: relative paths resolve against the project of the call. */\nfunction pathArg(a: Args, key: string, ctx: ToolContext): string | undefined {\n const v = a[key];\n return typeof v === 'string' ? path.resolve(projectOf(a, ctx), v) : undefined;\n}\n\n// ---- result helpers --------------------------------------------------------\n\n/** The command's `--json` object as structured content, and the same JSON as the text block. */\nfunction jsonResult(json: Record<string, unknown>, isError = false, extra: ToolContent[] = []): ToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(json) }, ...extra],\n structuredContent: json,\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction message(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction jpeg(buf: Buffer): ToolContent {\n return { type: 'image', data: buf.toString('base64'), mimeType: 'image/jpeg' };\n}\n\nfunction rt(): { config: ReturnType<typeof getRuntime>['config']; logger: ReturnType<typeof getRuntime>['logger'] } {\n const { config, logger } = getRuntime();\n return { config, logger };\n}\n\nconst SMOKE: Record<string, JsonSchema> = {\n smoke: bool(\n 'After launch, wait for the process, take a screenshot after smokeDelay, and fail (isError) when the process ' +\n 'died or the screen is blank; a crash is reported from the faultlog.',\n false,\n ),\n smokeDelay: int('With smoke: wait between the process appearing and the screenshot, ms.', {\n minimum: 0,\n default: DEFAULT_SMOKE_DELAY_MS,\n }),\n smokeScreenshot: str('With smoke: where to write the screenshot (default: a file in the system temp dir).'),\n};\n\nconst INPUT_TYPES: UiInputType[] = [\n 'click',\n 'doubleClick',\n 'longClick',\n 'swipe',\n 'drag',\n 'fling',\n 'keyEvent',\n 'inputText',\n 'clearText',\n 'hideKeyboard',\n];\n\n// ---- tools -----------------------------------------------------------------\n\nconst build: Tool = {\n name: 'build',\n title: 'Build the app',\n description:\n 'Build an OpenHarmony or HarmonyOS app via hvigorw (`oniro-app build --json`). Returns ok, exitCode, durationMs, ' +\n 'failedTask, diagnostics (severity, source, code, rule, message, file, line, column, task), summary, discoveredHaps, ' +\n 'warnings, error and rawTail. An OpenHarmony project fails early, naming the release to install, when the SDK for ' +\n 'its compileSdkVersion is missing. isError when the build fails.',\n inputSchema: object({\n ...PROJECT,\n product: str('hvigor product name.', { default: 'default' }),\n module: str('Restrict the build to a specific module.'),\n mode: str('hvigor build mode (e.g. release, debug).'),\n task: str('hvigor task to run.', { default: 'assembleHap' }),\n deps: bool('Run `ohpm install --all` when oh_modules/ is missing (false = --no-deps).', true),\n parallel: bool('Build modules in parallel (false = --no-parallel).', true),\n installSdk: bool('Install the OpenHarmony SDK the project compiles against when it is missing, then build.', false),\n }),\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n try {\n const report = await runBuild(projectOf(a, ctx), {\n product: a.product as string,\n module: a.module as string | undefined,\n mode: a.mode as string | undefined,\n task: a.task as string,\n deps: a.deps as boolean,\n parallel: a.parallel as boolean,\n installSdk: a.installSdk as boolean,\n });\n return jsonResult(report as unknown as Args, !report.ok);\n } catch (err) {\n // The build could not run at all: the object `build --json` prints then.\n return jsonResult({ ok: false, exitCode: 1, error: message(err), diagnostics: [] }, true);\n }\n },\n};\n\nconst checkArktsTool: Tool = {\n name: 'check_arkts',\n title: 'Check ArkTS',\n description:\n \"Type-check and lint ArkTS with the SDK's own ArkTS checker (what the build's CompileArkTS runs), plus the ArkUI \" +\n 'component-model and project-config rules the build enforces later (V1/V2 decorators, @Entry root, route maps, ' +\n 'resources, permissions), in seconds and without a build (`oniro-app check arkts --json`). Returns ok, completed, ' +\n 'diagnostics (severity, source, rule, message, file, line, column), fixed, alsoModified, summary, sdk, durationMs, ' +\n 'error. isError when it found an error or could not run (completed: false means nothing is known).',\n inputSchema: object({\n ...PROJECT,\n files: {\n type: 'array',\n items: { type: 'string' },\n minItems: 1,\n description: 'Check only these .ets files (project-wide rules such as main_pages.json and module.json5 are then skipped).',\n },\n fix: bool(\n \"Apply the fixes the checker can verify (the compiler's `Did you mean` suggestions, import paths, a missing \" +\n '`export`, the @Component/@ComponentV2 decorator), re-check, and revert any fix that adds an error.',\n false,\n ),\n sdk: str('SDK directory to check against (holding ets/), instead of the one compileSdkVersion names.'),\n }),\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const report = await arktsCheckOrError(projectOf(a, ctx), {\n files: a.files as string[] | undefined,\n fix: a.fix as boolean,\n sdk: pathArg(a, 'sdk', ctx),\n });\n return jsonResult(report as unknown as Args, arktsCheckExitCode(report) !== 0);\n },\n};\n\nconst test: Tool = {\n name: 'test',\n title: 'Run the ohosTest suite',\n description:\n \"Build a module's main and ohosTest HAPs, install both on the device, run the suite with `aa test` (Hypium) and \" +\n 'report each case (`oniro-app test --json`). Returns ok, outcome, tests (suite, name, status, statusCode, durationMs, ' +\n 'message, stack), summary, resultCode, haps, log, error. isError when a case failed or the run did not complete. ' +\n 'Installs on the device; the test module is left installed.',\n inputSchema: object({\n ...PROJECT,\n module: str('Module whose src/ohosTest suite runs.', { default: 'entry' }),\n product: str('hvigor product name.', { default: 'default' }),\n class: str('Run only these cases: `Suite`, `Suite#case`, or several joined by commas.'),\n timeout: int('Per-case timeout passed to the runner, ms.', { minimum: 1, default: 15_000 }),\n runTimeout: int('Wall-clock limit for the whole run, ms; aa test can hang when the app dies.', { minimum: 1, default: 600_000 }),\n build: bool('Build the HAPs first (false = --no-build: use the HAPs already built).', true),\n wake: bool(\n 'Turn the screen on, swipe a credential-less lock screen away and keep it on during the run (false = --no-wake).',\n true,\n ),\n mode: str('hvigor build mode (e.g. debug).'),\n deps: bool('Run `ohpm install --all` when oh_modules/ is missing (false = --no-deps).', true),\n ...DEVICE,\n }),\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n changesDevice: true,\n async call(a, ctx) {\n const { config, logger } = rt();\n const report = await runTests({\n config,\n projectDir: projectOf(a, ctx),\n module: a.module as string,\n product: a.product as string,\n testClass: a.class as string | undefined,\n caseTimeoutMs: a.timeout as number,\n runTimeoutMs: a.runTimeout as number,\n build: a.build as boolean,\n wakeScreen: a.wake as boolean,\n mode: a.mode as string | undefined,\n autoInstallDeps: a.deps as boolean,\n deviceSerial: deviceOf(a, ctx),\n logger,\n });\n return jsonResult(report as unknown as Args, testExitCode(report) !== 0);\n },\n};\n\nconst apply: Tool = {\n name: 'apply',\n title: 'Install and apply a HAP',\n description:\n 'Install the HAP of the project (or `hap`) and verify the running process took the change (`oniro-app app apply ' +\n '--json`). Refuses a HAP of another bundle. Handles sign-info mismatch, asset-cache invalidation, and ' +\n 'persistent-bundle restart. Returns method, preInstallPid, postInstallPid, replaced, cacheCleared, and with smoke a ' +\n '`smoke` verdict (passed, failures, pid, alive, blankScreen, blankScore, crash, screenshot). isError when the smoke ' +\n 'check fails.',\n inputSchema: object({\n ...PROJECT,\n hap: str(\n 'An explicit .hap file (relative to the project); its own bundleName is the one applied unless `bundle` is given.',\n ),\n bundle: str('Bundle name to apply changes to. Defaults to the bundleName in the .hap file, else in the project AppScope/app.json5.'),\n module: str('Module to resolve the HAP from (multi-module projects).'),\n installedHap: str('Local path to the currently-installed HAP, to enable the asset-cache reboot.'),\n system: bool('Treat as a persistent/system bundle (refuses uninstall on sign-info mismatch).', false),\n allowUninstall: bool('Permit uninstalling a system bundle on sign-info mismatch (dangerous).', false),\n ...SMOKE,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n changesDevice: true,\n async call(a, ctx) {\n const hap = pathArg(a, 'hap', ctx);\n const report = await applyWithSmoke(rt(), {\n // A HAP goes in as the command's positional .hap, so its own bundle name is the one applied.\n target: hap ?? projectOf(a, ctx),\n bundle: a.bundle as string | undefined,\n module: a.module as string | undefined,\n installedHap: pathArg(a, 'installedHap', ctx),\n system: a.system as boolean,\n allowUninstall: a.allowUninstall as boolean,\n smoke: a.smoke as boolean,\n smokeDelay: a.smokeDelay as number,\n smokeScreenshot: pathArg(a, 'smokeScreenshot', ctx),\n device: deviceOf(a, ctx),\n });\n return jsonResult(report as unknown as Args, report.smoke ? !report.smoke.passed : false);\n },\n};\n\nconst launch: Tool = {\n name: 'launch',\n title: 'Launch the app',\n description:\n 'Launch an app on the device (`oniro-app app launch --json`). Project mode (default) resolves the bundle and main ' +\n 'ability from the project; bundle mode (`bundle`) launches an already-installed app. With smoke, waits for the ' +\n 'process, takes a screenshot and reports whether it died, crashed (from the faultlog) or shows a blank screen. ' +\n 'Returns bundle and, with smoke, `smoke` (passed, failures, pid, alive, blankScreen, blankScore, crash, screenshot). ' +\n 'isError when the smoke check fails.',\n inputSchema: object({\n ...PROJECT,\n bundle: str('Launch an already-installed app by bundle name (no project needed).'),\n module: str('Module folder name (project mode).', { default: 'entry' }),\n ability: str(\n 'Explicit ability to launch (defaults to the module mainElement in project mode, or the installed bundle main ability in bundle mode).',\n ),\n ...SMOKE,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n changesDevice: true,\n async call(a, ctx) {\n const report = await launchWithSmoke(rt(), {\n projectDir: projectOf(a, ctx),\n bundle: a.bundle as string | undefined,\n module: a.module as string,\n ability: a.ability as string | undefined,\n smoke: a.smoke as boolean,\n smokeDelay: a.smokeDelay as number,\n smokeScreenshot: pathArg(a, 'smokeScreenshot', ctx),\n device: deviceOf(a, ctx),\n });\n return jsonResult(report as unknown as Args, report.smoke ? !report.smoke.passed : false);\n },\n};\n\n/** A `dump layout` JSON saved earlier, for `diff`. */\nfunction readLayoutBaseline(file: string): DumpLayoutResult {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch (err) {\n throw new Error(`Cannot read the layout baseline ${file}: ${message(err)}`);\n }\n try {\n return parseLayoutBaseline(JSON.parse(text));\n } catch (err) {\n throw new Error(`${file} is not a saved \\`dump layout\\` JSON: ${message(err)}`);\n }\n}\n\nconst dumpLayoutTool: Tool = {\n name: 'dump_layout',\n title: 'Dump the UI layout',\n description:\n 'Dump the on-screen UI layout (`oniro-app dump layout`). Default: the pruned JSON tree (large; prefer flat or ' +\n 'summary). flat: one line per labelled or interactive element (type, label, center as 0-1 fractions, flags), as ' +\n 'text. summary: per window element, content, clickable and text-node counts. diff: compare with a layout saved ' +\n 'earlier (via `output`): matched elements with IoU, missing, extra, and a 0-1 similarity.',\n inputSchema: object({\n bundle: str('Filter the layout to a single window/bundle.'),\n raw: bool('Return the unpruned layout tree.', false),\n flat: bool('One line per element (type, label, center as 0-1 fractions, flags) instead of a JSON tree.', false),\n summary: bool('Per window: element, content, clickable and text-node counts (JSON).', false),\n diff: str(\n 'Compare with a saved `dump layout` JSON (relative to the project): matched elements with IoU, missing, extra, and a 0-1 similarity (JSON).',\n ),\n output: str('Also write what is returned (the JSON, or the flat text) to this file, e.g. as a later diff baseline.'),\n selector: str(\n 'Return only the elements matching this selector (attribute clauses or xpath=..., as in input), numbered for its [n] ' +\n 'suffix: { display, selector, matches }.',\n ),\n window: windowProperty,\n ...PROJECT,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const { config, logger } = rt();\n if (a.raw && a.flat) throw new Error('raw and flat cannot be combined.');\n const modes = [a.flat && 'flat', a.summary && 'summary', a.diff !== undefined && 'diff'].filter(Boolean);\n if (modes.length > 1) throw new Error(`${modes.join(' and ')} cannot be combined.`);\n if (a.raw && modes.length > 0) throw new Error(`raw cannot be combined with ${modes[0]}.`);\n const selector = a.selector === undefined ? undefined : parseSelector(a.selector as string);\n if (selector && (a.raw || a.summary || a.diff !== undefined)) {\n throw new Error('selector cannot be combined with raw, summary or diff.');\n }\n const windowId = windowFromArgs(a);\n const diffPath = pathArg(a, 'diff', ctx);\n // Read the baseline before touching the device, so a bad path fails fast.\n const baseline = diffPath !== undefined ? readLayoutBaseline(diffPath) : undefined;\n const result = await dumpLayout({\n config,\n bundleName: a.bundle as string | undefined,\n windowId,\n prune: !a.raw,\n detectKeyboard: !a.raw,\n deviceSerial: deviceOf(a, ctx),\n logger,\n });\n const output = pathArg(a, 'output', ctx);\n if (selector) {\n const matches = findLayoutNodes(selectableTree(result, windowId), selector);\n const json = { display: result.display, selector: selector.raw, matches } as unknown as Args;\n if (output) fs.writeFileSync(output, `${JSON.stringify(json, null, 2)}\\n`);\n return jsonResult(json);\n }\n if (a.flat) {\n const text = formatFlatLayout(result);\n if (output) fs.writeFileSync(output, text);\n return { content: [{ type: 'text', text }] };\n }\n let json: Args;\n if (a.summary) json = summarizeLayout(result) as unknown as Args;\n else if (baseline) json = diffLayouts(baseline, result) as unknown as Args;\n else json = result as unknown as Args;\n if (output) fs.writeFileSync(output, `${JSON.stringify(json, null, 2)}\\n`);\n return jsonResult(json);\n },\n};\n\nconst input: Tool = {\n name: 'input',\n title: 'Send a UI input',\n description:\n 'Inject a UI input event via uitest uiInput (`oniro-app input`). Position it with target/targetId/targetType (an ' +\n 'on-screen element), fx/fy (0-1 fractions of the display, as in dump_layout flat and the screenshot grid), or x/y ' +\n '(pixels). Returns x, y (the resolved start point in pixels), target (the element it resolved to) and keyboardHidden.',\n inputSchema: object(\n {\n type: { type: 'string', enum: INPUT_TYPES, description: 'Input type.' },\n ...targetProperties('Act on'),\n fx: num('Start X as a 0-1 fraction of the display width.', { minimum: 0, maximum: 1 }),\n fy: num('Start Y as a 0-1 fraction of the display height.', { minimum: 0, maximum: 1 }),\n fx2: num('End X fraction (swipe/drag/fling).', { minimum: 0, maximum: 1 }),\n fy2: num('End Y fraction (swipe/drag/fling).', { minimum: 0, maximum: 1 }),\n x: num('X pixel (click/swipe start).'),\n y: num('Y pixel (click/swipe start).'),\n x2: num('End X pixel (swipe/drag/fling).'),\n y2: num('End Y pixel (swipe/drag/fling).'),\n speed: num('Velocity for swipe/drag/fling, px/s.'),\n key: str(\n 'Key for keyEvent: Back/Home/Power, a name (Delete, Enter, Tab, Escape, MoveHome, MoveEnd, …), a letter, a ' +\n 'KeyCode id, or a combo like Ctrl+A.',\n ),\n text: str('Text for inputText.'),\n clear: bool('inputText: clear the field (Ctrl+A, Delete) before typing.', false),\n hideKeyboard: bool('Dismiss the soft keyboard afterwards, if it is up.', false),\n ...DEVICE,\n },\n ['type'],\n ),\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n changesDevice: true,\n async call(a, ctx) {\n const { config, logger } = rt();\n const result = await performInput({\n config,\n type: a.type as UiInputType,\n target: selectorFromArgs(a),\n targetIndex: targetIndexFromArgs(a),\n windowId: windowFromArgs(a),\n fx: a.fx as number | undefined,\n fy: a.fy as number | undefined,\n fx2: a.fx2 as number | undefined,\n fy2: a.fy2 as number | undefined,\n pxX: a.x as number | undefined,\n pxY: a.y as number | undefined,\n pxX2: a.x2 as number | undefined,\n pxY2: a.y2 as number | undefined,\n speed: a.speed as number | undefined,\n key: a.key as string | undefined,\n text: a.text as string | undefined,\n clear: a.clear as boolean,\n hideKeyboard: a.hideKeyboard as boolean,\n deviceSerial: deviceOf(a, ctx),\n logger,\n });\n return jsonResult(result as unknown as Args);\n },\n};\n\nconst DEFAULT_CONTACT_SHEET_FRAMES = 8;\n// Margin kept around a target element when cropping to it, as a fraction of the display (as `screenshot --target`).\nconst TARGET_CROP_PAD = 0.02;\n\nconst screenshot: Tool = {\n name: 'screenshot',\n title: 'Take a screenshot',\n description:\n 'Capture the screen and return it as an image, downscaled so its longest side is at most maxDim ' +\n '(`oniro-app screenshot --max-dim`). grid: overlay a 10x10 grid (axes 0.0-1.0) for picking fx/fy tap coordinates. ' +\n 'crop / target*: a full-resolution crop of one region or element, for checking detail cheaply. contactSheet: ' +\n 'capture a burst and tile it into one image with per-frame change diffs. diff: compare the screen with a baseline ' +\n 'JPEG (pHash/dHash distance, pixel-change ratio, mean change). output: also write the image to a file (with diff: ' +\n 'the full-resolution capture, usable as a later baseline).',\n inputSchema: object({\n output: str('Also write the image to this file (relative to the project).'),\n grid: bool('Overlay a 10x10 coordinate grid.', false),\n maxDim: int('Longest-side cap of the returned image, px.', { minimum: 256, maximum: 4096, default: 1024 }),\n crop: str('Crop to this region, given as 0-1 fractions of the screen: \"x1,y1,x2,y2\".'),\n ...targetProperties('Crop to'),\n contactSheet: bool('Capture a burst and composite it into one tiled contact sheet.', false),\n burst: int('With contactSheet: the number of frames.', { minimum: 1, default: DEFAULT_CONTACT_SHEET_FRAMES }),\n interval: int('With contactSheet: delay between frames, ms.', { minimum: 0, default: 50 }),\n diff: str(\n 'Compare the screen with this baseline JPEG (relative to the project): pHash and dHash distance, pixel-change ' +\n 'ratio, mean change.',\n ),\n ...PROJECT,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const { config, logger } = rt();\n const deviceSerial = deviceOf(a, ctx);\n const maxDim = a.maxDim as number;\n const output = pathArg(a, 'output', ctx);\n const selector = selectorFromArgs(a);\n const windowId = windowFromArgs(a);\n\n if (a.diff !== undefined) {\n if (a.crop !== undefined || selector || windowId !== undefined || a.grid || a.contactSheet) {\n throw new Error('diff cannot be combined with crop, target* / selector / window, grid, or contactSheet.');\n }\n const baselinePath = pathArg(a, 'diff', ctx)!;\n let baseline: Buffer;\n try {\n baseline = fs.readFileSync(baselinePath);\n } catch (err) {\n throw new Error(`Cannot read the baseline ${baselinePath}: ${message(err)}`);\n }\n const shot = await takeScreenshot({ config, deviceSerial, logger });\n if (output) fs.writeFileSync(output, shot.pixels);\n const diff = await diffScreenshots(baseline, shot.pixels);\n const shown = await renderWithGrid(shot.pixels, { maxDim });\n return jsonResult({ baseline: baselinePath, current: output ?? null, ...diff }, false, [jpeg(shown.buf)]);\n }\n\n if (a.crop !== undefined || selector || windowId !== undefined) {\n if (a.crop !== undefined && (selector || windowId !== undefined)) {\n throw new Error('Use either crop or target* / selector / window, not both.');\n }\n if (a.grid || a.contactSheet) throw new Error('crop / target cannot be combined with grid or contactSheet.');\n let rect: CropRect;\n let label: string;\n if (selector) {\n // Leave the keyboard alone: dismissing it would change what we are capturing.\n const located = await locateTarget({\n config,\n selector,\n index: targetIndexFromArgs(a),\n windowId,\n hideKeyboard: false,\n deviceSerial,\n logger,\n });\n if (!located.node.b) throw new Error(`${describeLayoutNode(located.node)} has no bounds to crop to.`);\n rect = padCropRect(located.node.b, TARGET_CROP_PAD);\n label = describeLayoutNode(located.node);\n } else if (windowId !== undefined) {\n const { tree } = await dumpLayout({ config, windowId, deviceSerial, logger });\n const win = listLayoutWindows(tree).find((w) => w.windowId === windowId);\n if (!win?.b) throw new Error(`Window ${windowId} has no bounds to crop to.`);\n rect = win.b;\n label = `window ${windowId}${win.bundle ? ` (${win.bundle})` : ''}`;\n } else {\n rect = parseCropRect(a.crop as string);\n label = rect.map((n) => n.toFixed(3)).join(',');\n }\n const shot = await takeScreenshot({ config, deviceSerial, logger });\n const cropped = await cropImage(shot.pixels, rect, { maxDim });\n if (output) fs.writeFileSync(output, cropped.buf);\n const { buf, ...dims } = cropped;\n return jsonResult({ output: output ?? null, region: label, ...dims }, false, [jpeg(buf)]);\n }\n\n if (a.contactSheet) {\n const intervalMs = a.interval as number;\n const frames = await captureBurst({ config, count: a.burst as number, intervalMs, deviceSerial, logger });\n const diffs = await frameDiffs(frames);\n const sheet = await buildContactSheet(frames, { maxDim, diffs });\n if (output) fs.writeFileSync(output, sheet.buf);\n const json = {\n sheet: output ?? null,\n frameCount: frames.length,\n cols: sheet.cols,\n rows: sheet.rows,\n intervalMs,\n note: 't_ms is nominal (idx*interval); diffVsPrev is 0..1 mean greyscale diff vs the previous frame.',\n frames: frames.map((_, i) => ({ idx: i, t_ms: i * intervalMs, diffVsPrev: diffs[i] ?? 0 })),\n };\n return jsonResult(json, false, [jpeg(sheet.buf)]);\n }\n\n const shot = await takeScreenshot({ config, deviceSerial, logger });\n const rendered = await renderWithGrid(shot.pixels, { maxDim, grid: !!a.grid });\n if (output) fs.writeFileSync(output, rendered.buf);\n const { buf, ...dims } = rendered;\n return jsonResult({ output: output ?? null, grid: !!a.grid, ...dims }, false, [jpeg(buf)]);\n },\n};\n\nconst wait: Tool = {\n name: 'wait',\n title: 'Wait for a device condition',\n description:\n 'Wait for a device condition (`oniro-app wait --json`): a hilog line (log), boot (boot), a bundle to start ' +\n '(bundle), or an on-screen element (target / targetId / targetType or selector, optionally in one window, or its absence with gone). Returns the ' +\n 'matched log entry or element, or {booted}, {gone}, {bundle, running}. isError on timeout.',\n inputSchema: object({\n log: str('Resolve when a hilog line (tag: message) logged after the call starts matches this regex.'),\n since: str(\n 'With log: also match lines logged up to N seconds before the call started, measured on the device clock; ' +\n '\"all\" matches everything still in the device log buffer.',\n ),\n boot: bool('Resolve when the device is reachable (optionally also pidOf).', false),\n bundle: str('With log: filter to this bundle. Alone: wait until this bundle is running.'),\n pidOf: str('With boot: also require this process to have a pid.'),\n domain: str('With log: hilog domain filter (e.g. 0xD003900).'),\n ...targetProperties('Resolve when', { index: false }),\n gone: bool('With target*: resolve when no uncovered element matches any more.', false),\n interval: int('With target*: poll interval, ms (each poll is a layout dump).', { minimum: 1, default: 500 }),\n timeout: int('Max wait, ms.', { minimum: 0, default: 30_000 }),\n ...DEVICE,\n }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const { config, logger } = rt();\n const deviceSerial = deviceOf(a, ctx);\n const timeoutMs = a.timeout as number;\n const selector = selectorFromArgs(a);\n const windowId = windowFromArgs(a);\n if (windowId !== undefined && !selector) throw new Error('window applies only to target* and selector.');\n if (a.since !== undefined && !a.log) throw new Error('since applies only to log.');\n if (a.log) {\n const entry = await waitForLog({\n config,\n pattern: new RegExp(a.log as string),\n timeoutMs,\n bundle: a.bundle as string | undefined,\n domain: a.domain as string | undefined,\n deviceSerial,\n lookbackMs: parseSince(a.since as string | undefined),\n logger,\n });\n return jsonResult(entry as unknown as Args);\n }\n if (a.boot) {\n await waitForBoot({ config, untilPidOf: a.pidOf as string | undefined, timeoutMs, deviceSerial, logger });\n return jsonResult({ booted: true });\n }\n if (selector) {\n const node = await waitForTarget({\n config,\n selector,\n gone: a.gone as boolean,\n windowId,\n timeoutMs,\n pollMs: a.interval as number,\n deviceSerial,\n logger,\n });\n return jsonResult(node ? (node as unknown as Args) : { gone: true });\n }\n if (a.bundle) {\n await waitForBundle({ config, bundle: a.bundle as string, timeoutMs, deviceSerial, logger });\n return jsonResult({ bundle: a.bundle, running: true });\n }\n throw new Error('Specify one of log, boot, bundle, target (or targetId / targetType), or selector.');\n },\n};\n\nconst logsCrash: Tool = {\n name: 'logs_crash',\n title: 'Explain the last crash',\n description:\n 'Fetch the newest faultlog of an app from the device and say what happened (`oniro-app logs crash --json`): a ' +\n 'native crash (cpp_crash), an uncaught ArkTS/JS error (js_crash), a freeze (app_freeze), or none. Returns crashed, ' +\n 'kind, subtype, confidence, bundle, pid, time, reason, topFrame, projectFrame, file, line, column, jsError, stack, ' +\n 'nativeFrames, jsFrames, binderChain, deadlocks, notes, path, rawPath; `{crashed: false, kind: null}` when there is ' +\n 'no fault. Not an error when there was no crash: check `crashed`.',\n inputSchema: object({\n bundle: str(\"App to look for (default: the bundleName of the project, else any process).\"),\n since: str('Only faults from the last N seconds (device clock), or since an ISO 8601 time.'),\n wait: int(\n 'Keep looking this long when there is no fault yet, ms; hiview writes the faultlog a few seconds after the process dies.',\n { minimum: 0, default: 0 },\n ),\n path: str('Analyse this local faultlog (or faultloggerd .json crash record) instead of fetching one.'),\n output: str('Where to save the fetched faultlog.', { default: path.join(os.homedir(), '.oniro', 'faultlogs') }),\n ...PROJECT,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const since = parseCrashSince(a.since as string | undefined);\n const local = pathArg(a, 'path', ctx);\n const bundle = (a.bundle as string | undefined) ?? (local ? undefined : projectBundle(projectOf(a, ctx)));\n let verdict: CrashVerdict | null;\n if (local) {\n verdict = analyzeFaultLog(fs.readFileSync(local, 'utf8'), { name: path.basename(local), path: local, rawPath: local });\n } else {\n const { config, logger } = rt();\n verdict = await latestCrash({\n config,\n bundle,\n since,\n waitMs: a.wait as number,\n deviceSerial: deviceOf(a, ctx),\n saveDir: pathArg(a, 'output', ctx),\n logger,\n });\n }\n const none = { crashed: false, kind: null, bundle: bundle ?? null, since: since instanceof Date ? since.toISOString() : since ?? null };\n return jsonResult((verdict ?? none) as unknown as Args);\n },\n};\n\nconst perfTraceTool: Tool = {\n name: 'perf_trace',\n title: 'Measure frames, jank and startup',\n description:\n 'Capture a hitrace trace while the app cold-launches (`launch`), a flow file is replayed (`flow`), or for a fixed ' +\n 'time (`for`), and summarise it (`oniro-app perf trace --json`). Returns ok, bundle, durationMs, trace (local ' +\n 'path), refreshRateHz, frames (total, janky, jankRate, p50Ms, p95Ms, maxMs, missedVsyncs, longest), startup ' +\n '(coldMs, firstFrameMs, processMs, from, to) or null, flow (the replay report) or null, pid, mainThread, scenes ' +\n \"(RenderService's own jank reports), hiperf, notes, gate (passed, failures), error. isError when the capture failed \" +\n 'or a threshold (maxJankRate, maxStartupMs) or the flow failed. Launching force-stops the app first.',\n inputSchema: object({\n bundle: str(\"The app to measure (default: the flow's bundle, else the bundleName of the project).\"),\n launch: bool('Force-stop the app, start tracing, then cold-launch it and report its startup time.', false),\n flow: str('A flow file (as for `replay`) to replay while tracing; relative to the project.'),\n for: int('Without flow: how long to capture (after the launch with launch), ms. With flow: how long to keep capturing after it.', {\n minimum: 1,\n }),\n ability: str('Ability `launch` starts (default: the main ability).'),\n out: str('Where to save the trace (default: a file in the system temp dir).'),\n categories: { type: 'array', items: { type: 'string' }, description: `hitrace categories (default ${DEFAULT_TRACE_CATEGORIES.join(', ')}).` },\n bufferKb: int('hitrace buffer size, KB.', { minimum: 1, default: DEFAULT_TRACE_BUFFER_KB }),\n hiperf: bool(\"Also sample the app's process with hiperf and list its top functions.\", false),\n maxJankRate: num('Fail (isError) when the share of janky frames is above this.', { minimum: 0, maximum: 1 }),\n maxStartupMs: int('Fail (isError) when the cold start takes longer than this, ms (needs launch).', { minimum: 1 }),\n stepTimeout: int(\"With flow: how long to wait for a step's selector and expect, ms.\", { minimum: 1 }),\n fallback: bool(\"With flow: act on a step's fallback point when its selector is not found.\", false),\n wake: bool('With launch or flow: wake the screen and swipe a credential-less lock screen away (false = --no-wake).', true),\n ...PROJECT,\n ...DEVICE,\n }),\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n // It force-stops and launches the app, and a flow taps and swipes.\n changesDevice: true,\n async call(a, ctx) {\n const { config, logger } = rt();\n const flowFile = pathArg(a, 'flow', ctx);\n const flow = flowFile ? readFlowFile(flowFile) : undefined;\n const report = await perfTrace({\n config,\n logger,\n deviceSerial: deviceOf(a, ctx),\n bundle: (a.bundle as string | undefined) ?? flow?.bundle ?? projectBundle(projectOf(a, ctx)),\n ability: a.ability as string | undefined,\n launch: a.launch as boolean,\n flow,\n replay: { stepTimeoutMs: a.stepTimeout as number | undefined, fallback: a.fallback as boolean },\n forMs: a.for as number | undefined,\n out: pathArg(a, 'out', ctx),\n categories: a.categories as string[] | undefined,\n bufferKb: a.bufferKb as number,\n hiperf: a.hiperf as boolean,\n wake: a.wake as boolean,\n });\n const gate = evaluatePerfGate(report, { maxJankRate: a.maxJankRate as number | undefined, maxStartupMs: a.maxStartupMs as number | undefined });\n return jsonResult({ ...report, gate } as unknown as Args, perfExitCode(report, gate) !== 0);\n },\n};\n\nconst screens: Tool = {\n name: 'screens',\n title: 'Inventory pages and routes',\n description:\n 'Static inventory of the pages and routes of a project, from its sources, without a build or a device ' +\n '(`oniro-app screens --json`): @Entry and NavDestination pages, the router/NavPathStack call sites between them, ' +\n 'the content nodes each page renders, and placeholder markers (TODO/FIXME, placeholder-like text, empty build()). ' +\n 'Returns pages (name, module, file, line, component, entry, kind, registered, contentNodes, routesOut), routes ' +\n '(from, to, file, line, via, dynamic), placeholders (file, line, text, kind), warnings, modules, projectDir.',\n inputSchema: object({ ...PROJECT }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n try {\n return jsonResult(inventoryScreens({ projectDir: projectOf(a, ctx) }) as unknown as Args);\n } catch (err) {\n return jsonResult({ error: message(err) }, true);\n }\n },\n};\n\nconst SDK_PROPS: Record<string, JsonSchema> = {\n api: int(\n \"The SDK API level to read. Default: the project's compileSdkVersion, else the newest installed SDK.\",\n { minimum: 1 },\n ),\n sdk: str('An SDK API directory (holding ets/) to read instead.'),\n project: str(\"The project whose compileSdkVersion picks the SDK (default: the server's --project).\"),\n rebuild: bool('Rebuild the index even if the cached one is current.', false),\n};\n\nconst API_KINDS = [\n 'namespace',\n 'class',\n 'interface',\n 'enum',\n 'enumMember',\n 'type',\n 'function',\n 'method',\n 'constructor',\n 'property',\n 'variable',\n 'component',\n 'decorator',\n 'macro',\n 'typedef',\n 'struct',\n];\n\nfunction sdkOpts(a: Args, ctx: ToolContext): { api?: string; sdk?: string; project: string; rebuild?: boolean } {\n return {\n api: a.api !== undefined ? String(a.api) : undefined,\n sdk: pathArg(a, 'sdk', ctx),\n project: projectOf(a, ctx),\n rebuild: a.rebuild as boolean,\n };\n}\n\nconst apiSearch: Tool = {\n name: 'api_search',\n title: 'Search the SDK API',\n description:\n \"Ranked search of the SDK's declarations at one API level (`oniro-app api search --json`): the ArkTS API, the \" +\n 'ArkUI components and decorators, and the Node-API C headers. Every word must match a symbol name (exact > prefix > ' +\n 'camelCase part > substring) or its doc line; a dotted word matches qualified names (`router.pushUrl`). Returns ' +\n 'sdk, query, total, hits (name, qualifiedName, kind, kit, import, module, since, deprecated, useInstead, syscap, ' +\n 'systemApi, file, path, line, signature, doc, overloads, score). isError when nothing matches.',\n inputSchema: object(\n {\n query: str('The search words, e.g. \"navigation push\" or \"router.pushUrl\".'),\n kit: str('Only symbols this kit exports (`ArkUI` or `@kit.ArkUI`).'),\n kind: { type: 'array', items: { type: 'string', enum: API_KINDS }, description: 'Only these kinds.' },\n lang: { type: 'string', enum: ['arkts', 'c'], description: 'Only `arkts` declarations or `c` (Node-API headers).' },\n limit: int('At most n hits.', { minimum: 1, default: 20 }),\n deprecated: bool('Include @deprecated symbols (false = --no-deprecated).', true),\n systemapi: bool('Include @systemapi symbols, for system apps only (false = --no-systemapi).', true),\n ...SDK_PROPS,\n },\n ['query'],\n ),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const run = runApiSearch(a.query as string, {\n ...sdkOpts(a, ctx),\n kit: a.kit as string | undefined,\n kind: a.kind as string[] | undefined,\n lang: a.lang as string | undefined,\n limit: String(a.limit),\n deprecated: a.deprecated as boolean,\n systemapi: a.systemapi as boolean,\n });\n return jsonResult(run.json, run.total === 0);\n },\n};\n\nconst apiShow: Tool = {\n name: 'api_show',\n title: 'Look up one SDK symbol',\n description:\n 'Exact lookup (`oniro-app api show --json`): is `symbol` declared at this API level? Takes a qualified name ' +\n '(`NavPathStack.pushPathByName`, `router.pushUrl`, `Column`, `@Local`, `napi_create_threadsafe_function`); when none ' +\n 'matches, names that end with it. Returns sdk, symbol, found, entries (the api_search hit fields, every overload), ' +\n 'and on a miss alsoIn ([{api, since}], the other installed SDKs that declare it) and suggestions. isError when it is ' +\n 'not declared.',\n inputSchema: object(\n {\n symbol: str('The symbol, e.g. `NavPathStack.pushPathByName`.'),\n kit: str('Only declarations this kit exports.'),\n otherSdks: bool('On a miss, look in the other installed SDKs (false = --no-other-sdks).', true),\n ...SDK_PROPS,\n },\n ['symbol'],\n ),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const run = runApiShow(a.symbol as string, {\n ...sdkOpts(a, ctx),\n kit: a.kit as string | undefined,\n otherSdks: a.otherSdks as boolean,\n });\n return jsonResult(run.json, !run.found);\n },\n};\n\nconst doctor: Tool = {\n name: 'doctor',\n title: 'Check the toolchain',\n description:\n 'Check that this machine can build, check, sign, install and test (`oniro-app doctor --json`): node, java, the SDK ' +\n 'the project compiles with, the command-line tools, a `check arkts` self-test, hdc and a reachable device at the ' +\n \"project's API, signing material, free disk space. Returns ok, checks (id, status ok/warn/fail/skip, detail, fix, \" +\n 'fixed), project, versions. isError when a check fails.',\n inputSchema: object({\n project: str(\"Project directory (default: the server's --project when it holds build-profile.json5).\"),\n fix: bool(\"Install the project's missing OpenHarmony SDK.\", false),\n device: bool('Check the device (false = --no-device, for a machine that only builds).', true),\n serial: str(\"The device to check, when several are connected (default: the server's --device).\"),\n arktsCheck: bool('Run the `check arkts` self-test (false = --no-arkts-check).', true),\n }),\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a, ctx) {\n const { config, logger, progress } = getRuntime();\n let dir: string | undefined;\n if (typeof a.project === 'string') dir = projectOf(a, ctx);\n else if (fs.existsSync(path.join(ctx.projectDir, 'build-profile.json5'))) dir = ctx.projectDir;\n const report = await runDoctor({\n config,\n projectDir: dir,\n fix: a.fix as boolean,\n device: a.device as boolean,\n deviceSerial: (a.serial as string | undefined) ?? ctx.deviceSerial,\n arktsSelfTest: a.arktsCheck as boolean,\n logger,\n progress,\n });\n return jsonResult(report as unknown as Args, doctorExitCode(report) !== 0);\n },\n};\n\nconst devices: Tool = {\n name: 'devices',\n title: 'List devices',\n description:\n 'List the connected hdc devices (`oniro-app devices --json`), as `{devices: [{serial, connection, status}]}`. ' +\n 'long: also ask each connected device for its OS family, version, API level, CPU ABI, device type and model (`info`).',\n inputSchema: object({\n long: bool(\n 'Also ask each connected device for its OS family (HarmonyOS / OpenHarmony), version, API level, CPU ABI, device type and model.',\n false,\n ),\n }),\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n changesDevice: false,\n async call(a) {\n const long = a.long as boolean;\n const { devices: list, infos } = await queryDevices(long);\n return jsonResult({ devices: devicesJson(list, infos, long) });\n },\n};\n\n/** Every tool, in the order `tools/list` shows them. */\nexport const ALL_TOOLS: readonly Tool[] = [\n build,\n checkArktsTool,\n test,\n apply,\n launch,\n dumpLayoutTool,\n input,\n screenshot,\n wait,\n logsCrash,\n perfTraceTool,\n screens,\n apiSearch,\n apiShow,\n doctor,\n devices,\n];\n\nexport const TOOL_NAMES: readonly string[] = ALL_TOOLS.map((t) => t.name);\n\n/**\n * The tools to expose: `names` (all when undefined), less those that change the\n * device when `readOnly`. Throws on an unknown name.\n */\nexport function selectTools(names: string[] | undefined, readOnly: boolean): Tool[] {\n if (names) {\n const unknown = names.filter((n) => !TOOL_NAMES.includes(n));\n if (unknown.length) throw new Error(`Unknown tool${unknown.length > 1 ? 's' : ''} ${unknown.join(', ')}. Tools: ${TOOL_NAMES.join(', ')}.`);\n }\n return ALL_TOOLS.filter((t) => (!names || names.includes(t.name)) && !(readOnly && t.changesDevice));\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as path from 'node:path';\nimport {\n DEFAULT_PERF_FLOW_TAIL_MS,\n DEFAULT_PERF_FOR_MS,\n DEFAULT_TRACE_BUFFER_KB,\n DEFAULT_TRACE_CATEGORIES,\n evaluatePerfGate,\n parseTraceFile,\n perfSliceFilter,\n perfTrace,\n readFlowFile,\n summarizeTrace,\n type PerfGateResult,\n type PerfThresholds,\n type PerfTraceReport,\n type TraceSummary,\n} from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { withInterrupt } from '../lib/interrupt.js';\nimport { projectBundle } from '../lib/crashReport.js';\n\ninterface TraceOpts {\n flow?: string;\n launch?: boolean;\n for?: number;\n bundle?: string;\n ability?: string;\n out?: string;\n categories?: string[];\n bufferKb: number;\n hiperf?: boolean;\n maxJankRate?: number;\n maxStartupMs?: number;\n stepTimeout?: number;\n fallback?: boolean;\n wake: boolean;\n device?: string;\n json?: boolean;\n}\n\ninterface SummaryOpts {\n bundle?: string;\n launched?: boolean;\n pid?: number;\n refreshRate?: number;\n maxJankRate?: number;\n maxStartupMs?: number;\n json?: boolean;\n}\n\nfunction positiveMs(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError('Expected a positive number of milliseconds.');\n return Math.floor(n);\n}\n\nfunction rate(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n < 0 || n > 1) throw new InvalidArgumentError('Expected a rate between 0 and 1, e.g. 0.05.');\n return n;\n}\n\nfunction positiveInt(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n) || n <= 0) throw new InvalidArgumentError('Expected a positive integer.');\n return n;\n}\n\nfunction positiveNumber(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError('Expected a positive number.');\n return n;\n}\n\nfunction list(raw: string): string[] {\n return raw.split(/[,\\s]+/).filter(Boolean);\n}\n\n/** 2 when the capture did not complete, 1 when a threshold (or the flow) failed, else 0. */\nexport function perfExitCode(report: Pick<PerfTraceReport, 'ok'>, gate: PerfGateResult): number {\n if (!report.ok) return 2;\n return gate.passed ? 0 : 1;\n}\n\nconst ms = (n: number): string => `${Math.round(n * 10) / 10} ms`;\n\n/** The text report. */\nexport function formatPerfReport(\n r: Pick<PerfTraceReport, 'bundle' | 'durationMs' | 'refreshRateHz' | 'frames' | 'startup' | 'mainThread' | 'scenes' | 'notes' | 'pid'> &\n Partial<Pick<PerfTraceReport, 'flow' | 'trace' | 'hiperf'>>,\n gate?: PerfGateResult,\n): string {\n const lines = [\n `${r.bundle}${r.pid !== null ? ` (pid ${r.pid})` : ''}: ${(r.durationMs / 1000).toFixed(1)} s captured` +\n (r.refreshRateHz ? `, display ${r.refreshRateHz} Hz (${ms(1000 / r.refreshRateHz)} per frame)` : ''),\n ];\n const f = r.frames;\n if (f) {\n lines.push(\n ` frames: ${f.total}, janky ${f.janky} (${(f.jankRate * 100).toFixed(1)}%), p50 ${ms(f.p50Ms)}, p95 ${ms(f.p95Ms)}, ` +\n `max ${ms(f.maxMs)}, ${f.missedVsyncs} vsync(s) missed`,\n );\n if (f.longest.length) lines.push(` longest: ${f.longest.map((l) => `${ms(l.ms)} at +${(l.atMs / 1000).toFixed(2)} s`).join(', ')}`);\n }\n if (r.startup) {\n const s = r.startup;\n lines.push(\n ` startup: cold ${ms(s.coldMs)} (${s.from} → ${s.to})` +\n (s.processMs !== null ? `, process up after ${ms(s.processMs)}` : '') +\n (s.firstFrameMs !== null ? `, first frame ${ms(s.firstFrameMs)}` : ''),\n );\n }\n if (r.mainThread) {\n lines.push(` main thread: ${ms(r.mainThread.busyMs)} in traced work${r.mainThread.cpuMs !== null ? `, ${ms(r.mainThread.cpuMs)} on CPU` : ''}`);\n }\n for (const s of r.scenes) {\n const parts = [\n s.maxFrameMs !== undefined ? `max frame ${s.maxFrameMs} ms` : '',\n s.maxHitchMs !== undefined ? `max hitch ${s.maxHitchMs} ms` : '',\n s.hitchMsPerS !== undefined ? `hitch ${Math.round(s.hitchMsPerS * 10) / 10} ms/s` : '',\n s.responseMs !== undefined ? `response ${s.responseMs} ms` : '',\n ].filter(Boolean);\n lines.push(` RenderService ${s.scene}${s.page ? ` ${s.page}` : ''}: ${parts.join(', ')}`);\n }\n if (r.flow) {\n lines.push(\n r.flow.outcome === 'passed'\n ? ` flow: passed (${r.flow.steps.length} step(s))`\n : ` flow: ${r.flow.outcome} at step ${r.flow.failedStep ?? '?'} (${r.flow.reason ?? r.flow.error ?? ''}): ${r.flow.message ?? ''}`,\n );\n }\n if (r.hiperf) {\n if ('error' in r.hiperf) lines.push(` hiperf: ${r.hiperf.error}`);\n else {\n lines.push(` hiperf: ${r.hiperf.samples} sample(s)${r.hiperf.event ? ` of ${r.hiperf.event}` : ''}${r.hiperf.data ? `, data ${r.hiperf.data}` : ''}`);\n for (const t of r.hiperf.top.slice(0, 10)) lines.push(` ${t.percent.toFixed(2).padStart(6)}% ${t.func} (${t.dso})`);\n }\n }\n if (r.trace) lines.push(` trace: ${r.trace}`);\n for (const n of r.notes) lines.push(` note: ${n}`);\n if (gate && !gate.passed) for (const fail of gate.failures) lines.push(`GATE FAILED: ${fail}`);\n return lines.join('\\n');\n}\n\nexport function registerPerfCommand(program: Command): void {\n const perf = program.command('perf').description('Measure app performance on the device: frames, jank and startup from a hitrace capture.');\n\n perf\n .command('trace')\n .description(\n 'Capture a hitrace trace while the app cold-launches (--launch), a flow is replayed (--flow), or for a fixed ' +\n \"time (--for); pull it and summarise it for the bundle: its UI frames (janky when one takes longer than the \" +\n \"display's refresh interval, from its vsync to done), p50/p95/max frame time, cold-start time (launch request \" +\n 'to the first frame composited), main-thread load and RenderService jank reports. Exits 0 when the capture ' +\n 'completed, 1 when --max-jank-rate or --max-startup-ms is exceeded (or the flow diverged), 2 when it could not ' +\n 'capture.',\n )\n .option('--flow <file>', 'Replay this flow file (see `replay`) while tracing; its bundle is the default --bundle.')\n .option('--launch', 'Force-stop the app, start tracing, then cold-launch it and report its startup time.')\n .option(\n '--for <ms>',\n `Without --flow: how long to capture (after the launch with --launch), default ${DEFAULT_PERF_FOR_MS}. With --flow: how long to keep capturing after it, default ${DEFAULT_PERF_FLOW_TAIL_MS}.`,\n positiveMs,\n )\n .option('--bundle <bundle>', 'The app to measure (default: the flow\\'s bundle, else the project in the current directory).')\n .option('--ability <name>', 'Ability --launch starts (default: the main ability).')\n .option('--out <file>', 'Where to save the trace (default: a file in the system temp dir).')\n .option('--categories <list>', `hitrace categories, comma-separated (default ${DEFAULT_TRACE_CATEGORIES.join(',')}; add sched for main-thread CPU time).`, list)\n .option('--buffer-kb <kb>', 'hitrace buffer size in KB.', positiveInt, DEFAULT_TRACE_BUFFER_KB)\n .option('--hiperf', \"Also sample the app's process with hiperf during the capture and list its top functions.\")\n .option('--max-jank-rate <r>', 'Exit 1 when the share of janky frames is above this (0..1).', rate)\n .option('--max-startup-ms <ms>', 'Exit 1 when the cold start takes longer than this (needs --launch).', positiveMs)\n .option('--step-timeout <ms>', \"With --flow: how long to wait for a step's selector and expect.\", positiveMs)\n .option('--fallback', \"With --flow: act on a step's fallback point when its selector is not found.\")\n .option('--no-wake', 'Leave the screen as it is (by default, with --launch or --flow, it is woken, a credential-less lock screen swiped away, and kept on).')\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Print the report as JSON: ok, bundle, durationMs, trace, refreshRateHz, frames, startup, flow, pid, mainThread, scenes, hiperf, notes, gate, error.')\n .action(async (opts: TraceOpts) => {\n const { config, logger } = getRuntime();\n const thresholds: PerfThresholds = { maxJankRate: opts.maxJankRate, maxStartupMs: opts.maxStartupMs };\n let report: PerfTraceReport;\n try {\n const flow = opts.flow ? readFlowFile(path.resolve(opts.flow)) : undefined;\n report = await withInterrupt(logger, 'stopping the trace', (abortSignal) => perfTrace({\n config,\n logger,\n abortSignal,\n deviceSerial: opts.device,\n bundle: opts.bundle ?? flow?.bundle ?? projectBundle(process.cwd()),\n ability: opts.ability,\n launch: opts.launch,\n flow,\n replay: {\n stepTimeoutMs: opts.stepTimeout,\n fallback: opts.fallback,\n onStep: opts.json ? undefined : (s) => logger.info(`flow step ${s.index} ${s.action} ${s.ok ? 'ok' : 'FAILED'}`),\n },\n forMs: opts.for,\n out: opts.out ? path.resolve(opts.out) : undefined,\n categories: opts.categories,\n bufferKb: opts.bufferKb,\n hiperf: opts.hiperf,\n wake: opts.wake,\n }));\n } catch (err) {\n report = emptyReport(opts.bundle ?? '', (err as Error).message);\n }\n const gate = evaluatePerfGate(report, thresholds);\n if (opts.json) process.stdout.write(`${JSON.stringify({ ...report, gate }, null, 2)}\\n`);\n else if (report.ok) process.stdout.write(`${formatPerfReport(report, gate)}\\n`);\n if (report.error) logger.error(report.error);\n process.exitCode = perfExitCode(report, gate);\n });\n\n perf\n .command('summary <trace>')\n .description(\n 'Summarise a hitrace text trace taken earlier (by `perf trace --out`, or `hitrace -o` by hand) for a bundle, ' +\n 'the same way `perf trace` does. Exit codes as `perf trace`.',\n )\n .option('--bundle <bundle>', 'The app to summarise (default: the project in the current directory).')\n .option('--launched', 'The trace holds a cold launch: report startup and leave the first frame out of the frame stats.')\n .option('--pid <pid>', \"The app's pid, when the trace holds several of its processes.\", positiveInt)\n .option('--refresh-rate <hz>', 'Refresh rate to use when the trace has no vsync period.', positiveNumber)\n .option('--max-jank-rate <r>', 'Exit 1 when the share of janky frames is above this (0..1).', rate)\n .option('--max-startup-ms <ms>', 'Exit 1 when the cold start takes longer than this.', positiveMs)\n .option('--json', 'Print the summary as JSON.')\n .action(async (trace: string, opts: SummaryOpts) => {\n const { logger } = getRuntime();\n const bundle = opts.bundle ?? projectBundle(process.cwd());\n const file = path.resolve(trace);\n let report: PerfTraceReport;\n if (!bundle) report = emptyReport('', 'No bundle to summarise: pass --bundle.');\n else {\n try {\n const model = await parseTraceFile(file, { keepSlice: perfSliceFilter });\n const s: TraceSummary = summarizeTrace(model, { bundle, launched: opts.launched, pid: opts.pid, refreshRateHz: opts.refreshRate });\n report = { ...emptyReport(bundle), ...s, ok: true, trace: file };\n } catch (err) {\n report = emptyReport(bundle, `Could not read ${file}: ${(err as Error).message}`);\n }\n }\n const gate = evaluatePerfGate(report, { maxJankRate: opts.maxJankRate, maxStartupMs: opts.maxStartupMs });\n if (opts.json) process.stdout.write(`${JSON.stringify({ ...report, gate }, null, 2)}\\n`);\n else if (report.ok) process.stdout.write(`${formatPerfReport(report, gate)}\\n`);\n if (report.error) logger.error(report.error);\n process.exitCode = perfExitCode(report, gate);\n });\n}\n\nfunction emptyReport(bundle: string, error?: string): PerfTraceReport {\n return {\n ok: false,\n bundle,\n durationMs: 0,\n trace: null,\n refreshRateHz: null,\n frames: null,\n startup: null,\n flow: null,\n pid: null,\n mainThread: null,\n scenes: [],\n categories: [],\n notes: [],\n ...(error ? { error } : {}),\n };\n}\n","import type { Logger } from '@oniroproject/core';\n\n/**\n * Run `fn` with an abort signal that the first Ctrl+C fires, so the command's\n * cleanup (stopping a device-side capture, restoring a setting) still runs; a\n * second Ctrl+C exits at once.\n */\nexport async function withInterrupt<T>(logger: Logger, what: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T> {\n const controller = new AbortController();\n const onSigint = (): void => {\n if (controller.signal.aborted) process.exit(130);\n logger.info(`${what}… (Ctrl+C again to quit at once)`);\n controller.abort();\n };\n process.on('SIGINT', onSigint);\n try {\n return await fn(controller.signal);\n } finally {\n process.off('SIGINT', onSigint);\n }\n}\n","import type { ElementQuery } from '@oniroproject/core';\nimport { selectorFrom, windowIdFrom } from '../lib/target.js';\nimport type { JsonSchema } from './schema.js';\n\n/**\n * The element-selector inputs shared by the `input`, `wait`, `screenshot` and\n * `dump_layout` tools: the MCP side of `--target`, `--target-id`,\n * `--target-type`, `--target-index`, `--selector` and `--window`\n * (src/lib/target.ts), checked by the same rules.\n */\nexport function targetProperties(verb: string, opts: { index?: boolean } = {}): Record<string, JsonSchema> {\n const props: Record<string, JsonSchema> = {\n target: {\n type: 'string',\n description:\n `${verb} the element whose text, description, or placeholder matches ` +\n '(case-insensitive; exact matches win, else substring). Covered elements are skipped.',\n },\n targetId: { type: 'string', description: 'Match the element by its id or key.' },\n targetType: { type: 'string', description: 'Restrict the match to a component type (e.g. Button, TextInput).' },\n selector: {\n type: 'string',\n description:\n 'Instead of target*: an exact selector. Attributes as comma-separated key<op>value clauses ' +\n '(keys text, desc, hint, id, key, type, enabled, focused, checked, selected, visible, clickable, scrollable; ' +\n 'ops = *= ^= $= /=regex) with an optional [n] index, e.g. \"type=Button,text*=Sign[1]\"; or ' +\n '\"xpath=//Button[@text=\\\\\"OK\\\\\"]\".',\n },\n window: windowProperty,\n };\n if (opts.index !== false) {\n props.targetIndex = { type: 'integer', minimum: 0, description: 'Pick the n-th (0-based) of several matching elements.' };\n }\n return props;\n}\n\n/** The `window` input on its own, for tools that take a window but no element. */\nexport const windowProperty: JsonSchema = {\n type: 'integer',\n minimum: 0,\n description: 'Only this window (an id from `dump windows`, or the [window <id> ...] header of a flat dump).',\n};\n\n/** The element query built from the arguments, or undefined when none was given. */\nexport function selectorFromArgs(args: Record<string, unknown>): ElementQuery | undefined {\n return selectorFrom({\n target: args.target as string | undefined,\n targetId: args.targetId as string | undefined,\n targetType: args.targetType as string | undefined,\n targetIndex: args.targetIndex === undefined ? undefined : String(args.targetIndex),\n selector: args.selector as string | undefined,\n });\n}\n\nexport function targetIndexFromArgs(args: Record<string, unknown>): number | undefined {\n return args.targetIndex as number | undefined;\n}\n\nexport function windowFromArgs(args: Record<string, unknown>): number | undefined {\n return windowIdFrom({ window: args.window === undefined ? undefined : String(args.window) });\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { formatFlow, recordFlow } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { withInterrupt } from '../lib/interrupt.js';\n\ninterface RecordOpts {\n out: string;\n for?: number;\n bundle?: string;\n wake: boolean;\n device?: string;\n json?: boolean;\n raw?: string;\n}\n\nfunction positiveMs(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError('Expected a positive number of milliseconds.');\n return Math.floor(n);\n}\n\nexport function registerRecordCommand(program: Command): void {\n program\n .command('record')\n .description(\n \"Record what is done on the device into a flow file for `replay`. Runs uitest's recorder \" +\n '(`uitest uiRecord record -l`), which logs every tap, swipe and key with the widget under the finger and ' +\n 'dumps the layout after each one; each event becomes a step with the most specific stable selector for that ' +\n 'widget in the layout on screen when it happened, a fallback point, and an `expect` element that appeared ' +\n 'after it. Typing collapses into one inputText step per field. Stops on Ctrl+C or after --for.',\n )\n .requiredOption('--out <file>', 'Where to write the flow (JSON).')\n .option('--for <ms>', 'Stop after this long instead of waiting for Ctrl+C.', positiveMs)\n .option('--bundle <bundle>', 'The app being recorded (default: the foreground app when recording starts).')\n .option('--no-wake', 'Leave the screen as it is (by default it is turned on, a lock screen without a credential is swiped away, and it is kept on while recording).')\n .option('--raw <dir>', \"Also keep uitest's raw recording (events, layouts, touch times) in this directory, for bug reports.\")\n .option('--device <serial>', 'Target device serial.')\n .option('--json', 'Print {out, steps, events, warnings} as JSON.')\n .action(async (opts: RecordOpts) => {\n const { config, logger } = getRuntime();\n await withInterrupt(logger, 'stopping the recorder', async (abortSignal) => {\n const result = await recordFlow({\n config,\n durationMs: opts.for,\n abortSignal,\n bundle: opts.bundle,\n wake: opts.wake,\n rawDir: opts.raw,\n deviceSerial: opts.device,\n logger,\n onEvents: (n) => logger.info(`${n} event line(s) recorded`),\n });\n const out = path.resolve(opts.out);\n fs.mkdirSync(path.dirname(out), { recursive: true });\n fs.writeFileSync(out, formatFlow(result.flow));\n for (const w of result.warnings) logger.warn(w);\n if (opts.json) {\n process.stdout.write(\n `${JSON.stringify({ out, steps: result.flow.steps.length, events: result.events, warnings: result.warnings }, null, 2)}\\n`,\n );\n } else {\n process.stdout.write(`Wrote ${result.flow.steps.length} step(s) to ${out}.\\n`);\n }\n });\n });\n}\n","import { Command, InvalidArgumentError } from 'commander';\nimport * as path from 'node:path';\nimport { readFlowFile, replayFlow, type ReplayReport, type ReplayStepResult } from '@oniroproject/core';\nimport { getRuntime } from '../lib/runtime.js';\nimport { withInterrupt } from '../lib/interrupt.js';\n\ninterface ReplayOpts {\n json?: boolean;\n from?: number;\n to?: number;\n stepTimeout: number;\n screenshots?: string;\n fallback?: boolean;\n launch?: boolean;\n wake: boolean;\n device?: string;\n}\n\nfunction stepIndex(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n) || n < 0) throw new InvalidArgumentError('Expected a step index (0-based).');\n return n;\n}\n\nfunction positiveMs(raw: string): number {\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError('Expected a positive number of milliseconds.');\n return Math.floor(n);\n}\n\n/** 0 when every step ran, 1 when the flow diverged, 2 when it could not run. */\nexport function replayExitCode(report: Pick<ReplayReport, 'outcome'>): number {\n return report.outcome === 'passed' ? 0 : report.outcome === 'diverged' ? 1 : 2;\n}\n\n/** `[2] click type=Button,id=continueBtn ok 1.2 s` */\nexport function formatReplayStep(s: ReplayStepResult): string {\n const what = s.selector ? ` ${s.selector}` : '';\n const how = s.usedFallback ? ' (at the recorded point)' : '';\n return `[${s.index}] ${s.action}${what}${how} ${s.ok ? 'ok' : 'FAILED'} ${(s.durationMs / 1000).toFixed(1)} s`;\n}\n\n/** The divergence part of the text report. */\nexport function formatDivergence(r: ReplayReport): string {\n const lines = [`Diverged at step ${r.failedStep} (${r.reason}): ${r.message}`];\n if (r.screenshot) lines.push(` screenshot: ${r.screenshot}`);\n for (const n of r.nearMatches ?? []) lines.push(` near match: ${n.element} (differs in ${n.differs})`);\n if (r.layout) {\n const where = r.layout.appOnScreen ? `on screen in ${r.bundle}` : 'on screen';\n lines.push(` ${where} (${r.layout.elementCount} element(s)${r.layout.keyboard ? ', keyboard up' : ''}):`);\n for (const e of r.layout.elements) lines.push(` ${e}`);\n if (r.layout.elementCount > r.layout.elements.length) lines.push(` … ${r.layout.elementCount - r.layout.elements.length} more`);\n }\n return lines.join('\\n');\n}\n\nexport function registerReplayCommand(program: Command): void {\n program\n .command('replay <flow>')\n .description(\n 'Replay a flow file (written by `record` or by hand) on the device: for each step, wait for its selector, ' +\n 'act on it the way `input --selector` does, then wait for its `expect`. Stops at the first step that fails ' +\n 'and reports the step, why (not-found, expect-not-found, wrong-screen, ambiguous, covered, action-failed), ' +\n 'a screenshot and what was on screen. Exits 0 when every step ran, 1 when the flow diverged, 2 when it ' +\n 'could not run (invalid flow file, no device).',\n )\n .option('--from <i>', 'First step to run (0-based).', stepIndex)\n .option('--to <i>', 'Last step to run (0-based, inclusive).', stepIndex)\n .option('--step-timeout <ms>', \"How long to wait for a step's selector and its expect (a step's timeoutMs overrides it).\", positiveMs, 10_000)\n .option('--screenshots <dir>', 'Save a screenshot after every step (step-<i>.jpeg), and the divergence screenshot, here.')\n .option('--fallback', \"When a step's selector is not found, act on its recorded fallback point instead of stopping.\")\n .option('--launch', \"Force-stop and start the flow's app (its bundle and ability) before the first step.\")\n .option('--no-wake', 'Leave the screen as it is (by default it is turned on, a lock screen without a credential is swiped away, and it is kept on during the run).')\n .option('--device <serial>', 'Target device serial.')\n .option(\n '--json',\n 'Print the report as JSON: ok, outcome, steps, failedStep, reason, message, selector, screenshot, layout, nearMatches, error, warnings.',\n )\n .action(async (flowPath: string, opts: ReplayOpts) => {\n const { config, logger } = getRuntime();\n let report: ReplayReport;\n try {\n const flow = readFlowFile(path.resolve(flowPath));\n report = await withInterrupt(logger, 'stopping the replay', (abortSignal) => replayFlow({\n config,\n flow,\n abortSignal,\n from: opts.from,\n to: opts.to,\n stepTimeoutMs: opts.stepTimeout,\n screenshotsDir: opts.screenshots,\n fallback: opts.fallback,\n launch: opts.launch,\n wake: opts.wake,\n deviceSerial: opts.device,\n logger,\n onStep: opts.json ? undefined : (s) => process.stdout.write(`${formatReplayStep(s)}\\n`),\n }));\n } catch (err) {\n report = { ok: false, outcome: 'error', range: [0, 0], steps: [], error: (err as Error).message, warnings: [] };\n }\n\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else if (report.outcome === 'passed') {\n process.stdout.write(`Flow passed: ${report.steps.length} step(s).\\n`);\n } else if (report.outcome === 'diverged') {\n process.stdout.write(`${formatDivergence(report)}\\n`);\n }\n for (const w of report.warnings) logger.warn(w);\n if (report.error) logger.error(report.error);\n process.exitCode = replayExitCode(report);\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,WAAS,sBAAsB;AACxC,SAAS,cAAAC,mBAAkB;;;ACA3B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACNA,SAAS,kBAA0B;AACxC,QAAM,eAAe,QAAQ,IAAI,gBAAgB,OAAO,QAAQ,IAAI,gBA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,OAAO;AAC7B,2BAAyB,OAAO;AAChC,wBAAsB,OAAO;AAC7B,sBAAoB,OAAO;AAC3B,uBAAqB,OAAO;AAC5B,4BAA0B,OAAO;AACjC,sBAAoB,OAAO;AAC3B,yBAAuB,OAAO;AAC9B,sBAAoB,OAAO;AAC3B,sBAAoB,OAAO;AAC3B,uBAAqB,OAAO;AAC5B,wBAAsB,OAAO;AAC7B,yBAAuB,OAAO;AAC9B,qBAAmB,OAAO;AAC1B,sBAAoB,OAAO;AAC3B,uBAAqB,OAAO;AAC5B,wBAAsB,OAAO;AAC7B,wBAAsB,OAAO;AAC7B,sBAAoB,OAAO;AAC3B,sBAAoB,OAAO;AAC3B,qBAAmB,OAAO;AAC1B,uBAAqB,OAAO;AAE5B,SAAO;AACT;AAEA,eAAe,OAAsB;AACnC,QAAM,UAAU,aAAa;AAC7B,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,QAAI,eAAe,gBAAgB;AAEjC,cAAQ,WAAW,IAAI;AACvB;AAAA,IACF;AACA,UAAMC,WAAU,eAAeC,cAAa,IAAI,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACzG,UAAM,QAAQ,QAAQ,IAAI,gBAAgB,OAAO,eAAe,SAAS,IAAI,QAAQ,GAAG,IAAI,KAAK;AAAA,IAAO;AAGxG,YAAQ,OAAO,MAAM,WAAWD,QAAO;AAAA,EAAK,KAAK,IAAI,MAAM,QAAQ,KAAK,CAAC,CAAC;AAAA,EAC5E;AACF;AAEA,KAAK,KAAK;","names":["Command","OniroError","message","rows","path","downloadAndInstallSdk","build","downloadAndInstallSdk","path","OniroError","OniroError","result","InvalidArgumentError","createHarmonyOsSession","createHarmonyOsSession","InvalidArgumentError","os","path","OniroError","jpeg","input","OniroError","jpeg","rt","launch","apply","path","ALL_SDKS","fs","path","ALL_SDKS","list","Option","Option","wait","fs","path","describeLayoutNode","screenshot","shot","describeLayoutNode","fs","dumpLayout","dumpLayout","os","devices","InvalidArgumentError","path","detectRuntimeOs","path","InvalidArgumentError","detectRuntimeOs","InvalidArgumentError","path","InvalidArgumentError","fs","path","path","Option","describeLayoutNode","input","Option","describeLayoutNode","fs","os","path","latestCrash","fs","path","input","relative","text","fs","path","getBundleName","latestCrash","resolve","path","OniroError","OniroError","fs","path","OniroError","readline","message","input","fs","os","path","analyzeFaultLog","captureBurst","describeLayoutNode","findLayoutNodes","listLayoutWindows","selectableTree","diffLayouts","dumpLayout","inventoryScreens","latestCrash","locateTarget","parseLayoutBaseline","parseSelector","performInput","runDoctor","runTests","summarizeLayout","takeScreenshot","waitForBoot","waitForBundle","waitForLog","waitForTarget","DEFAULT_SMOKE_DELAY_MS","DEFAULT_TRACE_BUFFER_KB","DEFAULT_TRACE_CATEGORIES","evaluatePerfGate","perfTrace","readFlowFile","InvalidArgumentError","path","positiveMs","InvalidArgumentError","num","DEFAULT_SMOKE_DELAY_MS","INPUT_TYPES","runTests","parseLayoutBaseline","parseSelector","dumpLayout","findLayoutNodes","selectableTree","json","summarizeLayout","diffLayouts","performInput","DEFAULT_CONTACT_SHEET_FRAMES","TARGET_CROP_PAD","shot","takeScreenshot","locateTarget","describeLayoutNode","listLayoutWindows","buf","dims","captureBurst","waitForLog","waitForBoot","waitForTarget","waitForBundle","analyzeFaultLog","latestCrash","DEFAULT_TRACE_CATEGORIES","DEFAULT_TRACE_BUFFER_KB","readFlowFile","perfTrace","evaluatePerfGate","inventoryScreens","runDoctor","list","OniroError","InvalidArgumentError","fs","path","positiveMs","InvalidArgumentError","InvalidArgumentError","path","readFlowFile","InvalidArgumentError","positiveMs","readFlowFile","Command","message","OniroError"]}