systemd-ts 0.3.0 → 0.3.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main-BXq7TQdg.mjs","names":["ok","err","I"],"sources":["../src/main/errors.ts","../src/main/executable.ts","../src/main/internal.ts","../src/main/notify.ts","../src/main/systemd-service.ts","../src/main/systemd-timer.ts","../src/main/systemctl.ts","../src/main/systemd.ts","../src/main/index.ts"],"sourcesContent":["import type { StartStatus } from \"./types.ts\";\n\nexport type SystemdTsErrorCode =\n | `SYSTEMD_TS_INVALID_EXEC_DIRECTIVE`\n | `SYSTEMD_TS_NO_UNITS_PROVIDED`\n | `SYSTEMD_TS_EXECUTABLE_INFERENCE`\n | `SYSTEMD_TS_UNIT_MATERIALIZATION`\n | `SYSTEMD_TS_UNIT_ENABLE`\n | `SYSTEMD_TS_UNIT_START`\n | `SYSTEMD_TS_UNIT_LOGS`\n | `SYSTEMD_TS_SYSTEMCTL`\n | `SYSTEMD_TS_NOTIFY_SEND`;\n\nexport interface SystemdTsErrorOptions {\n readonly cause?: unknown;\n}\n\nexport interface SystemdCommandErrorOptions extends SystemdTsErrorOptions {\n readonly args?: readonly string[];\n readonly command?: string;\n readonly environmentReason?: SystemdCommandEnvironmentReason;\n readonly stage?: string;\n readonly unitName?: string;\n readonly unitPath?: string;\n}\n\nexport interface UnitStartDiagnostics {\n readonly showOutput?: string;\n readonly showStatus?: StartStatus;\n readonly statusOutput?: string;\n}\n\nexport interface UnitStartErrorOptions extends SystemdCommandErrorOptions {\n readonly diagnostics?: UnitStartDiagnostics;\n}\n\nexport interface UnitMaterializationErrorOptions extends SystemdTsErrorOptions {\n readonly reason?: UnitMaterializationErrorReason;\n readonly operation?: `create-directory` | `write-file`;\n readonly unitName?: string;\n readonly unitPath?: string;\n}\n\nexport type UnitMaterializationErrorReason =\n | `file-system-failed`\n | `invalid-unit-directory`\n | `permission-denied`;\n\nexport interface UnitLogsReadErrorOptions extends SystemdCommandErrorOptions {\n readonly reason?: UnitLogsReadErrorReason;\n readonly unitPath?: string;\n}\n\nexport type UnitLogsReadErrorReason =\n | `missing-log-file`\n | `log-file-read-failed`\n | `status-command-failed`;\n\nexport interface NotifySendErrorOptions extends SystemdCommandErrorOptions {\n readonly reason?: NotifySendErrorReason;\n}\n\nexport type NotifySendErrorReason = `executor-failed` | `systemd-notify-failed`;\n\nexport interface SystemctlCommandErrorOptions extends SystemdCommandErrorOptions {\n readonly operation?: string;\n readonly reason?: SystemctlCommandErrorReason;\n}\n\nexport type SystemctlCommandErrorReason = `executor-failed` | `invalid-json`;\n\nexport type SystemdCommandEnvironmentReason =\n | `manager-unavailable`\n | `missing-command`\n | `permission-denied`;\n\nexport class SystemdTsError extends Error {\n public readonly code: SystemdTsErrorCode;\n\n public constructor(\n code: SystemdTsErrorCode,\n message: string,\n options: SystemdTsErrorOptions = {},\n ) {\n super(message, { cause: options.cause });\n this.code = code;\n this.name = new.target.name;\n }\n}\n\nexport class InvalidExecDirectiveError extends SystemdTsError {\n public readonly directive: string;\n\n public constructor(directive: string, options: SystemdTsErrorOptions = {}) {\n super(\n `SYSTEMD_TS_INVALID_EXEC_DIRECTIVE`,\n `${directive} must use an absolute executable path for systemd`,\n options,\n );\n this.directive = directive;\n }\n}\n\nexport class NoUnitsProvidedError extends SystemdTsError {\n public readonly operation: string;\n\n public constructor(operation: string, options: SystemdTsErrorOptions = {}) {\n super(\n `SYSTEMD_TS_NO_UNITS_PROVIDED`,\n `${operation} requires at least one service or timer`,\n options,\n );\n this.operation = operation;\n }\n}\n\nexport class ExecutableInferenceError extends SystemdTsError {\n public constructor(options: SystemdTsErrorOptions = {}) {\n super(\n `SYSTEMD_TS_EXECUTABLE_INFERENCE`,\n `Could not infer the calling module path for defineExecutable(); pass { modulePath } explicitly`,\n options,\n );\n }\n}\n\nexport class UnitMaterializationError extends SystemdTsError {\n public readonly operation: `create-directory` | `write-file` | undefined;\n public readonly reason: UnitMaterializationErrorReason | undefined;\n public readonly unitName: string | undefined;\n public readonly unitPath: string | undefined;\n\n public constructor(message: string, options: UnitMaterializationErrorOptions = {}) {\n super(`SYSTEMD_TS_UNIT_MATERIALIZATION`, message, options);\n this.operation = options.operation;\n this.reason = options.reason;\n this.unitName = options.unitName;\n this.unitPath = options.unitPath;\n }\n}\n\nexport class UnitEnableError extends SystemdTsError {\n public readonly args: readonly string[] | undefined;\n public readonly command: string | undefined;\n public readonly environmentReason: SystemdCommandEnvironmentReason | undefined;\n public readonly exitCode: number | undefined;\n public readonly stage: string | undefined;\n public readonly stderr: string | undefined;\n public readonly stdout: string | undefined;\n public readonly unitName: string | undefined;\n public readonly unitPath: string | undefined;\n\n public constructor(message: string, options: SystemdCommandErrorOptions = {}) {\n super(`SYSTEMD_TS_UNIT_ENABLE`, message, options);\n const details = extractCommandErrorDetails(options.cause);\n this.args = options.args;\n this.command = options.command;\n this.environmentReason =\n options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);\n this.exitCode = details.exitCode;\n this.stage = options.stage;\n this.stderr = details.stderr;\n this.stdout = details.stdout;\n this.unitName = options.unitName;\n this.unitPath = options.unitPath;\n }\n}\n\nexport class UnitStartError extends SystemdTsError {\n public readonly args: readonly string[] | undefined;\n public readonly command: string | undefined;\n public readonly diagnostics: UnitStartDiagnostics | undefined;\n public readonly environmentReason: SystemdCommandEnvironmentReason | undefined;\n public readonly exitCode: number | undefined;\n public readonly stage: string | undefined;\n public readonly stderr: string | undefined;\n public readonly stdout: string | undefined;\n public readonly unitName: string | undefined;\n public readonly unitPath: string | undefined;\n\n public constructor(message: string, options: UnitStartErrorOptions = {}) {\n super(`SYSTEMD_TS_UNIT_START`, message, options);\n const details = extractCommandErrorDetails(options.cause);\n this.args = options.args;\n this.command = options.command;\n this.diagnostics = options.diagnostics;\n this.environmentReason =\n options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);\n this.exitCode = details.exitCode;\n this.stage = options.stage;\n this.stderr = details.stderr;\n this.stdout = details.stdout;\n this.unitName = options.unitName;\n this.unitPath = options.unitPath;\n }\n}\n\nexport class UnitLogsReadError extends SystemdTsError {\n public readonly args: readonly string[] | undefined;\n public readonly command: string | undefined;\n public readonly environmentReason: SystemdCommandEnvironmentReason | undefined;\n public readonly exitCode: number | undefined;\n public readonly reason: UnitLogsReadErrorReason | undefined;\n public readonly stage: string | undefined;\n public readonly stderr: string | undefined;\n public readonly stdout: string | undefined;\n public readonly unitName: string | undefined;\n public readonly unitPath: string | undefined;\n\n public constructor(message: string, options: UnitLogsReadErrorOptions = {}) {\n super(`SYSTEMD_TS_UNIT_LOGS`, message, options);\n const details = extractCommandErrorDetails(options.cause);\n this.args = options.args;\n this.command = options.command;\n this.environmentReason =\n options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);\n this.exitCode = details.exitCode;\n this.reason = options.reason;\n this.stage = options.stage;\n this.stderr = details.stderr;\n this.stdout = details.stdout;\n this.unitName = options.unitName;\n this.unitPath = options.unitPath;\n }\n}\n\nexport class NotifySendError extends SystemdTsError {\n public readonly args: readonly string[] | undefined;\n public readonly command: string | undefined;\n public readonly environmentReason: SystemdCommandEnvironmentReason | undefined;\n public readonly exitCode: number | undefined;\n public readonly reason: NotifySendErrorReason | undefined;\n public readonly stage: string | undefined;\n public readonly stderr: string | undefined;\n public readonly stdout: string | undefined;\n\n public constructor(message: string, options: NotifySendErrorOptions = {}) {\n super(`SYSTEMD_TS_NOTIFY_SEND`, message, options);\n const details = extractCommandErrorDetails(options.cause);\n this.args = options.args;\n this.command = options.command;\n this.environmentReason =\n options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);\n this.exitCode = details.exitCode;\n this.reason = options.reason;\n this.stage = options.stage;\n this.stderr = details.stderr;\n this.stdout = details.stdout;\n }\n}\n\nexport class SystemctlCommandError extends SystemdTsError {\n public readonly args: readonly string[] | undefined;\n public readonly command: string | undefined;\n public readonly environmentReason: SystemdCommandEnvironmentReason | undefined;\n public readonly exitCode: number | undefined;\n public readonly operation: string | undefined;\n public readonly reason: SystemctlCommandErrorReason | undefined;\n public readonly stage: string | undefined;\n public readonly stderr: string | undefined;\n public readonly stdout: string | undefined;\n\n public constructor(message: string, options: SystemctlCommandErrorOptions = {}) {\n super(`SYSTEMD_TS_SYSTEMCTL`, message, options);\n const details = extractCommandErrorDetails(options.cause);\n this.args = options.args;\n this.command = options.command;\n this.environmentReason =\n options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);\n this.exitCode = details.exitCode;\n this.operation = options.operation;\n this.reason = options.reason;\n this.stage = options.stage;\n this.stderr = details.stderr;\n this.stdout = details.stdout;\n }\n}\n\nexport function classifyCommandEnvironmentReason(\n cause: unknown,\n): SystemdCommandEnvironmentReason | undefined {\n if (cause === null || typeof cause !== `object`) {\n return undefined;\n }\n\n const record = cause as Record<string, unknown>;\n if (record[`code`] === `ENOENT`) {\n return `missing-command`;\n }\n\n if (record[`code`] === `EACCES` || record[`code`] === `EPERM`) {\n return `permission-denied`;\n }\n\n const combinedOutput = [record[`stderr`], record[`stdout`]]\n .filter((value): value is string => typeof value === `string` && value.length > 0)\n .join(`\\n`);\n\n if (\n combinedOutput.includes(`Failed to connect to bus`) ||\n combinedOutput.includes(`System has not been booted with systemd`) ||\n combinedOutput.includes(`Failed to get D-Bus connection`)\n ) {\n return `manager-unavailable`;\n }\n\n return undefined;\n}\n\nexport function classifyMaterializationReason(\n cause: unknown,\n): UnitMaterializationErrorReason | undefined {\n if (cause === null || typeof cause !== `object`) {\n return undefined;\n }\n\n const record = cause as Record<string, unknown>;\n if (record[`code`] === `EACCES` || record[`code`] === `EPERM` || record[`code`] === `EROFS`) {\n return `permission-denied`;\n }\n\n if (record[`code`] === `EEXIST` || record[`code`] === `ENOTDIR` || record[`code`] === `EISDIR`) {\n return `invalid-unit-directory`;\n }\n\n return `file-system-failed`;\n}\n\nfunction extractCommandErrorDetails(cause: unknown): {\n readonly exitCode: number | undefined;\n readonly stderr: string | undefined;\n readonly stdout: string | undefined;\n} {\n if (cause === null || typeof cause !== `object`) {\n return {\n exitCode: undefined,\n stderr: undefined,\n stdout: undefined,\n };\n }\n\n const record = cause as Record<string, unknown>;\n return {\n exitCode: typeof record[`code`] === `number` ? record[`code`] : undefined,\n stderr: typeof record[`stderr`] === `string` ? record[`stderr`] : undefined,\n stdout: typeof record[`stdout`] === `string` ? record[`stdout`] : undefined,\n };\n}\n","import { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { ExecutableInferenceError } from \"./errors.ts\";\nimport type { Result } from \"./internal.ts\";\nimport type { ExecutableOptions } from \"./types.ts\";\n\nconst currentModulePath = fileURLToPath(import.meta.url);\n\n/**\n * An immutable description of a runnable module entrypoint that can be used in\n * executable-valued systemd unit directives.\n *\n * `Executable` captures three pieces of information:\n * - the absolute runtime binary that should launch the module\n * - the absolute path to the module itself\n * - any additional arguments that should be passed after the module path\n *\n * Most consumers will create one via {@link defineExecutable} and then pass it\n * into a {@link SystemdService} directive such as `ExecStart`, `ExecStop`, or\n * `ExecReload`.\n */\nexport class Executable {\n /** Additional arguments passed after the module path. */\n public readonly args: readonly string[];\n /** Inference issue captured when no explicit module path was provided. */\n public readonly inferenceError: ExecutableInferenceError | undefined;\n /** Absolute path to the module that should be executed. */\n public readonly modulePath: string;\n /** Absolute path to the runtime binary that should launch the module. */\n public readonly runtimeEntrypoint: string;\n\n /**\n * Creates an executable description.\n *\n * When `modulePath` is omitted, the calling module is inferred from the\n * current stack so `defineExecutable()` can be used inline from the module\n * that should become runnable.\n *\n * When `runtimeEntrypoint` is omitted, the current process executable is\n * used. This works well for the common case where the same runtime that is\n * evaluating your module should also be used by systemd.\n */\n public constructor(options: ExecutableOptions = {}) {\n this.runtimeEntrypoint = options.runtimeEntrypoint ?? process.execPath;\n const inferredModulePath = options.modulePath ?? tryInferCallerModulePath();\n this.inferenceError =\n inferredModulePath === undefined && options.modulePath === undefined\n ? new ExecutableInferenceError()\n : undefined;\n this.modulePath = inferredModulePath ?? ``;\n this.args = Object.freeze([...(options.args ?? [])]);\n Object.freeze(this);\n }\n\n /**\n * Returns the executable as raw command parts.\n *\n * The first element is always the runtime entrypoint, followed by the module\n * path and any configured arguments.\n */\n public toCommandParts(): Result<readonly [string, ...string[]], ExecutableInferenceError> {\n if (this.inferenceError !== undefined) {\n return {\n ok: false,\n error: this.inferenceError,\n };\n }\n\n return {\n ok: true,\n value: [this.runtimeEntrypoint, this.modulePath, ...this.args],\n };\n }\n\n /**\n * Renders the executable as a shell-quoted command string suitable for\n * executable-valued systemd directives such as `ExecStart=`.\n */\n public toExecStart(): Result<string, ExecutableInferenceError> {\n const commandParts = this.toCommandParts();\n if (!commandParts.ok) {\n return commandParts;\n }\n\n return {\n ok: true,\n value: commandParts.value.map(shellQuote).join(` `),\n };\n }\n}\n\n/**\n * Defines a module as a runnable executable and returns its immutable\n * `Executable` description.\n *\n * This helper is designed for the pattern:\n *\n * ```ts\n * export default defineExecutable(async () => {\n * // do work here\n * });\n * ```\n *\n * When the defining module is executed as the main entrypoint, `fn` is invoked.\n * When the module is merely imported, `fn` is not run and only the executable\n * description is returned.\n *\n * Pass `options.runtimeEntrypoint` to override the default runtime binary when\n * the current process is not the exact runtime you want systemd to use.\n */\nexport function defineExecutable(\n fn: () => void | Promise<void>,\n options: ExecutableOptions = {},\n): Executable {\n const executable = new Executable(options);\n\n if (executable.inferenceError === undefined && isMainModule(executable.modulePath)) {\n void Promise.resolve(fn()).catch((error: unknown) => {\n process.exitCode = 1;\n throw error;\n });\n }\n\n return executable;\n}\n\nfunction tryInferCallerModulePath(): string | undefined {\n const stack = new Error().stack ?? ``;\n for (const line of stack.split(`\\n`).slice(1)) {\n const candidate = extractStackPath(line);\n if (candidate === undefined || candidate === currentModulePath) {\n continue;\n }\n\n return candidate;\n }\n\n return undefined;\n}\n\nfunction extractStackPath(line: string): string | undefined {\n const fileUrlMatch = line.match(/(file:\\/\\/\\/[^)\\s:]+(?:\\.[cm]?[jt]s)?)/u);\n if (fileUrlMatch !== null) {\n return fileURLToPath(fileUrlMatch[1]);\n }\n\n const pathMatch = line.match(/(\\/[^)\\s:]+(?:\\.[cm]?[jt]s)?)/u);\n if (pathMatch !== null) {\n return pathMatch[1];\n }\n\n return undefined;\n}\n\nfunction isMainModule(modulePath: string): boolean {\n const mainArg = process.argv[1];\n if (mainArg === undefined) {\n return false;\n }\n\n return normalizeFilePath(mainArg) === normalizeFilePath(modulePath);\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(`'`, `'\\\\''`)}'`;\n}\n\nfunction normalizeFilePath(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n","import { execFile } from \"node:child_process\";\nimport { access } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\n\nimport { ExecutableInferenceError, InvalidExecDirectiveError, NotifySendError } from \"./errors.ts\";\nimport { Executable } from \"./executable.ts\";\nimport type {\n CommandExecutionOptions,\n CommandOutput,\n NotifyOptions,\n SystemdServiceSection,\n StartStatus,\n SystemdServiceOptions,\n SystemdTimerOptions,\n UnitValue,\n} from \"./types.ts\";\n\nexport type Result<TValue, TError> =\n | {\n readonly ok: true;\n readonly value: TValue;\n }\n | {\n readonly ok: false;\n readonly error: TError;\n };\n\ntype ExecDirectiveKey = (typeof EXEC_DIRECTIVE_KEYS)[number];\n\nconst EXEC_DIRECTIVE_KEYS = [\n `ExecCondition`,\n `ExecReload`,\n `ExecReloadPost`,\n `ExecStart`,\n `ExecStartPost`,\n `ExecStartPre`,\n `ExecStop`,\n `ExecStopPost`,\n] as const;\nconst execFileAsync = promisify(execFile);\ntype SectionLike = object;\n\nexport function normalizeUnitName(name: string, suffix: `.service` | `.timer`): string {\n return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;\n}\n\nexport function resolveTimerTargetUnit(options: SystemdTimerOptions): string {\n const explicitTarget = options.timer[`Unit`];\n if (typeof explicitTarget === `string` && explicitTarget.length > 0) {\n return explicitTarget;\n }\n\n return `${normalizeUnitName(options.name, `.timer`)}.service`;\n}\n\nexport function defaultUnitDirForScope(scope: `system` | `user`): string {\n if (scope === `user`) {\n return `${process.env[`HOME`] ?? `~`}/.config/systemd/user`;\n }\n\n return `/etc/systemd/system`;\n}\n\nexport function freezeUnitOptions<TOptions extends SystemdServiceOptions | SystemdTimerOptions>(\n options: TOptions,\n): Readonly<TOptions> {\n return Object.freeze({\n ...options,\n ...(options.unit === undefined ? {} : { unit: cloneUnitSection(options.unit) }),\n ...(options.install === undefined ? {} : { install: cloneUnitSection(options.install) }),\n ...(hasServiceSection(options) ? { service: cloneUnitSection(options.service) } : {}),\n ...(hasTimerSection(options) ? { timer: cloneUnitSection(options.timer) } : {}),\n }) as Readonly<TOptions>;\n}\n\nexport function cloneUnitSection<TSection extends SectionLike | undefined>(\n section: TSection,\n): TSection {\n if (section === undefined) {\n return section;\n }\n\n const entries = Object.entries(section).map(([key, value]) => {\n if (isUnitValueList(value)) {\n return [key, Object.freeze([...value])] as const;\n }\n\n return [key, value] as const;\n });\n\n return Object.freeze(Object.fromEntries(entries)) as TSection;\n}\n\nexport function validateServiceSection(\n service: SystemdServiceSection,\n): Result<void, InvalidExecDirectiveError> {\n for (const key of EXEC_DIRECTIVE_KEYS) {\n const validation = assertAbsoluteExecValue(key, service[key]);\n if (!validation.ok) {\n return validation;\n }\n }\n\n return {\n ok: true,\n value: undefined,\n };\n}\n\nexport function parseStartStatus(unit: string, output: string): StartStatus {\n const properties = Object.fromEntries(\n output\n .split(`\\n`)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => {\n const separatorIndex = line.indexOf(`=`);\n if (separatorIndex === -1) {\n return [line, ``] as const;\n }\n\n return [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)] as const;\n }),\n );\n\n return {\n activeState: properties[`ActiveState`] ?? `unknown`,\n execMainStatus:\n properties[`ExecMainStatus`] === undefined || properties[`ExecMainStatus`] === ``\n ? undefined\n : Number(properties[`ExecMainStatus`]),\n result: properties[`Result`] ?? `unknown`,\n subState: properties[`SubState`] ?? `unknown`,\n unit: properties[`Id`] ?? unit,\n };\n}\n\nexport function renderUnitFile(\n sections: ReadonlyArray<readonly [string, SectionLike | undefined]>,\n): Result<string, ExecutableInferenceError> {\n try {\n const renderedSections = sections\n .flatMap(([sectionName, section]) => {\n if (section === undefined) {\n return [];\n }\n\n const lines: string[] = [];\n for (const [key, value] of Object.entries(section as Record<string, unknown>)) {\n if (value === undefined) {\n continue;\n }\n\n if (isUnitValueList(value)) {\n for (const entry of value) {\n const rendered = stringifyUnitValue(entry);\n if (!rendered.ok) {\n throw rendered.error;\n }\n lines.push(`${key}=${rendered.value}`);\n }\n continue;\n }\n\n const rendered = stringifyUnitValue(value as UnitValue);\n if (!rendered.ok) {\n throw rendered.error;\n }\n lines.push(`${key}=${rendered.value}`);\n }\n\n if (lines.length === 0) {\n return [];\n }\n\n return [`[${sectionName}]`, ...lines, ``];\n })\n .join(`\\n`);\n\n return {\n ok: true,\n value: renderedSections.endsWith(`\\n`) ? renderedSections : `${renderedSections}\\n`,\n };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof ExecutableInferenceError\n ? error\n : new ExecutableInferenceError({ cause: error }),\n };\n }\n}\n\nexport async function defaultCommandExecutor(\n command: string,\n args: readonly string[],\n options: CommandExecutionOptions = {},\n): Promise<CommandOutput> {\n const result = await execFileAsync(\n command,\n [...args],\n options.env === undefined ? {} : { env: { ...process.env, ...options.env } },\n );\n return {\n stderr: result.stderr,\n stdout: result.stdout,\n };\n}\n\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function sendNotify(\n state: `READY=1` | `WATCHDOG=1`,\n options: NotifyOptions,\n): Promise<void> {\n const args: string[] = [`--no-block`, state];\n if (options.pid !== undefined) {\n args.push(`MAINPID=${options.pid}`);\n }\n if (options.status !== undefined) {\n args.push(`STATUS=${options.status}`);\n }\n\n if (options.executor !== undefined) {\n try {\n await options.executor(\n `systemd-notify`,\n args,\n options.socketPath === undefined ? {} : { env: { NOTIFY_SOCKET: options.socketPath } },\n );\n } catch (cause) {\n throw new NotifySendError(\n `Failed to send systemd notification through the configured executor`,\n {\n args,\n cause,\n command: `systemd-notify`,\n reason: `executor-failed`,\n stage: `executor`,\n },\n );\n }\n return;\n }\n\n try {\n const result = await execFileAsync(`systemd-notify`, args, {\n env: {\n ...process.env,\n ...(options.socketPath === undefined ? {} : { NOTIFY_SOCKET: options.socketPath }),\n },\n });\n\n void result;\n } catch (cause) {\n throw new NotifySendError(`Failed to send systemd notification with systemd-notify`, {\n args,\n cause,\n command: `systemd-notify`,\n reason: `systemd-notify-failed`,\n stage: `systemd-notify`,\n });\n }\n}\n\nexport function extractCommandOutput(cause: unknown): CommandOutput | undefined {\n if (cause === null || typeof cause !== `object`) {\n return undefined;\n }\n\n const record = cause as Record<string, unknown>;\n const stdout = typeof record[`stdout`] === `string` ? record[`stdout`] : undefined;\n const stderr = typeof record[`stderr`] === `string` ? record[`stderr`] : undefined;\n if (stdout === undefined && stderr === undefined) {\n return undefined;\n }\n\n return {\n stderr: stderr ?? ``,\n stdout: stdout ?? ``,\n };\n}\n\nfunction hasServiceSection(\n options: SystemdServiceOptions | SystemdTimerOptions,\n): options is SystemdServiceOptions {\n return `service` in options;\n}\n\nfunction hasTimerSection(\n options: SystemdServiceOptions | SystemdTimerOptions,\n): options is SystemdTimerOptions {\n return `timer` in options;\n}\n\nfunction assertAbsoluteExecValue(\n key: ExecDirectiveKey,\n value: unknown,\n): Result<void, InvalidExecDirectiveError> {\n if (isUnitValueList(value)) {\n for (const entry of value) {\n const validation = assertAbsoluteExecEntry(key, entry);\n if (!validation.ok) {\n return validation;\n }\n }\n\n return {\n ok: true,\n value: undefined,\n };\n }\n\n return assertAbsoluteExecEntry(key, value as UnitValue | undefined);\n}\n\nfunction assertAbsoluteExecEntry(\n key: ExecDirectiveKey,\n value: UnitValue | undefined,\n): Result<void, InvalidExecDirectiveError> {\n if (typeof value === `string` && value.length > 0 && !isAbsoluteExecCommand(value)) {\n return {\n ok: false,\n error: new InvalidExecDirectiveError(key),\n };\n }\n\n if (value instanceof Executable && !value.runtimeEntrypoint.startsWith(`/`)) {\n return {\n ok: false,\n error: new InvalidExecDirectiveError(key),\n };\n }\n\n return {\n ok: true,\n value: undefined,\n };\n}\n\nfunction stringifyUnitValue(value: UnitValue): Result<string, ExecutableInferenceError> {\n if (value instanceof Executable) {\n return value.toExecStart();\n }\n\n if (typeof value === `boolean`) {\n return {\n ok: true,\n value: value ? `true` : `false`,\n };\n }\n\n return {\n ok: true,\n value: String(value),\n };\n}\n\nfunction isUnitValueList(value: unknown): value is readonly UnitValue[] {\n return Array.isArray(value);\n}\n\nfunction isAbsoluteExecCommand(value: string): boolean {\n let index = 0;\n let hasPrivilegePrefix = false;\n\n while (index < value.length) {\n const prefix = value[index];\n if (prefix === `@` || prefix === `-` || prefix === `:`) {\n index += 1;\n continue;\n }\n\n if (prefix === `+`) {\n if (hasPrivilegePrefix) {\n return false;\n }\n\n hasPrivilegePrefix = true;\n index += 1;\n continue;\n }\n\n if (prefix === `!`) {\n if (hasPrivilegePrefix) {\n return false;\n }\n\n hasPrivilegePrefix = true;\n index += value[index + 1] === `!` ? 2 : 1;\n continue;\n }\n\n break;\n }\n\n return value[index] === `/`;\n}\n","import { NotifySendError } from \"./errors.ts\";\nimport { sendNotify, type Result } from \"./internal.ts\";\nimport type { NotifyOptions } from \"./types.ts\";\n\n/**\n * Helpers for sending `sd_notify` state updates to systemd.\n *\n * These helpers send notification payloads to the socket identified by\n * `NOTIFY_SOCKET`, or to `options.socketPath` when one is provided explicitly.\n * They are useful both in real services and in tests that want to observe\n * readiness or watchdog traffic directly.\n *\n * Source:\n * - https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html\n * - https://www.freedesktop.org/software/systemd/man/latest/systemd-notify.html\n */\nexport const notify = {\n /**\n * Sends `READY=1` to systemd.\n *\n * Use this when a `Type=notify` service has completed its startup work and is\n * ready to be considered fully started. If `options.status` is provided, it is\n * sent as an additional `STATUS=...` field.\n */\n async ready(options: NotifyOptions = {}): Promise<Result<void, NotifySendError>> {\n try {\n await sendNotify(`READY=1`, options);\n return { ok: true, value: undefined };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof NotifySendError\n ? error\n : new NotifySendError(`Failed to send READY=1 notification`, {\n cause: error,\n stage: `ready`,\n }),\n };\n }\n },\n\n /**\n * Sends `WATCHDOG=1` to systemd.\n *\n * Use this when a service configured with `WatchdogSec=` needs to emit a\n * watchdog heartbeat. If `options.pid` is provided, it is sent as\n * `MAINPID=...`, and `options.status` is forwarded as `STATUS=...`.\n */\n async watchdog(options: NotifyOptions = {}): Promise<Result<void, NotifySendError>> {\n try {\n await sendNotify(`WATCHDOG=1`, options);\n return { ok: true, value: undefined };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof NotifySendError\n ? error\n : new NotifySendError(`Failed to send WATCHDOG=1 notification`, {\n cause: error,\n stage: `watchdog`,\n }),\n };\n }\n },\n};\n","import {\n cloneUnitSection,\n freezeUnitOptions,\n normalizeUnitName,\n renderUnitFile,\n validateServiceSection,\n} from \"./internal.ts\";\nimport type { ExecutableInferenceError, InvalidExecDirectiveError } from \"./errors.ts\";\nimport type { Result } from \"./internal.ts\";\nimport type {\n ExactSystemdServiceOptions,\n ServiceBaseName,\n ServiceFilename,\n SystemdServiceOptions,\n} from \"./types.ts\";\n\n/**\n * An immutable definition of a `.service` unit.\n *\n * `SystemdService` is a pure value object: it captures the intended unit name\n * and section contents, but it does not write files or talk to `systemd`\n * directly. Operational actions such as installation or startup belong on\n * {@link Systemd}.\n *\n * Source:\n * - https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html\n */\nexport class SystemdService<const TOptions extends SystemdServiceOptions = SystemdServiceOptions> {\n /** Optional `[Install]` section for enable-time relationships. */\n public readonly install: TOptions[`install`] | undefined;\n /** The normalized base unit name, without the `.service` suffix. */\n public readonly name: ServiceBaseName<TOptions[`name`]>;\n /** The fully frozen original options used to construct this service. */\n public readonly options: Readonly<TOptions>;\n /** The `[Service]` section payload. */\n public readonly service: TOptions[`service`];\n /** Optional `[Unit]` section metadata and dependency configuration. */\n public readonly unit: TOptions[`unit`] | undefined;\n\n /**\n * Creates an immutable service definition.\n *\n * The constructor preserves literal types where possible and rejects unknown\n * directive names within the provided sections, while still allowing custom\n * `X-...` extension directives.\n */\n public constructor(options: TOptions & ExactSystemdServiceOptions<TOptions>) {\n this.options = freezeUnitOptions(options as unknown as TOptions);\n this.name = normalizeUnitName(options.name, `.service`) as ServiceBaseName<TOptions[`name`]>;\n this.unit = cloneUnitSection(options.unit) as TOptions[`unit`] | undefined;\n this.service = (cloneUnitSection(options.service) ?? {}) as TOptions[`service`];\n this.install = cloneUnitSection(options.install) as TOptions[`install`] | undefined;\n Object.freeze(this);\n }\n\n /** The canonical unit filename, including the `.service` suffix. */\n public get filename(): ServiceFilename<TOptions[`name`]> {\n return `${this.name}.service` as ServiceFilename<TOptions[`name`]>;\n }\n\n /**\n * Renders the service as a complete unit file.\n *\n * Rendering also validates executable-valued directives such as `ExecStart`\n * and `ExecStop`, ensuring they use absolute runtime entrypoints as required\n * by systemd.\n */\n public render(): Result<string, ExecutableInferenceError | InvalidExecDirectiveError> {\n const validation = validateServiceSection(this.service);\n if (!validation.ok) {\n return validation;\n }\n\n return renderUnitFile([\n [`Unit`, this.unit],\n [`Service`, this.service],\n [`Install`, this.install],\n ]);\n }\n}\n","import {\n cloneUnitSection,\n freezeUnitOptions,\n normalizeUnitName,\n renderUnitFile,\n resolveTimerTargetUnit,\n} from \"./internal.ts\";\nimport type { ExecutableInferenceError } from \"./errors.ts\";\nimport type { Result } from \"./internal.ts\";\nimport type {\n ExactSystemdTimerOptions,\n SystemdTimerOptions,\n TimerBaseName,\n TimerFilename,\n TimerTargetServiceName,\n TimerTargetUnit,\n} from \"./types.ts\";\n\n/**\n * An immutable definition of a `.timer` unit.\n *\n * Like {@link SystemdService}, this is a pure value object. It models the timer\n * configuration and its attachment target, but does not write files or interact\n * with the service manager directly.\n *\n * Source:\n * - https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html\n */\nexport class SystemdTimer<const TOptions extends SystemdTimerOptions = SystemdTimerOptions> {\n /** Optional `[Install]` section for enable-time relationships. */\n public readonly install: TOptions[`install`] | undefined;\n /** The normalized base unit name, without the `.timer` suffix. */\n public readonly name: TimerBaseName<TOptions[`name`]>;\n /** The fully frozen original options used to construct this timer. */\n public readonly options: Readonly<TOptions>;\n /** The attached service basename inferred from `targetUnit`. */\n public readonly targetServiceName: TimerTargetServiceName<TOptions>;\n /** The unit name this timer activates, explicit or implicit. */\n public readonly targetUnit: TimerTargetUnit<TOptions>;\n /** The `[Timer]` section payload. */\n public readonly timer: TOptions[`timer`];\n /** Optional `[Unit]` section metadata and dependency configuration. */\n public readonly unit: TOptions[`unit`] | undefined;\n\n /**\n * Creates an immutable timer definition.\n *\n * If no explicit `timer.Unit` is provided, the target defaults to the service\n * with the same basename, matching systemd's native timer behavior.\n */\n public constructor(options: TOptions & ExactSystemdTimerOptions<TOptions>) {\n this.options = freezeUnitOptions(options as unknown as TOptions);\n this.name = normalizeUnitName(options.name, `.timer`) as TimerBaseName<TOptions[`name`]>;\n this.unit = cloneUnitSection(options.unit) as TOptions[`unit`] | undefined;\n this.timer = (cloneUnitSection(options.timer) ?? {}) as TOptions[`timer`];\n this.install = cloneUnitSection(options.install) as TOptions[`install`] | undefined;\n this.targetUnit = resolveTimerTargetUnit(\n options as unknown as TOptions,\n ) as TimerTargetUnit<TOptions>;\n this.targetServiceName = normalizeUnitName(\n this.targetUnit,\n `.service`,\n ) as TimerTargetServiceName<TOptions>;\n Object.freeze(this);\n }\n\n /** The canonical unit filename, including the `.timer` suffix. */\n public get filename(): TimerFilename<TOptions[`name`]> {\n return `${this.name}.timer` as TimerFilename<TOptions[`name`]>;\n }\n\n /** Renders the timer as a complete unit file. */\n public render(): Result<string, ExecutableInferenceError> {\n return renderUnitFile([\n [`Unit`, this.unit],\n [`Timer`, this.timer],\n [`Install`, this.install],\n ]);\n }\n}\n","import { defaultCommandExecutor, parseStartStatus } from \"./internal.ts\";\nimport { SystemctlCommandError } from \"./errors.ts\";\nimport type { Result } from \"./internal.ts\";\nimport type {\n SystemctlActiveState,\n CommandExecutor,\n CommandOutput,\n StartStatus,\n SystemctlEnablementState,\n SystemctlIsEnabledOptions,\n SystemctlIsSystemRunningOptions,\n SystemctlListTimersOptions,\n SystemctlOptions,\n SystemctlServiceStatus,\n SystemctlStateQueryOptions,\n SystemctlShowOptions,\n SystemctlStatusOptions,\n SystemctlSystemRunningState,\n SystemctlTimerListEntry,\n} from \"./types.ts\";\n\n/**\n * A TypeScript-first client for invoking `systemctl` with structured argument\n * vectors instead of shell-composed command strings.\n *\n * This lower-level primitive is useful both on its own and as the subprocess\n * transport underneath higher-level abstractions such as {@link Systemd}.\n */\nexport class Systemctl {\n /** Command executor used for `systemctl` subprocesses. */\n public readonly executor: CommandExecutor;\n /** The target manager scope, either `system` or `user`. */\n public readonly scope: `system` | `user`;\n\n public constructor(options: SystemctlOptions = {}) {\n this.scope = options.scope ?? `system`;\n this.executor = options.executor ?? defaultCommandExecutor;\n Object.freeze(this);\n }\n\n /** Reloads the targeted systemd manager. */\n public async daemonReload(): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`daemon-reload`);\n }\n\n /** Enables a unit by filename. */\n public async enable(unit: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`enable`, unit);\n }\n\n /** Disables a unit by filename. */\n public async disable(unit: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`disable`, unit);\n }\n\n /** Links a unit file path into the targeted manager. */\n public async link(path: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`link`, path);\n }\n\n /**\n * Checks the install-time enablement state of a unit file.\n *\n * Source:\n * - systemd v260.1, `systemctl(1)`\n */\n public async isEnabled(\n unit: string,\n options: SystemctlIsEnabledOptions = {},\n ): Promise<Result<SystemctlEnablementState, SystemctlCommandError>> {\n const output = await this.run(\n `is-enabled`,\n ...(options.full ? [`--full`] : []),\n ...(options.quiet ? [`--quiet`] : []),\n unit,\n );\n if (!output.ok) {\n return output;\n }\n return ok(firstNonEmptyOutputLine(output.value) as SystemctlEnablementState);\n }\n\n /**\n * Checks the runtime active state of a unit.\n *\n * Unless `quiet` is set, this returns the state string printed by\n * `systemctl is-active`.\n */\n public async isActive(\n unit: string,\n options: SystemctlStateQueryOptions = {},\n ): Promise<Result<SystemctlActiveState, SystemctlCommandError>> {\n const output = await this.run(`is-active`, ...(options.quiet ? [`--quiet`] : []), unit);\n if (!output.ok) {\n return output;\n }\n return ok(firstNonEmptyOutputLine(output.value) as SystemctlActiveState);\n }\n\n /**\n * Checks whether a unit is in the failed state.\n *\n * Unless `quiet` is set, this returns the state string printed by\n * `systemctl is-failed`.\n */\n public async isFailed(\n unit: string,\n options: SystemctlStateQueryOptions = {},\n ): Promise<Result<SystemctlActiveState, SystemctlCommandError>> {\n const output = await this.run(`is-failed`, ...(options.quiet ? [`--quiet`] : []), unit);\n if (!output.ok) {\n return output;\n }\n return ok(firstNonEmptyOutputLine(output.value) as SystemctlActiveState);\n }\n\n /**\n * Queries the overall manager state reported by `systemctl is-system-running`.\n *\n * Source:\n * - systemd v260.1, `systemctl(1)`\n */\n public async isSystemRunning(\n options: SystemctlIsSystemRunningOptions = {},\n ): Promise<Result<SystemctlSystemRunningState, SystemctlCommandError>> {\n const output = await this.run(`is-system-running`, ...(options.wait ? [`--wait`] : []));\n if (!output.ok) {\n return output;\n }\n return ok(firstNonEmptyOutputLine(output.value) as SystemctlSystemRunningState);\n }\n\n /**\n * Queries `systemctl show` for a unit.\n *\n * When `properties` are provided, only those properties are requested.\n */\n public async show(\n unit: string,\n options: SystemctlShowOptions = {},\n ): Promise<Result<CommandOutput, SystemctlCommandError>> {\n const propertyFlag =\n options.properties === undefined || options.properties.length === 0\n ? []\n : [`--property=${options.properties.join(`,`)}`];\n return this.run(`show`, unit, ...propertyFlag);\n }\n\n /**\n * Queries `systemctl show` and parses the result into a key-value object.\n *\n * Properties are returned exactly as printed by `systemctl show`.\n */\n public async showProperties(\n unit: string,\n options: SystemctlShowOptions = {},\n ): Promise<Result<Readonly<Record<string, string>>, SystemctlCommandError>> {\n const output = await this.show(unit, options);\n if (!output.ok) {\n return output;\n }\n return ok(parseSystemctlShowOutput(output.value.stdout));\n }\n\n /**\n * Queries the standard status-related `show` properties for a unit and\n * returns a parsed snapshot.\n */\n public async showStatus(unit: string): Promise<Result<StartStatus, SystemctlCommandError>> {\n return this.showServiceStatus(unit);\n }\n\n /**\n * Queries the standard service-status `show` properties for a service unit\n * and returns a parsed snapshot.\n */\n public async showServiceStatus(\n unit: string,\n ): Promise<Result<SystemctlServiceStatus, SystemctlCommandError>> {\n const output = await this.show(unit, {\n properties: [`Id`, `ActiveState`, `SubState`, `Result`, `ExecMainStatus`],\n });\n if (!output.ok) {\n return output;\n }\n return ok(parseStartStatus(unit, output.value.stdout));\n }\n\n /**\n * Queries `systemctl list-timers` and returns the observed JSON payload\n * shape directly, with raw integer timestamps left intact.\n */\n public async listTimers(\n options: SystemctlListTimersOptions = {},\n ): Promise<Result<readonly SystemctlTimerListEntry[], SystemctlCommandError>> {\n const args = [\n `list-timers`,\n ...(options.all ? [`--all`] : []),\n ...((options.noPager ?? true) ? [`--no-pager`] : []),\n `--output=json`,\n ...(options.patterns ?? []),\n ] as const;\n const output = await this.run(...args);\n if (!output.ok) {\n return output;\n }\n try {\n return ok(JSON.parse(output.value.stdout) as readonly SystemctlTimerListEntry[]);\n } catch (cause) {\n return err(\n new SystemctlCommandError(`Failed to parse JSON output from systemctl list-timers`, {\n args: [...this.scopeArgs(), ...args],\n cause,\n command: `systemctl`,\n operation: `list-timers`,\n reason: `invalid-json`,\n }),\n );\n }\n }\n\n /** Starts a unit by filename. */\n public async start(unit: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`start`, unit);\n }\n\n /** Stops a unit by filename. */\n public async stop(unit: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`stop`, unit);\n }\n\n /** Restarts a unit by filename. */\n public async restart(unit: string): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`restart`, unit);\n }\n\n /**\n * Resets the failed state for matching units, or for all units when no\n * patterns are provided.\n */\n public async resetFailed(\n patterns: readonly string[] = [],\n ): Promise<Result<CommandOutput, SystemctlCommandError>> {\n return this.run(`reset-failed`, ...patterns);\n }\n\n /**\n * Queries `systemctl status` for a unit.\n *\n * This is primarily a human-oriented command and is best paired with\n * `show()` when structured state is needed.\n */\n public async status(\n unit: string,\n options: SystemctlStatusOptions = {},\n ): Promise<Result<CommandOutput, SystemctlCommandError>> {\n const args = [`status`, unit] as string[];\n if (options.noPager ?? true) {\n args.push(`--no-pager`);\n }\n if (options.lines !== undefined) {\n args.push(`--lines`, String(options.lines));\n }\n\n return this.run(...args);\n }\n\n /** Executes a raw `systemctl` invocation with scope-aware arguments. */\n public async run(\n ...args: readonly string[]\n ): Promise<Result<CommandOutput, SystemctlCommandError>> {\n const scopedArgs = [...this.scopeArgs(), ...args];\n try {\n return ok(await this.executor(`systemctl`, scopedArgs));\n } catch (cause) {\n return err(\n new SystemctlCommandError(`Failed to run systemctl ${args[0] ?? `command`}`, {\n args: scopedArgs,\n cause,\n command: `systemctl`,\n operation: args[0],\n reason: `executor-failed`,\n }),\n );\n }\n }\n\n private scopeArgs(): readonly string[] {\n return this.scope === `user` ? [`--user`] : [];\n }\n}\n\nfunction ok<TValue>(value: TValue): Result<TValue, never> {\n return { ok: true, value };\n}\n\nfunction err<TError>(error: TError): Result<never, TError> {\n return { ok: false, error };\n}\n\nfunction parseSystemctlShowOutput(output: string): Readonly<Record<string, string>> {\n return Object.freeze(\n Object.fromEntries(\n output\n .split(`\\n`)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => {\n const separatorIndex = line.indexOf(`=`);\n if (separatorIndex === -1) {\n return [line, ``] as const;\n }\n\n return [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)] as const;\n }),\n ),\n );\n}\n\nfunction firstNonEmptyOutputLine(output: CommandOutput): string {\n const line = [output.stdout, output.stderr]\n .flatMap((value) => value.split(`\\n`))\n .map((value) => value.trim())\n .find((value) => value.length > 0);\n return line ?? ``;\n}\n","import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n defaultCommandExecutor,\n defaultUnitDirForScope,\n extractCommandOutput,\n fileExists,\n parseStartStatus,\n type Result,\n} from \"./internal.ts\";\nimport {\n classifyMaterializationReason,\n NoUnitsProvidedError,\n ExecutableInferenceError,\n InvalidExecDirectiveError,\n UnitEnableError,\n UnitLogsReadError,\n UnitMaterializationError,\n UnitStartError,\n} from \"./errors.ts\";\nimport { SystemdService } from \"./systemd-service.ts\";\nimport { Systemctl } from \"./systemctl.ts\";\nimport { SystemdTimer } from \"./systemd-timer.ts\";\nimport type {\n CommandExecutor,\n MaterializedUnit,\n LogsOptions,\n StartStatus,\n SystemdOptions,\n SystemdUnit,\n ValidInstallUnits,\n} from \"./types.ts\";\n\nexport interface SystemdTsAttachOptions {\n readonly owner: string;\n readonly enable?: boolean;\n readonly start?: boolean;\n}\n\nexport interface SystemdTsDetachOptions {\n readonly deleteUnitFiles?: boolean;\n readonly disable?: boolean;\n readonly stop?: boolean;\n}\n\nexport interface SystemdTsReattachOptions extends SystemdTsAttachOptions {\n readonly disableRemoved?: boolean;\n readonly prune?: boolean;\n readonly restartUpdated?: boolean;\n readonly stopRemoved?: boolean;\n}\n\nexport interface SystemdTsAttachmentSelector {\n readonly owner: string;\n}\n\nexport interface SystemdTsAttachmentResult {\n readonly added: readonly string[];\n readonly directory: string;\n readonly enabled: readonly string[];\n readonly manifestPath: string;\n readonly owner: string;\n readonly removed: readonly string[];\n readonly restarted: readonly string[];\n readonly started: readonly string[];\n readonly unchanged: readonly string[];\n readonly updated: readonly string[];\n}\n\ninterface AttachmentManifest {\n readonly owner: string;\n readonly units: readonly {\n readonly filename: string;\n readonly path: string;\n }[];\n readonly version: 1;\n}\n\n/**\n * A successful systemd unit materialization.\n *\n * It records the target directory and the on-disk path associated with each\n * materialized unit.\n */\nexport class SystemdMaterialization<\n TUnits extends readonly SystemdUnit[] = readonly SystemdUnit[],\n> {\n /** The directory units were written into. */\n public readonly directory: string;\n /** The materialized units together with their resolved on-disk paths. */\n public readonly materialized: readonly MaterializedUnit<TUnits[number]>[];\n\n public constructor(directory: string, materialized: readonly MaterializedUnit<TUnits[number]>[]) {\n this.directory = directory;\n this.materialized = Object.freeze([...materialized]);\n Object.freeze(this);\n }\n}\n\n/**\n * A configured interface to a specific systemd environment.\n *\n * `Systemd` combines unit-file materialization with a command execution\n * strategy. It knows which scope it is targeting, where unit files should be\n * written, and how `systemctl` should be invoked.\n *\n * This abstraction is intentionally close to `systemctl` concepts while still\n * accepting full unit definitions instead of loose unit-name strings.\n */\nexport class Systemd {\n /** Command executor used for `systemctl` and related subprocess calls. */\n public readonly executor: CommandExecutor;\n /** Whether units should be linked into systemd before manager operations. */\n public readonly linkUnits: boolean;\n /** The target manager scope, either `system` or `user`. */\n public readonly scope: `system` | `user`;\n /** The low-level `systemctl` client for this configured target. */\n public readonly systemctl: Systemctl;\n /** Higher-level `systemd-ts` upkeep helpers for application-owned units. */\n public readonly ts: SystemdTs;\n /** The directory used when materializing unit files. */\n public readonly unitDir: string;\n\n /**\n * Creates a configured `Systemd` facade.\n *\n * By default, this targets the system scope and `/etc/systemd/system`. Use\n * `scope: \"user\"` or an explicit `unitDir` to target a different manager or\n * unit-file location.\n */\n public constructor(options: SystemdOptions = {}) {\n this.scope = options.scope ?? `system`;\n this.unitDir = options.unitDir ?? defaultUnitDirForScope(this.scope);\n this.linkUnits = options.linkUnits ?? false;\n this.executor = options.executor ?? defaultCommandExecutor;\n this.systemctl = new Systemctl({\n executor: this.executor,\n scope: this.scope,\n });\n this.ts = new SystemdTs(this);\n Object.freeze(this);\n }\n\n /**\n * Renders and writes one or more units into this instance's `unitDir`.\n *\n * This is intentionally a file-materialization step. It does not enable or\n * start the units on its own.\n */\n public async materialize<const TUnits extends readonly SystemdUnit[]>(\n ...units: TUnits & ValidInstallUnits<TUnits>\n ): Promise<\n Result<\n SystemdMaterialization<TUnits>,\n | ExecutableInferenceError\n | InvalidExecDirectiveError\n | NoUnitsProvidedError\n | UnitMaterializationError\n >\n > {\n return this.materializeUnits(units);\n }\n\n /**\n * Enables one or more units via `systemctl enable`.\n *\n * When `linkUnits` is enabled, this first links materialized unit files into the\n * target manager and reloads systemd so the units are visible before the\n * enable operation runs.\n */\n public async enable(\n ...units: readonly SystemdUnit[]\n ): Promise<Result<void, NoUnitsProvidedError | UnitEnableError>> {\n if (units.length === 0) {\n return err(new NoUnitsProvidedError(`Systemd.enable()`));\n }\n\n const scopeArgs = this.scopeArgs();\n try {\n await this.prepareUnits(scopeArgs, units, `enable`);\n } catch (cause) {\n if (cause instanceof UnitEnableError) {\n return err(cause);\n }\n\n return err(\n new UnitEnableError(`Failed to prepare units for enable`, {\n cause,\n stage: `prepare`,\n unitName: units[0]?.filename,\n }),\n );\n }\n\n for (const unit of units) {\n const args = [...scopeArgs, `enable`, unit.filename] as const;\n const enabled = await this.systemctl.enable(unit.filename);\n if (!enabled.ok) {\n const errorOptions = {\n args,\n cause: enabled.error,\n command: `systemctl`,\n stage: `enable`,\n unitName: unit.filename,\n ...(enabled.error.environmentReason === undefined\n ? {}\n : { environmentReason: enabled.error.environmentReason }),\n };\n return err(new UnitEnableError(`Failed to enable ${unit.filename}`, errorOptions));\n }\n }\n\n return ok(undefined);\n }\n\n /**\n * Starts a unit and returns a parsed `systemctl show` snapshot of its final\n * observed state.\n *\n * For oneshot services, a successful result commonly means `ActiveState` is\n * already back to `inactive` by the time the status snapshot is collected.\n */\n public async start(unit: SystemdUnit): Promise<Result<StartStatus, UnitStartError>> {\n const scopeArgs = this.scopeArgs();\n try {\n await this.prepareUnits(scopeArgs, [unit], `start`);\n } catch (cause) {\n if (cause instanceof UnitStartError) {\n return err(cause);\n }\n\n return err(\n new UnitStartError(`Failed to prepare ${unit.filename} for start`, {\n cause,\n diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),\n stage: `prepare`,\n unitName: unit.filename,\n }),\n );\n }\n\n const startArgs = [...scopeArgs, `start`, unit.filename] as const;\n const started = await this.systemctl.start(unit.filename);\n if (!started.ok) {\n const errorOptions = {\n args: startArgs,\n cause: started.error,\n command: `systemctl`,\n diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),\n stage: `start`,\n unitName: unit.filename,\n ...(started.error.environmentReason === undefined\n ? {}\n : { environmentReason: started.error.environmentReason }),\n };\n return err(new UnitStartError(`Failed to start ${unit.filename}`, errorOptions));\n }\n\n const status = await this.systemctl.showServiceStatus(unit.filename);\n if (!status.ok) {\n const errorOptions = {\n args: [\n ...scopeArgs,\n `show`,\n unit.filename,\n `--property=Id,ActiveState,SubState,Result,ExecMainStatus`,\n ] as const,\n cause: status.error,\n command: `systemctl`,\n diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),\n stage: `show-status`,\n unitName: unit.filename,\n ...(status.error.environmentReason === undefined\n ? {}\n : { environmentReason: status.error.environmentReason }),\n };\n return err(\n new UnitStartError(`Started ${unit.filename} but failed to query its status`, errorOptions),\n );\n }\n return ok(status.value);\n }\n\n /**\n * Reads recent output for a managed unit.\n *\n * If the unit is configured with file-backed `StandardOutput` or\n * `StandardError`, this reads directly from that file. Otherwise it falls back\n * to `systemctl status --lines ...`.\n */\n public async logs(\n unit: SystemdUnit,\n options?: LogsOptions,\n ): Promise<Result<string, UnitLogsReadError>> {\n const fileLogPath = resolveUnitLogPath(unit);\n if (fileLogPath !== undefined) {\n try {\n const output = await readFile(fileLogPath, `utf8`);\n return ok(tailLines(output, options?.lines ?? 50));\n } catch (cause) {\n return err(\n new UnitLogsReadError(`Failed to read logs for ${unit.filename} from ${fileLogPath}`, {\n cause,\n reason: isMissingPathError(cause) ? `missing-log-file` : `log-file-read-failed`,\n stage: `read-log-file`,\n unitName: unit.filename,\n unitPath: fileLogPath,\n }),\n );\n }\n }\n\n const scopeArgs = this.scopeArgs();\n const lines = options?.lines ?? 50;\n const logs = await this.systemctl.status(unit.filename, {\n lines,\n });\n if (logs.ok) {\n return ok(joinCommandOutput(logs.value));\n }\n\n const errorOutput = extractCommandOutput(logs.error);\n if (errorOutput !== undefined) {\n return ok(joinCommandOutput(errorOutput));\n }\n\n const args = [\n ...scopeArgs,\n `status`,\n unit.filename,\n `--no-pager`,\n `--lines`,\n String(lines),\n ] as const;\n return err(\n new UnitLogsReadError(`Failed to query logs for ${unit.filename} from systemctl status`, {\n args,\n cause: logs.error,\n command: `systemctl`,\n reason: `status-command-failed`,\n stage: `status`,\n unitName: unit.filename,\n }),\n );\n }\n\n /** Returns the on-disk unit-file path this instance uses for the given unit. */\n public pathFor(unit: SystemdUnit): string {\n return join(this.unitDir, unit.filename);\n }\n\n private async prepareUnits(\n scopeArgs: readonly string[],\n units: readonly SystemdUnit[],\n operation: `enable` | `start`,\n ): Promise<void> {\n if (this.linkUnits) {\n const linkPaths = await this.collectLinkPaths(units);\n for (const path of linkPaths) {\n const args = [...scopeArgs, `link`, path] as const;\n const linked = await this.systemctl.link(path);\n if (!linked.ok) {\n const linkedUnit = units.find((candidate) => this.pathFor(candidate) === path);\n const errorContext = {\n args,\n cause: linked.error,\n command: `systemctl`,\n stage: `link`,\n unitPath: path,\n ...(linked.error.environmentReason === undefined\n ? {}\n : { environmentReason: linked.error.environmentReason }),\n ...(linkedUnit === undefined ? {} : { unitName: linkedUnit.filename }),\n };\n throw operation === `enable`\n ? new UnitEnableError(`Failed to link ${path} before enable`, errorContext)\n : new UnitStartError(`Failed to link ${path} before start`, errorContext);\n }\n }\n }\n\n const args = [...scopeArgs, `daemon-reload`] as const;\n const reloaded = await this.systemctl.daemonReload();\n if (!reloaded.ok) {\n const errorContext = {\n args,\n cause: reloaded.error,\n command: `systemctl`,\n stage: `daemon-reload`,\n ...(reloaded.error.environmentReason === undefined\n ? {}\n : { environmentReason: reloaded.error.environmentReason }),\n ...(units[0]?.filename === undefined ? {} : { unitName: units[0].filename }),\n };\n throw operation === `enable`\n ? new UnitEnableError(`Failed to reload systemd before enable`, errorContext)\n : new UnitStartError(`Failed to reload systemd before start`, errorContext);\n }\n }\n\n private scopeArgs(): readonly string[] {\n return this.scope === `user` ? [`--user`] : [];\n }\n\n private async collectStartDiagnostics(\n scopeArgs: readonly string[],\n unitName: string,\n ): Promise<{\n readonly showOutput?: string;\n readonly showStatus?: StartStatus;\n readonly statusOutput?: string;\n }> {\n const diagnostics: {\n showOutput?: string;\n showStatus?: StartStatus;\n statusOutput?: string;\n } = {};\n\n const showArgs = [\n ...scopeArgs,\n `show`,\n unitName,\n `--property=Id,ActiveState,SubState,Result,ExecMainStatus`,\n ] as const;\n const show = await this.tryBestEffortCommand(`systemctl`, showArgs);\n if (show !== undefined) {\n const showOutput = joinCommandOutput(show);\n if (showOutput.length > 0) {\n diagnostics.showOutput = showOutput;\n }\n if (show.stdout.length > 0) {\n diagnostics.showStatus = parseStartStatus(unitName, show.stdout);\n }\n }\n\n const statusArgs = [...scopeArgs, `status`, unitName, `--no-pager`, `--lines`, `20`] as const;\n const status = await this.tryBestEffortCommand(`systemctl`, statusArgs);\n if (status !== undefined) {\n const statusOutput = joinCommandOutput(status);\n if (statusOutput.length > 0) {\n diagnostics.statusOutput = statusOutput;\n }\n }\n\n return diagnostics;\n }\n\n private async collectLinkPaths(units: readonly SystemdUnit[]): Promise<readonly string[]> {\n const paths = new Set<string>();\n\n for (const unit of units) {\n paths.add(this.pathFor(unit));\n\n if (unit instanceof SystemdTimer) {\n const targetPath = join(this.unitDir, unit.targetUnit);\n if (await fileExists(targetPath)) {\n paths.add(targetPath);\n }\n }\n }\n\n return [...paths];\n }\n\n private async materializeUnits<const TUnits extends readonly SystemdUnit[]>(\n units: TUnits & ValidInstallUnits<TUnits>,\n ): Promise<\n Result<\n SystemdMaterialization<TUnits>,\n | ExecutableInferenceError\n | InvalidExecDirectiveError\n | NoUnitsProvidedError\n | UnitMaterializationError\n >\n > {\n if (units.length === 0) {\n return err(new NoUnitsProvidedError(`Systemd.materialize()`));\n }\n\n try {\n await writeUnitDirectory(this.unitDir);\n } catch (cause) {\n const reason = classifyMaterializationReason(cause);\n return err(\n new UnitMaterializationError(`Failed to create unit directory ${this.unitDir}`, {\n cause,\n operation: `create-directory`,\n ...(reason === undefined ? {} : { reason }),\n unitPath: this.unitDir,\n }),\n );\n }\n\n const materialized: MaterializedUnit<TUnits[number]>[] = [];\n for (const unit of units) {\n const path = join(this.unitDir, unit.filename);\n const rendered = unit.render();\n if (!rendered.ok) {\n return err(rendered.error);\n }\n try {\n await writeFile(path, rendered.value, `utf8`);\n } catch (cause) {\n if (cause instanceof InvalidExecDirectiveError) {\n return err(cause);\n }\n\n const reason = classifyMaterializationReason(cause);\n return err(\n new UnitMaterializationError(`Failed to materialize ${unit.filename} into ${path}`, {\n cause,\n operation: `write-file`,\n ...(reason === undefined ? {} : { reason }),\n unitName: unit.filename,\n unitPath: path,\n }),\n );\n }\n materialized.push({ path, unit });\n }\n\n return ok(new SystemdMaterialization<TUnits>(this.unitDir, materialized));\n }\n\n private async tryBestEffortCommand(\n command: string,\n args: readonly string[],\n ): Promise<\n | {\n readonly stderr: string;\n readonly stdout: string;\n }\n | undefined\n > {\n try {\n return await this.executor(command, args);\n } catch (cause) {\n const output = extractCommandOutput(cause);\n if (output !== undefined) {\n return output;\n }\n return undefined;\n }\n }\n}\n\n/**\n * Opinionated `systemd-ts` upkeep helpers for application-owned units.\n *\n * This layer is intentionally analogous to a subset of `portablectl`'s\n * ownership workflow, but it operates on regular materialized units instead of\n * portable service images.\n */\nexport class SystemdTs {\n private readonly systemd: Systemd;\n\n public constructor(systemd: Systemd) {\n this.systemd = systemd;\n Object.freeze(this);\n }\n\n public async attach(\n units: readonly SystemdUnit[],\n options: SystemdTsAttachOptions,\n ): Promise<\n Result<\n SystemdTsAttachmentResult,\n | ExecutableInferenceError\n | InvalidExecDirectiveError\n | NoUnitsProvidedError\n | UnitEnableError\n | UnitMaterializationError\n | UnitStartError\n >\n > {\n if (units.length === 0) {\n return err(new NoUnitsProvidedError(`Systemd.ts.attach()`));\n }\n\n const described = await this.describeUnits(units);\n if (!described.ok) {\n return described;\n }\n\n const manifestPath = this.manifestPathFor(options.owner);\n const prior = await this.readManifest(options.owner);\n const diff = await this.diffManifest(prior, described.value);\n const materialized = await this.systemd.materialize(...(units as readonly SystemdUnit[]));\n if (!materialized.ok) {\n return materialized;\n }\n\n const enabled: string[] = [];\n if (options.enable ?? false) {\n const result = await this.systemd.enable(...units);\n if (!result.ok) {\n return result;\n }\n enabled.push(...units.map((unit) => unit.filename));\n }\n\n const started: string[] = [];\n if (options.start ?? false) {\n for (const unit of units) {\n const result = await this.systemd.start(unit);\n if (!result.ok) {\n return result;\n }\n started.push(unit.filename);\n }\n }\n\n await this.writeManifest(options.owner, described.value);\n\n return ok({\n added: diff.added,\n directory: this.systemd.unitDir,\n enabled,\n manifestPath,\n owner: options.owner,\n removed: diff.removed,\n restarted: [],\n started,\n unchanged: diff.unchanged,\n updated: diff.updated,\n });\n }\n\n public async detach(\n selector: SystemdTsAttachmentSelector,\n options: SystemdTsDetachOptions = {},\n ): Promise<\n Result<\n {\n readonly deleted: readonly string[];\n readonly detached: readonly string[];\n readonly disabled: readonly string[];\n readonly owner: string;\n readonly stopped: readonly string[];\n },\n Error\n >\n > {\n const manifest = await this.readManifest(selector.owner);\n if (manifest === undefined) {\n return ok({\n deleted: [],\n detached: [],\n disabled: [],\n owner: selector.owner,\n stopped: [],\n });\n }\n\n const filenames = manifest.units.map((unit) => unit.filename);\n const deleted: string[] = [];\n const disabled: string[] = [];\n const stopped: string[] = [];\n\n if (options.stop ?? true) {\n await this.runSystemctl(`stop`, filenames);\n stopped.push(...filenames);\n }\n if (options.disable ?? true) {\n await this.runSystemctl(`disable`, filenames);\n disabled.push(...filenames);\n }\n if (options.deleteUnitFiles ?? true) {\n for (const unit of manifest.units) {\n await this.removeManagedUnitPath(unit.path);\n await rm(unit.path, { force: true });\n deleted.push(unit.filename);\n }\n await this.runSystemctl(`daemon-reload`);\n }\n\n await rm(this.manifestPathFor(selector.owner), { force: true });\n\n return ok({\n deleted,\n detached: filenames,\n disabled,\n owner: selector.owner,\n stopped,\n });\n }\n\n public async reattach(\n units: readonly SystemdUnit[],\n options: SystemdTsReattachOptions,\n ): Promise<\n Result<\n SystemdTsAttachmentResult,\n | ExecutableInferenceError\n | InvalidExecDirectiveError\n | NoUnitsProvidedError\n | UnitEnableError\n | UnitMaterializationError\n | UnitStartError\n | Error\n >\n > {\n if (units.length === 0) {\n return err(new NoUnitsProvidedError(`Systemd.ts.reattach()`));\n }\n\n const described = await this.describeUnits(units);\n if (!described.ok) {\n return described;\n }\n\n const manifestPath = this.manifestPathFor(options.owner);\n const prior = await this.readManifest(options.owner);\n const diff = await this.diffManifest(prior, described.value);\n\n if ((options.stopRemoved ?? true) && diff.removed.length > 0) {\n await this.runSystemctl(`stop`, diff.removed);\n }\n if ((options.disableRemoved ?? true) && diff.removed.length > 0) {\n await this.runSystemctl(`disable`, diff.removed);\n }\n if ((options.prune ?? true) && prior !== undefined) {\n for (const unit of prior.units) {\n if (!diff.removed.includes(unit.filename)) {\n continue;\n }\n await this.removeManagedUnitPath(unit.path);\n await rm(unit.path, { force: true });\n }\n if (diff.removed.length > 0) {\n await this.runSystemctl(`daemon-reload`);\n }\n }\n\n const materialized = await this.systemd.materialize(...(units as readonly SystemdUnit[]));\n if (!materialized.ok) {\n return materialized;\n }\n\n const enabled: string[] = [];\n if (options.enable ?? false) {\n const result = await this.systemd.enable(...units);\n if (!result.ok) {\n return result;\n }\n enabled.push(...units.map((unit) => unit.filename));\n }\n\n const restarted: string[] = [];\n if (options.restartUpdated ?? false) {\n const restartable = units\n .filter((unit) => diff.updated.includes(unit.filename))\n .map((unit) => unit.filename);\n if (restartable.length > 0) {\n await this.runSystemctl(`restart`, restartable);\n restarted.push(...restartable);\n }\n }\n\n const started: string[] = [];\n if (options.start ?? false) {\n for (const unit of units) {\n if (restarted.includes(unit.filename)) {\n continue;\n }\n const result = await this.systemd.start(unit);\n if (!result.ok) {\n return result;\n }\n started.push(unit.filename);\n }\n }\n\n await this.writeManifest(options.owner, described.value);\n\n return ok({\n added: diff.added,\n directory: this.systemd.unitDir,\n enabled,\n manifestPath,\n owner: options.owner,\n removed: diff.removed,\n restarted,\n started,\n unchanged: diff.unchanged,\n updated: diff.updated,\n });\n }\n\n private async describeUnits(units: readonly SystemdUnit[]): Promise<\n Result<\n readonly {\n readonly filename: string;\n readonly path: string;\n readonly rendered: string;\n }[],\n ExecutableInferenceError | InvalidExecDirectiveError\n >\n > {\n const described = [];\n for (const unit of units) {\n const rendered = unit.render();\n if (!rendered.ok) {\n return rendered;\n }\n described.push({\n filename: unit.filename,\n path: this.systemd.pathFor(unit),\n rendered: rendered.value,\n });\n }\n\n return ok(described);\n }\n\n private async diffManifest(\n prior: AttachmentManifest | undefined,\n desired: readonly {\n readonly filename: string;\n readonly path: string;\n readonly rendered: string;\n }[],\n ): Promise<{\n readonly added: readonly string[];\n readonly removed: readonly string[];\n readonly unchanged: readonly string[];\n readonly updated: readonly string[];\n }> {\n const priorUnits = new Map(prior?.units.map((unit) => [unit.filename, unit.path]) ?? []);\n const desiredNames = new Set(desired.map((unit) => unit.filename));\n const added: string[] = [];\n const removed = [...priorUnits.keys()].filter((filename) => !desiredNames.has(filename));\n const unchanged: string[] = [];\n const updated: string[] = [];\n\n for (const unit of desired) {\n const priorPath = priorUnits.get(unit.filename);\n if (priorPath === undefined) {\n added.push(unit.filename);\n continue;\n }\n\n try {\n const current = await readFile(priorPath, `utf8`);\n if (current === unit.rendered) {\n unchanged.push(unit.filename);\n continue;\n }\n } catch {\n added.push(unit.filename);\n continue;\n }\n\n updated.push(unit.filename);\n }\n\n return {\n added,\n removed,\n unchanged,\n updated,\n };\n }\n\n private async manifestDir(): Promise<string> {\n const directory = join(this.systemd.unitDir, `.systemd-ts`);\n await mkdir(directory, { recursive: true });\n return directory;\n }\n\n private manifestPathFor(owner: string): string {\n return join(this.systemd.unitDir, `.systemd-ts`, `${encodeURIComponent(owner)}.json`);\n }\n\n private async readManifest(owner: string): Promise<AttachmentManifest | undefined> {\n try {\n const content = await readFile(this.manifestPathFor(owner), `utf8`);\n return JSON.parse(content) as AttachmentManifest;\n } catch {\n return undefined;\n }\n }\n\n private async runSystemctl(action: string, units: readonly string[] = []): Promise<void> {\n const args =\n action === `daemon-reload`\n ? [...this.scopeArgs(), action]\n : [...this.scopeArgs(), action, ...units];\n await this.systemd.executor(`systemctl`, args);\n }\n\n private async removeManagedUnitPath(path: string): Promise<void> {\n await this.systemd.executor(`rm`, [`-f`, path]);\n }\n\n private scopeArgs(): readonly string[] {\n return this.systemd.scope === `user` ? [`--user`] : [];\n }\n\n private async writeManifest(\n owner: string,\n units: readonly {\n readonly filename: string;\n readonly path: string;\n readonly rendered: string;\n }[],\n ): Promise<void> {\n await this.manifestDir();\n const manifest: AttachmentManifest = {\n owner,\n units: units.map((unit) => ({\n filename: unit.filename,\n path: unit.path,\n })),\n version: 1,\n };\n await writeFile(this.manifestPathFor(owner), JSON.stringify(manifest, null, 2), `utf8`);\n }\n}\n\nfunction ok<TValue>(value: TValue): Result<TValue, never> {\n return { ok: true, value };\n}\n\nfunction err<TError>(error: TError): Result<never, TError> {\n return { ok: false, error };\n}\n\nfunction joinCommandOutput(output: { readonly stderr: string; readonly stdout: string }): string {\n return [output.stdout, output.stderr].filter((value) => value.length > 0).join(`\\n`);\n}\n\nlet lazyDefaultSystemd: Systemd | undefined;\n\n/**\n * Returns the lazily created default `Systemd` instance.\n *\n * The default instance uses the library defaults for scope, unit directory, and\n * command execution.\n */\nexport function defaultSystemd(): Systemd {\n lazyDefaultSystemd ??= new Systemd();\n return lazyDefaultSystemd;\n}\n\nfunction resolveUnitLogPath(unit: SystemdUnit): string | undefined {\n if (!(unit instanceof SystemdService)) {\n return undefined;\n }\n\n for (const key of [`StandardOutput`, `StandardError`] as const) {\n const value = unit.service[key];\n if (typeof value !== `string`) {\n continue;\n }\n\n const path = parseFileLogPath(value);\n if (path !== undefined) {\n return path;\n }\n }\n\n return undefined;\n}\n\nfunction parseFileLogPath(value: string): string | undefined {\n for (const prefix of [`append:`, `file:`] as const) {\n if (value.startsWith(prefix)) {\n return value.slice(prefix.length);\n }\n }\n\n return undefined;\n}\n\nfunction tailLines(output: string, lines: number): string {\n return output.split(`\\n`).slice(-lines).join(`\\n`);\n}\n\nfunction isMissingPathError(cause: unknown): boolean {\n if (cause === null || typeof cause !== `object`) {\n return false;\n }\n\n return (cause as Record<string, unknown>)[`code`] === `ENOENT`;\n}\n\nasync function writeUnitDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true });\n}\n","export {\n ExecutableInferenceError,\n InvalidExecDirectiveError,\n NoUnitsProvidedError,\n NotifySendError,\n SystemctlCommandError,\n SystemdTsError,\n UnitEnableError,\n UnitLogsReadError,\n UnitMaterializationError,\n UnitStartError,\n} from \"./errors.ts\";\nexport { Executable, defineExecutable } from \"./executable.ts\";\nexport { notify } from \"./notify.ts\";\nexport { SystemdService } from \"./systemd-service.ts\";\nexport { SystemdTimer } from \"./systemd-timer.ts\";\nexport { Systemctl } from \"./systemctl.ts\";\nexport { Systemd, SystemdMaterialization, SystemdTs, defaultSystemd } from \"./systemd.ts\";\nexport type {\n SystemdTsAttachmentSelector,\n SystemdTsAttachOptions,\n SystemdTsAttachmentResult,\n SystemdTsDetachOptions,\n SystemdTsReattachOptions,\n} from \"./systemd.ts\";\nexport type { Result } from \"./internal.ts\";\nexport type {\n AnySystemdService,\n AnySystemdTimer,\n CommandExecutionOptions,\n CommandExecutor,\n CommandOutput,\n ExecutableOptions,\n MaterializedUnit,\n LogsOptions,\n NotifyOptions,\n ServiceBaseName,\n ServiceFilename,\n StartStatus,\n SystemdOptions,\n SystemdServiceOptions,\n SystemctlActiveState,\n SystemctlEnablementState,\n SystemctlIsEnabledOptions,\n SystemctlIsSystemRunningOptions,\n SystemctlListTimersOptions,\n SystemctlOptions,\n SystemctlServiceStatus,\n SystemctlSystemRunningState,\n SystemctlStateQueryOptions,\n SystemctlShowOptions,\n SystemctlStatusOptions,\n SystemctlTimerListEntry,\n SystemdTimerOptions,\n SystemdUnit,\n TimerBaseName,\n TimerFilename,\n TimerTargetServiceName,\n TimerTargetUnit,\n UnitValue,\n ValidInstallUnits,\n} from \"./types.ts\";\nexport type {\n NotifySendErrorReason,\n SystemctlCommandErrorReason,\n SystemdCommandEnvironmentReason,\n UnitLogsReadErrorReason,\n UnitMaterializationErrorReason,\n} from \"./errors.ts\";\n\nimport * as I from \"./internal.ts\";\n/**\n * Internal helpers are exposed for advanced use, but they are not a stable public API.\n * Expect breaking changes here outside the package's normal compatibility guarantees.\n */\nexport const Internal: typeof I = I;\n"],"mappings":";;;;;;;;AA4EA,IAAa,iBAAb,cAAoC,MAAM;CACxC;CAEA,YACE,MACA,SACA,UAAiC,EAAE,EACnC;AACA,QAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AACxC,OAAK,OAAO;AACZ,OAAK,OAAO,IAAI,OAAO;;;AAI3B,IAAa,4BAAb,cAA+C,eAAe;CAC5D;CAEA,YAAmB,WAAmB,UAAiC,EAAE,EAAE;AACzE,QACE,qCACA,GAAG,UAAU,oDACb,QACD;AACD,OAAK,YAAY;;;AAIrB,IAAa,uBAAb,cAA0C,eAAe;CACvD;CAEA,YAAmB,WAAmB,UAAiC,EAAE,EAAE;AACzE,QACE,gCACA,GAAG,UAAU,0CACb,QACD;AACD,OAAK,YAAY;;;AAIrB,IAAa,2BAAb,cAA8C,eAAe;CAC3D,YAAmB,UAAiC,EAAE,EAAE;AACtD,QACE,mCACA,kGACA,QACD;;;AAIL,IAAa,2BAAb,cAA8C,eAAe;CAC3D;CACA;CACA;CACA;CAEA,YAAmB,SAAiB,UAA2C,EAAE,EAAE;AACjF,Q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AAGxD,eAAe,mBAAmB,MAA6B;AAC7D,OAAM,MAAM,MAAM,EAAE,WAAW,MAAM,CAAC;;;;;;;;ACl5BxC,MAAa,WAAqBC"}
package/dist/test.d.mts CHANGED
@@ -1,3 +1,5 @@
1
+ import { j as CommandExecutor, n as Systemd } from "./index-DeNBLyGA.mjs";
2
+
1
3
  //#region src/test/host.d.ts
