ubuntu-service-create 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 KeshavSoft
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,148 @@
1
- # Temporary Holding Version
1
+ # ubuntu-service-create
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/badge/npm-v1.0.0-orange.svg)](https://www.npmjs.com/package/ubuntu-service-create)
4
+ [![License: ISC](https://img.shields.io/badge/License-ISC-green.svg)](https://opensource.org/licenses/ISC)
5
+ [![Docs Hub](https://img.shields.io/badge/docs-ubuntu--service--docs-sky.svg)](https://keshavsoft.github.io/ubuntu-service-docs/)
6
+ [![Organization](https://img.shields.io/badge/org-KeshavSoft-purple.svg)](https://github.com/keshavsoft)
7
+ [![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org)
8
+
9
+ > **Author, validate, and write standard Ubuntu systemd service unit files matching KeshavSoft VPS conventions.**
10
+ > The creation & birth engine of the `ubuntu-service` single-service family.
11
+
12
+ ---
13
+
14
+ ## 🎯 Purpose in the Service Lifecycle
15
+
16
+ When deploying an application on an Ubuntu VPS, the lifecycle consists of four decoupled steps:
17
+
18
+ ```
19
+ 1. CREATE ➔ ubuntu-service-create (Birth of .service file on VPS)
20
+ 2. DETECT ➔ ubuntu-service-detect (Locates service belonging to cwd)
21
+ 3. RESTART ➔ ubuntu-service-restart (Safely executes systemctl restart & poll)
22
+ 4. NETWORK ➔ ubuntu-service-port (Maps and verifies active port assignments)
23
+ ```
24
+
25
+ `ubuntu-service-create` is responsible for **Step 1**: generating valid systemd unit files conforming to KeshavSoft conventions (`EnvironmentFile=.env`, `ExecStart=node app.js`, `Restart=on-failure`, `PORT=<port>`), and optionally writing them directly to `/etc/systemd/system/` and activating them.
26
+
27
+ ---
28
+
29
+ ## ⚡ Quick Start (CLI)
30
+
31
+ Run directly via `npx` with zero installation:
32
+
33
+ ```bash
34
+ # 1. Inside your app directory (/root/KeshavSoft/appointment-booking):
35
+ npx ubuntu-service-create 3004
36
+
37
+ # 2. Or using the shortcut binary 'usc':
38
+ npx usc appointment-booking 3004
39
+
40
+ # 3. Write directly to /etc/systemd/system/appointment-booking.service:
41
+ npx usc appointment-booking 3004 --write
42
+
43
+ # 4. Complete 1-shot deployment: write + reload daemon + enable & start now:
44
+ npx usc appointment-booking 3004 --enable
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 📋 CLI Usage & Options
50
+
51
+ ```text
52
+ ubuntu-service-create (usc) — Author and create Ubuntu systemd services for KeshavSoft VPS apps
53
+
54
+ Usage:
55
+ npx ubuntu-service-create <name> <port> [workingDir] [options]
56
+ npx ubuntu-service-create <port> [options]
57
+
58
+ Commands:
59
+ (default) Generate service unit file content to stdout
60
+ --write, -w Write the service unit file directly to /etc/systemd/system/
61
+ --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
62
+
63
+ Options:
64
+ --dir <path> Target directory (defaults to /etc/systemd/system)
65
+ --exec <cmd> Custom ExecStart command
66
+ --user <user> Service user (defaults to 'root')
67
+ --env <env> NODE_ENV value (defaults to 'production')
68
+ --json Output machine-readable JSON
69
+ -h, --help Show this help message
70
+ -v, --version Show version number
71
+ ```
72
+
73
+ ---
74
+
75
+ ## 💻 Programmatic API
76
+
77
+ ```bash
78
+ npm install ubuntu-service-create
79
+ ```
80
+
81
+ ```javascript
82
+ import { generateServiceUnit, writeServiceUnit, createService } from "ubuntu-service-create";
83
+
84
+ // 1. Pure text generation (zero side-effects)
85
+ const unitContent = generateServiceUnit({
86
+ name: "appointment-booking",
87
+ port: 3004,
88
+ workingDirectory: "/root/KeshavSoft/appointment-booking"
89
+ });
90
+
91
+ console.log(unitContent);
92
+
93
+ // 2. High-level creator with direct write
94
+ const result = createService({
95
+ name: "appointment-booking",
96
+ port: 3004,
97
+ write: true,
98
+ enable: true // Reloads daemon and starts service
99
+ });
100
+
101
+ console.log(result.path); // /etc/systemd/system/appointment-booking.service
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 📄 Output Unit Standard
107
+
108
+ ```ini
109
+ [Unit]
110
+ Description=appointment-booking Node Service
111
+ After=network.target
112
+
113
+ [Service]
114
+ Type=simple
115
+ User=root
116
+ WorkingDirectory=/root/KeshavSoft/appointment-booking
117
+
118
+ Environment=NODE_ENV=production
119
+ Environment=PORT=3004
120
+ EnvironmentFile=/root/KeshavSoft/appointment-booking/.env
121
+
122
+ ExecStart=/root/.nvm/versions/node/v24.13.0/bin/node app.js
123
+
124
+ Restart=on-failure
125
+ RestartSec=5
126
+
127
+ StandardOutput=journal
128
+ StandardError=journal
129
+
130
+ [Install]
131
+ WantedBy=multi-user.target
132
+ ```
133
+
134
+ ---
135
+
136
+ ## 🧪 Testing
137
+
138
+ Run the native Node.js test suite:
139
+
140
+ ```bash
141
+ npm test
142
+ ```
143
+
144
+ ---
145
+
146
+ ## 📄 License
147
+
148
+ ISC License (c) 2026 KeshavSoft
package/bin/index.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from "../src/cli.js";
4
+
5
+ const code = runCli(process.argv.slice(2));
6
+ if (typeof code === "number") {
7
+ process.exitCode = code;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "ubuntu-service-create",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Author, validate, and write standard Ubuntu systemd service unit files matching KeshavSoft VPS conventions.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./v1": "./src/v1/index.js"
10
+ },
11
+ "bin": {
12
+ "ubuntu-service-create": "bin/index.js",
13
+ "usc": "bin/index.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "start": "node bin/index.js",
22
+ "cli": "node bin/index.js",
23
+ "test": "node --test"
24
+ },
25
+ "keywords": [
26
+ "ubuntu",
27
+ "systemd",
28
+ "service",
29
+ "create",
30
+ "generate",
31
+ "cli",
32
+ "keshavsoft",
33
+ "vps",
34
+ "hosting"
35
+ ],
36
+ "author": "KeshavSoft",
37
+ "license": "ISC",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/keshavsoft/ubuntu-service-create.git"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/keshavsoft/ubuntu-service-create/issues"
44
+ },
45
+ "homepage": "https://keshavsoft.github.io/ubuntu-service-docs/",
46
+ "engines": {
47
+ "node": ">=18.0.0"
48
+ }
49
+ }
package/src/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./v1/cli.js";
2
+ export { default } from "./v1/cli.js";
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./v1/index.js";
2
+ export { default } from "./v1/index.js";
package/src/v1/cli.js ADDED
@@ -0,0 +1,166 @@
1
+ import { generateServiceUnit } from "./generator.js";
2
+ import { writeServiceUnit, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
+ import { basename } from "node:path";
4
+
5
+ export function printHelp() {
6
+ console.log(`
7
+ ubuntu-service-create (usc) — Author and create Ubuntu systemd services for KeshavSoft VPS apps
8
+
9
+ Usage:
10
+ npx ubuntu-service-create <name> <port> [workingDir] [options]
11
+ npx ubuntu-service-create <port> [options]
12
+
13
+ Commands:
14
+ (default) Generate service unit file content to stdout
15
+ --write, -w Write the service unit file directly to /etc/systemd/system/
16
+ --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
17
+
18
+ Options:
19
+ --dir <path> Target directory (defaults to /etc/systemd/system)
20
+ --exec <cmd> Custom ExecStart command
21
+ --user <user> Service user (defaults to 'root')
22
+ --env <env> NODE_ENV value (defaults to 'production')
23
+ --json Output machine-readable JSON
24
+ -h, --help Show this help message
25
+ -v, --version Show version number
26
+
27
+ Examples:
28
+ # Stand in /root/KeshavSoft/appointment-booking and print unit file:
29
+ npx usc 3004
30
+
31
+ # Explicit name and port:
32
+ npx usc appointment-booking 3004
33
+
34
+ # Write unit file to /etc/systemd/system/appointment-booking.service:
35
+ npx usc appointment-booking 3004 --write
36
+
37
+ # Complete 1-shot deployment: write, reload daemon, and start immediately:
38
+ npx usc appointment-booking 3004 --enable
39
+ `);
40
+ }
41
+
42
+ export function runCli(argv = process.argv.slice(2)) {
43
+ if (argv.includes("-h") || argv.includes("--help")) {
44
+ printHelp();
45
+ return 0;
46
+ }
47
+
48
+ if (argv.includes("-v") || argv.includes("--version")) {
49
+ console.log("1.0.0");
50
+ return 0;
51
+ }
52
+
53
+ const isJson = argv.includes("--json");
54
+ const isWrite = argv.includes("-w") || argv.includes("--write");
55
+ const isEnable = argv.includes("-e") || argv.includes("--enable");
56
+
57
+ // Extract options
58
+ let customDir = null;
59
+ const dirIdx = argv.indexOf("--dir");
60
+ if (dirIdx !== -1 && argv[dirIdx + 1]) {
61
+ customDir = argv[dirIdx + 1];
62
+ }
63
+
64
+ let customExec = null;
65
+ const execIdx = argv.indexOf("--exec");
66
+ if (execIdx !== -1 && argv[execIdx + 1]) {
67
+ customExec = argv[execIdx + 1];
68
+ }
69
+
70
+ let customUser = "root";
71
+ const userIdx = argv.indexOf("--user");
72
+ if (userIdx !== -1 && argv[userIdx + 1]) {
73
+ customUser = argv[userIdx + 1];
74
+ }
75
+
76
+ let customEnv = "production";
77
+ const envIdx = argv.indexOf("--env");
78
+ if (envIdx !== -1 && argv[envIdx + 1]) {
79
+ customEnv = argv[envIdx + 1];
80
+ }
81
+
82
+ // Filter out flags from positional arguments
83
+ const positional = argv.filter((arg, i) => {
84
+ if (["--json", "-h", "--help", "-v", "--version", "-w", "--write", "-e", "--enable"].includes(arg)) return false;
85
+ if (["--dir", "--exec", "--user", "--env"].includes(arg)) return false;
86
+ if (i > 0 && ["--dir", "--exec", "--user", "--env"].includes(argv[i - 1])) return false;
87
+ return true;
88
+ });
89
+
90
+ if (positional.length === 0) {
91
+ console.error("Error: Port number is required.");
92
+ console.error("Example: npx usc 3004 or npx usc appointment-booking 3004");
93
+ return 1;
94
+ }
95
+
96
+ let serviceName;
97
+ let port;
98
+ let workingDirectory = null;
99
+
100
+ // Check if first arg is purely a port number (e.g. `usc 3004`)
101
+ if (/^\d{2,5}$/.test(positional[0]) && positional.length === 1) {
102
+ port = positional[0];
103
+ serviceName = basename(process.cwd());
104
+ } else {
105
+ serviceName = positional[0];
106
+ port = positional[1];
107
+ if (positional[2]) {
108
+ workingDirectory = positional[2];
109
+ }
110
+ }
111
+
112
+ if (!port || isNaN(Number(port))) {
113
+ console.error(`Error: A valid port number is required. Received: '${port}'`);
114
+ return 1;
115
+ }
116
+
117
+ try {
118
+ const unitContent = generateServiceUnit({
119
+ name: serviceName,
120
+ port,
121
+ workingDirectory,
122
+ execStart: customExec || undefined,
123
+ user: customUser,
124
+ nodeEnv: customEnv
125
+ });
126
+
127
+ if (isWrite || isEnable) {
128
+ const writeResult = writeServiceUnit(serviceName, unitContent, {
129
+ dir: customDir,
130
+ enable: isEnable
131
+ });
132
+
133
+ if (isJson) {
134
+ console.log(JSON.stringify(writeResult, null, 2));
135
+ return writeResult.success ? 0 : 1;
136
+ }
137
+
138
+ console.log(`\n======================================================`);
139
+ console.log(` ✅ Service Unit Created: ${writeResult.unitName}`);
140
+ console.log(` Location: ${writeResult.path}`);
141
+ if (isEnable) {
142
+ console.log(` Status: ${writeResult.simulated ? "Simulated (Non-Linux)" : (writeResult.started ? "Enabled & Active" : "Failed to start")}`);
143
+ }
144
+ console.log(`======================================================\n`);
145
+ return 0;
146
+ }
147
+
148
+ // Default: Print to stdout
149
+ if (isJson) {
150
+ console.log(JSON.stringify({
151
+ serviceName,
152
+ port,
153
+ unitContent
154
+ }, null, 2));
155
+ return 0;
156
+ }
157
+
158
+ process.stdout.write(unitContent);
159
+ return 0;
160
+ } catch (err) {
161
+ console.error(`Error: ${err.message}`);
162
+ return 1;
163
+ }
164
+ }
165
+
166
+ export default runCli;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Systemd unit file generator for KeshavSoft VPS Node.js applications.
3
+ * Zero external dependencies.
4
+ */
5
+
6
+ export function generateServiceUnit({
7
+ name,
8
+ port,
9
+ workingDirectory,
10
+ execStart = "/root/.nvm/versions/node/v24.13.0/bin/node app.js",
11
+ user = "root",
12
+ nodeEnv = "production",
13
+ restartSec = 5,
14
+ description
15
+ }) {
16
+ if (!name) {
17
+ throw new Error("generateServiceUnit requires a service name / domain string.");
18
+ }
19
+
20
+ const cleanName = String(name).replace(/\.service$/i, "").trim();
21
+ if (!cleanName) {
22
+ throw new Error("Service name cannot be empty.");
23
+ }
24
+
25
+ const serviceDescription = description || `${cleanName} Node Service`;
26
+ const cleanWorkingDir = workingDirectory || `/root/KeshavSoft/${cleanName}`;
27
+
28
+ const lines = [
29
+ "[Unit]",
30
+ `Description=${serviceDescription}`,
31
+ "After=network.target",
32
+ "",
33
+ "[Service]",
34
+ "Type=simple",
35
+ `User=${user}`,
36
+ `WorkingDirectory=${cleanWorkingDir}`,
37
+ "",
38
+ `Environment=NODE_ENV=${nodeEnv}`
39
+ ];
40
+
41
+ if (port !== undefined && port !== null && port !== "") {
42
+ const numPort = Number(port);
43
+ if (isNaN(numPort) || numPort < 1 || numPort > 65535) {
44
+ throw new Error(`Invalid port number: ${port}. Must be between 1 and 65535.`);
45
+ }
46
+ lines.push(`Environment=PORT=${numPort}`);
47
+ }
48
+
49
+ lines.push(
50
+ `EnvironmentFile=${cleanWorkingDir}/.env`,
51
+ "",
52
+ `ExecStart=${execStart}`,
53
+ "",
54
+ "Restart=on-failure",
55
+ `RestartSec=${restartSec}`,
56
+ "",
57
+ "StandardOutput=journal",
58
+ "StandardError=journal",
59
+ "",
60
+ "[Install]",
61
+ "WantedBy=multi-user.target"
62
+ );
63
+
64
+ return lines.join("\n") + "\n";
65
+ }
@@ -0,0 +1,53 @@
1
+ import { generateServiceUnit } from "./generator.js";
2
+ import { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
+ import { basename } from "node:path";
4
+
5
+ export { generateServiceUnit } from "./generator.js";
6
+ export { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
7
+
8
+ /**
9
+ * High-level service creator. Combines generation and optional writing / enabling.
10
+ */
11
+ export function createService(options = {}) {
12
+ const cwdName = basename(process.cwd());
13
+ const name = options.name || cwdName;
14
+ const port = options.port;
15
+ const workingDirectory = options.workingDirectory || (process.platform === "linux" ? `/root/KeshavSoft/${name}` : process.cwd());
16
+
17
+ const unitContent = generateServiceUnit({
18
+ name,
19
+ port,
20
+ workingDirectory,
21
+ execStart: options.execStart,
22
+ user: options.user,
23
+ nodeEnv: options.nodeEnv,
24
+ restartSec: options.restartSec,
25
+ description: options.description
26
+ });
27
+
28
+ if (options.write || options.enable) {
29
+ const writeResult = writeServiceUnit(name, unitContent, {
30
+ dir: options.dir,
31
+ enable: options.enable
32
+ });
33
+ return {
34
+ ...writeResult,
35
+ content: unitContent
36
+ };
37
+ }
38
+
39
+ return {
40
+ success: true,
41
+ unitName: `${String(name).replace(/\.service$/i, "")}.service`,
42
+ content: unitContent,
43
+ written: false
44
+ };
45
+ }
46
+
47
+ export default {
48
+ generateServiceUnit,
49
+ writeServiceUnit,
50
+ createService,
51
+ isSystemctlAvailable,
52
+ DEFAULT_SYSTEMD_DIR
53
+ };
@@ -0,0 +1,66 @@
1
+ import { writeFileSync, mkdirSync, existsSync } from "node:fs";
2
+ import { resolve, join } from "node:path";
3
+ import { execSync } from "node:child_process";
4
+
5
+ export const DEFAULT_SYSTEMD_DIR = "/etc/systemd/system";
6
+
7
+ export function isSystemctlAvailable() {
8
+ if (process.platform !== "linux") return false;
9
+ try {
10
+ execSync("which systemctl 2>/dev/null", { stdio: "ignore" });
11
+ return true;
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+
17
+ export function writeServiceUnit(name, content, options = {}) {
18
+ if (!name) throw new Error("Service name is required to write unit file.");
19
+ if (!content) throw new Error("Unit content is required.");
20
+
21
+ const cleanName = String(name).replace(/\.service$/i, "").trim();
22
+ const unitFileName = `${cleanName}.service`;
23
+ const targetDir = options.dir ? resolve(options.dir) : DEFAULT_SYSTEMD_DIR;
24
+
25
+ if (!existsSync(targetDir)) {
26
+ mkdirSync(targetDir, { recursive: true });
27
+ }
28
+
29
+ const filePath = join(targetDir, unitFileName);
30
+ writeFileSync(filePath, content, "utf-8");
31
+
32
+ let enabled = false;
33
+ let started = false;
34
+ let simulated = false;
35
+
36
+ if (options.enable) {
37
+ if (!isSystemctlAvailable()) {
38
+ simulated = true;
39
+ } else {
40
+ try {
41
+ execSync("systemctl daemon-reload", { stdio: "inherit", timeout: 10000 });
42
+ execSync(`systemctl enable --now ${unitFileName}`, { stdio: "inherit", timeout: 15000 });
43
+ enabled = true;
44
+ started = true;
45
+ } catch (err) {
46
+ return {
47
+ success: true,
48
+ path: filePath,
49
+ unitName: unitFileName,
50
+ enabled: false,
51
+ started: false,
52
+ error: err.message
53
+ };
54
+ }
55
+ }
56
+ }
57
+
58
+ return {
59
+ success: true,
60
+ path: filePath,
61
+ unitName: unitFileName,
62
+ enabled: options.enable ? (simulated ? true : enabled) : false,
63
+ started: options.enable ? (simulated ? true : started) : false,
64
+ simulated
65
+ };
66
+ }