systemd-ts 0.2.0 → 0.3.1

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.
package/dist/index.mjs CHANGED
@@ -1,1125 +1,2 @@
1
- import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
2
- import { realpathSync } from "node:fs";
3
- import { fileURLToPath } from "node:url";
4
- import { execFile } from "node:child_process";
5
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
6
- import { promisify } from "node:util";
7
- import { join } from "node:path";
8
- //#region src/main/errors.ts
9
- var SystemdTsError = class extends Error {
10
- code;
11
- constructor(code, message, options = {}) {
12
- super(message, { cause: options.cause });
13
- this.code = code;
14
- this.name = new.target.name;
15
- }
16
- };
17
- var InvalidExecDirectiveError = class extends SystemdTsError {
18
- directive;
19
- constructor(directive, options = {}) {
20
- super(`SYSTEMD_TS_INVALID_EXEC_DIRECTIVE`, `${directive} must use an absolute executable path for systemd`, options);
21
- this.directive = directive;
22
- }
23
- };
24
- var NoUnitsProvidedError = class extends SystemdTsError {
25
- operation;
26
- constructor(operation, options = {}) {
27
- super(`SYSTEMD_TS_NO_UNITS_PROVIDED`, `${operation} requires at least one service or timer`, options);
28
- this.operation = operation;
29
- }
30
- };
31
- var ExecutableInferenceError = class extends SystemdTsError {
32
- constructor(options = {}) {
33
- super(`SYSTEMD_TS_EXECUTABLE_INFERENCE`, `Could not infer the calling module path for defineExecutable(); pass { modulePath } explicitly`, options);
34
- }
35
- };
36
- var UnitMaterializationError = class extends SystemdTsError {
37
- operation;
38
- reason;
39
- unitName;
40
- unitPath;
41
- constructor(message, options = {}) {
42
- super(`SYSTEMD_TS_UNIT_MATERIALIZATION`, message, options);
43
- this.operation = options.operation;
44
- this.reason = options.reason;
45
- this.unitName = options.unitName;
46
- this.unitPath = options.unitPath;
47
- }
48
- };
49
- var UnitEnableError = class extends SystemdTsError {
50
- args;
51
- command;
52
- environmentReason;
53
- exitCode;
54
- stage;
55
- stderr;
56
- stdout;
57
- unitName;
58
- unitPath;
59
- constructor(message, options = {}) {
60
- super(`SYSTEMD_TS_UNIT_ENABLE`, message, options);
61
- const details = extractCommandErrorDetails(options.cause);
62
- this.args = options.args;
63
- this.command = options.command;
64
- this.environmentReason = options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);
65
- this.exitCode = details.exitCode;
66
- this.stage = options.stage;
67
- this.stderr = details.stderr;
68
- this.stdout = details.stdout;
69
- this.unitName = options.unitName;
70
- this.unitPath = options.unitPath;
71
- }
72
- };
73
- var UnitStartError = class extends SystemdTsError {
74
- args;
75
- command;
76
- diagnostics;
77
- environmentReason;
78
- exitCode;
79
- stage;
80
- stderr;
81
- stdout;
82
- unitName;
83
- unitPath;
84
- constructor(message, options = {}) {
85
- super(`SYSTEMD_TS_UNIT_START`, message, options);
86
- const details = extractCommandErrorDetails(options.cause);
87
- this.args = options.args;
88
- this.command = options.command;
89
- this.diagnostics = options.diagnostics;
90
- this.environmentReason = options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);
91
- this.exitCode = details.exitCode;
92
- this.stage = options.stage;
93
- this.stderr = details.stderr;
94
- this.stdout = details.stdout;
95
- this.unitName = options.unitName;
96
- this.unitPath = options.unitPath;
97
- }
98
- };
99
- var UnitLogsReadError = class extends SystemdTsError {
100
- args;
101
- command;
102
- environmentReason;
103
- exitCode;
104
- reason;
105
- stage;
106
- stderr;
107
- stdout;
108
- unitName;
109
- unitPath;
110
- constructor(message, options = {}) {
111
- super(`SYSTEMD_TS_UNIT_LOGS`, message, options);
112
- const details = extractCommandErrorDetails(options.cause);
113
- this.args = options.args;
114
- this.command = options.command;
115
- this.environmentReason = options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);
116
- this.exitCode = details.exitCode;
117
- this.reason = options.reason;
118
- this.stage = options.stage;
119
- this.stderr = details.stderr;
120
- this.stdout = details.stdout;
121
- this.unitName = options.unitName;
122
- this.unitPath = options.unitPath;
123
- }
124
- };
125
- var NotifySendError = class extends SystemdTsError {
126
- args;
127
- command;
128
- environmentReason;
129
- exitCode;
130
- reason;
131
- stage;
132
- stderr;
133
- stdout;
134
- constructor(message, options = {}) {
135
- super(`SYSTEMD_TS_NOTIFY_SEND`, message, options);
136
- const details = extractCommandErrorDetails(options.cause);
137
- this.args = options.args;
138
- this.command = options.command;
139
- this.environmentReason = options.environmentReason ?? classifyCommandEnvironmentReason(options.cause);
140
- this.exitCode = details.exitCode;
141
- this.reason = options.reason;
142
- this.stage = options.stage;
143
- this.stderr = details.stderr;
144
- this.stdout = details.stdout;
145
- }
146
- };
147
- function classifyCommandEnvironmentReason(cause) {
148
- if (cause === null || typeof cause !== `object`) return;
149
- const record = cause;
150
- if (record[`code`] === `ENOENT`) return `missing-command`;
151
- if (record[`code`] === `EACCES` || record[`code`] === `EPERM`) return `permission-denied`;
152
- const combinedOutput = [record[`stderr`], record[`stdout`]].filter((value) => typeof value === `string` && value.length > 0).join(`\n`);
153
- if (combinedOutput.includes(`Failed to connect to bus`) || combinedOutput.includes(`System has not been booted with systemd`) || combinedOutput.includes(`Failed to get D-Bus connection`)) return `manager-unavailable`;
154
- }
155
- function classifyMaterializationReason(cause) {
156
- if (cause === null || typeof cause !== `object`) return;
157
- const record = cause;
158
- if (record[`code`] === `EACCES` || record[`code`] === `EPERM` || record[`code`] === `EROFS`) return `permission-denied`;
159
- if (record[`code`] === `EEXIST` || record[`code`] === `ENOTDIR` || record[`code`] === `EISDIR`) return `invalid-unit-directory`;
160
- return `file-system-failed`;
161
- }
162
- function extractCommandErrorDetails(cause) {
163
- if (cause === null || typeof cause !== `object`) return {
164
- exitCode: void 0,
165
- stderr: void 0,
166
- stdout: void 0
167
- };
168
- const record = cause;
169
- return {
170
- exitCode: typeof record[`code`] === `number` ? record[`code`] : void 0,
171
- stderr: typeof record[`stderr`] === `string` ? record[`stderr`] : void 0,
172
- stdout: typeof record[`stdout`] === `string` ? record[`stdout`] : void 0
173
- };
174
- }
175
- //#endregion
176
- //#region src/main/executable.ts
177
- const currentModulePath = fileURLToPath(import.meta.url);
178
- /**
179
- * An immutable description of a runnable module entrypoint that can be used in
180
- * executable-valued systemd unit directives.
181
- *
182
- * `Executable` captures three pieces of information:
183
- * - the absolute runtime binary that should launch the module
184
- * - the absolute path to the module itself
185
- * - any additional arguments that should be passed after the module path
186
- *
187
- * Most consumers will create one via {@link defineExecutable} and then pass it
188
- * into a {@link SystemdService} directive such as `ExecStart`, `ExecStop`, or
189
- * `ExecReload`.
190
- */
191
- var Executable = class {
192
- /** Additional arguments passed after the module path. */
193
- args;
194
- /** Inference issue captured when no explicit module path was provided. */
195
- inferenceError;
196
- /** Absolute path to the module that should be executed. */
197
- modulePath;
198
- /** Absolute path to the runtime binary that should launch the module. */
199
- runtimeEntrypoint;
200
- /**
201
- * Creates an executable description.
202
- *
203
- * When `modulePath` is omitted, the calling module is inferred from the
204
- * current stack so `defineExecutable()` can be used inline from the module
205
- * that should become runnable.
206
- *
207
- * When `runtimeEntrypoint` is omitted, the current process executable is
208
- * used. This works well for the common case where the same runtime that is
209
- * evaluating your module should also be used by systemd.
210
- */
211
- constructor(options = {}) {
212
- this.runtimeEntrypoint = options.runtimeEntrypoint ?? process.execPath;
213
- const inferredModulePath = options.modulePath ?? tryInferCallerModulePath();
214
- this.inferenceError = inferredModulePath === void 0 && options.modulePath === void 0 ? new ExecutableInferenceError() : void 0;
215
- this.modulePath = inferredModulePath ?? ``;
216
- this.args = Object.freeze([...options.args ?? []]);
217
- Object.freeze(this);
218
- }
219
- /**
220
- * Returns the executable as raw command parts.
221
- *
222
- * The first element is always the runtime entrypoint, followed by the module
223
- * path and any configured arguments.
224
- */
225
- toCommandParts() {
226
- if (this.inferenceError !== void 0) return {
227
- ok: false,
228
- error: this.inferenceError
229
- };
230
- return {
231
- ok: true,
232
- value: [
233
- this.runtimeEntrypoint,
234
- this.modulePath,
235
- ...this.args
236
- ]
237
- };
238
- }
239
- /**
240
- * Renders the executable as a shell-quoted command string suitable for
241
- * executable-valued systemd directives such as `ExecStart=`.
242
- */
243
- toExecStart() {
244
- const commandParts = this.toCommandParts();
245
- if (!commandParts.ok) return commandParts;
246
- return {
247
- ok: true,
248
- value: commandParts.value.map(shellQuote$1).join(` `)
249
- };
250
- }
251
- };
252
- /**
253
- * Defines a module as a runnable executable and returns its immutable
254
- * `Executable` description.
255
- *
256
- * This helper is designed for the pattern:
257
- *
258
- * ```ts
259
- * export default defineExecutable(async () => {
260
- * // do work here
261
- * });
262
- * ```
263
- *
264
- * When the defining module is executed as the main entrypoint, `fn` is invoked.
265
- * When the module is merely imported, `fn` is not run and only the executable
266
- * description is returned.
267
- *
268
- * Pass `options.runtimeEntrypoint` to override the default runtime binary when
269
- * the current process is not the exact runtime you want systemd to use.
270
- */
271
- function defineExecutable(fn, options = {}) {
272
- const executable = new Executable(options);
273
- if (executable.inferenceError === void 0 && isMainModule(executable.modulePath)) Promise.resolve(fn()).catch((error) => {
274
- process.exitCode = 1;
275
- throw error;
276
- });
277
- return executable;
278
- }
279
- function tryInferCallerModulePath() {
280
- const stack = (/* @__PURE__ */ new Error()).stack ?? ``;
281
- for (const line of stack.split(`\n`).slice(1)) {
282
- const candidate = extractStackPath(line);
283
- if (candidate === void 0 || candidate === currentModulePath) continue;
284
- return candidate;
285
- }
286
- }
287
- function extractStackPath(line) {
288
- const fileUrlMatch = line.match(/(file:\/\/\/[^)\s:]+(?:\.[cm]?[jt]s)?)/u);
289
- if (fileUrlMatch !== null) return fileURLToPath(fileUrlMatch[1]);
290
- const pathMatch = line.match(/(\/[^)\s:]+(?:\.[cm]?[jt]s)?)/u);
291
- if (pathMatch !== null) return pathMatch[1];
292
- }
293
- function isMainModule(modulePath) {
294
- const mainArg = process.argv[1];
295
- if (mainArg === void 0) return false;
296
- return normalizeFilePath(mainArg) === normalizeFilePath(modulePath);
297
- }
298
- function shellQuote$1(value) {
299
- return `'${value.replaceAll(`'`, `'\\''`)}'`;
300
- }
301
- function normalizeFilePath(path) {
302
- try {
303
- return realpathSync(path);
304
- } catch {
305
- return path;
306
- }
307
- }
308
- //#endregion
309
- //#region src/main/internal.ts
310
- var internal_exports = /* @__PURE__ */ __exportAll({
311
- cloneUnitSection: () => cloneUnitSection,
312
- defaultCommandExecutor: () => defaultCommandExecutor,
313
- defaultUnitDirForScope: () => defaultUnitDirForScope,
314
- fileExists: () => fileExists,
315
- freezeUnitOptions: () => freezeUnitOptions,
316
- normalizeUnitName: () => normalizeUnitName,
317
- parseStartStatus: () => parseStartStatus,
318
- renderUnitFile: () => renderUnitFile,
319
- resolveTimerTargetUnit: () => resolveTimerTargetUnit,
320
- sendNotify: () => sendNotify,
321
- shellQuote: () => shellQuote,
322
- validateServiceSection: () => validateServiceSection
323
- });
324
- const EXEC_DIRECTIVE_KEYS = [
325
- `ExecCondition`,
326
- `ExecReload`,
327
- `ExecReloadPost`,
328
- `ExecStart`,
329
- `ExecStartPost`,
330
- `ExecStartPre`,
331
- `ExecStop`,
332
- `ExecStopPost`
333
- ];
334
- const execFileAsync = promisify(execFile);
335
- function normalizeUnitName(name, suffix) {
336
- return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;
337
- }
338
- function resolveTimerTargetUnit(options) {
339
- const explicitTarget = options.timer[`Unit`];
340
- if (typeof explicitTarget === `string` && explicitTarget.length > 0) return explicitTarget;
341
- return `${normalizeUnitName(options.name, `.timer`)}.service`;
342
- }
343
- function defaultUnitDirForScope(scope) {
344
- if (scope === `user`) return `${process.env[`HOME`] ?? `~`}/.config/systemd/user`;
345
- return `/etc/systemd/system`;
346
- }
347
- function freezeUnitOptions(options) {
348
- return Object.freeze({
349
- ...options,
350
- ...options.unit === void 0 ? {} : { unit: cloneUnitSection(options.unit) },
351
- ...options.install === void 0 ? {} : { install: cloneUnitSection(options.install) },
352
- ...hasServiceSection(options) ? { service: cloneUnitSection(options.service) } : {},
353
- ...hasTimerSection(options) ? { timer: cloneUnitSection(options.timer) } : {}
354
- });
355
- }
356
- function cloneUnitSection(section) {
357
- if (section === void 0) return section;
358
- const entries = Object.entries(section).map(([key, value]) => {
359
- if (isUnitValueList(value)) return [key, Object.freeze([...value])];
360
- return [key, value];
361
- });
362
- return Object.freeze(Object.fromEntries(entries));
363
- }
364
- function validateServiceSection(service) {
365
- for (const key of EXEC_DIRECTIVE_KEYS) {
366
- const validation = assertAbsoluteExecValue(key, service[key]);
367
- if (!validation.ok) return validation;
368
- }
369
- return {
370
- ok: true,
371
- value: void 0
372
- };
373
- }
374
- function parseStartStatus(unit, output) {
375
- const properties = Object.fromEntries(output.split(`\n`).map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
376
- const separatorIndex = line.indexOf(`=`);
377
- if (separatorIndex === -1) return [line, ``];
378
- return [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)];
379
- }));
380
- return {
381
- activeState: properties[`ActiveState`] ?? `unknown`,
382
- execMainStatus: properties[`ExecMainStatus`] === void 0 || properties[`ExecMainStatus`] === `` ? void 0 : Number(properties[`ExecMainStatus`]),
383
- result: properties[`Result`] ?? `unknown`,
384
- subState: properties[`SubState`] ?? `unknown`,
385
- unit: properties[`Id`] ?? unit
386
- };
387
- }
388
- function renderUnitFile(sections) {
389
- try {
390
- const renderedSections = sections.flatMap(([sectionName, section]) => {
391
- if (section === void 0) return [];
392
- const lines = [];
393
- for (const [key, value] of Object.entries(section)) {
394
- if (value === void 0) continue;
395
- if (isUnitValueList(value)) {
396
- for (const entry of value) {
397
- const rendered = stringifyUnitValue(entry);
398
- if (!rendered.ok) throw rendered.error;
399
- lines.push(`${key}=${rendered.value}`);
400
- }
401
- continue;
402
- }
403
- const rendered = stringifyUnitValue(value);
404
- if (!rendered.ok) throw rendered.error;
405
- lines.push(`${key}=${rendered.value}`);
406
- }
407
- if (lines.length === 0) return [];
408
- return [
409
- `[${sectionName}]`,
410
- ...lines,
411
- ``
412
- ];
413
- }).join(`\n`);
414
- return {
415
- ok: true,
416
- value: renderedSections.endsWith(`\n`) ? renderedSections : `${renderedSections}\n`
417
- };
418
- } catch (error) {
419
- return {
420
- ok: false,
421
- error: error instanceof ExecutableInferenceError ? error : new ExecutableInferenceError({ cause: error })
422
- };
423
- }
424
- }
425
- function shellQuote(value) {
426
- return `'${value.replaceAll(`'`, `'\\''`)}'`;
427
- }
428
- async function defaultCommandExecutor(command, args) {
429
- const result = await execFileAsync(command, [...args]);
430
- return {
431
- stderr: result.stderr,
432
- stdout: result.stdout
433
- };
434
- }
435
- async function fileExists(path) {
436
- try {
437
- await access(path);
438
- return true;
439
- } catch {
440
- return false;
441
- }
442
- }
443
- async function sendNotify(state, options) {
444
- const args = [state];
445
- if (options.pid !== void 0) args.push(`MAINPID=${options.pid}`);
446
- if (options.status !== void 0) args.push(`STATUS=${options.status}`);
447
- if (options.executor !== void 0) {
448
- const command = buildNotifyShellCommand(args, options.socketPath);
449
- try {
450
- await options.executor(`bash`, [`-lc`, command]);
451
- } catch (cause) {
452
- throw new NotifySendError(`Failed to send systemd notification through the configured executor`, {
453
- args: [`-lc`, command],
454
- cause,
455
- command: `bash`,
456
- reason: `executor-failed`,
457
- stage: `executor`
458
- });
459
- }
460
- return;
461
- }
462
- try {
463
- await execFileAsync(`systemd-notify`, args, { env: {
464
- ...process.env,
465
- ...options.socketPath === void 0 ? {} : { NOTIFY_SOCKET: options.socketPath }
466
- } });
467
- } catch (cause) {
468
- throw new NotifySendError(`Failed to send systemd notification with systemd-notify`, {
469
- args,
470
- cause,
471
- command: `systemd-notify`,
472
- reason: `systemd-notify-failed`,
473
- stage: `systemd-notify`
474
- });
475
- }
476
- }
477
- function hasServiceSection(options) {
478
- return `service` in options;
479
- }
480
- function hasTimerSection(options) {
481
- return `timer` in options;
482
- }
483
- function assertAbsoluteExecValue(key, value) {
484
- if (isUnitValueList(value)) {
485
- for (const entry of value) {
486
- const validation = assertAbsoluteExecEntry(key, entry);
487
- if (!validation.ok) return validation;
488
- }
489
- return {
490
- ok: true,
491
- value: void 0
492
- };
493
- }
494
- return assertAbsoluteExecEntry(key, value);
495
- }
496
- function assertAbsoluteExecEntry(key, value) {
497
- if (typeof value === `string` && value.length > 0 && !isAbsoluteExecCommand(value)) return {
498
- ok: false,
499
- error: new InvalidExecDirectiveError(key)
500
- };
501
- if (value instanceof Executable && !value.runtimeEntrypoint.startsWith(`/`)) return {
502
- ok: false,
503
- error: new InvalidExecDirectiveError(key)
504
- };
505
- return {
506
- ok: true,
507
- value: void 0
508
- };
509
- }
510
- function stringifyUnitValue(value) {
511
- if (value instanceof Executable) return value.toExecStart();
512
- if (typeof value === `boolean`) return {
513
- ok: true,
514
- value: value ? `true` : `false`
515
- };
516
- return {
517
- ok: true,
518
- value: String(value)
519
- };
520
- }
521
- function isUnitValueList(value) {
522
- return Array.isArray(value);
523
- }
524
- function isAbsoluteExecCommand(value) {
525
- let index = 0;
526
- let hasPrivilegePrefix = false;
527
- while (index < value.length) {
528
- const prefix = value[index];
529
- if (prefix === `@` || prefix === `-` || prefix === `:`) {
530
- index += 1;
531
- continue;
532
- }
533
- if (prefix === `+`) {
534
- if (hasPrivilegePrefix) return false;
535
- hasPrivilegePrefix = true;
536
- index += 1;
537
- continue;
538
- }
539
- if (prefix === `!`) {
540
- if (hasPrivilegePrefix) return false;
541
- hasPrivilegePrefix = true;
542
- index += value[index + 1] === `!` ? 2 : 1;
543
- continue;
544
- }
545
- break;
546
- }
547
- return value[index] === `/`;
548
- }
549
- function buildNotifyShellCommand(args, socketPath) {
550
- return `${socketPath === void 0 ? `` : `NOTIFY_SOCKET=${shellQuote(socketPath)} `}${[`systemd-notify`, ...args].map(shellQuote).join(` `)}`;
551
- }
552
- //#endregion
553
- //#region src/main/notify.ts
554
- /**
555
- * Helpers for sending `sd_notify` state updates to systemd.
556
- *
557
- * These helpers send notification payloads to the socket identified by
558
- * `NOTIFY_SOCKET`, or to `options.socketPath` when one is provided explicitly.
559
- * They are useful both in real services and in tests that want to observe
560
- * readiness or watchdog traffic directly.
561
- *
562
- * Source:
563
- * - https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html
564
- * - https://www.freedesktop.org/software/systemd/man/latest/systemd-notify.html
565
- */
566
- const notify = {
567
- /**
568
- * Sends `READY=1` to systemd.
569
- *
570
- * Use this when a `Type=notify` service has completed its startup work and is
571
- * ready to be considered fully started. If `options.status` is provided, it is
572
- * sent as an additional `STATUS=...` field.
573
- */
574
- async ready(options = {}) {
575
- try {
576
- await sendNotify(`READY=1`, options);
577
- return {
578
- ok: true,
579
- value: void 0
580
- };
581
- } catch (error) {
582
- return {
583
- ok: false,
584
- error: error instanceof NotifySendError ? error : new NotifySendError(`Failed to send READY=1 notification`, {
585
- cause: error,
586
- stage: `ready`
587
- })
588
- };
589
- }
590
- },
591
- /**
592
- * Sends `WATCHDOG=1` to systemd.
593
- *
594
- * Use this when a service configured with `WatchdogSec=` needs to emit a
595
- * watchdog heartbeat. If `options.pid` is provided, it is sent as
596
- * `MAINPID=...`, and `options.status` is forwarded as `STATUS=...`.
597
- */
598
- async watchdog(options = {}) {
599
- try {
600
- await sendNotify(`WATCHDOG=1`, options);
601
- return {
602
- ok: true,
603
- value: void 0
604
- };
605
- } catch (error) {
606
- return {
607
- ok: false,
608
- error: error instanceof NotifySendError ? error : new NotifySendError(`Failed to send WATCHDOG=1 notification`, {
609
- cause: error,
610
- stage: `watchdog`
611
- })
612
- };
613
- }
614
- }
615
- };
616
- //#endregion
617
- //#region src/main/systemd-service.ts
618
- /**
619
- * An immutable definition of a `.service` unit.
620
- *
621
- * `SystemdService` is a pure value object: it captures the intended unit name
622
- * and section contents, but it does not write files or talk to `systemd`
623
- * directly. Operational actions such as installation or startup belong on
624
- * {@link Systemd}.
625
- *
626
- * Source:
627
- * - https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html
628
- */
629
- var SystemdService = class {
630
- /** Optional `[Install]` section for enable-time relationships. */
631
- install;
632
- /** The normalized base unit name, without the `.service` suffix. */
633
- name;
634
- /** The fully frozen original options used to construct this service. */
635
- options;
636
- /** The `[Service]` section payload. */
637
- service;
638
- /** Optional `[Unit]` section metadata and dependency configuration. */
639
- unit;
640
- /**
641
- * Creates an immutable service definition.
642
- *
643
- * The constructor preserves literal types where possible and rejects unknown
644
- * directive names within the provided sections, while still allowing custom
645
- * `X-...` extension directives.
646
- */
647
- constructor(options) {
648
- this.options = freezeUnitOptions(options);
649
- this.name = normalizeUnitName(options.name, `.service`);
650
- this.unit = cloneUnitSection(options.unit);
651
- this.service = cloneUnitSection(options.service) ?? {};
652
- this.install = cloneUnitSection(options.install);
653
- Object.freeze(this);
654
- }
655
- /** The canonical unit filename, including the `.service` suffix. */
656
- get filename() {
657
- return `${this.name}.service`;
658
- }
659
- /**
660
- * Renders the service as a complete unit file.
661
- *
662
- * Rendering also validates executable-valued directives such as `ExecStart`
663
- * and `ExecStop`, ensuring they use absolute runtime entrypoints as required
664
- * by systemd.
665
- */
666
- render() {
667
- const validation = validateServiceSection(this.service);
668
- if (!validation.ok) return validation;
669
- return renderUnitFile([
670
- [`Unit`, this.unit],
671
- [`Service`, this.service],
672
- [`Install`, this.install]
673
- ]);
674
- }
675
- };
676
- //#endregion
677
- //#region src/main/systemd-timer.ts
678
- /**
679
- * An immutable definition of a `.timer` unit.
680
- *
681
- * Like {@link SystemdService}, this is a pure value object. It models the timer
682
- * configuration and its attachment target, but does not write files or interact
683
- * with the service manager directly.
684
- *
685
- * Source:
686
- * - https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html
687
- */
688
- var SystemdTimer = class {
689
- /** Optional `[Install]` section for enable-time relationships. */
690
- install;
691
- /** The normalized base unit name, without the `.timer` suffix. */
692
- name;
693
- /** The fully frozen original options used to construct this timer. */
694
- options;
695
- /** The attached service basename inferred from `targetUnit`. */
696
- targetServiceName;
697
- /** The unit name this timer activates, explicit or implicit. */
698
- targetUnit;
699
- /** The `[Timer]` section payload. */
700
- timer;
701
- /** Optional `[Unit]` section metadata and dependency configuration. */
702
- unit;
703
- /**
704
- * Creates an immutable timer definition.
705
- *
706
- * If no explicit `timer.Unit` is provided, the target defaults to the service
707
- * with the same basename, matching systemd's native timer behavior.
708
- */
709
- constructor(options) {
710
- this.options = freezeUnitOptions(options);
711
- this.name = normalizeUnitName(options.name, `.timer`);
712
- this.unit = cloneUnitSection(options.unit);
713
- this.timer = cloneUnitSection(options.timer) ?? {};
714
- this.install = cloneUnitSection(options.install);
715
- this.targetUnit = resolveTimerTargetUnit(options);
716
- this.targetServiceName = normalizeUnitName(this.targetUnit, `.service`);
717
- Object.freeze(this);
718
- }
719
- /** The canonical unit filename, including the `.timer` suffix. */
720
- get filename() {
721
- return `${this.name}.timer`;
722
- }
723
- /** Renders the timer as a complete unit file. */
724
- render() {
725
- return renderUnitFile([
726
- [`Unit`, this.unit],
727
- [`Timer`, this.timer],
728
- [`Install`, this.install]
729
- ]);
730
- }
731
- };
732
- //#endregion
733
- //#region src/main/systemd.ts
734
- /**
735
- * A successful systemd unit materialization.
736
- *
737
- * It records the target directory and the on-disk path associated with each
738
- * materialized unit.
739
- */
740
- var SystemdMaterialization = class {
741
- /** The directory units were written into. */
742
- directory;
743
- /** The materialized units together with their resolved on-disk paths. */
744
- materialized;
745
- constructor(directory, materialized) {
746
- this.directory = directory;
747
- this.materialized = Object.freeze([...materialized]);
748
- Object.freeze(this);
749
- }
750
- };
751
- /**
752
- * A configured interface to a specific systemd environment.
753
- *
754
- * `Systemd` combines unit-file materialization with a command execution
755
- * strategy. It knows which scope it is targeting, where unit files should be
756
- * written, and how `systemctl` should be invoked.
757
- *
758
- * This abstraction is intentionally close to `systemctl` concepts while still
759
- * accepting full unit definitions instead of loose unit-name strings.
760
- */
761
- var Systemd = class {
762
- /** Command executor used for `systemctl` and related subprocess calls. */
763
- executor;
764
- /** Whether units should be linked into systemd before manager operations. */
765
- linkUnits;
766
- /** The target manager scope, either `system` or `user`. */
767
- scope;
768
- /** The directory used when materializing unit files. */
769
- unitDir;
770
- /**
771
- * Creates a configured `Systemd` facade.
772
- *
773
- * By default, this targets the system scope and `/etc/systemd/system`. Use
774
- * `scope: "user"` or an explicit `unitDir` to target a different manager or
775
- * unit-file location.
776
- */
777
- constructor(options = {}) {
778
- this.scope = options.scope ?? `system`;
779
- this.unitDir = options.unitDir ?? defaultUnitDirForScope(this.scope);
780
- this.linkUnits = options.linkUnits ?? false;
781
- this.executor = options.executor ?? defaultCommandExecutor;
782
- Object.freeze(this);
783
- }
784
- /**
785
- * Renders and writes one or more units into this instance's `unitDir`.
786
- *
787
- * This is intentionally a file-materialization step. It does not enable or
788
- * start the units on its own.
789
- */
790
- async materialize(...units) {
791
- return this.materializeUnits(units);
792
- }
793
- /**
794
- * Enables one or more units via `systemctl enable`.
795
- *
796
- * When `linkUnits` is enabled, this first links materialized unit files into the
797
- * target manager and reloads systemd so the units are visible before the
798
- * enable operation runs.
799
- */
800
- async enable(...units) {
801
- if (units.length === 0) return err(new NoUnitsProvidedError(`Systemd.enable()`));
802
- const scopeArgs = this.scopeArgs();
803
- try {
804
- await this.prepareUnits(scopeArgs, units, `enable`);
805
- } catch (cause) {
806
- if (cause instanceof UnitEnableError) return err(cause);
807
- return err(new UnitEnableError(`Failed to prepare units for enable`, {
808
- cause,
809
- stage: `prepare`,
810
- unitName: units[0]?.filename
811
- }));
812
- }
813
- for (const unit of units) {
814
- const args = [
815
- ...scopeArgs,
816
- `enable`,
817
- unit.filename
818
- ];
819
- try {
820
- await this.executor(`systemctl`, args);
821
- } catch (cause) {
822
- return err(new UnitEnableError(`Failed to enable ${unit.filename}`, {
823
- args,
824
- cause,
825
- command: `systemctl`,
826
- stage: `enable`,
827
- unitName: unit.filename
828
- }));
829
- }
830
- }
831
- return ok(void 0);
832
- }
833
- /**
834
- * Starts a unit and returns a parsed `systemctl show` snapshot of its final
835
- * observed state.
836
- *
837
- * For oneshot services, a successful result commonly means `ActiveState` is
838
- * already back to `inactive` by the time the status snapshot is collected.
839
- */
840
- async start(unit) {
841
- const scopeArgs = this.scopeArgs();
842
- try {
843
- await this.prepareUnits(scopeArgs, [unit], `start`);
844
- } catch (cause) {
845
- if (cause instanceof UnitStartError) return err(cause);
846
- return err(new UnitStartError(`Failed to prepare ${unit.filename} for start`, {
847
- cause,
848
- diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),
849
- stage: `prepare`,
850
- unitName: unit.filename
851
- }));
852
- }
853
- const startArgs = [
854
- ...scopeArgs,
855
- `start`,
856
- unit.filename
857
- ];
858
- try {
859
- await this.executor(`systemctl`, startArgs);
860
- } catch (cause) {
861
- return err(new UnitStartError(`Failed to start ${unit.filename}`, {
862
- args: startArgs,
863
- cause,
864
- command: `systemctl`,
865
- diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),
866
- stage: `start`,
867
- unitName: unit.filename
868
- }));
869
- }
870
- const statusArgs = [
871
- ...scopeArgs,
872
- `show`,
873
- unit.filename,
874
- `--property=Id,ActiveState,SubState,Result,ExecMainStatus`
875
- ];
876
- let status;
877
- try {
878
- status = await this.executor(`systemctl`, statusArgs);
879
- } catch (cause) {
880
- return err(new UnitStartError(`Started ${unit.filename} but failed to query its status`, {
881
- args: statusArgs,
882
- cause,
883
- command: `systemctl`,
884
- diagnostics: await this.collectStartDiagnostics(scopeArgs, unit.filename),
885
- stage: `show-status`,
886
- unitName: unit.filename
887
- }));
888
- }
889
- return ok(parseStartStatus(unit.filename, status.stdout));
890
- }
891
- /**
892
- * Reads recent output for a managed unit.
893
- *
894
- * If the unit is configured with file-backed `StandardOutput` or
895
- * `StandardError`, this reads directly from that file. Otherwise it falls back
896
- * to `systemctl status --lines ...`.
897
- */
898
- async logs(unit, options) {
899
- const fileLogPath = resolveUnitLogPath(unit);
900
- if (fileLogPath !== void 0) try {
901
- return ok(tailLines(await readFile(fileLogPath, `utf8`), options?.lines ?? 50));
902
- } catch (cause) {
903
- return err(new UnitLogsReadError(`Failed to read logs for ${unit.filename} from ${fileLogPath}`, {
904
- cause,
905
- reason: isMissingPathError(cause) ? `missing-log-file` : `log-file-read-failed`,
906
- stage: `read-log-file`,
907
- unitName: unit.filename,
908
- unitPath: fileLogPath
909
- }));
910
- }
911
- const scopeArgs = this.scopeArgs();
912
- const lines = options?.lines ?? 50;
913
- const args = [`-lc`, `${[
914
- `systemctl`,
915
- ...scopeArgs,
916
- `status`,
917
- unit.filename,
918
- `--no-pager`,
919
- `--lines`,
920
- String(lines)
921
- ].map(shellQuote).join(` `)} 2>&1 || true`];
922
- let logs;
923
- try {
924
- logs = await this.executor(`bash`, args);
925
- } catch (cause) {
926
- return err(new UnitLogsReadError(`Failed to query logs for ${unit.filename} from systemctl status`, {
927
- args,
928
- cause,
929
- command: `bash`,
930
- reason: `status-command-failed`,
931
- stage: `status`,
932
- unitName: unit.filename
933
- }));
934
- }
935
- return ok([logs.stdout, logs.stderr].filter((value) => value.length > 0).join(`\n`));
936
- }
937
- /** Returns the on-disk unit-file path this instance uses for the given unit. */
938
- pathFor(unit) {
939
- return join(this.unitDir, unit.filename);
940
- }
941
- async prepareUnits(scopeArgs, units, operation) {
942
- if (this.linkUnits) {
943
- const linkPaths = await this.collectLinkPaths(units);
944
- for (const path of linkPaths) {
945
- const args = [
946
- ...scopeArgs,
947
- `link`,
948
- path
949
- ];
950
- try {
951
- await this.executor(`systemctl`, args);
952
- } catch (cause) {
953
- const linkedUnit = units.find((candidate) => this.pathFor(candidate) === path);
954
- const errorContext = {
955
- args,
956
- cause,
957
- command: `systemctl`,
958
- stage: `link`,
959
- ...linkedUnit === void 0 ? {} : { unitName: linkedUnit.filename },
960
- unitPath: path
961
- };
962
- throw operation === `enable` ? new UnitEnableError(`Failed to link ${path} before enable`, errorContext) : new UnitStartError(`Failed to link ${path} before start`, errorContext);
963
- }
964
- }
965
- }
966
- const args = [...scopeArgs, `daemon-reload`];
967
- try {
968
- await this.executor(`systemctl`, args);
969
- } catch (cause) {
970
- throw operation === `enable` ? new UnitEnableError(`Failed to reload systemd before enable`, {
971
- args,
972
- cause,
973
- command: `systemctl`,
974
- stage: `daemon-reload`,
975
- unitName: units[0]?.filename
976
- }) : new UnitStartError(`Failed to reload systemd before start`, {
977
- args,
978
- cause,
979
- command: `systemctl`,
980
- stage: `daemon-reload`,
981
- unitName: units[0]?.filename
982
- });
983
- }
984
- }
985
- scopeArgs() {
986
- return this.scope === `user` ? [`--user`] : [];
987
- }
988
- async collectStartDiagnostics(scopeArgs, unitName) {
989
- const diagnostics = {};
990
- const showCommand = [
991
- `systemctl`,
992
- ...scopeArgs,
993
- `show`,
994
- unitName,
995
- `--property=Id,ActiveState,SubState,Result,ExecMainStatus`
996
- ].map(shellQuote).join(` `);
997
- const show = await this.tryBestEffortCommand(`bash`, [`-lc`, `${showCommand} 2>&1 || true`]);
998
- if (show !== void 0 && show.length > 0) {
999
- diagnostics.showOutput = show;
1000
- diagnostics.showStatus = parseStartStatus(unitName, show);
1001
- }
1002
- const statusCommand = [
1003
- `systemctl`,
1004
- ...scopeArgs,
1005
- `status`,
1006
- unitName,
1007
- `--no-pager`,
1008
- `--lines`,
1009
- `20`
1010
- ].map(shellQuote).join(` `);
1011
- const status = await this.tryBestEffortCommand(`bash`, [`-lc`, `${statusCommand} 2>&1 || true`]);
1012
- if (status !== void 0 && status.length > 0) diagnostics.statusOutput = status;
1013
- return diagnostics;
1014
- }
1015
- async collectLinkPaths(units) {
1016
- const paths = /* @__PURE__ */ new Set();
1017
- for (const unit of units) {
1018
- paths.add(this.pathFor(unit));
1019
- if (unit instanceof SystemdTimer) {
1020
- const targetPath = join(this.unitDir, unit.targetUnit);
1021
- if (await fileExists(targetPath)) paths.add(targetPath);
1022
- }
1023
- }
1024
- return [...paths];
1025
- }
1026
- async materializeUnits(units) {
1027
- if (units.length === 0) return err(new NoUnitsProvidedError(`Systemd.materialize()`));
1028
- try {
1029
- await writeUnitDirectory(this.unitDir);
1030
- } catch (cause) {
1031
- const reason = classifyMaterializationReason(cause);
1032
- return err(new UnitMaterializationError(`Failed to create unit directory ${this.unitDir}`, {
1033
- cause,
1034
- operation: `create-directory`,
1035
- ...reason === void 0 ? {} : { reason },
1036
- unitPath: this.unitDir
1037
- }));
1038
- }
1039
- const materialized = [];
1040
- for (const unit of units) {
1041
- const path = join(this.unitDir, unit.filename);
1042
- const rendered = unit.render();
1043
- if (!rendered.ok) return err(rendered.error);
1044
- try {
1045
- await writeFile(path, rendered.value, `utf8`);
1046
- } catch (cause) {
1047
- if (cause instanceof InvalidExecDirectiveError) return err(cause);
1048
- const reason = classifyMaterializationReason(cause);
1049
- return err(new UnitMaterializationError(`Failed to materialize ${unit.filename} into ${path}`, {
1050
- cause,
1051
- operation: `write-file`,
1052
- ...reason === void 0 ? {} : { reason },
1053
- unitName: unit.filename,
1054
- unitPath: path
1055
- }));
1056
- }
1057
- materialized.push({
1058
- path,
1059
- unit
1060
- });
1061
- }
1062
- return ok(new SystemdMaterialization(this.unitDir, materialized));
1063
- }
1064
- async tryBestEffortCommand(command, args) {
1065
- try {
1066
- return (await this.executor(command, args)).stdout;
1067
- } catch {
1068
- return;
1069
- }
1070
- }
1071
- };
1072
- function ok(value) {
1073
- return {
1074
- ok: true,
1075
- value
1076
- };
1077
- }
1078
- function err(error) {
1079
- return {
1080
- ok: false,
1081
- error
1082
- };
1083
- }
1084
- let lazyDefaultSystemd;
1085
- /**
1086
- * Returns the lazily created default `Systemd` instance.
1087
- *
1088
- * The default instance uses the library defaults for scope, unit directory, and
1089
- * command execution.
1090
- */
1091
- function defaultSystemd() {
1092
- lazyDefaultSystemd ??= new Systemd();
1093
- return lazyDefaultSystemd;
1094
- }
1095
- function resolveUnitLogPath(unit) {
1096
- if (!(unit instanceof SystemdService)) return;
1097
- for (const key of [`StandardOutput`, `StandardError`]) {
1098
- const value = unit.service[key];
1099
- if (typeof value !== `string`) continue;
1100
- const path = parseFileLogPath(value);
1101
- if (path !== void 0) return path;
1102
- }
1103
- }
1104
- function parseFileLogPath(value) {
1105
- for (const prefix of [`append:`, `file:`]) if (value.startsWith(prefix)) return value.slice(prefix.length);
1106
- }
1107
- function tailLines(output, lines) {
1108
- return output.split(`\n`).slice(-lines).join(`\n`);
1109
- }
1110
- function isMissingPathError(cause) {
1111
- if (cause === null || typeof cause !== `object`) return false;
1112
- return cause[`code`] === `ENOENT`;
1113
- }
1114
- async function writeUnitDirectory(path) {
1115
- await mkdir(path, { recursive: true });
1116
- }
1117
- //#endregion
1118
- //#region src/main/index.ts
1119
- /**
1120
- * Internal helpers are exposed for advanced use, but they are not a stable public API.
1121
- * Expect breaking changes here outside the package's normal compatibility guarantees.
1122
- */
1123
- const Internal = internal_exports;
1124
- //#endregion
1125
- export { Executable, ExecutableInferenceError, Internal, InvalidExecDirectiveError, NoUnitsProvidedError, NotifySendError, Systemd, SystemdMaterialization, SystemdService, SystemdTimer, SystemdTsError, UnitEnableError, UnitLogsReadError, UnitMaterializationError, UnitStartError, defaultSystemd, defineExecutable, notify };
1
+ import { _ as SystemdTsError, a as defaultSystemd, b as UnitMaterializationError, c as SystemdService, d as defineExecutable, f as ExecutableInferenceError, g as SystemctlCommandError, h as NotifySendError, i as SystemdTs, l as notify, m as NoUnitsProvidedError, n as Systemd, o as Systemctl, p as InvalidExecDirectiveError, r as SystemdMaterialization, s as SystemdTimer, t as Internal, u as Executable, v as UnitEnableError, x as UnitStartError, y as UnitLogsReadError } from "./main-BXq7TQdg.mjs";
2
+ export { Executable, ExecutableInferenceError, Internal, InvalidExecDirectiveError, NoUnitsProvidedError, NotifySendError, Systemctl, SystemctlCommandError, Systemd, SystemdMaterialization, SystemdService, SystemdTimer, SystemdTs, SystemdTsError, UnitEnableError, UnitLogsReadError, UnitMaterializationError, UnitStartError, defaultSystemd, defineExecutable, notify };