2
4
  interface TestHostInfo {
3
5
  readonly backend: TestHostBackendName;
@@ -12,6 +14,32 @@ declare function getTestHostInfo(): TestHostInfo;
12
14
  declare function ensureTestHost(): Promise<TestHostInfo>;
13
15
  declare function closeTestHost(): void;
14
16
  declare function runGuestCommand(script: string): Promise<string>;
17
+ declare function runIsolatedGuestCommand(script: string): Promise<string>;
18
+ //#endregion
19
+ //#region src/test/harness.d.ts
20
+ /**
21
+ * Creates a command executor that runs argv-style commands inside the current
22
+ * test host guest shell.
23
+ */
24
+ declare function createGuestCommandExecutor(runCommand: (script: string) => Promise<string>): CommandExecutor;
25
+ /**
26
+ * Executor that reuses the warm guest shell for fast sandbox-backed tests.
27
+ */
28
+ declare const guestCommandExecutor: CommandExecutor;
29
+ /**
30
+ * Executor that runs each guest command in a fresh isolated guest shell.
31
+ */
32
+ declare const isolatedGuestCommandExecutor: CommandExecutor;
33
+ /**
34
+ * Creates a `Systemd` instance scoped to the active test sandbox and backed by
35
+ * the warm guest-shell executor.
36
+ */
37
+ declare function sandboxSystemd(): Systemd;
38
+ /**
39
+ * Creates a `Systemd` instance scoped to the active test sandbox and backed by
40
+ * a fresh guest shell per command.
41
+ */
42
+ declare function isolatedSandboxSystemd(): Systemd;
15
43
  //#endregion
16
44
  //#region src/test/sandbox.d.ts
17
45
  interface TestSandbox {
@@ -25,4 +53,5 @@ declare function createTestSandbox(testName?: string): Promise<TestSandbox>;
25
53
  declare function destroyCurrentTestSandbox(): Promise<void>;
26
54
  declare function useCurrentTestSandbox(): TestSandbox;
27
55
  //#endregion
28
- export { type TestHostInfo, type TestSandbox, closeTestHost, createTestSandbox, destroyCurrentTestSandbox, ensureTestHost, getTestHostInfo, runGuestCommand, useCurrentTestSandbox };
56
+ export { type TestHostInfo, type TestSandbox, closeTestHost, createGuestCommandExecutor, createTestSandbox, destroyCurrentTestSandbox, ensureTestHost, getTestHostInfo, guestCommandExecutor, isolatedGuestCommandExecutor, isolatedSandboxSystemd, runGuestCommand, runIsolatedGuestCommand, sandboxSystemd, useCurrentTestSandbox };
57
+ //# sourceMappingURL=test.d.mts.map
package/dist/test.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { n as Systemd } from "./main-BXq7TQdg.mjs";
1
2
  import { fileURLToPath } from "node:url";
2
3
  import { execFile, spawn } from "node:child_process";
3
4
  import { promisify } from "node:util";
@@ -35,6 +36,9 @@ function closeTestHost() {
35
36
  async function runGuestCommand(script) {
36
37
  return getGuestShell().run(script);
37
38
  }
39
+ async function runIsolatedGuestCommand(script) {
40
+ return backend.runIsolatedCommand(script);
41
+ }
38
42
  async function ensureTestHostInner() {
39
43
  logTestHost(`Ensuring ${backend.info.backend} test host`);
40
44
  await backend.ensureHost();
@@ -287,16 +291,16 @@ var DockerBackend = class {
287
291
  `bash`,
288
292
  `-lc`,
289
293
  [
290
- `mkdir -p ${shellQuote$1(dockerStateRoot)}`,
291
- `chown ${runtimeInfo.userId}:${runtimeInfo.userId} ${shellQuote$1(dockerStateRoot)}`,
292
- `loginctl enable-linger ${shellQuote$1(dockerUser)}`,
294
+ `mkdir -p ${shellQuote$2(dockerStateRoot)}`,
295
+ `chown ${runtimeInfo.userId}:${runtimeInfo.userId} ${shellQuote$2(dockerStateRoot)}`,
296
+ `loginctl enable-linger ${shellQuote$2(dockerUser)}`,
293
297
  `systemctl start user@${runtimeInfo.userId}.service`
294
298
  ].join(`\n`)
295
299
  ], { timeout: dockerExecTimeoutMs });
296
300
  await this.execDockerAsUser(runtimeInfo, [
297
301
  `bash`,
298
302
  `-lc`,
299
- `mkdir -p ${shellQuote$1(`${dockerStateRoot}/tests`)}`
303
+ `mkdir -p ${shellQuote$2(`${dockerStateRoot}/tests`)}`
300
304
  ]);
301
305
  logTestHost(`User session started for ${dockerUser}`);
302
306
  }
@@ -344,7 +348,7 @@ var DockerBackend = class {
344
348
  dockerContainer,
345
349
  `bash`,
346
350
  `-lc`,
347
- `getent passwd ${shellQuote$1(dockerUser)} | cut -d: -f6`
351
+ `getent passwd ${shellQuote$2(dockerUser)} | cut -d: -f6`
348
352
  ])).trim();
