systemd-ts 261.2.1 → 261.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -387,7 +387,7 @@ interface SystemdUnitSection extends CustomDirectiveSection {
387
387
  readonly Description?: string;
388
388
  /** A space-separated list of URIs referencing documentation for this unit or its configuration. Accepted are only URIs of the types http://, https://, file:, info:, man:. For more information about the syntax of these URIs, see uri(7). The URIs should be listed in order of relevance, starting with the most relevant. It is a good idea to first reference documentation that explains what the unit's purpose is, followed by how it is configured, followed by any other related documentation. This option may be specified more than once, in which case the specified list of URIs is merged. If the empty string is assigned to this option, the list is reset and all prior assignments will have no effect. Source: systemd v260.1, `systemd.unit(5)`. */
389
389
  readonly Documentation?: string | readonly string[];
390
- /** Action to take when the unit stops in a failed state. Source: systemd v260.1, `systemd.unit(5)`. */
390
+ /** Action to take when the unit stops in a failed state. For `exit` and `exit-force`, the manager returns the main process exit status, or 255 if none is available, unless overridden by `FailureActionExitStatus=`. Source: systemd v261.3, `systemd.unit(5)`. */
391
391
  readonly FailureAction?: UnitActionDirectiveValue;
392
392
  /** Exit status to propagate when `FailureAction=` triggers `exit` or `exit-force`. Source: systemd v260.1, `systemd.unit(5)`. */
393
393
  readonly FailureActionExitStatus?: string | number;
@@ -443,7 +443,7 @@ interface SystemdUnitSection extends CustomDirectiveSection {
443
443
  readonly StopPropagatedFrom?: string | readonly string[];
444
444
  /** If true, this unit will be stopped when it is no longer used. Note that, in order to minimize the work to be executed, systemd will not stop units by default unless they are conflicting with other units, or the user explicitly requested their shut down. If this option is set, a unit will be automatically cleaned up if no other active unit requires it. Defaults to false. Source: systemd v260.1, `systemd.unit(5)`. */
445
445
  readonly StopWhenUnneeded?: boolean;
446
- /** Action to take when the unit stops in an inactive state. Source: systemd v260.1, `systemd.unit(5)`. */
446
+ /** Action to take when the unit stops in an inactive state. For `exit` and `exit-force`, the manager returns the main process exit status, or leaves its exit status unchanged if none is available, unless overridden by `SuccessActionExitStatus=`. Source: systemd v261.3, `systemd.unit(5)`. */
447
447
  readonly SuccessAction?: UnitActionDirectiveValue;
448
448
  /** Exit status to propagate when `SuccessAction=` triggers `exit` or `exit-force`. Source: systemd v260.1, `systemd.unit(5)`. */
449
449
  readonly SuccessActionExitStatus?: string | number;
@@ -907,7 +907,7 @@ interface SystemdServiceSection extends CustomDirectiveSection {
907
907
  readonly RestrictNetworkInterfaces?: string | readonly string[];
908
908
  /** If set, any attempts to enable realtime scheduling in a process of the unit are refused. This restricts access to realtime task scheduling policies such as SCHED_FIFO, SCHED_RR or SCHED_DEADLINE. See sched7 for details about these scheduling policies. Realtime scheduling policies may be used to monopolize CPU time for longer periods of time, and may hence be used to lock up or otherwise trigger Denial-of-Service situations on the system. It is hence recommended to restrict access to realtime scheduling to the few programs that actually require them. Defaults to off. Source: systemd v260.1, `systemd.exec(5)`. */
909
909
  readonly RestrictRealtime?: boolean;
910
- /** If set, any attempts to set the set-user-ID (SUID) or set-group-ID (SGID) bits on files or directories will be denied (for details on these bits see inode7). As the SUID/SGID bits are mechanisms to elevate privileges, and allow users to acquire the identity of other users, it is recommended to restrict creation of SUID/SGID files to the few programs that actually require them. Note that this restricts marking of any type of file system object with these bits, including both regular files and directories (where the SGID is a different meaning than for files, see documentation). This option is implied if DynamicUser= is enabled. Source: systemd v260.1, `systemd.exec(5)`. */
910
+ /** If set, any attempts to set the set-user-ID (SUID) or set-group-ID (SGID) bits on files or directories will be denied (for details on these bits see inode7). As the SUID/SGID bits are mechanisms to elevate privileges, and allow users to acquire the identity of other users, it is recommended to restrict creation of SUID/SGID files to the few programs that actually require them. Note that this restricts marking of any type of file system object with these bits, including both regular files and directories (where the SGID is a different meaning than for files, see documentation). This option is implied if DynamicUser= is enabled. Seccomp blocks calls with directly supplied mode bits only when SUID or SGID is requested, but blocks calls such as openat2() entirely because their mode bits cannot be inspected. Source: systemd v261.3, `systemd.exec(5)`. */
911
911
  readonly RestrictSUIDSGID?: boolean;
912
912
  /** Takes a directory path relative to the host's root directory (i.e. the root of the system running the service manager). Sets the root directory for executed processes, with the pivot_root2 or chroot2 system call. If this is used, it must be ensured that the process binary and all its auxiliary files are available in the new root. Note that setting this parameter might result in additional dependencies to be added to the unit (see above). Source: systemd v260.1, `systemd.exec(5)`. */
913
913
  readonly RootDirectory?: string;
@@ -963,15 +963,15 @@ interface SystemdServiceSection extends CustomDirectiveSection {
963
963
  readonly SocketBindDeny?: string | readonly string[];
964
964
  /** Specifies the name of the socket units this service shall inherit socket file descriptors from when the service is started. Normally, it should not be necessary to use this setting, as all socket file descriptors whose unit shares the same name as the service (subject to the different unit name suffix of course) are passed to the spawned process. Source: systemd v260.1, `systemd.service(5)`. */
965
965
  readonly Sockets?: string | readonly string[];
966
- /** Controls where file descriptor 2 (stderr) of the executed processes is connected to. The available options are identical to those of StandardOutput=, with some exceptions: if set to inherit the file descriptor used for standard output is duplicated for standard error, while fd:name will use a default file descriptor name of stderr. Source: systemd v260.1, `systemd.exec(5)`. */
966
+ /** Controls where file descriptor 2 (stderr) of the executed processes is connected to. The available options are identical to those of StandardOutput=, with some exceptions: if set to inherit the file descriptor used for standard output is duplicated for standard error, while fd:name will use a default file descriptor name of stderr. File paths are opened by the service manager before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
967
967
  readonly StandardError?: StandardErrorDirectiveValue;
968
- /** Controls where file descriptor 0 (STDIN) of the executed processes is connected to. Takes one of null, tty, tty-force, tty-fail, data, file:path, socket or fd:name. Source: systemd v260.1, `systemd.exec(5)`. */
968
+ /** Controls where file descriptor 0 (STDIN) of the executed processes is connected to. Takes one of null, tty, tty-force, tty-fail, data, file:path, socket or fd:name. For file:path, the service manager opens the path before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
969
969
  readonly StandardInput?: StandardInputDirectiveValue;
970
970
  /** Configures arbitrary textual or binary data to pass via file descriptor 0 (STDIN) to the executed processes. These settings have no effect unless StandardInput= is set to data (which is the default if StandardInput= is not set otherwise, but StandardInputText=/StandardInputData= is). Use this option to embed process input data directly in the unit file. Source: systemd v260.1, `systemd.exec(5)`. */
971
971
  readonly StandardInputData?: string | readonly string[];
972
972
  /** Configures arbitrary textual or binary data to pass via file descriptor 0 (STDIN) to the executed processes. These settings have no effect unless StandardInput= is set to data (which is the default if StandardInput= is not set otherwise, but StandardInputText=/StandardInputData= is). Use this option to embed process input data directly in the unit file. Source: systemd v260.1, `systemd.exec(5)`. */
973
973
  readonly StandardInputText?: string | readonly string[];
974
- /** Controls where file descriptor 1 (stdout) of the executed processes is connected to. Takes one of inherit, null, tty, journal, kmsg, journal+console, kmsg+console, file:path, append:path, truncate:path, socket or fd:name. Source: systemd v260.1, `systemd.exec(5)`. */
974
+ /** Controls where file descriptor 1 (stdout) of the executed processes is connected to. Takes one of inherit, null, tty, journal, kmsg, journal+console, kmsg+console, file:path, append:path, truncate:path, socket or fd:name. For file:path, append:path, and truncate:path, the service manager opens the path before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
975
975
  readonly StandardOutput?: StandardOutputDirectiveValue;
976
976
  /** This setting controls the cpuset controller in the unified hierarchy. Source: systemd v260.1, `systemd.resource-control(5)`. */
977
977
  readonly StartupAllowedCPUs?: string;
@@ -1059,7 +1059,7 @@ interface SystemdServiceSection extends CustomDirectiveSection {
1059
1059
  readonly USBFunctionDescriptors?: string;
1060
1060
  /** Configure the location of a file containing USB FunctionFS strings. Behavior is similar to USBFunctionDescriptors= above. Source: systemd v260.1, `systemd.service(5)`. */
1061
1061
  readonly USBFunctionStrings?: string;
1062
- /** Explicitly unset environment variable assignments that would normally be passed from the service manager to invoked processes of this unit. Takes a space-separated list of variable names or variable assignments. This option may be specified more than once, in which case all listed variables/assignments will be unset. If the empty string is assigned to this option, the list of environment variables/assignments to unset is reset. If a variable assignment is specified (that is: a variable name, followed by =, followed by its value), then any environment variable matching this precise assignment is removed. If a variable name is specified (that is a variable name without any following = or value), then any assignment matching the variable name, regardless of its value is removed. Note that the effect of UnsetEnvironment= is applied as final step when the environment list passed to executed processes is compiled. That means it may undo assignments from any configuration source, including assignments made through Environment= or EnvironmentFile=, inherited from the system manager's global set of environment variables, inherited via PassEnvironment=, set by the service manager itself (such as $NOTIFY_SOCKET and such), or set by a PAM module (in case PAMName= is used). Source: systemd v260.1, `systemd.exec(5)`. */
1062
+ /** Explicitly unset environment variable assignments that would normally be passed from the service manager to invoked processes of this unit. Takes a space-separated list of variable names or variable assignments. This option may be specified more than once, in which case all listed variables/assignments will be unset. If the empty string is assigned to this option, the list of environment variables/assignments to unset is reset. If a variable assignment is specified (that is: a variable name, followed by =, followed by its value), then any environment variable matching this precise assignment is removed. If a variable name is specified (that is a variable name without any following = or value), then any assignment matching the variable name, regardless of its value is removed. Note that the effect of UnsetEnvironment= is applied as final step when the environment list passed to executed processes is compiled. That means it may undo assignments from any configuration source, including assignments made through Environment= or EnvironmentFile=, inherited from the system manager's global set of environment variables, inherited via PassEnvironment=, set by the service manager itself (such as $NOTIFY_SOCKET and such), or set by a PAM module (in case PAMName= is used). Command-line variable expansion in ExecStart= and related directives happens before this removal and is unaffected. Source: systemd v261.3, `systemd.exec(5)`. */
1063
1063
  readonly UnsetEnvironment?: string | readonly string[];
1064
1064
  /** Set the UNIX user or group that the processes are executed as, respectively. Takes a single user or group name, or a numeric ID as argument. For system services (services run by the system service manager, i.e. managed by PID 1) and for user services of the root user (services managed by root's instance of systemd --user), the default is root, but this directive may be used to specify a different identity. For user services of any other user, switching user identity is not permitted, hence the only valid setting is the same user the user's service manager is running as. If no group is set, the default group of the user is used. This setting does not affect commands whose command line is prefixed with +. Source: systemd v260.1, `systemd.exec(5)`. */
1065
1065
  readonly User?: string;
@@ -1632,4 +1632,4 @@ declare function defaultSystemd(): Systemd;
1632
1632
  declare const Internal: typeof internal_d_exports;
1633
1633
  //#endregion
1634
1634
  export { SystemdServiceOptions as $, CommandExecutionOptions as A, SystemctlActiveState as B, UnitLogsReadError as C, UnitStartError as D, UnitMaterializationErrorReason as E, MaterializedUnit as F, SystemctlOptions as G, SystemctlIsEnabledOptions as H, NotifyOptions as I, SystemctlStateQueryOptions as J, SystemctlServiceStatus as K, ServiceBaseName as L, CommandOutput as M, ExecutableOptions as N, AnySystemdService as O, LogsOptions as P, SystemdOptions as Q, ServiceFilename as R, UnitEnableError as S, UnitMaterializationError as T, SystemctlIsSystemRunningOptions as U, SystemctlEnablementState as V, SystemctlListTimersOptions as W, SystemctlSystemRunningState as X, SystemctlStatusOptions as Y, SystemctlTimerListEntry as Z, NotifySendErrorReason as _, SystemdTsAttachOptions as a, TimerTargetUnit as at, SystemdCommandEnvironmentReason as b, SystemdTsDetachOptions as c, SystemdTimer as ct, Systemctl as d, defineExecutable as dt, SystemdTimerOptions as et, notify as f, Result as ft, NotifySendError as g, NoUnitsProvidedError as h, SystemdTs as i, TimerTargetServiceName as it, CommandExecutor as j, AnySystemdTimer as k, SystemdTsReattachOptions as l, SystemdService as lt, InvalidExecDirectiveError as m, Systemd as n, TimerBaseName as nt, SystemdTsAttachmentResult as o, UnitValue as ot, ExecutableInferenceError as p, SystemctlShowOptions as q, SystemdMaterialization as r, TimerFilename as rt, SystemdTsAttachmentSelector as s, ValidInstallUnits as st, Internal as t, SystemdUnit as tt, defaultSystemd as u, Executable as ut, SystemctlCommandError as v, UnitLogsReadErrorReason as w, SystemdTsError as x, SystemctlCommandErrorReason as y, StartStatus as z };
1635
- //# sourceMappingURL=index-gV6lNweL.d.mts.map
1635
+ //# sourceMappingURL=index-6lsBWH4h.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-6lsBWH4h.d.mts","names":[],"sources":["../src/main/internal.ts","../src/main/executable.ts","../src/main/systemd-service.ts","../src/main/systemd-timer.ts","../src/main/types.ts","../src/main/errors.ts","../src/main/notify.ts","../src/main/systemctl.ts","../src/main/systemd.ts","../src/main/index.ts"],"mappings":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;KAEX;EA+CJ,SACE,gBAAgB,eAChB,SAAS,2BACR,QACD,OACE,2BACE,2BACA,4BACA,uBACA,kBACA,2BACA,iBACA;UA0FQ;UA0BA;UAiDA;UAMN;UAIM;UASA;UAQA;UAIN;UAIM;;;;;;;;iBAyCA,kBAAkB;;;;;;;cCl2BrB,iBAAiB"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as SystemdServiceOptions, A as CommandExecutionOptions, B as SystemctlActiveState, C as UnitLogsReadError, D as UnitStartError, E as UnitMaterializationErrorReason, F as MaterializedUnit, G as SystemctlOptions, H as SystemctlIsEnabledOptions, I as NotifyOptions, J as SystemctlStateQueryOptions, K as SystemctlServiceStatus, L as ServiceBaseName, M as CommandOutput, N as ExecutableOptions, O as AnySystemdService, P as LogsOptions, Q as SystemdOptions, R as ServiceFilename, S as UnitEnableError, T as UnitMaterializationError, U as SystemctlIsSystemRunningOptions, V as SystemctlEnablementState, W as SystemctlListTimersOptions, X as SystemctlSystemRunningState, Y as SystemctlStatusOptions, Z as SystemctlTimerListEntry, _ as NotifySendErrorReason, a as SystemdTsAttachOptions, at as TimerTargetUnit, b as SystemdCommandEnvironmentReason, c as SystemdTsDetachOptions, ct as SystemdTimer, d as Systemctl, dt as defineExecutable, et as SystemdTimerOptions, f as notify, ft as Result, g as NotifySendError, h as NoUnitsProvidedError, i as SystemdTs, it as TimerTargetServiceName, j as CommandExecutor, k as AnySystemdTimer, l as SystemdTsReattachOptions, lt as SystemdService, m as InvalidExecDirectiveError, n as Systemd, nt as TimerBaseName, o as SystemdTsAttachmentResult, ot as UnitValue, p as ExecutableInferenceError, q as SystemctlShowOptions, r as SystemdMaterialization, rt as TimerFilename, s as SystemdTsAttachmentSelector, st as ValidInstallUnits, t as Internal, tt as SystemdUnit, u as defaultSystemd, ut as Executable, v as SystemctlCommandError, w as UnitLogsReadErrorReason, x as SystemdTsError, y as SystemctlCommandErrorReason, z as StartStatus } from "./index-gV6lNweL.mjs";
1
+ import { $ as SystemdServiceOptions, A as CommandExecutionOptions, B as SystemctlActiveState, C as UnitLogsReadError, D as UnitStartError, E as UnitMaterializationErrorReason, F as MaterializedUnit, G as SystemctlOptions, H as SystemctlIsEnabledOptions, I as NotifyOptions, J as SystemctlStateQueryOptions, K as SystemctlServiceStatus, L as ServiceBaseName, M as CommandOutput, N as ExecutableOptions, O as AnySystemdService, P as LogsOptions, Q as SystemdOptions, R as ServiceFilename, S as UnitEnableError, T as UnitMaterializationError, U as SystemctlIsSystemRunningOptions, V as SystemctlEnablementState, W as SystemctlListTimersOptions, X as SystemctlSystemRunningState, Y as SystemctlStatusOptions, Z as SystemctlTimerListEntry, _ as NotifySendErrorReason, a as SystemdTsAttachOptions, at as TimerTargetUnit, b as SystemdCommandEnvironmentReason, c as SystemdTsDetachOptions, ct as SystemdTimer, d as Systemctl, dt as defineExecutable, et as SystemdTimerOptions, f as notify, ft as Result, g as NotifySendError, h as NoUnitsProvidedError, i as SystemdTs, it as TimerTargetServiceName, j as CommandExecutor, k as AnySystemdTimer, l as SystemdTsReattachOptions, lt as SystemdService, m as InvalidExecDirectiveError, n as Systemd, nt as TimerBaseName, o as SystemdTsAttachmentResult, ot as UnitValue, p as ExecutableInferenceError, q as SystemctlShowOptions, r as SystemdMaterialization, rt as TimerFilename, s as SystemdTsAttachmentSelector, st as ValidInstallUnits, t as Internal, tt as SystemdUnit, u as defaultSystemd, ut as Executable, v as SystemctlCommandError, w as UnitLogsReadErrorReason, x as SystemdTsError, y as SystemctlCommandErrorReason, z as StartStatus } from "./index-6lsBWH4h.mjs";
2
2
  export { type AnySystemdService, type AnySystemdTimer, type CommandExecutionOptions, type CommandExecutor, type CommandOutput, Executable, ExecutableInferenceError, type ExecutableOptions, Internal, InvalidExecDirectiveError, type LogsOptions, type MaterializedUnit, NoUnitsProvidedError, type NotifyOptions, NotifySendError, type NotifySendErrorReason, type Result, type ServiceBaseName, type ServiceFilename, type StartStatus, Systemctl, type SystemctlActiveState, SystemctlCommandError, type SystemctlCommandErrorReason, type SystemctlEnablementState, type SystemctlIsEnabledOptions, type SystemctlIsSystemRunningOptions, type SystemctlListTimersOptions, type SystemctlOptions, type SystemctlServiceStatus, type SystemctlShowOptions, type SystemctlStateQueryOptions, type SystemctlStatusOptions, type SystemctlSystemRunningState, type SystemctlTimerListEntry, Systemd, type SystemdCommandEnvironmentReason, SystemdMaterialization, type SystemdOptions, SystemdService, type SystemdServiceOptions, SystemdTimer, type SystemdTimerOptions, SystemdTs, type SystemdTsAttachOptions, type SystemdTsAttachmentResult, type SystemdTsAttachmentSelector, type SystemdTsDetachOptions, SystemdTsError, type SystemdTsReattachOptions, type SystemdUnit, type TimerBaseName, type TimerFilename, type TimerTargetServiceName, type TimerTargetUnit, UnitEnableError, UnitLogsReadError, type UnitLogsReadErrorReason, UnitMaterializationError, type UnitMaterializationErrorReason, UnitStartError, type UnitValue, type ValidInstallUnits, defaultSystemd, defineExecutable, notify };
@@ -1 +1 @@
1
- {"version":3,"file":"main-DqJ5f7Al.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,CAAC,GAClC;EACA,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvC,KAAK,OAAO;EACZ,KAAK,OAAO,IAAI,OAAO;CACzB;A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B,OAAuB;CACxD,OAAO,OAAO,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI;AACnD;AAEA,SAAS,mBAAmB,OAAyB;CACnD,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAGT,OAAQ,MAAkC,YAAY;AACxD;AAEA,eAAe,mBAAmB,MAA6B;CAC7D,MAAM,MAAM,MAAM,EAAE,WAAW,KAAK,CAAC;AACvC;;;;;;;ACn5BA,MAAa,WAAqBC"}
1
+ {"version":3,"file":"main-DqJ5f7Al.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,CAAC,GAClC;EACA,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvC,KAAK,OAAO;EACZ,KAAK,OAAO,WAAW;CACzB;AACF;AAEA,IAAa,4BAAb,cAA+C,eAAe;CAC5D;CAEA,YAAmB,WAAmB,UAAiC,CAAC,GAAG;EACzE,MACE,qCACA,GAAG,UAAU,oDACb,OACF;EACA,KAAK,YAAY;CACnB;AACF;AAEA,IAAa,uBAAb,cAA0C,eAAe;CACvD;CAEA,YAAmB,WAAmB,UAAiC,CAAC,GAAG;EACzE,MACE,gCACA,GAAG,UAAU,0CACb,OACF;EACA,KAA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AC;AACvC;;;;;;;ACn5BA,MAAa,WAAqBC"}
package/dist/test.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as CommandExecutor, n as Systemd } from "./index-gV6lNweL.mjs";
1
+ import { j as CommandExecutor, n as Systemd } from "./index-6lsBWH4h.mjs";
2
2
  //#region src/test/host.d.ts
3
3
  interface TestHostInfo {
4
4
  readonly backend: TestHostBackendName;
@@ -9,36 +9,36 @@ interface TestHostInfo {
9
9
  readonly stateRoot: string;
10
10
  }
11
11
  type TestHostBackendName = `colima` | `docker`;
12
- declare function getTestHostInfo(): TestHostInfo;
13
- declare function ensureTestHost(): Promise<TestHostInfo>;
14
- declare function closeTestHost(): void;
15
- declare function runGuestCommand(script: string): Promise<string>;
16
- declare function runIsolatedGuestCommand(script: string): Promise<string>;
12
+ export declare function getTestHostInfo(): TestHostInfo;
13
+ export declare function ensureTestHost(): Promise<TestHostInfo>;
14
+ export declare function closeTestHost(): void;
15
+ export declare function runGuestCommand(script: string): Promise<string>;
16
+ export declare function runIsolatedGuestCommand(script: string): Promise<string>;
17
17
  //#endregion
18
18
  //#region src/test/harness.d.ts
19
19
  /**
20
20
  * Creates a command executor that runs argv-style commands inside the current
21
21
  * test host guest shell.
22
22
  */
23
- declare function createGuestCommandExecutor(runCommand: (script: string) => Promise<string>): CommandExecutor;
23
+ export declare function createGuestCommandExecutor(runCommand: (script: string) => Promise<string>): CommandExecutor;
24
24
  /**
25
25
  * Executor that reuses the warm guest shell for fast sandbox-backed tests.
26
26
  */
27
- declare const guestCommandExecutor: CommandExecutor;
27
+ export declare const guestCommandExecutor: CommandExecutor;
28
28
  /**
29
29
  * Executor that runs each guest command in a fresh isolated guest shell.
30
30
  */
31
- declare const isolatedGuestCommandExecutor: CommandExecutor;
31
+ export declare const isolatedGuestCommandExecutor: CommandExecutor;
32
32
  /**
33
33
  * Creates a `Systemd` instance scoped to the active test sandbox and backed by
34
34
  * the warm guest-shell executor.
35
35
  */
36
- declare function sandboxSystemd(): Systemd;
36
+ export declare function sandboxSystemd(): Systemd;
37
37
  /**
38
38
  * Creates a `Systemd` instance scoped to the active test sandbox and backed by
39
39
  * a fresh guest shell per command.
40
40
  */
41
- declare function isolatedSandboxSystemd(): Systemd;
41
+ export declare function isolatedSandboxSystemd(): Systemd;
42
42
  //#endregion
43
43
  //#region src/test/sandbox.d.ts
44
44
  interface TestSandbox {
@@ -48,9 +48,9 @@ interface TestSandbox {
48
48
  readonly rootDir: string;
49
49
  readonly workDir: string;
50
50
  }
51
- declare function createTestSandbox(testName?: string): Promise<TestSandbox>;
52
- declare function destroyCurrentTestSandbox(): Promise<void>;
53
- declare function useCurrentTestSandbox(): TestSandbox;
51
+ export declare function createTestSandbox(testName?: string): Promise<TestSandbox>;
52
+ export declare function destroyCurrentTestSandbox(): Promise<void>;
53
+ export declare function useCurrentTestSandbox(): TestSandbox;
54
54
  //#endregion
55
- export { type TestHostInfo, type TestSandbox, closeTestHost, createGuestCommandExecutor, createTestSandbox, destroyCurrentTestSandbox, ensureTestHost, getTestHostInfo, guestCommandExecutor, isolatedGuestCommandExecutor, isolatedSandboxSystemd, runGuestCommand, runIsolatedGuestCommand, sandboxSystemd, useCurrentTestSandbox };
55
+ export type { TestHostInfo, TestSandbox };
56
56
  //# sourceMappingURL=test.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"test.d.mts","names":[],"sources":["../src/test/host.ts","../src/test/harness.ts","../src/test/sandbox.ts"],"mappings":";;UAwBiB;WACN,SAAS;WACT;WACA;WACA;WACA;WACA;;KAGN;iBAYW,mBAAmB;iBAInB,kBAAkB,QAAQ;iBAK1B;iBAIM,gBAAgB,iBAAiB;iBAKjC,wBAAwB,iBAAiB;;;;;;;iBCjD/C,2BACd,aAAa,mBAAmB,kBAC/B;;;;cAqBU,sBAAsB;;;;cAKtB,8BAA8B;;;;;iBAO3B,kBAAkB;;;;;iBAclB,0BAA0B;;;UC3DzB;WACN;WACA;WACA;WACA;WACA;;iBASW,kBAAkB,oBAAoB,QAAQ;iBAyB9C,6BAA6B;iBAgCnC,yBAAyB"}
1
+ {"version":3,"file":"test.d.mts","names":[],"sources":["../src/test/host.ts","../src/test/harness.ts","../src/test/sandbox.ts"],"mappings":";;UAwBiB;WACN,SAAS;WACT;WACA;WACA;WACA;WACA;;KAGN;wBAYW,mBAAmB;wBAInB,kBAAkB,QAAQ;wBAK1B;wBAIM,gBAAgB,iBAAiB;wBAKjC,wBAAwB,iBAAiB;;;;;;;wBCjD/C,2BACd,aAAa,mBAAmB,kBAC/B;;;;qBAqBU,sBAAsB;;;;qBAKtB,8BAA8B;;;;;wBAO3B,kBAAkB;;;;;wBAclB,0BAA0B;;;UC3DzB;WACN;WACA;WACA;WACA;WACA;;wBASW,kBAAkB,oBAAoB,QAAQ;wBAyB9C,6BAA6B;wBAgCnC,yBAAyB"}
package/dist/test.mjs CHANGED
@@ -6,10 +6,10 @@ import { createHash, randomUUID } from "node:crypto";
6
6
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
7
  //#region src/test/host.ts
8
8
  const execFileAsync = promisify(execFile);
9
- const commandMaxBufferBytes = 16 * 1024 * 1024;
10
- const dockerBuildTimeoutMs = 300 * 1e3;
11
- const dockerExecTimeoutMs = 60 * 1e3;
12
- const guestCommandTimeoutMs = 10 * 1e3;
9
+ const commandMaxBufferBytes = 16777216;
10
+ const dockerBuildTimeoutMs = 3e5;
11
+ const dockerExecTimeoutMs = 6e4;
12
+ const guestCommandTimeoutMs = 1e4;
13
13
  const repoRoot = fileURLToPath(new URL(`../../../../`, import.meta.url));
14
14
  const dockerfilePath = fileURLToPath(new URL(`./systemd-container.Dockerfile`, import.meta.url));
15
15
  const selectedBackendName = resolveBackendName(process.env[`SYSTEMD_TS_TEST_HOST_BACKEND`]);
package/dist/test.mjs.map CHANGED
@@ -1 +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: CommandExecutor = createGuestCommandExecutor(runGuestCommand);\n\n/**\n * Executor that runs each guest command in a fresh isolated guest shell.\n */\nexport const isolatedGuestCommandExecutor: CommandExecutor =\n 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,QAAQ;AACxC,MAAM,wBAAwB,KAAK,OAAO;AAC1C,MAAM,uBAAuB,MAAS;AACtC,MAAM,sBAAsB,KAAK;AACjC,MAAM,wBAAwB,KAAK;AACnC,MAAM,WAAW,cAAc,IAAI,IAAI,gBAAgB,OAAO,KAAK,GAAG,CAAC;AACvE,MAAM,iBAAiB,cAAc,IAAI,IAAI,kCAAkC,OAAO,KAAK,GAAG,CAAC;AAC/F,MAAM,sBAAsB,mBAAmB,QAAQ,IAAI,+BAA+B;AAC1F,MAAM,aAAa,QAAQ,IAAI,kBAAkB,GAAG,SAAS;AAC7D,MAAM,WAAW,QAAQ,IAAI,gBAAgB,GAAG,WAAW;AAC3D,MAAM,gBAAgB,QAAQ,IAAI,qBAAqB;AACvD,MAAM,kBAAkB,QAAQ,IAAI,g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;CACnB,CAAC;AACH;;;;;AAMA,SAAgB,yBAAkC;CAChD,MAAM,UAAU,sBAAsB;CACtC,OAAO,IAAI,QAAQ;EACjB,UAAU;EACV,WAAW;EACX,OAAO;EACP,SAAS,QAAQ;CACnB,CAAC;AACH;AAEA,SAAS,kBACP,SACA,MACA,SACQ;CAQR,OAAO;EAAC;EAAO,GANb,QAAQ,QAAQ,KAAA,IACZ,CAAC,IACD,OAAO,QAAQ,QAAQ,GAAG,CAAC,CAAC,SAAS,CAAC,KAAK,WACzC,UAAU,KAAA,IAAY,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,OAAO,CACxD;EAEqB;EAAS,GAAG;CAAI,CAAC,CAAC,KAAK,SAAS,WAAW,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AACvF;AAEA,SAAS,wBAAwB,OAAuB;CACtD,IAAI,iBAAiB,OACnB,OAAO,OAAO,OAAO,OAAO;EAC1B,MAAM;EACN,QAAQ;EACR,QAAQ,MAAM;CAChB,CAAC;CAGH,OAAO,OAAO,uBAAO,IAAI,MAAM,sBAAsB,GAAG;EACtD,MAAM;EACN,QAAQ;EACR,QAAQ;CACV,CAAC;AACH;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAC5C"}
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: CommandExecutor = createGuestCommandExecutor(runGuestCommand);\n\n/**\n * Executor that runs each guest command in a fresh isolated guest shell.\n */\nexport const isolatedGuestCommandExecutor: CommandExecutor =\n 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,QAAQ;AACxC,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,WAAW,cAAc,IAAI,IAAI,gBAAgB,YAAY,GAAG,CAAC;AACvE,MAAM,iBAAiB,cAAc,IAAI,IAAI,kCAAkC,YAAY,GAAG,CAAC;AAC/F,MAAM,sBAAsB,mBAAmB,QAAQ,IAAI,+BAA+B;AAC1F,MAAM,aAAa,QAAQ,IAAI,kBAAkB,GAAG,SAAS;AAC7D,MAAM,WAAW,QAAQ,IAAI,gBAAgB,GAAG,WAAW;AAC3D,MAAM,gBAAgB,QAAQ,IAAI,qBAAqB;AACvD,MAAM,kBAAkB,QAAQ,IAAI,gCAAgC,GAAG,SAAS;AAChF,MAAM,cAAc,QAAQ,IAAI,mCAAmC;AACnE,MAAM,aAAa,QAAQ,IAAI,kCAAkC;AACjE,MAAM,yBAAyB,QAAQ,IAAI;AAC3C,MAAM,kBACJ,QAAQ,IAAI,uCAAuC,2BAA2B;AAoBhF,IAAI;AACJ,IAAI;AAEJ,SAAgB,kBAAgC;CAC9C,OAAO,QAAQ;AACjB;AAEA,SAAgB,iBAAwC;CACtD,gBAAgB,oBAAoB;CACpC,OAAO;AACT;AAEA,SAAgB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U,KAAA,IAAY,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,OAAO,CACxD;EAEqB;EAAS,GAAG;CAAI,CAAC,CAAC,KAAK,SAAS,WAAW,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AACvF;AAEA,SAAS,wBAAwB,OAAuB;CACtD,IAAI,iBAAiB,OACnB,OAAO,OAAO,OAAO,OAAO;EAC1B,MAAM;EACN,QAAQ;EACR,QAAQ,MAAM;CAChB,CAAC;CAGH,OAAO,OAAO,uBAAO,IAAI,MAAM,sBAAsB,GAAG;EACtD,MAAM;EACN,QAAQ;EACR,QAAQ;CACV,CAAC;AACH;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAC5C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "systemd-ts",
3
- "version": "261.2.1",
3
+ "version": "261.3.0",
4
4
  "description": "TypeScript builders and helpers for systemd services and timers.",
5
5
  "license": "LGPL-2.1-or-later",
6
6
  "repository": {
@@ -22,12 +22,12 @@
22
22
  "access": "public"
23
23
  },
24
24
  "devDependencies": {
25
- "@types/node": "25.9.5",
25
+ "@types/node": "25.9.6",
26
26
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
27
- "takua": "0.2.2",
27
+ "takua": "0.2.3",
28
28
  "typescript": "7.0.2",
29
- "vite-plus": "0.2.7",
30
- "vitest": "4.1.10"
29
+ "vite-plus": "0.3.1",
30
+ "vitest": "5.0.0"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "vp pack",
package/src/main/types.ts CHANGED
@@ -312,7 +312,7 @@ export interface SystemdUnitSection extends CustomDirectiveSection {
312
312
  readonly Description?: string;
313
313
  /** A space-separated list of URIs referencing documentation for this unit or its configuration. Accepted are only URIs of the types http://, https://, file:, info:, man:. For more information about the syntax of these URIs, see uri(7). The URIs should be listed in order of relevance, starting with the most relevant. It is a good idea to first reference documentation that explains what the unit's purpose is, followed by how it is configured, followed by any other related documentation. This option may be specified more than once, in which case the specified list of URIs is merged. If the empty string is assigned to this option, the list is reset and all prior assignments will have no effect. Source: systemd v260.1, `systemd.unit(5)`. */
314
314
  readonly Documentation?: string | readonly string[];
315
- /** Action to take when the unit stops in a failed state. Source: systemd v260.1, `systemd.unit(5)`. */
315
+ /** Action to take when the unit stops in a failed state. For `exit` and `exit-force`, the manager returns the main process exit status, or 255 if none is available, unless overridden by `FailureActionExitStatus=`. Source: systemd v261.3, `systemd.unit(5)`. */
316
316
  readonly FailureAction?: UnitActionDirectiveValue;
317
317
  /** Exit status to propagate when `FailureAction=` triggers `exit` or `exit-force`. Source: systemd v260.1, `systemd.unit(5)`. */
318
318
  readonly FailureActionExitStatus?: string | number;
@@ -368,7 +368,7 @@ export interface SystemdUnitSection extends CustomDirectiveSection {
368
368
  readonly StopPropagatedFrom?: string | readonly string[];
369
369
  /** If true, this unit will be stopped when it is no longer used. Note that, in order to minimize the work to be executed, systemd will not stop units by default unless they are conflicting with other units, or the user explicitly requested their shut down. If this option is set, a unit will be automatically cleaned up if no other active unit requires it. Defaults to false. Source: systemd v260.1, `systemd.unit(5)`. */
370
370
  readonly StopWhenUnneeded?: boolean;
371
- /** Action to take when the unit stops in an inactive state. Source: systemd v260.1, `systemd.unit(5)`. */
371
+ /** Action to take when the unit stops in an inactive state. For `exit` and `exit-force`, the manager returns the main process exit status, or leaves its exit status unchanged if none is available, unless overridden by `SuccessActionExitStatus=`. Source: systemd v261.3, `systemd.unit(5)`. */
372
372
  readonly SuccessAction?: UnitActionDirectiveValue;
373
373
  /** Exit status to propagate when `SuccessAction=` triggers `exit` or `exit-force`. Source: systemd v260.1, `systemd.unit(5)`. */
374
374
  readonly SuccessActionExitStatus?: string | number;
@@ -835,7 +835,7 @@ export interface SystemdServiceSection extends CustomDirectiveSection {
835
835
  readonly RestrictNetworkInterfaces?: string | readonly string[];
836
836
  /** If set, any attempts to enable realtime scheduling in a process of the unit are refused. This restricts access to realtime task scheduling policies such as SCHED_FIFO, SCHED_RR or SCHED_DEADLINE. See sched7 for details about these scheduling policies. Realtime scheduling policies may be used to monopolize CPU time for longer periods of time, and may hence be used to lock up or otherwise trigger Denial-of-Service situations on the system. It is hence recommended to restrict access to realtime scheduling to the few programs that actually require them. Defaults to off. Source: systemd v260.1, `systemd.exec(5)`. */
837
837
  readonly RestrictRealtime?: boolean;
838
- /** If set, any attempts to set the set-user-ID (SUID) or set-group-ID (SGID) bits on files or directories will be denied (for details on these bits see inode7). As the SUID/SGID bits are mechanisms to elevate privileges, and allow users to acquire the identity of other users, it is recommended to restrict creation of SUID/SGID files to the few programs that actually require them. Note that this restricts marking of any type of file system object with these bits, including both regular files and directories (where the SGID is a different meaning than for files, see documentation). This option is implied if DynamicUser= is enabled. Source: systemd v260.1, `systemd.exec(5)`. */
838
+ /** If set, any attempts to set the set-user-ID (SUID) or set-group-ID (SGID) bits on files or directories will be denied (for details on these bits see inode7). As the SUID/SGID bits are mechanisms to elevate privileges, and allow users to acquire the identity of other users, it is recommended to restrict creation of SUID/SGID files to the few programs that actually require them. Note that this restricts marking of any type of file system object with these bits, including both regular files and directories (where the SGID is a different meaning than for files, see documentation). This option is implied if DynamicUser= is enabled. Seccomp blocks calls with directly supplied mode bits only when SUID or SGID is requested, but blocks calls such as openat2() entirely because their mode bits cannot be inspected. Source: systemd v261.3, `systemd.exec(5)`. */
839
839
  readonly RestrictSUIDSGID?: boolean;
840
840
  /** Takes a directory path relative to the host's root directory (i.e. the root of the system running the service manager). Sets the root directory for executed processes, with the pivot_root2 or chroot2 system call. If this is used, it must be ensured that the process binary and all its auxiliary files are available in the new root. Note that setting this parameter might result in additional dependencies to be added to the unit (see above). Source: systemd v260.1, `systemd.exec(5)`. */
841
841
  readonly RootDirectory?: string;
@@ -891,15 +891,15 @@ export interface SystemdServiceSection extends CustomDirectiveSection {
891
891
  readonly SocketBindDeny?: string | readonly string[];
892
892
  /** Specifies the name of the socket units this service shall inherit socket file descriptors from when the service is started. Normally, it should not be necessary to use this setting, as all socket file descriptors whose unit shares the same name as the service (subject to the different unit name suffix of course) are passed to the spawned process. Source: systemd v260.1, `systemd.service(5)`. */
893
893
  readonly Sockets?: string | readonly string[];
894
- /** Controls where file descriptor 2 (stderr) of the executed processes is connected to. The available options are identical to those of StandardOutput=, with some exceptions: if set to inherit the file descriptor used for standard output is duplicated for standard error, while fd:name will use a default file descriptor name of stderr. Source: systemd v260.1, `systemd.exec(5)`. */
894
+ /** Controls where file descriptor 2 (stderr) of the executed processes is connected to. The available options are identical to those of StandardOutput=, with some exceptions: if set to inherit the file descriptor used for standard output is duplicated for standard error, while fd:name will use a default file descriptor name of stderr. File paths are opened by the service manager before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
895
895
  readonly StandardError?: StandardErrorDirectiveValue;
896
- /** Controls where file descriptor 0 (STDIN) of the executed processes is connected to. Takes one of null, tty, tty-force, tty-fail, data, file:path, socket or fd:name. Source: systemd v260.1, `systemd.exec(5)`. */
896
+ /** Controls where file descriptor 0 (STDIN) of the executed processes is connected to. Takes one of null, tty, tty-force, tty-fail, data, file:path, socket or fd:name. For file:path, the service manager opens the path before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
897
897
  readonly StandardInput?: StandardInputDirectiveValue;
898
898
  /** Configures arbitrary textual or binary data to pass via file descriptor 0 (STDIN) to the executed processes. These settings have no effect unless StandardInput= is set to data (which is the default if StandardInput= is not set otherwise, but StandardInputText=/StandardInputData= is). Use this option to embed process input data directly in the unit file. Source: systemd v260.1, `systemd.exec(5)`. */
899
899
  readonly StandardInputData?: string | readonly string[];
900
900
  /** Configures arbitrary textual or binary data to pass via file descriptor 0 (STDIN) to the executed processes. These settings have no effect unless StandardInput= is set to data (which is the default if StandardInput= is not set otherwise, but StandardInputText=/StandardInputData= is). Use this option to embed process input data directly in the unit file. Source: systemd v260.1, `systemd.exec(5)`. */
901
901
  readonly StandardInputText?: string | readonly string[];
902
- /** Controls where file descriptor 1 (stdout) of the executed processes is connected to. Takes one of inherit, null, tty, journal, kmsg, journal+console, kmsg+console, file:path, append:path, truncate:path, socket or fd:name. Source: systemd v260.1, `systemd.exec(5)`. */
902
+ /** Controls where file descriptor 1 (stdout) of the executed processes is connected to. Takes one of inherit, null, tty, journal, kmsg, journal+console, kmsg+console, file:path, append:path, truncate:path, socket or fd:name. For file:path, append:path, and truncate:path, the service manager opens the path before SELinuxContext= or policy-defined transitions take effect; the process inherits the resulting descriptor. Source: systemd v261.3, `systemd.exec(5)`. */
903
903
  readonly StandardOutput?: StandardOutputDirectiveValue;
904
904
  /** This setting controls the cpuset controller in the unified hierarchy. Source: systemd v260.1, `systemd.resource-control(5)`. */
905
905
  readonly StartupAllowedCPUs?: string;
@@ -987,7 +987,7 @@ export interface SystemdServiceSection extends CustomDirectiveSection {
987
987
  readonly USBFunctionDescriptors?: string;
988
988
  /** Configure the location of a file containing USB FunctionFS strings. Behavior is similar to USBFunctionDescriptors= above. Source: systemd v260.1, `systemd.service(5)`. */
989
989
  readonly USBFunctionStrings?: string;
990
- /** Explicitly unset environment variable assignments that would normally be passed from the service manager to invoked processes of this unit. Takes a space-separated list of variable names or variable assignments. This option may be specified more than once, in which case all listed variables/assignments will be unset. If the empty string is assigned to this option, the list of environment variables/assignments to unset is reset. If a variable assignment is specified (that is: a variable name, followed by =, followed by its value), then any environment variable matching this precise assignment is removed. If a variable name is specified (that is a variable name without any following = or value), then any assignment matching the variable name, regardless of its value is removed. Note that the effect of UnsetEnvironment= is applied as final step when the environment list passed to executed processes is compiled. That means it may undo assignments from any configuration source, including assignments made through Environment= or EnvironmentFile=, inherited from the system manager's global set of environment variables, inherited via PassEnvironment=, set by the service manager itself (such as $NOTIFY_SOCKET and such), or set by a PAM module (in case PAMName= is used). Source: systemd v260.1, `systemd.exec(5)`. */
990
+ /** Explicitly unset environment variable assignments that would normally be passed from the service manager to invoked processes of this unit. Takes a space-separated list of variable names or variable assignments. This option may be specified more than once, in which case all listed variables/assignments will be unset. If the empty string is assigned to this option, the list of environment variables/assignments to unset is reset. If a variable assignment is specified (that is: a variable name, followed by =, followed by its value), then any environment variable matching this precise assignment is removed. If a variable name is specified (that is a variable name without any following = or value), then any assignment matching the variable name, regardless of its value is removed. Note that the effect of UnsetEnvironment= is applied as final step when the environment list passed to executed processes is compiled. That means it may undo assignments from any configuration source, including assignments made through Environment= or EnvironmentFile=, inherited from the system manager's global set of environment variables, inherited via PassEnvironment=, set by the service manager itself (such as $NOTIFY_SOCKET and such), or set by a PAM module (in case PAMName= is used). Command-line variable expansion in ExecStart= and related directives happens before this removal and is unaffected. Source: systemd v261.3, `systemd.exec(5)`. */
991
991
  readonly UnsetEnvironment?: string | readonly string[];
992
992
  /** Set the UNIX user or group that the processes are executed as, respectively. Takes a single user or group name, or a numeric ID as argument. For system services (services run by the system service manager, i.e. managed by PID 1) and for user services of the root user (services managed by root's instance of systemd --user), the default is root, but this directive may be used to specify a different identity. For user services of any other user, switching user identity is not permitted, hence the only valid setting is the same user the user's service manager is running as. If no group is set, the default group of the user is used. This setting does not affect commands whose command line is prefixed with +. Source: systemd v260.1, `systemd.exec(5)`. */
993
993
  readonly User?: string;
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-gV6lNweL.d.mts","names":[],"sources":["../src/main/internal.ts","../src/main/executable.ts","../src/main/systemd-service.ts","../src/main/systemd-timer.ts","../src/main/types.ts","../src/main/errors.ts","../src/main/notify.ts","../src/main/systemctl.ts","../src/main/systemd.ts","../src/main/index.ts"],"mappings":";;;KAiBY,OAAO,QAAQ;WAEZ;WACA,OAAO;;WAGP;WACA,OAAO;;KAgBjB;iBAEW,kBAAkB,cAAc;iBAIhC,uBAAuB,SAAS;iBAShC,uBAAuB;iBAQvB,kBAAkB,iBAAiB,wBAAwB,qBACzE,SAAS,WACR,SAAS;iBAUI,iBAAiB,iBAAiB,yBAChD,SAAS,WACR;iBAgBa,uBACd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