@adecore/service 0.0.1 → 0.17.0-beta.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/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Bas Milius
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # @adecore/service
2
+
3
+ Definitions and injectable managers for macOS launchd GUI jobs and Linux systemd user services. The host supplies identity, paths, environment, commands and files. It keeps installation authorization and executable policy.
4
+
5
+ The package is private at `0.0.0` pending first publication. Use its local `source` exports, or run the package build for compiled JavaScript and declarations. It retains the [FSL-1.1-MIT license](LICENSE).
6
+
7
+ ```ts
8
+ import { systemdUnit, type ServiceSpec } from '@adecore/service/definitions';
9
+
10
+ const spec: ServiceSpec = {
11
+ label: 'com.example.worker',
12
+ description: 'Example background worker',
13
+ program: '/opt/example/bin/worker',
14
+ args: ['--listen', '127.0.0.1'],
15
+ environment: { PATH: '/usr/bin:/bin' },
16
+ workingDirectory: '/home/ada',
17
+ logFile: '/home/ada/worker.log'
18
+ };
19
+ const definition = systemdUnit(spec);
20
+ ```
21
+
22
+ `/definitions` has no Node or Bun runtime imports. The root, `/manager`, `/platform` and `/system` are backend entrypoints. Importing them does not install or start a service.
23
+
24
+ `install()` returns whether an existing definition changed, so a first install returns `false`. Await `restart()` for a changed definition, otherwise call `start()`. Uninstall does not stop a running job. Managers supply no authorization, lock, cancellation or automatic lingering.
25
+
26
+ The full documentation covers [getting started](https://adecore.dev/service/getting-started), [definitions and identity](https://adecore.dev/service/definitions), [lifecycle](https://adecore.dev/service/lifecycle), [API reference](https://adecore.dev/service/reference) and [testing and host migration](https://adecore.dev/service/testing-migration). The first guide uses safe fakes rather than real service commands.
@@ -0,0 +1,12 @@
1
+ export interface ServiceSpec {
2
+ label: string;
3
+ description: string;
4
+ program: string;
5
+ args: string[];
6
+ environment: Record<string, string>;
7
+ workingDirectory: string;
8
+ logFile: string;
9
+ }
10
+ export declare function launchAgentPlist(spec: ServiceSpec): string;
11
+ export declare function systemdUnit(spec: ServiceSpec): string;
12
+ export declare function definitionRunsProgram(definition: string, program: string): boolean;
@@ -0,0 +1,69 @@
1
+ function xmlText(value) {
2
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3
+ }
4
+ function plistString(value, indent) {
5
+ return `${indent}<string>${xmlText(value)}</string>`;
6
+ }
7
+ /*
8
+ * `ProcessType=Interactive` avoids launchd throttling during a handover to a background process.
9
+ */
10
+ export function launchAgentPlist(spec) {
11
+ const lines = [
12
+ '<?xml version="1.0" encoding="UTF-8"?>',
13
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
14
+ '<plist version="1.0">',
15
+ '<dict>',
16
+ ' <key>Label</key>',
17
+ plistString(spec.label, ' '),
18
+ ' <key>ProgramArguments</key>',
19
+ ' <array>',
20
+ ...[spec.program, ...spec.args].map((arg) => plistString(arg, ' ')),
21
+ ' </array>',
22
+ ' <key>EnvironmentVariables</key>',
23
+ ' <dict>'
24
+ ];
25
+ for (const [name, value] of Object.entries(spec.environment)) {
26
+ lines.push(` <key>${xmlText(name)}</key>`, plistString(value, ' '));
27
+ }
28
+ lines.push(' </dict>', ' <key>WorkingDirectory</key>', plistString(spec.workingDirectory, ' '), ' <key>RunAtLoad</key>', ' <true/>', ' <key>KeepAlive</key>', ' <true/>', ' <key>ProcessType</key>', ' <string>Interactive</string>', ' <key>StandardOutPath</key>', plistString(spec.logFile, ' '), ' <key>StandardErrorPath</key>', plistString(spec.logFile, ' '), '</dict>', '</plist>', '');
29
+ return lines.join('\n');
30
+ }
31
+ /* systemd expands `%` specifiers everywhere and `$` variables in a command line, so both are doubled; quotes keep a space in a path. */
32
+ function unitWord(value, command) {
33
+ let escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%');
34
+ if (command) {
35
+ escaped = escaped.replace(/\$/g, '$$$$');
36
+ }
37
+ return `"${escaped}"`;
38
+ }
39
+ /*
40
+ * User services stop at logout unless the caller explicitly enables lingering.
41
+ */
42
+ export function systemdUnit(spec) {
43
+ const lines = [
44
+ '[Unit]',
45
+ `Description=${spec.description.replace(/%/g, '%%')}`,
46
+ '',
47
+ '[Service]',
48
+ 'Type=simple',
49
+ `ExecStart=${[spec.program, ...spec.args].map((word) => unitWord(word, true)).join(' ')}`,
50
+ ...Object.entries(spec.environment).map(([name, value]) => `Environment=${unitWord(`${name}=${value}`, false)}`),
51
+ // The one setting here that takes no quotes: it reads the rest of the line as the path.
52
+ `WorkingDirectory=${spec.workingDirectory.replace(/%/g, '%%')}`,
53
+ 'Restart=always',
54
+ 'RestartSec=2',
55
+ '',
56
+ '[Install]',
57
+ 'WantedBy=default.target',
58
+ ''
59
+ ];
60
+ return lines.join('\n');
61
+ }
62
+ /*
63
+ * Callers sharing a service identity can check executable ownership before replacing its definition.
64
+ */
65
+ export function definitionRunsProgram(definition, program) {
66
+ return (definition.includes(`<string>${xmlText(program)}</string>`) ||
67
+ definition.includes(`ExecStart=${unitWord(program, true)} `) ||
68
+ definition.includes(`ExecStart=${unitWord(program, true)}\n`));
69
+ }
@@ -0,0 +1,4 @@
1
+ export { definitionRunsProgram, launchAgentPlist, systemdUnit, type ServiceSpec } from './definitions.js';
2
+ export { launchdManager, systemdManager, type CommandResult, type CommandRunner, type LaunchdOptions, type ServiceFiles, type ServiceManager, type SystemdOptions } from './manager.js';
3
+ export { platformServiceManager, serviceDefinition, type PlatformServiceOptions } from './platform.js';
4
+ export { diskFiles, runCommand } from './system.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { definitionRunsProgram, launchAgentPlist, systemdUnit } from './definitions.js';
2
+ export { launchdManager, systemdManager } from './manager.js';
3
+ export { platformServiceManager, serviceDefinition } from './platform.js';
4
+ export { diskFiles, runCommand } from './system.js';
@@ -0,0 +1,45 @@
1
+ export interface CommandResult {
2
+ code: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ export type CommandRunner = (command: string, args: string[]) => CommandResult;
7
+ export interface ServiceFiles {
8
+ read(path: string): string | null;
9
+ write(path: string, text: string): void;
10
+ remove(path: string): void;
11
+ makeDirectory(path: string): void;
12
+ }
13
+ export interface ServiceManager {
14
+ readonly kind: 'launchd' | 'systemd';
15
+ readonly path: string;
16
+ isInstalled(): boolean;
17
+ read(): string | null;
18
+ install(definition: string): boolean;
19
+ start(): void;
20
+ restart(): Promise<void>;
21
+ stop(): void;
22
+ uninstall(): void;
23
+ linger?: {
24
+ enabled(): boolean;
25
+ enable(): void;
26
+ };
27
+ }
28
+ export interface LaunchdOptions {
29
+ uid: number;
30
+ home: string;
31
+ run: CommandRunner;
32
+ files: ServiceFiles;
33
+ sleep(ms: number): Promise<void>;
34
+ label: string;
35
+ logFile: string;
36
+ }
37
+ export declare function launchdManager(options: LaunchdOptions): ServiceManager;
38
+ export interface SystemdOptions {
39
+ configHome: string;
40
+ run: CommandRunner;
41
+ files: ServiceFiles;
42
+ user: string;
43
+ unitName: string;
44
+ }
45
+ export declare function systemdManager(options: SystemdOptions): ServiceManager;
@@ -0,0 +1,111 @@
1
+ import { dirname, join } from 'node:path';
2
+ function describe(result, what) {
3
+ return `${what} failed (${result.code}): ${(result.stderr || result.stdout).trim() || 'no output'}`;
4
+ }
5
+ function expectSuccess(result, what) {
6
+ if (result.code !== 0) {
7
+ throw new Error(describe(result, what));
8
+ }
9
+ }
10
+ /*
11
+ * A plist in ~/Library/LaunchAgents, loaded with `launchctl bootstrap` into the person's GUI domain.
12
+ * SMAppService (Electron's `agentService`) was the other way: it wants a plist that is sealed inside
13
+ * the bundle, where the login shell's PATH and a log path in the home cannot be written.
14
+ */
15
+ export function launchdManager(options) {
16
+ const label = options.label;
17
+ const path = join(options.home, 'Library', 'LaunchAgents', `${label}.plist`);
18
+ const domain = `gui/${options.uid}`;
19
+ const target = `${domain}/${label}`;
20
+ const launchctl = (...args) => options.run('/bin/launchctl', args);
21
+ const isLoaded = () => launchctl('print', target).code === 0;
22
+ const bootstrap = () => {
23
+ expectSuccess(launchctl('bootstrap', domain, path), 'launchctl bootstrap');
24
+ };
25
+ return {
26
+ kind: 'launchd',
27
+ path,
28
+ isInstalled: () => options.files.read(path) !== null,
29
+ read: () => options.files.read(path),
30
+ install(definition) {
31
+ // launchd opens the log but makes no folder for it, and a job whose log cannot open never starts.
32
+ options.files.makeDirectory(dirname(options.logFile));
33
+ const previous = options.files.read(path);
34
+ if (previous !== definition) {
35
+ options.files.write(path, definition);
36
+ }
37
+ return previous !== null && previous !== definition;
38
+ },
39
+ start() {
40
+ if (isLoaded()) {
41
+ expectSuccess(launchctl('kickstart', target), 'launchctl kickstart');
42
+ return;
43
+ }
44
+ bootstrap();
45
+ },
46
+ async restart() {
47
+ if (isLoaded()) {
48
+ launchctl('bootout', target);
49
+ // bootout returns before the label is released; bootstrapping sooner fails with an I/O error.
50
+ for (let attempt = 0; attempt < 25 && isLoaded(); attempt++) {
51
+ await options.sleep(200);
52
+ }
53
+ }
54
+ bootstrap();
55
+ },
56
+ stop() {
57
+ if (isLoaded()) {
58
+ launchctl('bootout', target);
59
+ }
60
+ },
61
+ uninstall() {
62
+ options.files.remove(path);
63
+ }
64
+ };
65
+ }
66
+ /* A user unit under ~/.config/systemd/user, enabled for `default.target`. */
67
+ export function systemdManager(options) {
68
+ const unit = options.unitName;
69
+ const path = join(options.configHome, 'systemd', 'user', unit);
70
+ const systemctl = (...args) => options.run('systemctl', ['--user', ...args]);
71
+ const reload = () => {
72
+ expectSuccess(systemctl('daemon-reload'), 'systemctl daemon-reload');
73
+ };
74
+ return {
75
+ kind: 'systemd',
76
+ path,
77
+ isInstalled: () => options.files.read(path) !== null,
78
+ read: () => options.files.read(path),
79
+ install(definition) {
80
+ const previous = options.files.read(path);
81
+ if (previous !== definition) {
82
+ options.files.write(path, definition);
83
+ reload();
84
+ }
85
+ expectSuccess(systemctl('enable', unit), 'systemctl enable');
86
+ return previous !== null && previous !== definition;
87
+ },
88
+ start() {
89
+ expectSuccess(systemctl('start', unit), 'systemctl start');
90
+ },
91
+ async restart() {
92
+ reload();
93
+ expectSuccess(systemctl('restart', unit), 'systemctl restart');
94
+ },
95
+ stop() {
96
+ systemctl('stop', unit);
97
+ },
98
+ uninstall() {
99
+ systemctl('disable', unit);
100
+ options.files.remove(path);
101
+ // A running unit stays loaded without its file, so `stop` still reaches it afterwards.
102
+ systemctl('daemon-reload');
103
+ },
104
+ linger: {
105
+ enabled: () => options.run('loginctl', ['show-user', options.user, '--property=Linger', '--value']).stdout.trim() === 'yes',
106
+ enable() {
107
+ expectSuccess(options.run('loginctl', ['enable-linger', options.user]), 'loginctl enable-linger');
108
+ }
109
+ }
110
+ };
111
+ }
@@ -0,0 +1,8 @@
1
+ import { type ServiceSpec } from './definitions.js';
2
+ import { type LaunchdOptions, type ServiceManager, type SystemdOptions } from './manager.js';
3
+ export interface PlatformServiceOptions {
4
+ launchd: LaunchdOptions;
5
+ systemd: SystemdOptions;
6
+ }
7
+ export declare function platformServiceManager(platform: NodeJS.Platform, options: PlatformServiceOptions): ServiceManager | null;
8
+ export declare function serviceDefinition(platform: NodeJS.Platform, spec: ServiceSpec): string;
@@ -0,0 +1,20 @@
1
+ import { launchAgentPlist, systemdUnit } from './definitions.js';
2
+ import { launchdManager, systemdManager } from './manager.js';
3
+ export function platformServiceManager(platform, options) {
4
+ if (platform === 'darwin') {
5
+ return launchdManager(options.launchd);
6
+ }
7
+ if (platform === 'linux') {
8
+ return systemdManager(options.systemd);
9
+ }
10
+ return null;
11
+ }
12
+ export function serviceDefinition(platform, spec) {
13
+ if (platform === 'darwin') {
14
+ return launchAgentPlist(spec);
15
+ }
16
+ if (platform === 'linux') {
17
+ return systemdUnit(spec);
18
+ }
19
+ throw new Error(`Background services are unsupported on ${platform}.`);
20
+ }
@@ -0,0 +1,3 @@
1
+ import type { CommandResult, ServiceFiles } from './manager.js';
2
+ export declare function runCommand(command: string, args: string[]): CommandResult;
3
+ export declare const diskFiles: ServiceFiles;
package/dist/system.js ADDED
@@ -0,0 +1,28 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ /* The real launchctl, systemctl and loginctl under a service manager, bounded so a hung one cannot hold up a quit. */
5
+ export function runCommand(command, args) {
6
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 15_000, stdio: ['ignore', 'pipe', 'pipe'] });
7
+ return { code: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr || result.error?.message || '' };
8
+ }
9
+ export const diskFiles = {
10
+ read(path) {
11
+ try {
12
+ return readFileSync(path, 'utf8');
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ },
18
+ write(path, text) {
19
+ mkdirSync(dirname(path), { recursive: true });
20
+ writeFileSync(path, text);
21
+ },
22
+ remove(path) {
23
+ rmSync(path, { force: true });
24
+ },
25
+ makeDirectory(path) {
26
+ mkdirSync(path, { recursive: true });
27
+ }
28
+ };
package/package.json CHANGED
@@ -1,11 +1,58 @@
1
1
  {
2
2
  "name": "@adecore/service",
3
- "version": "0.0.1",
4
- "description": "Placeholder for the first release.",
3
+ "version": "0.17.0-beta.1",
4
+ "description": "User service definitions and injectable launchd and systemd managers.",
5
5
  "license": "FSL-1.1-MIT",
6
+ "author": "Bas Milius",
6
7
  "repository": {
7
8
  "type": "git",
8
9
  "url": "git+https://github.com/basmilius/adecore.git",
9
10
  "directory": "packages/service"
11
+ },
12
+ "homepage": "https://adecore.dev/service/",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "files": [
16
+ "dist",
17
+ "src",
18
+ "!src/**/*.test.ts",
19
+ "!src/**/__snapshots__"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./definitions": {
28
+ "source": "./src/definitions.ts",
29
+ "types": "./dist/definitions.d.ts",
30
+ "default": "./dist/definitions.js"
31
+ },
32
+ "./manager": {
33
+ "source": "./src/manager.ts",
34
+ "types": "./dist/manager.d.ts",
35
+ "default": "./dist/manager.js"
36
+ },
37
+ "./platform": {
38
+ "source": "./src/platform.ts",
39
+ "types": "./dist/platform.d.ts",
40
+ "default": "./dist/platform.js"
41
+ },
42
+ "./system": {
43
+ "source": "./src/system.ts",
44
+ "types": "./dist/system.d.ts",
45
+ "default": "./dist/system.js"
46
+ }
47
+ },
48
+ "scripts": {
49
+ "build": "bun scripts/build.ts",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "bun test"
52
+ },
53
+ "devDependencies": {
54
+ "@types/bun": "^1.4.2",
55
+ "@types/node": "^24.13.6",
56
+ "typescript": "^7.0.2"
10
57
  }
11
58
  }