349
353
  if (home.length === 0) throw new Error(`Could not resolve home directory for Docker test user ${dockerUser}`);
350
354
  logTestHost(`Resolved home directory for ${dockerUser}: ${home}`);
@@ -357,7 +361,7 @@ var DockerBackend = class {
357
361
  dockerContainer,
358
362
  `bash`,
359
363
  `-lc`,
360
- `id -u ${shellQuote$1(dockerUser)}`
364
+ `id -u ${shellQuote$2(dockerUser)}`
361
365
  ]);
362
366
  const parsed = Number(output.trim());
363
367
  if (!Number.isInteger(parsed)) throw new Error(`Could not resolve uid for Docker test user ${dockerUser}`);
@@ -456,7 +460,7 @@ printf '\\n${marker}:%s\\n' "$status"
456
460
  this.drain();
457
461
  }
458
462
  };
459
- function shellQuote$1(value) {
463
+ function shellQuote$2(value) {
460
464
  return `'${value.replaceAll(`'`, `'\\''`)}'`;
461
465
  }
462
466
  const backend = createBackend(selectedBackendName);
@@ -470,8 +474,8 @@ async function createTestSandbox(testName) {
470
474
  const linkedUnitDir = `${rootDir}/linked-units`;
471
475
  const workDir = `${rootDir}/work`;
472
476
  await runGuestCommand(`set -euo pipefail
473
- rm -rf ${shellQuote(rootDir)}
474
- mkdir -p ${shellQuote(linkedUnitDir)} ${shellQuote(workDir)}`);
477
+ rm -rf ${shellQuote$1(rootDir)}
478
+ mkdir -p ${shellQuote$1(linkedUnitDir)} ${shellQuote$1(workDir)}`);
475
479
  currentSandbox = {
476
480
  id,
477
481
  linkedUnitDir,
@@ -485,24 +489,99 @@ async function destroyCurrentTestSandbox() {
485
489
  if (currentSandbox === void 0) return;
486
490
  const sandbox = currentSandbox;
487
491
  currentSandbox = void 0;
488
- const units = (await runGuestCommand(`systemctl --user list-unit-files --all --no-legend ${shellQuote(`${sandbox.namePrefix}*`)} 2>/dev/null | awk '{print $1}' || true`)).split(`\n`).map((unit) => unit.trim()).filter((unit) => unit.length > 0);
492
+ const units = (await runGuestCommand(`systemctl --user list-unit-files --all --no-legend ${shellQuote$1(`${sandbox.namePrefix}*`)} 2>/dev/null | awk '{print $1}' || true`)).split(`\n`).map((unit) => unit.trim()).filter((unit) => unit.length > 0);
489
493
  if (units.length > 0) {
490
- await runGuestCommand(`systemctl --user stop ${units.map(shellQuote).join(` `)} || true`);
491
- await runGuestCommand(`systemctl --user disable ${units.map(shellQuote).join(` `)} || true`);
492
- await runGuestCommand(`systemctl --user reset-failed ${units.map(shellQuote).join(` `)} || true`);
494
+ await runGuestCommand(`systemctl --user stop ${units.map(shellQuote$1).join(` `)} || true`);
495
+ await runGuestCommand(`systemctl --user disable ${units.map(shellQuote$1).join(` `)} || true`);
496
+ await runGuestCommand(`systemctl --user reset-failed ${units.map(shellQuote$1).join(` `)} || true`);
493
497
  }
494
498
  await runGuestCommand(`systemctl --user daemon-reload || true`);
495
- await runGuestCommand(`rm -rf ${shellQuote(sandbox.rootDir)}`);
499
+ await runGuestCommand(`rm -rf ${shellQuote$1(sandbox.rootDir)}`);
496
500
  }
497
501
  function useCurrentTestSandbox() {
498
502
  if (currentSandbox === void 0) throw new Error(`No active test sandbox is available`);
499
503
  return currentSandbox;
500
504
  }
501
- function shellQuote(value) {
505
+ function shellQuote$1(value) {
502
506
  return `'${value.replaceAll(`'`, `'\\''`)}'`;
503
507
  }
504
508
  function slugify(value) {
505
509
  return value.toLowerCase().replaceAll(/[^a-z0-9]+/g, `-`).replaceAll(/^-+|-+$/g, ``).slice(0, 32);
506
510
  }
507
511
  //#endregion
508
- export { closeTestHost, createTestSandbox, destroyCurrentTestSandbox, ensureTestHost, getTestHostInfo, runGuestCommand, useCurrentTestSandbox };
512
+ //#region src/test/harness.ts
513
+ /**
514
+ * Creates a command executor that runs argv-style commands inside the current
515
+ * test host guest shell.
516
+ */
517
+ function createGuestCommandExecutor(runCommand) {
518
+ return async (command, args, options = {}) => {
519
+ try {
520
+ return {
521
+ stderr: ``,
522
+ stdout: await runCommand(buildGuestCommand(command, args, options))
523
+ };
524
+ } catch (cause) {
525
+ throw enrichGuestCommandError(cause);
526
+ }
527
+ };
528
+ }
529
+ /**
530
+ * Executor that reuses the warm guest shell for fast sandbox-backed tests.
531
+ */
532
+ const guestCommandExecutor = createGuestCommandExecutor(runGuestCommand);
533
+ /**
534
+ * Executor that runs each guest command in a fresh isolated guest shell.
535
+ */
536
+ const isolatedGuestCommandExecutor = createGuestCommandExecutor(runIsolatedGuestCommand);
537
+ /**
538
+ * Creates a `Systemd` instance scoped to the active test sandbox and backed by
539
+ * the warm guest-shell executor.
540
+ */
541
+ function sandboxSystemd() {
542
+ return new Systemd({
543
+ executor: guestCommandExecutor,
544
+ linkUnits: true,
545
+ scope: `user`,
546
+ unitDir: useCurrentTestSandbox().linkedUnitDir
547
+ });
548
+ }
549
+ /**
550
+ * Creates a `Systemd` instance scoped to the active test sandbox and backed by
551
+ * a fresh guest shell per command.
552
+ */
553
+ function isolatedSandboxSystemd() {
554
+ return new Systemd({
555
+ executor: isolatedGuestCommandExecutor,
556
+ linkUnits: true,
557
+ scope: `user`,
558
+ unitDir: useCurrentTestSandbox().linkedUnitDir
559
+ });
560
+ }
561
+ function buildGuestCommand(command, args, options) {
562
+ return [
563
+ `env`,
564
+ ...options.env === void 0 ? [] : Object.entries(options.env).flatMap(([key, value]) => value === void 0 ? [`-u`, key] : [`${key}=${value}`]),
565
+ command,
566
+ ...args
567
+ ].map((part) => shellQuote(part)).join(` `);
568
+ }
569
+ function enrichGuestCommandError(cause) {
570
+ if (cause instanceof Error) return Object.assign(cause, {
571
+ code: 1,
572
+ stderr: ``,
573
+ stdout: cause.message
574
+ });
575
+ return Object.assign(/* @__PURE__ */ new Error(`Guest command failed`), {
576
+ code: 1,
577
+ stderr: ``,
578
+ stdout: ``
579
+ });
580
+ }
581
+ function shellQuote(value) {
582
+ return `'${value.replaceAll(`'`, `'\\''`)}'`;
583
+ }
584
+ //#endregion
585
+ export { closeTestHost, createGuestCommandExecutor, createTestSandbox, destroyCurrentTestSandbox, ensureTestHost, getTestHostInfo, guestCommandExecutor, isolatedGuestCommandExecutor, isolatedSandboxSystemd, runGuestCommand, runIsolatedGuestCommand, sandboxSystemd, useCurrentTestSandbox };
586
+
587
+ //# sourceMappingURL=test.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test.mjs","names":["delay","shellQuote","shellQuote"],"sources":["../src/test/host.ts","../src/test/sandbox.ts","../src/test/harness.ts"],"sourcesContent":["import { execFile, spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\nconst commandMaxBufferBytes = 16 * 1024 * 1024;\nconst dockerBuildTimeoutMs = 5 * 60 * 1_000;\nconst dockerExecTimeoutMs = 60 * 1_000;\nconst guestCommandTimeoutMs = 10 * 1_000;\nconst repoRoot = fileURLToPath(new URL(`../../../../`, import.meta.url));\nconst dockerfilePath = fileURLToPath(new URL(`./systemd-container.Dockerfile`, import.meta.url));\nconst selectedBackendName = resolveBackendName(process.env[`SYSTEMD_TS_TEST_HOST_BACKEND`]);\nconst colimaHome = process.env[`COLIMA_HOME`] ?? `${repoRoot}.colima`;\nconst limaHome = process.env[`LIMA_HOME`] ?? `${colimaHome}/_lima`;\nconst colimaProfile = process.env[`COLIMA_PROFILE`] ?? `systemd-ts`;\nconst dockerStateRoot = process.env[`SYSTEMD_TS_TEST_HOST_ROOT`] ?? `${repoRoot}.docker`;\nconst dockerImage = process.env[`SYSTEMD_TS_TEST_DOCKER_IMAGE`] ?? `systemd-ts-test-host:local`;\nconst dockerUser = process.env[`SYSTEMD_TS_TEST_DOCKER_USER`] ?? `runner`;\nconst dockerConfiguredUserId = process.env[`SYSTEMD_TS_TEST_DOCKER_UID`];\nconst dockerContainer =\n process.env[`SYSTEMD_TS_TEST_DOCKER_CONTAINER`] ?? defaultDockerContainerName();\n\nexport interface TestHostInfo {\n readonly backend: TestHostBackendName;\n readonly colimaHome?: string;\n readonly colimaProfile?: string;\n readonly limaHome?: string;\n readonly repoRoot: string;\n readonly stateRoot: string;\n}\n\ntype TestHostBackendName = `colima` | `docker`;\n\ninterface TestHostBackend {\n readonly info: TestHostInfo;\n ensureHost(): Promise<void>;\n createGuestShellProcess(): ChildProcessWithoutNullStreams;\n runIsolatedCommand(script: string): Promise<string>;\n}\n\nlet ensuredHost: Promise<TestHostInfo> | undefined;\nlet guestShell: GuestShell | undefined;\n\nexport function getTestHostInfo(): TestHostInfo {\n return backend.info;\n}\n\nexport function ensureTestHost(): Promise<TestHostInfo> {\n ensuredHost ??= ensureTestHostInner();\n return ensuredHost;\n}\n\nexport function closeTestHost(): void {\n closeGuestShell(`warmup complete`);\n}\n\nexport async function runGuestCommand(script: string): Promise<string> {\n const shell = getGuestShell();\n return shell.run(script);\n}\n\nexport async function runIsolatedGuestCommand(script: string): Promise<string> {\n return backend.runIsolatedCommand(script);\n}\n\nasync function ensureTestHostInner(): Promise<TestHostInfo> {\n logTestHost(`Ensuring ${backend.info.backend} test host`);\n await backend.ensureHost();\n logTestHost(`Waiting for systemd --user readiness`);\n await waitForUserSystemd();\n logTestHost(`Test host ready`);\n return getTestHostInfo();\n}\n\nasync function waitForUserSystemd(): Promise<void> {\n for (let attempt = 0; attempt < 30; attempt += 1) {\n const state = await runGuestCommandWithTimeout(\n `printf 'pid1=%s\\n' \"$(ps -p 1 -o comm=)\"; systemctl --user is-system-running || true; printf 'xdg=%s\\n' \"$XDG_RUNTIME_DIR\"`,\n guestCommandTimeoutMs,\n );\n\n if (\n state.includes(`pid1=systemd`) &&\n state.includes(`xdg=/run/user/`) &&\n [`running`, `degraded`].some((status) => state.includes(status))\n ) {\n logTestHost(\n `systemd --user ready after ${attempt + 1} attempt${attempt === 0 ? `` : `s`}: ${summarizeSystemdState(state)}`,\n );\n return;\n }\n\n if (attempt === 0 || (attempt + 1) % 5 === 0) {\n logTestHost(\n `systemd --user not ready yet (${attempt + 1}/30): ${summarizeSystemdState(state)}`,\n );\n }\n\n await delay(1_000);\n }\n\n throw new Error(`Timed out waiting for systemd --user in the ${backend.info.backend} guest`);\n}\n\nfunction getGuestShell(): GuestShell {\n guestShell ??= new GuestShell(\n () => backend.createGuestShellProcess(),\n () => {\n if (guestShell !== undefined) {\n guestShell = undefined;\n }\n },\n );\n return guestShell;\n}\n\nfunction closeGuestShell(reason: string): void {\n if (guestShell === undefined) {\n return;\n }\n\n logTestHost(`Resetting guest shell: ${reason}`);\n guestShell.close();\n guestShell = undefined;\n}\n\nasync function runGuestCommandWithTimeout(script: string, timeoutMs: number): Promise<string> {\n const shell = getGuestShell();\n try {\n return await shell.run(script, timeoutMs);\n } catch (error) {\n if (error instanceof Error && error.message.includes(`timed out`)) {\n closeGuestShell(error.message);\n }\n\n throw error;\n }\n}\n\nfunction mergeOutput(stdout: string, stderr: string): string {\n return [stdout, stderr].filter((output) => output.length > 0).join(`\\n`);\n}\n\nfunction summarizeSystemdState(state: string): string {\n return state\n .split(`\\n`)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(`; `);\n}\n\nfunction inferBackendName(): TestHostBackendName {\n if (process.platform === `darwin`) {\n return `colima`;\n }\n\n if (process.platform === `linux`) {\n return `docker`;\n }\n\n throw new Error(\n `Unsupported test host platform: ${process.platform}. Set SYSTEMD_TS_TEST_HOST_BACKEND explicitly if you have a compatible backend.`,\n );\n}\n\nfunction resolveBackendName(value: string | undefined): TestHostBackendName {\n if (value === undefined) {\n return inferBackendName();\n }\n\n if (value === `colima` || value === `docker`) {\n return value;\n }\n\n throw new Error(\n `Unsupported SYSTEMD_TS_TEST_HOST_BACKEND value: ${value}. Expected \"colima\" or \"docker\".`,\n );\n}\n\nfunction defaultDockerContainerName(): string {\n const digest = createHash(`sha256`).update(repoRoot).digest(`hex`).slice(0, 12);\n return `systemd-ts-${digest}`;\n}\n\nfunction logTestHost(message: string): void {\n console.info(`[systemd-ts:test-host] ${message}`);\n}\n\nfunction createBackend(name: TestHostBackendName): TestHostBackend {\n switch (name) {\n case `colima`:\n return new ColimaBackend();\n case `docker`:\n return new DockerBackend();\n }\n}\n\nclass ColimaBackend implements TestHostBackend {\n public readonly info: TestHostInfo = {\n backend: `colima`,\n colimaHome,\n colimaProfile,\n limaHome,\n repoRoot,\n stateRoot: colimaHome,\n };\n\n public async ensureHost(): Promise<void> {\n if (await this.isRunning()) {\n return;\n }\n\n console.info(`Starting repo-local Colima host for integration tests...`);\n await this.execColima([\n `start`,\n `--cpu`,\n `2`,\n `--memory`,\n `4`,\n `--disk`,\n `30`,\n `--runtime`,\n `containerd`,\n ]);\n }\n\n public createGuestShellProcess(): ChildProcessWithoutNullStreams {\n return spawn(`colima`, [`ssh`, `--`, `bash`, `--noprofile`, `--norc`, `-s`], {\n env: this.hostEnv,\n stdio: [`pipe`, `pipe`, `pipe`],\n });\n }\n\n public async runIsolatedCommand(script: string): Promise<string> {\n return this.execColima([`ssh`, `--`, `bash`, `-lc`, script]);\n }\n\n private readonly hostEnv = {\n ...process.env,\n COLIMA_HOME: colimaHome,\n COLIMA_PROFILE: colimaProfile,\n LIMA_HOME: limaHome,\n };\n\n private async isRunning(): Promise<boolean> {\n try {\n const status = await this.execColima([`status`]);\n return status.includes(`is running`);\n } catch {\n return false;\n }\n }\n\n private async execColima(args: readonly string[]): Promise<string> {\n const result = await execFileAsync(`colima`, args, {\n env: this.hostEnv,\n maxBuffer: commandMaxBufferBytes,\n });\n return mergeOutput(result.stdout, result.stderr);\n }\n}\n\nclass DockerBackend implements TestHostBackend {\n public readonly info: TestHostInfo = {\n backend: `docker`,\n repoRoot,\n stateRoot: dockerStateRoot,\n };\n\n private runtimeInfo:\n | {\n readonly home: string;\n readonly runtimeDir: string;\n readonly userId: number;\n }\n | undefined;\n\n public async ensureHost(): Promise<void> {\n logTestHost(`Building Docker test host image ${dockerImage}`);\n await this.execDocker(\n [`build`, `--quiet`, `--tag`, dockerImage, `--file`, dockerfilePath, repoRoot],\n { timeout: dockerBuildTimeoutMs },\n );\n logTestHost(`Docker test host image ready`);\n\n if (!(await this.isContainerRunning())) {\n await this.removeExistingContainer();\n logTestHost(`Starting Docker test host container ${dockerContainer}`);\n await this.execDocker([\n `run`,\n `--detach`,\n `--name`,\n dockerContainer,\n `--hostname`,\n `systemd-ts-test-host`,\n `--privileged`,\n `--cgroupns=host`,\n `--tmpfs`,\n `/run`,\n `--tmpfs`,\n `/run/lock`,\n `--volume`,\n `/sys/fs/cgroup:/sys/fs/cgroup:rw`,\n `--volume`,\n `${repoRoot}:${repoRoot}`,\n `--volume`,\n `${dockerStateRoot}:${dockerStateRoot}`,\n `--workdir`,\n repoRoot,\n dockerImage,\n ]);\n logTestHost(`Docker test host container started`);\n } else {\n logTestHost(`Reusing running Docker test host container ${dockerContainer}`);\n }\n\n await this.ensureUserSession();\n }\n\n public createGuestShellProcess(): ChildProcessWithoutNullStreams {\n const runtimeInfo = this.requireRuntimeInfo();\n return spawn(\n `docker`,\n [\n `exec`,\n `--interactive`,\n `--user`,\n dockerUser,\n `--env`,\n `HOME=${runtimeInfo.home}`,\n `--env`,\n `XDG_RUNTIME_DIR=${runtimeInfo.runtimeDir}`,\n `--env`,\n `DBUS_SESSION_BUS_ADDRESS=unix:path=${runtimeInfo.runtimeDir}/bus`,\n dockerContainer,\n `bash`,\n `--noprofile`,\n `--norc`,\n `-s`,\n ],\n {\n stdio: [`pipe`, `pipe`, `pipe`],\n },\n );\n }\n\n public async runIsolatedCommand(script: string): Promise<string> {\n const runtimeInfo = this.requireRuntimeInfo();\n const result = await this.execDockerAsUser(runtimeInfo, [`bash`, `-lc`, script]);\n\n return mergeOutput(result.stdout, result.stderr);\n }\n\n private async isContainerRunning(): Promise<boolean> {\n try {\n const status = await this.execDocker([\n `inspect`,\n `--format`,\n `{{.State.Running}}`,\n dockerContainer,\n ]);\n return status.trim() === `true`;\n } catch {\n return false;\n }\n }\n\n private async removeExistingContainer(): Promise<void> {\n try {\n await this.execDocker([`rm`, `--force`, dockerContainer]);\n } catch {\n // Ignore missing containers so the first run can proceed.\n }\n }\n\n private async ensureUserSession(): Promise<void> {\n const runtimeInfo = await this.resolveRuntimeInfo();\n logTestHost(\n `Ensuring user session for ${dockerUser} (uid=${runtimeInfo.userId}, home=${runtimeInfo.home})`,\n );\n await this.execDocker(\n [\n `exec`,\n dockerContainer,\n `bash`,\n `-lc`,\n [\n `mkdir -p ${shellQuote(dockerStateRoot)}`,\n `chown ${runtimeInfo.userId}:${runtimeInfo.userId} ${shellQuote(dockerStateRoot)}`,\n `loginctl enable-linger ${shellQuote(dockerUser)}`,\n `systemctl start user@${runtimeInfo.userId}.service`,\n ].join(`\\n`),\n ],\n { timeout: dockerExecTimeoutMs },\n );\n await this.execDockerAsUser(runtimeInfo, [\n `bash`,\n `-lc`,\n `mkdir -p ${shellQuote(`${dockerStateRoot}/tests`)}`,\n ]);\n logTestHost(`User session started for ${dockerUser}`);\n }\n\n private async execDocker(\n args: readonly string[],\n options?: {\n readonly timeout?: number;\n },\n ): Promise<string> {\n const result = await execFileAsync(`docker`, args, {\n maxBuffer: commandMaxBufferBytes,\n timeout: options?.timeout,\n });\n return mergeOutput(result.stdout, result.stderr);\n }\n\n private execDockerAsUser(\n runtimeInfo: {\n readonly home: string;\n readonly runtimeDir: string;\n readonly userId: number;\n },\n command: readonly string[],\n ) {\n return execFileAsync(\n `docker`,\n [\n `exec`,\n `--user`,\n dockerUser,\n `--env`,\n `HOME=${runtimeInfo.home}`,\n `--env`,\n `XDG_RUNTIME_DIR=${runtimeInfo.runtimeDir}`,\n `--env`,\n `DBUS_SESSION_BUS_ADDRESS=unix:path=${runtimeInfo.runtimeDir}/bus`,\n dockerContainer,\n ...command,\n ],\n { maxBuffer: commandMaxBufferBytes },\n );\n }\n\n private requireRuntimeInfo(): {\n readonly home: string;\n readonly runtimeDir: string;\n readonly userId: number;\n } {\n if (this.runtimeInfo === undefined) {\n throw new Error(`Docker test host runtime info is unavailable before ensureHost() completes`);\n }\n\n return this.runtimeInfo;\n }\n\n private async resolveRuntimeInfo(): Promise<{\n readonly home: string;\n readonly runtimeDir: string;\n readonly userId: number;\n }> {\n if (this.runtimeInfo !== undefined) {\n return this.runtimeInfo;\n }\n\n const userId =\n dockerConfiguredUserId === undefined\n ? await this.lookupUserId()\n : Number(dockerConfiguredUserId);\n const home = await this.lookupUserHome();\n\n this.runtimeInfo = {\n home,\n runtimeDir: `/run/user/${userId}`,\n userId,\n };\n\n return this.runtimeInfo;\n }\n\n private async lookupUserHome(): Promise<string> {\n logTestHost(`Resolving home directory for Docker test user ${dockerUser}`);\n const output = await this.execDocker([\n `exec`,\n dockerContainer,\n `bash`,\n `-lc`,\n `getent passwd ${shellQuote(dockerUser)} | cut -d: -f6`,\n ]);\n\n const home = output.trim();\n if (home.length === 0) {\n throw new Error(`Could not resolve home directory for Docker test user ${dockerUser}`);\n }\n\n logTestHost(`Resolved home directory for ${dockerUser}: ${home}`);\n return home;\n }\n\n private async lookupUserId(): Promise<number> {\n logTestHost(`Resolving uid for Docker test user ${dockerUser}`);\n const output = await this.execDocker([\n `exec`,\n dockerContainer,\n `bash`,\n `-lc`,\n `id -u ${shellQuote(dockerUser)}`,\n ]);\n\n const parsed = Number(output.trim());\n if (!Number.isInteger(parsed)) {\n throw new Error(`Could not resolve uid for Docker test user ${dockerUser}`);\n }\n\n logTestHost(`Resolved uid for ${dockerUser}: ${parsed}`);\n return parsed;\n }\n}\n\nclass GuestShell {\n private readonly process: ChildProcessWithoutNullStreams;\n private readonly onExitCleanup: () => void;\n private closed = false;\n private buffer = ``;\n private current:\n | {\n marker: string;\n timeoutId: NodeJS.Timeout | undefined;\n reject: (error: Error) => void;\n resolve: (output: string) => void;\n }\n | undefined;\n private readonly queue: Array<{\n script: string;\n reject: (error: Error) => void;\n resolve: (output: string) => void;\n timeoutMs: number | undefined;\n }> = [];\n\n public constructor(\n createProcess: () => ChildProcessWithoutNullStreams,\n onExitCleanup: () => void,\n ) {\n this.process = createProcess();\n this.onExitCleanup = onExitCleanup;\n this.process.stdout.setEncoding(`utf8`);\n this.process.stderr.setEncoding(`utf8`);\n this.process.stdout.on(`data`, (chunk: string) => this.onData(chunk));\n this.process.stderr.on(`data`, (chunk: string) => this.onData(chunk));\n this.process.on(`exit`, (code, signal) => {\n const reason = new Error(\n `Persistent guest shell exited unexpectedly (code=${code ?? `null`}, signal=${signal ?? `null`})`,\n );\n this.failCurrent(reason);\n while (this.queue.length > 0) {\n this.queue.shift()?.reject(reason);\n }\n this.onExitCleanup();\n });\n\n process.once(`exit`, () => {\n this.process.kill();\n });\n }\n\n public run(script: string, timeoutMs?: number): Promise<string> {\n return new Promise((resolve, reject) => {\n this.queue.push({ script, resolve, reject, timeoutMs });\n this.drain();\n });\n }\n\n public close(): void {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.process.kill();\n }\n\n private drain(): void {\n if (this.current !== undefined) {\n return;\n }\n\n const next = this.queue.shift();\n if (next === undefined) {\n return;\n }\n\n const marker = `__SYSTEMD_TS_END_${randomUUID()}__`;\n const timeoutId =\n next.timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n if (this.current?.marker !== marker) {\n return;\n }\n\n const reason = new Error(`Guest command timed out after ${next.timeoutMs}ms`);\n this.failCurrent(reason);\n this.close();\n }, next.timeoutMs);\n this.current = {\n marker,\n timeoutId,\n reject: next.reject,\n resolve: next.resolve,\n };\n\n this.buffer = ``;\n const command = `(\n${next.script}\n) 2>&1\nstatus=$?\nprintf '\\\\n${marker}:%s\\\\n' \"$status\"\n`;\n\n this.process.stdin.write(command);\n }\n\n private failCurrent(error: Error): void {\n const current = this.current;\n this.current = undefined;\n if (current?.timeoutId !== undefined) {\n clearTimeout(current.timeoutId);\n }\n current?.reject(error);\n }\n\n private onData(chunk: string): void {\n if (this.current === undefined) {\n return;\n }\n\n this.buffer += chunk;\n const markerIndex = this.buffer.indexOf(this.current.marker);\n if (markerIndex === -1) {\n return;\n }\n\n const output = this.buffer.slice(0, markerIndex).replace(/\\n$/, ``);\n const statusMatch = this.buffer\n .slice(markerIndex)\n .match(/^__SYSTEMD_TS_END_[^:]+__:(\\d+)\\r?\\n?/u);\n\n if (statusMatch === null) {\n return;\n }\n\n const status = Number(statusMatch[1]);\n const remainder = this.buffer.slice(markerIndex + statusMatch[0].length);\n const current = this.current;\n this.current = undefined;\n this.buffer = remainder;\n if (current.timeoutId !== undefined) {\n clearTimeout(current.timeoutId);\n }\n\n if (status === 0) {\n current.resolve(output);\n } else {\n current.reject(new Error(output.length > 0 ? output : `Guest command failed`));\n }\n\n this.drain();\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(`'`, `'\\\\''`)}'`;\n}\n\nconst backend = createBackend(selectedBackendName);\n","import { randomUUID } from \"node:crypto\";\n\nimport { getTestHostInfo, runGuestCommand } from \"./host.ts\";\n\nexport interface TestSandbox {\n readonly id: string;\n readonly linkedUnitDir: string;\n readonly namePrefix: string;\n readonly rootDir: string;\n readonly workDir: string;\n}\n\nexport interface DestroyTestSandboxOptions {\n readonly noisy?: boolean;\n}\n\nlet currentSandbox: TestSandbox | undefined;\n\nexport async function createTestSandbox(testName?: string): Promise<TestSandbox> {\n const id = randomUUID().slice(0, 8);\n const slug = slugify(testName ?? `sandbox`);\n const namePrefix = `systemd-ts-${slug}-${id}`;\n const rootDir = `${getTestHostInfo().stateRoot}/tests/${namePrefix}`;\n const linkedUnitDir = `${rootDir}/linked-units`;\n const workDir = `${rootDir}/work`;\n\n await runGuestCommand(\n `set -euo pipefail\nrm -rf ${shellQuote(rootDir)}\nmkdir -p ${shellQuote(linkedUnitDir)} ${shellQuote(workDir)}`,\n );\n\n currentSandbox = {\n id,\n linkedUnitDir,\n namePrefix,\n rootDir,\n workDir,\n };\n\n return currentSandbox;\n}\n\nexport async function destroyCurrentTestSandbox(): Promise<void> {\n if (currentSandbox === undefined) {\n return;\n }\n\n const sandbox = currentSandbox;\n currentSandbox = undefined;\n\n const unitsOutput = await runGuestCommand(\n `systemctl --user list-unit-files --all --no-legend ${shellQuote(`${sandbox.namePrefix}*`)} 2>/dev/null | awk '{print $1}' || true`,\n );\n\n const units = unitsOutput\n .split(`\\n`)\n .map((unit) => unit.trim())\n .filter((unit) => unit.length > 0);\n\n if (units.length > 0) {\n await runGuestCommand(`systemctl --user stop ${units.map(shellQuote).join(` `)} || true`);\n\n await runGuestCommand(`systemctl --user disable ${units.map(shellQuote).join(` `)} || true`);\n\n await runGuestCommand(\n `systemctl --user reset-failed ${units.map(shellQuote).join(` `)} || true`,\n );\n }\n\n await runGuestCommand(`systemctl --user daemon-reload || true`);\n\n await runGuestCommand(`rm -rf ${shellQuote(sandbox.rootDir)}`);\n}\n\nexport function useCurrentTestSandbox(): TestSandbox {\n if (currentSandbox === undefined) {\n throw new Error(`No active test sandbox is available`);\n }\n\n return currentSandbox;\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(`'`, `'\\\\''`)}'`;\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, `-`)\n .replaceAll(/^-+|-+$/g, ``)\n .slice(0, 32);\n}\n","import {\n Systemd,\n type CommandExecutionOptions,\n type CommandExecutor,\n type CommandOutput,\n} from \"../main/index.ts\";\n\nimport { runGuestCommand, runIsolatedGuestCommand } from \"./host.ts\";\nimport { useCurrentTestSandbox } from \"./sandbox.ts\";\n\n/**\n * Creates a command executor that runs argv-style commands inside the current\n * test host guest shell.\n */\nexport function createGuestCommandExecutor(\n runCommand: (script: string) => Promise<string>,\n): CommandExecutor {\n return async (\n command: string,\n args: readonly string[],\n options: CommandExecutionOptions = {},\n ): Promise<CommandOutput> => {\n try {\n const stdout = await runCommand(buildGuestCommand(command, args, options));\n return {\n stderr: ``,\n stdout,\n };\n } catch (cause) {\n throw enrichGuestCommandError(cause);\n }\n };\n}\n\n/**\n * Executor that reuses the warm guest shell for fast sandbox-backed tests.\n */\nexport const guestCommandExecutor = createGuestCommandExecutor(runGuestCommand);\n\n/**\n * Executor that runs each guest command in a fresh isolated guest shell.\n */\nexport const isolatedGuestCommandExecutor = createGuestCommandExecutor(runIsolatedGuestCommand);\n\n/**\n * Creates a `Systemd` instance scoped to the active test sandbox and backed by\n * the warm guest-shell executor.\n */\nexport function sandboxSystemd(): Systemd {\n const sandbox = useCurrentTestSandbox();\n return new Systemd({\n executor: guestCommandExecutor,\n linkUnits: true,\n scope: `user`,\n unitDir: sandbox.linkedUnitDir,\n });\n}\n\n/**\n * Creates a `Systemd` instance scoped to the active test sandbox and backed by\n * a fresh guest shell per command.\n */\nexport function isolatedSandboxSystemd(): Systemd {\n const sandbox = useCurrentTestSandbox();\n return new Systemd({\n executor: isolatedGuestCommandExecutor,\n linkUnits: true,\n scope: `user`,\n unitDir: sandbox.linkedUnitDir,\n });\n}\n\nfunction buildGuestCommand(\n command: string,\n args: readonly string[],\n options: CommandExecutionOptions,\n): string {\n const envArgs =\n options.env === undefined\n ? []\n : Object.entries(options.env).flatMap(([key, value]) =>\n value === undefined ? [`-u`, key] : [`${key}=${value}`],\n );\n\n return [`env`, ...envArgs, command, ...args].map((part) => shellQuote(part)).join(` `);\n}\n\nfunction enrichGuestCommandError(cause: unknown): Error {\n if (cause instanceof Error) {\n return Object.assign(cause, {\n code: 1,\n stderr: ``,\n stdout: cause.message,\n });\n }\n\n return Object.assign(new Error(`Guest command failed`), {\n code: 1,\n stderr: ``,\n stdout: ``,\n });\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(`'`, `'\\\\''`)}'`;\n}\n"],"mappings":";;;;;;;AAMA,MAAM,gBAAgB,UAAU,SAAS;AACzC,MAAM,wBAAwB,KAAK,OAAO;AAC1C,MAAM,uBA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gB,yBAAkC;AAEhD,QAAO,IAAI,QAAQ;EACjB,UAAU;EACV,WAAW;EACX,OAAO;EACP,SALc,uBAKE,CAAC;EAClB,CAAC;;AAGJ,SAAS,kBACP,SACA,MACA,SACQ;AAQR,QAAO;EAAC;EAAO,GANb,QAAQ,QAAQ,KAAA,IACZ,EAAE,GACF,OAAO,QAAQ,QAAQ,IAAI,CAAC,SAAS,CAAC,KAAK,WACzC,UAAU,KAAA,IAAY,CAAC,MAAM,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,QAAQ,CACxD;EAEoB;EAAS,GAAG;EAAK,CAAC,KAAK,SAAS,WAAW,KAAK,CAAC,CAAC,KAAK,IAAI;;AAGxF,SAAS,wBAAwB,OAAuB;AACtD,KAAI,iBAAiB,MACnB,QAAO,OAAO,OAAO,OAAO;EAC1B,MAAM;EACN,QAAQ;EACR,QAAQ,MAAM;EACf,CAAC;AAGJ,QAAO,OAAO,uBAAO,IAAI,MAAM,uBAAuB,EAAE;EACtD,MAAM;EACN,QAAQ;EACR,QAAQ;EACT,CAAC;;AAGJ,SAAS,WAAW,OAAuB;AACzC,QAAO,IAAI,MAAM,WAAW,KAAK,QAAQ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "systemd-ts",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "TypeScript builders and helpers for systemd services and timers.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -9,7 +9,8 @@
9
9
  "directory": "packages/systemd-ts"
10
10
  },
11
11
  "files": [
12
- "dist"
12
+ "dist",
13
+ "src"
13
14
  ],
14
15
  "type": "module",
15
16
  "exports": {
@@ -22,7 +23,7 @@
22
23
  },
23
24
  "devDependencies": {
24
25
  "@types/node": "25.6.2",
25
- "@typescript/native-preview": "7.0.0-dev.20260510.1",
26
+ "@typescript/native-preview": "7.0.0-dev.20260511.1",
26
27
  "takua": "0.1.1",
27
28
  "typescript": "6.0.3",
28
29
  "vite-plus": "0.1.20"