import { lstatSync } from 'node:fs'; import { dirname, isAbsolute, join } from 'node:path'; import { pathToFileURL } from 'node:url'; import type { StimContext } from '@stim-cli/core'; import { isJsonObject, SHIPPED_PLUGIN_PACKAGE_PREFIX, shippedPluginName } from '@stim-cli/core/state'; import { processContext } from '../cli-operation.ts'; import type { Finding } from '../diagnostics/doctor.ts'; import { unresolvedCleanup } from '../engine/acquire-artifact.ts'; import { runCancellationSignal } from '../engine/native-run.ts'; import { operationState } from '../engine/operation-state.ts'; import { fenceDeclaredSpawns } from '../engine/spawn-claims.ts'; import { getExecutor } from '../exec.ts'; import { startKitWorker, type KitWorker } from '../kit-host.ts'; import { withIosOperationScope, type IosOperationScope } from './ios-operation-scope.ts'; import { pluginOffloadPlan, pluginOffloadTarget } from './plugin-ios.ts'; import { builtInProjectFolder } from './project-folder.ts'; import type { OutputClean, OutputUse, ProjectOutputMembers, ProjectOutputs } from './project-outputs.ts'; import { moduleIosProblem } from './project-registry.ts'; import { containedModule, holdsMarkers, type ProjectPluginHost, type ProjectPluginManifest, } from '../project-plugin.ts'; import { shippedPluginNames } from '../shipped-plugins.ts'; import { pluginProjectAt, readProjectPlugins, type ProjectPluginEntry } from './plugin-projects.ts'; import { bundledProjectIds } from './projects.ts'; import type { IosPlugin, IosPluginOffload, IosPluginSource } from './plugin-ios.ts'; import type { ProjectDoctor } from './project-doctor.ts'; const LOAD_TIMEOUT_MS = 30_000; const OUTPUT_CLEAN_CALL_TIMEOUT_MS = 240_000; // @ref LLP 0023#frozen-and-experimental-plugin-kinds -- the module and its host children never see the setup ticket const MODULE_OMITTED_ENV = ['STIM_ACCESS_TICKET']; function moduleEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const copy = { ...env }; for (const name of MODULE_OMITTED_ENV) delete copy[name]; return copy; } type PluginMatch = Pick & { project: ProjectPluginManifest }; function reason(error: unknown): string { return (error instanceof Error ? error.message : String(error)).split('\n')[0]?.trim() || 'unknown error'; } type FailureKind = 'manifest' | 'module' | { member: string }; function failure(plugin: PluginMatch, root: string, why: string, kind: FailureKind = 'manifest'): Error { const shipped = shippedPluginName(plugin.reference) !== null; return Object.assign( new Error(`The plugin ${plugin.package} cannot serve the ${plugin.project.name} project at ${root}: ${why}.`), { code: 'STIM_NO_PROJECT', projectPluginFailure: true, remedy: shipped ? 'Update Stim with stim engine update, or remove the plugin from the machine setting plugins.' : typeof kind === 'object' ? `Fix ios.${kind.member}() in the plugin at ${plugin.dir}, then retry.` : kind === 'module' ? `Fix ${plugin.project.module ?? 'the module'} in the plugin at ${plugin.dir}, then run stim doctor --platform ios in ${root} to check that it loads.` : `Fix the plugin at ${plugin.dir} (stim plugin test ${plugin.dir} checks its package.json), then retry.`, }, ); } /** * The host's `exec` under `context`: for an iOS operation (`declared`), whose children join its ownership claims, or for an * output member call outside any operation. */ function execHost(root: string, context: StimContext, signal: AbortSignal, declared: boolean) { function execWindow() { const controller = new AbortController(); const childSignal = AbortSignal.any([signal, controller.signal]); const pending = new Set>(); let fence: ReturnType | undefined; let closing: Promise | undefined; return { start(args: Parameters) { const child = run( childSignal, () => { if (declared && operationState(context).declaring.size) fence ??= fenceDeclaredSpawns(context); }, ...args, ); pending.add(child); void child.then( () => pending.delete(child), (error: unknown) => { if (unresolvedCleanup(error)) cleanupFailure ??= error; pending.delete(child); }, ); return child; }, close() { controller.abort(); return (closing ??= (async () => { await Promise.allSettled(pending); try { await fence?.finish(cleanupFailure); } catch (error) { cleanupFailure = error; } })()); }, }; } let window: ReturnType | undefined; let cleanupFailure: unknown; let closed = false; let tail = Promise.resolve(); const checkCleanup = () => { if (cleanupFailure) throw cleanupFailure; }; const run = async ( childSignal: AbortSignal, protect: () => void, ...[file, args, options]: Parameters ): ReturnType => { childSignal.throwIfAborted(); if (!isString(file) || !Array.isArray(args) || !args.every(isString)) throw new TypeError('host.exec needs a program and an array of string arguments'); const timeoutMs = options?.timeoutMs; if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new TypeError(`host.exec needs timeoutMs, a positive number of milliseconds, not ${describe(timeoutMs)}`); const env = options?.env ?? {}; if (!isEnv(env)) throw new TypeError('host.exec needs an environment of string values'); let stderr = ''; const childEnv = Object.fromEntries( Object.entries({ ...context.env, ...env }).filter((pair): pair is [string, string] => pair[1] !== undefined), ); protect(); try { const stdout = await getExecutor().runFileAsync(file, [...args], { timeoutMs, signal: childSignal, ...(declared ? { context, declareFor: context } : {}), cleanupOnExit: true, cwd: root, env: childEnv, omitEnv: MODULE_OMITTED_ENV, untrimmed: true, onStderr: (captured) => { stderr = captured; }, }); return { code: 0, stdout, stderr }; } catch (error) { const code: unknown = error instanceof Error ? Reflect.get(error, 'code') : undefined; if ( childSignal.aborted || !(error instanceof Error) || !('status' in error) || code === 'ETIMEDOUT' || code === 'ENOBUFS' ) throw error; return { code: typeof error.status === 'number' ? error.status : null, stdout: String(Reflect.get(error, 'stdout') ?? ''), stderr: String(Reflect.get(error, 'stderr') ?? ''), }; } }; return { exec(...args: Parameters) { if (closed || !window) throw new Error('host.exec requires an active project plugin call'); return window.start(args); }, invoke(call: () => Promise): Promise { const result = tail.then(async () => { checkCleanup(); const active = execWindow(); window = active; try { return await call(); } finally { await active.close(); window = undefined; checkCleanup(); } }); tail = result.then( () => undefined, () => undefined, ); return result; }, async dispose() { closed = true; await window?.close(); }, checkCleanup, }; } const isString = (value: unknown): value is string => typeof value === 'string'; const isProblem = (value: unknown): value is { message: string; remedy: string } => isJsonObject(value) && isString(value.message) && isString(value.remedy); const isEnv = (value: unknown): value is NodeJS.ProcessEnv => isJsonObject(value) && Object.values(value).every((each) => each === undefined || isString(each)); function describe(value: unknown): string { try { return (JSON.stringify(value) ?? String(value)).slice(0, 120); } catch { return typeof value; } } type MemberCall = ( member: string, args: unknown[], valid: (value: unknown) => value is T, fallback?: () => T, ) => Promise; function memberCall( worker: KitWorker, fail: (why: string, kind: FailureKind) => Error, invoke: ReturnType['invoke'], ): MemberCall { return async (member, args, valid, fallback) => { if (fallback && !worker.members.includes(member)) return fallback(); const value = await invoke(async () => { try { return await worker.call(member, ...args); } catch (error) { throw fail(`its ios.${member}() failed: ${reason(error)}`, { member }); } }); if (!valid(value)) throw fail(`its ios.${member}() returned ${describe(value)}, which is not what it declares`, { member }); return value; }; } const FINDING_CODE = /^[a-z][a-z0-9-]{0,63}$/; function checkedIos( keepsCodes: boolean, cacheIneligible: string, call: MemberCall, fail: (why: string, kind: FailureKind) => Error, ): IosPlugin { return { cacheIneligible, configurationProblem: (scheme, configuration) => call( 'configurationProblem', [scheme, configuration], (value) => value === null || isProblem(value), () => null, ), bundleId: (root) => call( 'bundleId', [root], (value) => value === null || isString(value), () => null, ), simulator: (root) => call( 'simulator', [root], (value): value is Awaited> => value === null || (isJsonObject(value) && isString(value.reason) && isProblem(value.buildOnly)), () => null, ), incremental: (root, configuration, env) => call( 'incremental', [root, configuration, moduleEnv(env)], (value) => value === undefined || typeof value === 'boolean', () => undefined, ), build: async (input) => { const built = await call( 'build', [{ ...input, env: moduleEnv(input.env) }], (value): value is Awaited> => isJsonObject(value) && Array.isArray(value.argv) && value.argv.length > 0 && value.argv.every(isString) && isEnv(value.env), ); if (!isAbsolute(built.argv[0])) throw fail(`its ios.build() returned the program ${JSON.stringify(built.argv[0])}, not an absolute path`, { member: 'build', }); return built; }, result: (run) => call( 'result', [run], (value): value is Awaited> => isJsonObject(value) && (value.app === null || isString(value.app)) && Array.isArray(value.diagnostics) && value.diagnostics.every(isString), ), doctor: async () => { try { return ( await call( 'doctor', [], (value): value is Finding[] => Array.isArray(value) && value.every( (finding) => isJsonObject(finding) && (finding.code === undefined || (isString(finding.code) && FINDING_CODE.test(finding.code))) && (finding.level === 'note' || finding.level === 'cost') && isString(finding.title) && isString(finding.detail) && (finding.fix === null || isString(finding.fix)), ), () => [], ) ).map(({ code, level, title, detail, fix }) => { const finding: Finding = { level, title, detail, fix }; // @ref LLP 0023#frozen-and-experimental-plugin-kinds -- only a shipped plugin's finding keeps its code if (keepsCodes && code !== undefined) finding.code = code; return finding; }); } catch (error) { return [ { level: 'cost', title: 'A project plugin failed its doctor check', detail: reason(error), fix: null, }, ]; } }, }; } function localOnly(unsupported: string): IosPluginOffload { return { plan: () => ({ unsupported }), pins: () => null, payload: () => null, malformed: { offer: 'This Stim offloads no plugin build.', start: 'This Stim offloads no plugin build.', }, tools: () => [], source: () => null, project: () => null, env: ({ env }) => env, }; } const isPlan = (value: unknown): value is Awaited> => isJsonObject(value) && (isString(value.unsupported) || (isJsonObject(value.pins) && isJsonObject(value.payload) && isJsonObject(value.checkout) && isString(value.checkout.name) && (value.checkout.sibling === null || isString(value.checkout.sibling)))); const isToolProblems = (value: unknown): value is { reason: string; commands: string[] }[] => Array.isArray(value) && value.every( (each) => isJsonObject(each) && isString(each.reason) && Array.isArray(each.commands) && each.commands.every(isString), ); const COMMIT = /^[0-9a-f]{40}$/; /** The `offload` member of a module, as the host calls it with the operation's environment and checks its answers. */ function moduleOffload(name: string, call: MemberCall): IosPluginOffload { return { plan: (root, env) => call('offload.plan', [root, moduleEnv(env)], isPlan), pins: (value) => (isJsonObject(value) ? value : null), payload: (value) => (isJsonObject(value) ? value : null), malformed: { offer: `A ${name} offer needs the pins its plugin plans.`, start: `A ${name} build needs an iOS request with the pins, payload and checkout its plugin plans.`, }, check: (pins, payload) => call('offload.check', [pins, payload], (value): value is string | null => value === null || isString(value)), tools: (pins, env) => call('offload.tools', [pins, moduleEnv(env)], isToolProblems, () => []), source: (pins) => call( 'offload.source', [pins], (value): value is { dir: string; commit: string } => isJsonObject(value) && isString(value.dir) && isAbsolute(value.dir) && isString(value.commit) && COMMIT.test(value.commit), () => null, ), project: (root, payload) => call( 'offload.project', [root, payload], (value): value is { code: string; message: string } | null => value === null || (isJsonObject(value) && (value.code === 'bad-project' || value.code === 'bad-request') && isString(value.message)), () => null, ), env: (input) => call('offload.env', [{ ...input, env: moduleEnv(input.env) }], isEnv, () => input.env), }; } interface Opened { dir: string; module: string; version: string; name: string; } async function openPluginIos( plugin: PluginMatch, root: string, scope: IosOperationScope, fail: (why: string, kind?: FailureKind) => Error, select: () => Opened, ): Promise { const { context } = scope; const runSignal = runCancellationSignal(context); const signal = runSignal ? AbortSignal.any([context.signal, runSignal]) : context.signal; const { exec, invoke, dispose, checkCleanup } = execHost(root, context, signal, true); let started: ReturnType | undefined; const opening = invoke(async () => { const { dir, module, version, name } = select(); const found = containedModule(dir, module); if ('error' in found) throw fail(found.error); started = startKitWorker({ href: pathToFileURL(found.file).href, factory: 'createProjectPlugin', env: moduleEnv(context.env), project: { id: plugin.project.id, root, signal, memberTimeoutMs: LOAD_TIMEOUT_MS }, host: { exec }, disposeHost: dispose, timeoutMs: LOAD_TIMEOUT_MS, }); return { worker: await started, module, version, name }; }); scope.own(async () => { const worker = await started; if (worker && !('unavailable' in worker)) await worker.terminate(); checkCleanup(); }); const { worker, module, version, name } = await opening; if ('unavailable' in worker) throw fail(worker.unavailable, 'module'); if (!worker.project) throw fail('the worker returned no iOS project metadata', 'module'); const call = memberCall(worker, fail, invoke); return { id: plugin.project.id, name, version, buildTool: worker.project.buildTool ?? module, ios: checkedIos( shippedPluginName(plugin.reference) !== null, worker.project.cacheIneligible ?? `the plugin ${plugin.package} builds this ${name} project with its own module, on this machine and with no cache`, call, fail, ), // @ref LLP 0009#plugin-builds -- a build machine builds only the plugins shipped with Stim ...(!worker.members.includes('offload.plan') ? { offload: localOnly('a plugin build does not run on a build machine') } : shippedPluginName(plugin.reference) === null ? { offload: localOnly('a build machine builds only the plugins shipped with Stim') } : { offload: moduleOffload(name, call), offloads: true as const }), }; } // @ref LLP 0023#frozen-and-experimental-plugin-kinds export async function loadPluginIos( plugin: PluginMatch, root: string, scope?: IosOperationScope, lexicalStart: string = root, ): Promise { const fail = (why: string, kind?: FailureKind) => failure(plugin, root, why, kind); if (!scope) throw fail('an iOS operation is required to run its module'); const shipped = shippedPluginName(plugin.reference); if (shipped !== null) { const expected = `${SHIPPED_PLUGIN_PACKAGE_PREFIX}${shipped}`; if (plugin.package !== expected) throw fail(`its package.json is named ${plugin.package}, not ${expected}`); } return openPluginIos(plugin, root, scope, fail, () => { const problem = moduleIosProblem(root, plugin.package, lexicalStart); if (problem) throw Object.assign(new Error(problem.message), { code: 'STIM_NO_PROJECT', projectPluginFailure: true, remedy: problem.remedy, }); const current = pluginProjectAt(root, bundledProjectIds(), { fresh: true, target: 'ios' }); const module = current?.project.module; if ( !current || current.reference !== plugin.reference || current.dir !== plugin.dir || current.package !== plugin.package || current.project.id !== plugin.project.id || module === undefined || module !== plugin.project.module ) throw fail('the iOS project selection changed; select the project again'); return { dir: current.dir, module, version: current.version, name: current.project.name }; }); } /** * The plugin shipped with this Stim build that a build machine's job loads for a request naming the iOS project type * `id` at `version`, read from its manifest only; null when this build ships none. The job runs the client's own Stim * build, so its shipped plugins are the client's, and the machine's `plugins` setting plays no part. */ function shippedIosPlugin(id: unknown, version: unknown): (PluginMatch & { version: string }) | null { // @ref LLP 0009#plugin-builds -- the job finds the plugin in its own build by project id and version for (const { project, ...entry } of readProjectPlugins(shippedPluginNames(), bundledProjectIds())) if ( project && project.id === id && !entry.problem && entry.version === version && project.targets?.ios && project.module ) return { ...entry, project }; return null; } /** * Loads, in a build machine's job, the module of the shipped plugin a request names by its project id and version. * `project` is the synced project the build runs in, which must hold the plugin's markers outside any built-in project * folder; without it the module runs in `root`, an empty folder of the machine's, to check a request and the toolchain. */ export async function loadJobPluginIos( named: { id?: unknown; version?: unknown }, root: string, scope: IosOperationScope, { project }: { project: boolean }, ): Promise { const plugin = shippedIosPlugin(named.id, named.version); if (!plugin) return { code: 'unsupported-provider', message: `This Stim build ships no iOS plugin ${String(named.id)} at version ${String(named.version)}.`, }; if (project) { const problem = holdsMarkers(root, plugin.project) ? moduleIosProblem(root, plugin.package) : { message: `The transferred project does not hold every marker of the ${plugin.project.name} plugin.` }; if (problem) return { code: 'provider-mismatch', message: problem.message }; } const fail = (why: string, kind?: FailureKind) => failure(plugin, root, why, kind); const { dir, version } = plugin; const module = plugin.project.module ?? ''; return openPluginIos(plugin, root, scope, fail, () => ({ dir, module, version, name: plugin.project.name })); } function failureFinding(title: string, error: unknown): Finding { const remedy = error instanceof Error && 'remedy' in error && isString(error.remedy) ? error.remedy : null; return { level: 'cost', title, detail: reason(error), fix: remedy }; } export function pluginIosDoctorFor(plugin: PluginMatch, root: string, lexicalStart: string): ProjectDoctor { let planned: { source: IosPluginSource; plan: Parameters[2] } | null = null; return { inspect(context) { if (context.options.platform === 'android') return []; return withIosOperationScope(context.options.operation ?? processContext(root), async (scope) => { try { const source = await loadPluginIos(plugin, root, scope, lexicalStart); const findings = await source.ios.doctor(); const { operation, remoteEnv } = context.options; try { const plan = await pluginOffloadPlan(source, root, operation?.env ?? remoteEnv ?? {}); if (!('unsupported' in plan)) planned = { source, plan }; } catch (error) { findings.push(failureFinding(`The plugin ${plugin.package} cannot plan a build machine build`, error)); } return findings; } catch (error) { return [failureFinding(`The plugin ${plugin.package} cannot load`, error)]; } }); }, // @ref LLP 0009#plugin-builds -- doctor asks build machines with the plan its inspection made offloadTargets: ({ options: { platform } }) => { const found = planned; return found && (!platform || platform === 'ios') ? async () => [await pluginOffloadTarget(root, found.source, found.plan)] : null; }, }; } type OutputAnswer = { value: T } | { missing: true } | { unloaded: string } | { failed: string }; // @ref LLP 0023#project-plugin-output-members -- a fresh worker per call, never in a built-in project folder /** * Calls the output member `member` of `plugin`'s module in a fresh worker whose host is bound to `root`, the folder * holding the output folder, with `callMs` for the call, and ends the worker after. `unloaded` when the module did not start: `root` is a built-in * project folder or cannot be read to tell, or the module did not load; `missing` when it has no such member; `failed` * when the call threw, timed out or returned the wrong shape. A host child whose cleanup is unresolved, and an abort of * `signal`, throw. */ async function callOutputMember( plugin: PluginMatch, root: string, member: 'outputUse' | 'cleanOutput', args: unknown[], valid: (value: unknown) => value is T, signal: AbortSignal | undefined, callMs: number, ): Promise> { try { const project = builtInProjectFolder(root, root); if (project) return { unloaded: `Stim recognises ${root} as ${project.type}, where it loads no plugin code` }; } catch (error) { return { unloaded: `Stim cannot tell the project type at ${root}: ${reason(error)}` }; } const found = containedModule(plugin.dir, plugin.project.module ?? ''); if ('error' in found) return { unloaded: found.error }; const hostSignal = signal ?? new AbortController().signal; const context = processContext(root, hostSignal); const { exec, invoke, dispose, checkCleanup } = execHost(root, context, hostSignal, false); let worker: KitWorker | { unavailable: string } | undefined; try { worker = await invoke(() => startKitWorker({ href: pathToFileURL(found.file).href, factory: 'createProjectPlugin', env: moduleEnv(context.env), project: { id: plugin.project.id, root, signal: hostSignal, memberTimeoutMs: callMs, outputs: true }, host: { exec }, disposeHost: dispose, timeoutMs: LOAD_TIMEOUT_MS, }), ); if ('unavailable' in worker) { signal?.throwIfAborted(); return { unloaded: `its module did not load: ${worker.unavailable}` }; } if (!worker.members.includes(member)) return { missing: true }; const opened = worker; let value: unknown; try { value = await invoke(() => opened.call(member, ...args)); } catch (error) { if (unresolvedCleanup(error)) throw error; signal?.throwIfAborted(); return { failed: `its ${member}() failed: ${reason(error)}` }; } return valid(value) ? { value } : { failed: `its ${member}() returned ${describe(value)}, which is not what it declares` }; } finally { if (worker && !('unavailable' in worker)) await worker.terminate(); checkCleanup(); } } type ModuleUse = { lastUse: Record; recent?: string } | { unknown: string }; /** An object literal or one made with `Object.create(null)`; a `Map`, `Set` or `Date` lists no entries as its own. */ const isPlainObject = (value: unknown): value is Record => { if (typeof value !== 'object' || value === null) return false; const prototype: unknown = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null; }; type ModuleClean = Exclude; const isModuleUse = (value: unknown): value is ModuleUse => isJsonObject(value) && (isString(value.unknown) || (isPlainObject(value.lastUse) && Object.values(value.lastUse).every((at) => typeof at === 'number' && Number.isFinite(at)) && (value.recent === undefined || isString(value.recent)))); const isStrings = (value: unknown): value is string[] => Array.isArray(value) && value.every(isString); const CLEAN_STATUSES: readonly unknown[] = ['ok', 'busy', 'refused', 'failed']; const isModuleClean = (value: unknown): value is ModuleClean | { unsupported: string } | { unknown: string } => isJsonObject(value) && (isString(value.unsupported) || isString(value.unknown) || (CLEAN_STATUSES.includes(value.status) && isStrings(value.remove) && isStrings(value.held) && Array.isArray(value.kept) && value.kept.every((entry) => isJsonObject(entry) && isString(entry.path) && isString(entry.why)) && (value.error === undefined || isString(value.error)))); /** * The output members of the plugin `plugin`, which `plugins` names, for the outputs its manifest declares (`outputs`). * `outputUse` loads the module only for a folder holding one of those outputs' `useRecord`; `cleanOutput`, which the * whole delete calls only for the plugin's declared output beside its project, loads it on each call. Anything that * keeps the module from answering keeps the folder. */ export function pluginOutputMembers(plugin: PluginMatch, outputs: ProjectOutputs): ProjectOutputMembers { const records = outputs.outputs.flatMap(({ useRecord }) => (useRecord === null ? [] : [useRecord])); const recent = `the plugin ${plugin.package} records a use in that time`; return { async outputUse(dir, { signal } = {}): Promise { const record = records.find((name) => lstatSync(join(dir, name), { throwIfNoEntry: false })); if (record === undefined) return { lastUse: new Map(), recent }; const kept = (why: string): OutputUse => ({ unknown: `${outputs.name}'s ${record} dates its use, and the plugin ${plugin.package} cannot read it: ${why}`, }); const answer = await callOutputMember( plugin, dirname(dir), 'outputUse', [dir], isModuleUse, signal, LOAD_TIMEOUT_MS, ); if ('missing' in answer) return kept('its module has no outputUse()'); if ('unloaded' in answer) return kept(answer.unloaded); if ('failed' in answer) return kept(answer.failed); const { value } = answer; return 'unknown' in value ? kept(value.unknown) : { lastUse: new Map(Object.entries(value.lastUse)), recent: value.recent || recent }; }, async cleanOutput(dir, { dryRun = false, signal }): Promise { const answer = await callOutputMember( plugin, dirname(dir), 'cleanOutput', [dir, { dryRun }], isModuleClean, signal, OUTPUT_CLEAN_CALL_TIMEOUT_MS, ); if ('missing' in answer) return { unsupported: `the plugin ${plugin.package}'s module has no cleanOutput()` }; if ('unloaded' in answer) return { unsupported: answer.unloaded }; if ('failed' in answer) return dryRun ? { unsupported: answer.failed } : { unknown: answer.failed }; const { value } = answer; if ('unsupported' in value) return { unsupported: value.unsupported }; if ('unknown' in value) return { unknown: value.unknown }; const { status, remove, kept, held, error } = value; return { status, remove, kept: kept.map(({ path, why }) => ({ path, why })), held, ...(error === undefined ? {} : { error }), }; }, }; }