@@ -0,0 +1,104 @@
1
+ export interface ServiceSpec {
2
+ label: string;
3
+ description: string;
4
+ program: string;
5
+ args: string[];
6
+ environment: Record<string, string>;
7
+ workingDirectory: string;
8
+ /* launchd only: where stdout and stderr go. systemd has the journal. */
9
+ logFile: string;
10
+ }
11
+
12
+ function xmlText(value: string): string {
13
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
14
+ }
15
+
16
+ function plistString(value: string, indent: string): string {
17
+ return `${indent}<string>${xmlText(value)}</string>`;
18
+ }
19
+
20
+ /*
21
+ * `ProcessType=Interactive` avoids launchd throttling during a handover to a background process.
22
+ */
23
+ export function launchAgentPlist(spec: ServiceSpec): string {
24
+ const lines = [
25
+ '<?xml version="1.0" encoding="UTF-8"?>',
26
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
27
+ '<plist version="1.0">',
28
+ '<dict>',
29
+ ' <key>Label</key>',
30
+ plistString(spec.label, ' '),
31
+ ' <key>ProgramArguments</key>',
32
+ ' <array>',
33
+ ...[spec.program, ...spec.args].map((arg) => plistString(arg, ' ')),
34
+ ' </array>',
35
+ ' <key>EnvironmentVariables</key>',
36
+ ' <dict>'
37
+ ];
38
+ for (const [name, value] of Object.entries(spec.environment)) {
39
+ lines.push(` <key>${xmlText(name)}</key>`, plistString(value, ' '));
40
+ }
41
+ lines.push(
42
+ ' </dict>',
43
+ ' <key>WorkingDirectory</key>',
44
+ plistString(spec.workingDirectory, ' '),
45
+ ' <key>RunAtLoad</key>',
46
+ ' <true/>',
47
+ ' <key>KeepAlive</key>',
48
+ ' <true/>',
49
+ ' <key>ProcessType</key>',
50
+ ' <string>Interactive</string>',
51
+ ' <key>StandardOutPath</key>',
52
+ plistString(spec.logFile, ' '),
53
+ ' <key>StandardErrorPath</key>',
54
+ plistString(spec.logFile, ' '),
55
+ '</dict>',
56
+ '</plist>',
57
+ ''
58
+ );
59
+ return lines.join('\n');
60
+ }
61
+
62
+ /* systemd expands `%` specifiers everywhere and `$` variables in a command line, so both are doubled; quotes keep a space in a path. */
63
+ function unitWord(value: string, command: boolean): string {
64
+ let escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%');
65
+ if (command) {
66
+ escaped = escaped.replace(/\$/g, '$$$$');
67
+ }
68
+ return `"${escaped}"`;
69
+ }
70
+
71
+ /*
72
+ * User services stop at logout unless the caller explicitly enables lingering.
73
+ */
74
+ export function systemdUnit(spec: ServiceSpec): string {
75
+ const lines = [
76
+ '[Unit]',
77
+ `Description=${spec.description.replace(/%/g, '%%')}`,
78
+ '',
79
+ '[Service]',
80
+ 'Type=simple',
81
+ `ExecStart=${[spec.program, ...spec.args].map((word) => unitWord(word, true)).join(' ')}`,
82
+ ...Object.entries(spec.environment).map(([name, value]) => `Environment=${unitWord(`${name}=${value}`, false)}`),
83
+ // The one setting here that takes no quotes: it reads the rest of the line as the path.
84
+ `WorkingDirectory=${spec.workingDirectory.replace(/%/g, '%%')}`,
85
+ 'Restart=always',
86
+ 'RestartSec=2',
87
+ '',
88
+ '[Install]',
89
+ 'WantedBy=default.target',
90
+ ''
91
+ ];
92
+ return lines.join('\n');
93
+ }
94
+
95
+ /*
96
+ * Callers sharing a service identity can check executable ownership before replacing its definition.
97
+ */
98
+ export function definitionRunsProgram(definition: string, program: string): boolean {
99
+ return (
100
+ definition.includes(`<string>${xmlText(program)}</string>`) ||
101
+ definition.includes(`ExecStart=${unitWord(program, true)} `) ||
102
+ definition.includes(`ExecStart=${unitWord(program, true)}\n`)
103
+ );
104
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ export { definitionRunsProgram, launchAgentPlist, systemdUnit, type ServiceSpec } from './definitions.js';
2
+ export {
3
+ launchdManager,
4
+ systemdManager,
5
+ type CommandResult,
6
+ type CommandRunner,
7
+ type LaunchdOptions,
8
+ type ServiceFiles,
9
+ type ServiceManager,
10
+ type SystemdOptions
11
+ } from './manager.js';
12
+ export { platformServiceManager, serviceDefinition, type PlatformServiceOptions } from './platform.js';
13
+ export { diskFiles, runCommand } from './system.js';
package/src/manager.ts ADDED
@@ -0,0 +1,178 @@
1
+ import { dirname, join } from 'node:path';
2
+
3
+ export interface CommandResult {
4
+ code: number;
5
+ stdout: string;
6
+ stderr: string;
7
+ }
8
+
9
+ /* Runs a command to completion, bounded by a timeout. Synchronous, because quitting cannot wait on a promise. */
10
+ export type CommandRunner = (command: string, args: string[]) => CommandResult;
11
+
12
+ export interface ServiceFiles {
13
+ read(path: string): string | null;
14
+ write(path: string, text: string): void;
15
+ remove(path: string): void;
16
+ /* With every parent, and nothing when it is there already. */
17
+ makeDirectory(path: string): void;
18
+ }
19
+
20
+ export interface ServiceManager {
21
+ readonly kind: 'launchd' | 'systemd';
22
+ /* Where the definition lives, for the documentation and the error a person reads. */
23
+ readonly path: string;
24
+ isInstalled(): boolean;
25
+ /* The definition on disk, null when there is none. */
26
+ read(): string | null;
27
+ /*
28
+ * Puts the definition on disk, so the service starts with the person's session. A running daemon
29
+ * keeps running, on the definition it was started from: true says that one is not this one.
30
+ */
31
+ install(definition: string): boolean;
32
+ /* Starts the daemon from the definition on disk; nothing when it already runs. */
33
+ start(): void;
34
+ /* Ends the running daemon and starts it from the definition on disk, which is how a new binary takes over. */
35
+ restart(): Promise<void>;
36
+ /* Ends the running daemon. The definition stays. */
37
+ stop(): void;
38
+ /* Takes the definition away, so nothing starts it again. A running daemon keeps running until `stop`. */
39
+ uninstall(): void;
40
+ /* Linux only: whether the person's services outlive their session, and the step that makes them. */
41
+ linger?: { enabled(): boolean; enable(): void };
42
+ }
43
+
44
+ function describe(result: CommandResult, what: string): string {
45
+ return `${what} failed (${result.code}): ${(result.stderr || result.stdout).trim() || 'no output'}`;
46
+ }
47
+
48
+ function expectSuccess(result: CommandResult, what: string): void {
49
+ if (result.code !== 0) {
50
+ throw new Error(describe(result, what));
51
+ }
52
+ }
53
+
54
+ export interface LaunchdOptions {
55
+ uid: number;
56
+ home: string;
57
+ run: CommandRunner;
58
+ files: ServiceFiles;
59
+ sleep(ms: number): Promise<void>;
60
+ label: string;
61
+ logFile: string;
62
+ }
63
+
64
+ /*
65
+ * A plist in ~/Library/LaunchAgents, loaded with `launchctl bootstrap` into the person's GUI domain.
66
+ * SMAppService (Electron's `agentService`) was the other way: it wants a plist that is sealed inside
67
+ * the bundle, where the login shell's PATH and a log path in the home cannot be written.
68
+ */
69
+ export function launchdManager(options: LaunchdOptions): ServiceManager {
70
+ const label = options.label;
71
+ const path = join(options.home, 'Library', 'LaunchAgents', `${label}.plist`);
72
+ const domain = `gui/${options.uid}`;
73
+ const target = `${domain}/${label}`;
74
+ const launchctl = (...args: string[]): CommandResult => options.run('/bin/launchctl', args);
75
+ const isLoaded = (): boolean => launchctl('print', target).code === 0;
76
+
77
+ const bootstrap = (): void => {
78
+ expectSuccess(launchctl('bootstrap', domain, path), 'launchctl bootstrap');
79
+ };
80
+
81
+ return {
82
+ kind: 'launchd',
83
+ path,
84
+ isInstalled: () => options.files.read(path) !== null,
85
+ read: () => options.files.read(path),
86
+ install(definition) {
87
+ // launchd opens the log but makes no folder for it, and a job whose log cannot open never starts.
88
+ options.files.makeDirectory(dirname(options.logFile));
89
+ const previous = options.files.read(path);
90
+ if (previous !== definition) {
91
+ options.files.write(path, definition);
92
+ }
93
+ return previous !== null && previous !== definition;
94
+ },
95
+ start() {
96
+ if (isLoaded()) {
97
+ expectSuccess(launchctl('kickstart', target), 'launchctl kickstart');
98
+ return;
99
+ }
100
+ bootstrap();
101
+ },
102
+ async restart() {
103
+ if (isLoaded()) {
104
+ launchctl('bootout', target);
105
+ // bootout returns before the label is released; bootstrapping sooner fails with an I/O error.
106
+ for (let attempt = 0; attempt < 25 && isLoaded(); attempt++) {
107
+ await options.sleep(200);
108
+ }
109
+ }
110
+ bootstrap();
111
+ },
112
+ stop() {
113
+ if (isLoaded()) {
114
+ launchctl('bootout', target);
115
+ }
116
+ },
117
+ uninstall() {
118
+ options.files.remove(path);
119
+ }
120
+ };
121
+ }
122
+
123
+ export interface SystemdOptions {
124
+ configHome: string;
125
+ run: CommandRunner;
126
+ files: ServiceFiles;
127
+ user: string;
128
+ unitName: string;
129
+ }
130
+
131
+ /* A user unit under ~/.config/systemd/user, enabled for `default.target`. */
132
+ export function systemdManager(options: SystemdOptions): ServiceManager {
133
+ const unit = options.unitName;
134
+ const path = join(options.configHome, 'systemd', 'user', unit);
135
+ const systemctl = (...args: string[]): CommandResult => options.run('systemctl', ['--user', ...args]);
136
+
137
+ const reload = (): void => {
138
+ expectSuccess(systemctl('daemon-reload'), 'systemctl daemon-reload');
139
+ };
140
+
141
+ return {
142
+ kind: 'systemd',
143
+ path,
144
+ isInstalled: () => options.files.read(path) !== null,
145
+ read: () => options.files.read(path),
146
+ install(definition) {
147
+ const previous = options.files.read(path);
148
+ if (previous !== definition) {
149
+ options.files.write(path, definition);
150
+ reload();
151
+ }
152
+ expectSuccess(systemctl('enable', unit), 'systemctl enable');
153
+ return previous !== null && previous !== definition;
154
+ },
155
+ start() {
156
+ expectSuccess(systemctl('start', unit), 'systemctl start');
157
+ },
158
+ async restart() {
159
+ reload();
160
+ expectSuccess(systemctl('restart', unit), 'systemctl restart');
161
+ },
162
+ stop() {
163
+ systemctl('stop', unit);
164
+ },
165
+ uninstall() {
166
+ systemctl('disable', unit);
167
+ options.files.remove(path);
168
+ // A running unit stays loaded without its file, so `stop` still reaches it afterwards.
169
+ systemctl('daemon-reload');
170
+ },
171
+ linger: {
172
+ enabled: () => options.run('loginctl', ['show-user', options.user, '--property=Linger', '--value']).stdout.trim() === 'yes',
173
+ enable() {
174
+ expectSuccess(options.run('loginctl', ['enable-linger', options.user]), 'loginctl enable-linger');
175
+ }
176
+ }
177
+ };
178
+ }
@@ -0,0 +1,27 @@
1
+ import { launchAgentPlist, systemdUnit, type ServiceSpec } from './definitions.js';
2
+ import { launchdManager, systemdManager, type LaunchdOptions, type ServiceManager, type SystemdOptions } from './manager.js';
3
+
4
+ export interface PlatformServiceOptions {
5
+ launchd: LaunchdOptions;
6
+ systemd: SystemdOptions;
7
+ }
8
+
9
+ export function platformServiceManager(platform: NodeJS.Platform, options: PlatformServiceOptions): ServiceManager | null {
10
+ if (platform === 'darwin') {
11
+ return launchdManager(options.launchd);
12
+ }
13
+ if (platform === 'linux') {
14
+ return systemdManager(options.systemd);
15
+ }
16
+ return null;
17
+ }
18
+
19
+ export function serviceDefinition(platform: NodeJS.Platform, spec: ServiceSpec): string {
20
+ if (platform === 'darwin') {
21
+ return launchAgentPlist(spec);
22
+ }
23
+ if (platform === 'linux') {
24
+ return systemdUnit(spec);
25
+ }
26
+ throw new Error(`Background services are unsupported on ${platform}.`);
27
+ }
package/src/system.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ import type { CommandResult, ServiceFiles } from './manager.js';
5
+
6
+ /* The real launchctl, systemctl and loginctl under a service manager, bounded so a hung one cannot hold up a quit. */
7
+ export function runCommand(command: string, args: string[]): CommandResult {
8
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 15_000, stdio: ['ignore', 'pipe', 'pipe'] });
9
+ return { code: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr || result.error?.message || '' };
10
+ }
11
+
12
+ export const diskFiles: ServiceFiles = {
13
+ read(path) {
14
+ try {
15
+ return readFileSync(path, 'utf8');
16
+ } catch {
17
+ return null;
18
+ }
19
+ },
20
+ write(path, text) {
21
+ mkdirSync(dirname(path), { recursive: true });
22
+ writeFileSync(path, text);
23
+ },
24
+ remove(path) {
25
+ rmSync(path, { force: true });
26
+ },
27
+ makeDirectory(path) {
28
+ mkdirSync(path, { recursive: true });
29
+ }
30
+ };