@stagepass/cli 1.0.1 → 2.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.
@@ -0,0 +1,96 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import {
5
+ formatBackupStamp,
6
+ migrateLegacyContent,
7
+ parseBlocks,
8
+ } from './caddyfile.js';
9
+ import { ensureMigratedProject } from './projects.js';
10
+ import { getCaddyfilePath, getProjectsPath } from './paths.js';
11
+
12
+ /**
13
+ * Detect legacy blocks, backup once, rewrite, sync projects.json.
14
+ * Idempotent: second run changes nothing and creates no backup.
15
+ *
16
+ * @param {object} [options]
17
+ * @param {string} [options.caddyfilePath]
18
+ * @param {string} [options.projectsPath]
19
+ * @param {boolean} [options.silent]
20
+ * @returns {Promise<{ changed: boolean, migrated: Array, skipped: Array, backupPath: string|null }>}
21
+ */
22
+ export async function ensureCaddyfileMigrated(options = {}) {
23
+ const caddyfilePath = options.caddyfilePath || getCaddyfilePath();
24
+ const projectsPath = options.projectsPath || getProjectsPath();
25
+ const silent = options.silent === true;
26
+
27
+ if (!(await fs.pathExists(caddyfilePath))) {
28
+ return { changed: false, migrated: [], skipped: [], backupPath: null };
29
+ }
30
+
31
+ const original = await fs.readFile(caddyfilePath, 'utf-8');
32
+ const result = migrateLegacyContent(original, {
33
+ warn: silent
34
+ ? () => {}
35
+ : (msg) => console.log(chalk.yellow(` ${msg}`)),
36
+ });
37
+
38
+ if (!result.changed) {
39
+ return {
40
+ changed: false,
41
+ migrated: [],
42
+ skipped: result.skipped,
43
+ backupPath: null,
44
+ };
45
+ }
46
+
47
+ const backupPath = `${caddyfilePath}.bak-${formatBackupStamp()}`;
48
+ await fs.copy(caddyfilePath, backupPath);
49
+ await fs.writeFile(caddyfilePath, result.content, 'utf-8');
50
+
51
+ for (const item of result.migrated) {
52
+ await ensureMigratedProject(item.domain, item.root, projectsPath);
53
+ }
54
+
55
+ if (!silent) {
56
+ console.log(
57
+ chalk.yellow(
58
+ ` Migrated ${result.migrated.length} legacy Caddy block(s). Backup: ${path.basename(backupPath)}`
59
+ )
60
+ );
61
+ for (const item of result.migrated) {
62
+ console.log(chalk.dim(` → ${item.domain} (allow-all-origins enabled for compatibility)`));
63
+ }
64
+ console.log(
65
+ chalk.yellow(
66
+ ' Tip: add your live domain with `stagepass link --origin example.com`, then `stagepass link --no-allow-all-origins`.'
67
+ )
68
+ );
69
+ }
70
+
71
+ return {
72
+ changed: true,
73
+ migrated: result.migrated,
74
+ skipped: result.skipped,
75
+ backupPath,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Print a one-line security warning when any linked project uses allowAllOrigins.
81
+ */
82
+ export async function warnIfAllowAllOriginsActive(options = {}) {
83
+ const caddyfilePath = options.caddyfilePath || getCaddyfilePath();
84
+ if (!(await fs.pathExists(caddyfilePath))) return;
85
+
86
+ const content = await fs.readFile(caddyfilePath, 'utf-8');
87
+ const blocks = parseBlocks(content);
88
+ const open = blocks.filter((b) => !b.isLegacy && b.options.allowAllOrigins);
89
+ if (open.length === 0) return;
90
+
91
+ console.log(
92
+ chalk.yellow(
93
+ ` Warning: allow-all-origins is active for: ${open.map((b) => b.domain).join(', ')}`
94
+ )
95
+ );
96
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * CORS origin allowlist helpers.
3
+ *
4
+ * Default patterns (anchored, case-insensitive):
5
+ * - https://*.sp
6
+ * - http(s)://localhost[:port]
7
+ * - http(s)://127.0.0.1[:port]
8
+ * - per-project live hostnames / *.wildcards / https:// origins
9
+ * (including explicit `*.webflow.io` when passed via --origin)
10
+ */
11
+
12
+ const UNSAFE_ORIGIN_RE = /[\s#"'{}$\\;()[\],<>|/]/;
13
+ const HOSTNAME_LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
14
+
15
+ /** Built-in Origin regex alternatives (without leading ^ / trailing $ / (?i)). */
16
+ export const DEFAULT_ORIGIN_ALTERNATIVES = Object.freeze([
17
+ 'https://([a-z0-9-]+\\.)*[a-z0-9-]+\\.sp',
18
+ 'https?://localhost(:[0-9]{1,5})?',
19
+ 'https?://127\\.0\\.0\\.1(:[0-9]{1,5})?',
20
+ ]);
21
+
22
+ /**
23
+ * Broad Webflow wildcards that allow any Webflow user's site.
24
+ * Allowed when passed explicitly via --origin, but deserve a warning.
25
+ *
26
+ * @param {string} entry - validated origin entry
27
+ * @returns {boolean}
28
+ */
29
+ export function isBroadWebflowWildcard(entry) {
30
+ return entry === '*.webflow.io' || entry === '*.webflow.com';
31
+ }
32
+
33
+ /**
34
+ * Validate a single live-domain / origin entry.
35
+ * Accepts: example.com | www.example.com | *.example.com | https://example.com
36
+ * Also accepts full Webflow staging hosts (my-project.webflow.io) and explicit
37
+ * wildcards (*.webflow.io) when passed by the user.
38
+ *
39
+ * @param {string} input
40
+ * @returns {{ ok: true, value: string } | { ok: false, error: string }}
41
+ */
42
+ export function validateOriginEntry(input) {
43
+ if (typeof input !== 'string' || input.trim() === '') {
44
+ return { ok: false, error: 'Origin entry is empty.' };
45
+ }
46
+
47
+ let raw = input.trim().toLowerCase();
48
+
49
+ if (/[\x00-\x1f\x7f]/.test(raw)) {
50
+ return { ok: false, error: 'Origin contains control characters.' };
51
+ }
52
+
53
+ // Optional https:// only (http reserved for localhost defaults)
54
+ if (raw.startsWith('http://')) {
55
+ return { ok: false, error: 'Live origins must use https:// (or a bare hostname).' };
56
+ }
57
+ if (raw.startsWith('https://')) {
58
+ raw = raw.slice('https://'.length);
59
+ }
60
+
61
+ // Reject paths / query / credentials leftovers
62
+ if (raw.includes('/') || raw.includes('?') || raw.includes('@') || raw.includes(':')) {
63
+ return { ok: false, error: 'Origin must be a hostname (optional leading *.), no path or port.' };
64
+ }
65
+
66
+ let wildcard = false;
67
+ if (raw.startsWith('*.')) {
68
+ wildcard = true;
69
+ raw = raw.slice(2);
70
+ }
71
+
72
+ if (!raw || raw.startsWith('.') || raw.endsWith('.') || raw.includes('..')) {
73
+ return { ok: false, error: 'Invalid hostname in origin entry.' };
74
+ }
75
+
76
+ // After stripping protocol / wildcard, remaining must be safe hostname chars only
77
+ if (UNSAFE_ORIGIN_RE.test(raw) || raw.includes('*')) {
78
+ return { ok: false, error: 'Origin contains invalid characters.' };
79
+ }
80
+
81
+ const labels = raw.split('.');
82
+ if (!labels.every((l) => HOSTNAME_LABEL_RE.test(l))) {
83
+ return { ok: false, error: 'Origin hostname labels are not DNS-safe.' };
84
+ }
85
+
86
+ const value = wildcard ? `*.${raw}` : raw;
87
+ return { ok: true, value };
88
+ }
89
+
90
+ /**
91
+ * @param {string[]} entries
92
+ * @returns {{ ok: true, origins: string[] } | { ok: false, error: string }}
93
+ */
94
+ export function validateOriginList(entries) {
95
+ const out = [];
96
+ const seen = new Set();
97
+ for (const entry of entries || []) {
98
+ const result = validateOriginEntry(entry);
99
+ if (!result.ok) return result;
100
+ if (!seen.has(result.value)) {
101
+ seen.add(result.value);
102
+ out.push(result.value);
103
+ }
104
+ }
105
+ return { ok: true, origins: out };
106
+ }
107
+
108
+ /**
109
+ * Escape a hostname for use inside a RE2 / Caddy regex (dots only; labels already validated).
110
+ * @param {string} hostname
111
+ */
112
+ export function escapeHostnameForRegex(hostname) {
113
+ return hostname.replace(/\./g, '\\.');
114
+ }
115
+
116
+ /**
117
+ * Convert a stored origin entry into a regex alternative matching https://...
118
+ * @param {string} entry - validated hostname or *.hostname
119
+ */
120
+ export function originEntryToRegexAlternative(entry) {
121
+ if (entry.startsWith('*.')) {
122
+ const host = escapeHostnameForRegex(entry.slice(2));
123
+ return `https://([a-z0-9-]+\\.)*${host}`;
124
+ }
125
+ return `https://${escapeHostnameForRegex(entry)}`;
126
+ }
127
+
128
+ /**
129
+ * Full Origin header regex for Caddy header_regexp (includes (?i) and anchors).
130
+ * @param {string[]} [customOrigins]
131
+ */
132
+ export function buildOriginAllowlistRegex(customOrigins = []) {
133
+ const validated = validateOriginList(customOrigins);
134
+ const customs = validated.ok ? validated.origins : [];
135
+ const parts = [
136
+ ...DEFAULT_ORIGIN_ALTERNATIVES,
137
+ ...customs.map(originEntryToRegexAlternative),
138
+ ];
139
+ return `(?i)^(?:${parts.join('|')})$`;
140
+ }
141
+
142
+ /**
143
+ * Whether a browser Origin would match the allowlist (for unit tests).
144
+ * Note: Caddy/RE2 accepts (?i) inline; JS RegExp needs the `i` flag instead.
145
+ * @param {string} origin
146
+ * @param {string[]} [customOrigins]
147
+ */
148
+ export function originMatchesAllowlist(origin, customOrigins = []) {
149
+ try {
150
+ let pattern = buildOriginAllowlistRegex(customOrigins);
151
+ let flags = '';
152
+ if (pattern.startsWith('(?i)')) {
153
+ pattern = pattern.slice(4);
154
+ flags = 'i';
155
+ }
156
+ return new RegExp(pattern, flags).test(origin);
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
@@ -0,0 +1,74 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+
4
+ /** Stagepass config directory (~/.stagepass). */
5
+ export function getStagepassDir() {
6
+ return path.join(os.homedir(), '.stagepass');
7
+ }
8
+
9
+ export function getCaddyfilePath() {
10
+ return path.join(getStagepassDir(), 'Caddyfile');
11
+ }
12
+
13
+ export function getProjectsPath() {
14
+ return path.join(getStagepassDir(), 'projects.json');
15
+ }
16
+
17
+ export function getServerLogPath() {
18
+ return path.join(getStagepassDir(), 'server.log');
19
+ }
20
+
21
+ /** System / dangerous roots that must never be linked as site roots. */
22
+ export const FORBIDDEN_ROOTS = Object.freeze([
23
+ '/',
24
+ '/Users',
25
+ '/System',
26
+ '/Library',
27
+ '/Applications',
28
+ '/private',
29
+ '/etc',
30
+ '/bin',
31
+ '/usr',
32
+ '/sbin',
33
+ '/var',
34
+ '/dev',
35
+ ]);
36
+
37
+ /**
38
+ * Escape a path for use inside a Caddyfile double-quoted token.
39
+ * @param {string} value
40
+ * @returns {string}
41
+ */
42
+ export function escapeCaddyQuotedString(value) {
43
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
44
+ }
45
+
46
+ /**
47
+ * Validate a project root path before writing it into the Caddyfile.
48
+ * @param {string} rootPath
49
+ * @returns {{ ok: true, path: string } | { ok: false, error: string }}
50
+ */
51
+ export function validateRoot(rootPath) {
52
+ if (typeof rootPath !== 'string' || rootPath.length === 0) {
53
+ return { ok: false, error: 'Project path is empty.' };
54
+ }
55
+
56
+ if (/[\x00-\x1f\x7f]/.test(rootPath)) {
57
+ return { ok: false, error: 'Project path contains control characters or newlines.' };
58
+ }
59
+
60
+ const resolved = path.resolve(rootPath);
61
+ const home = path.resolve(os.homedir());
62
+
63
+ if (resolved === home) {
64
+ return { ok: false, error: 'Refusing to link your home directory as a site root.' };
65
+ }
66
+
67
+ for (const forbidden of FORBIDDEN_ROOTS) {
68
+ if (resolved === path.resolve(forbidden)) {
69
+ return { ok: false, error: `Refusing to link system path "${forbidden}" as a site root.` };
70
+ }
71
+ }
72
+
73
+ return { ok: true, path: resolved };
74
+ }
@@ -0,0 +1,181 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import { getProjectsPath } from './paths.js';
4
+ import { validateOriginList } from './origins.js';
5
+
6
+ /**
7
+ * Per-project CORS settings stored in ~/.stagepass/projects.json
8
+ *
9
+ * Shape:
10
+ * {
11
+ * "version": 1,
12
+ * "projects": {
13
+ * "my-app.sp": {
14
+ * "root": "/absolute/path",
15
+ * "origins": ["example.com", "*.example.org"],
16
+ * "allowAllOrigins": false
17
+ * }
18
+ * }
19
+ * }
20
+ */
21
+
22
+ const DEFAULT_DOC = { version: 1, projects: {} };
23
+
24
+ /**
25
+ * @returns {Promise<{ version: number, projects: Record<string, object> }>}
26
+ */
27
+ export async function loadProjects(filePath = getProjectsPath()) {
28
+ if (!(await fs.pathExists(filePath))) {
29
+ return structuredClone(DEFAULT_DOC);
30
+ }
31
+ try {
32
+ const raw = await fs.readFile(filePath, 'utf-8');
33
+ const data = JSON.parse(raw);
34
+ if (!data || typeof data !== 'object' || typeof data.projects !== 'object') {
35
+ return structuredClone(DEFAULT_DOC);
36
+ }
37
+ return {
38
+ version: 1,
39
+ projects: data.projects || {},
40
+ };
41
+ } catch {
42
+ return structuredClone(DEFAULT_DOC);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * @param {{ version: number, projects: Record<string, object> }} doc
48
+ */
49
+ export async function saveProjects(doc, filePath = getProjectsPath()) {
50
+ await fs.ensureDir(path.dirname(filePath));
51
+ const payload = {
52
+ version: 1,
53
+ projects: doc.projects || {},
54
+ };
55
+ await fs.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf-8');
56
+ }
57
+
58
+ /**
59
+ * @param {string} domain
60
+ * @returns {Promise<{ root?: string, origins: string[], allowAllOrigins: boolean }|null>}
61
+ */
62
+ export async function getProject(domain, filePath = getProjectsPath()) {
63
+ const doc = await loadProjects(filePath);
64
+ const entry = doc.projects[domain];
65
+ if (!entry) return null;
66
+ return normalizeProjectEntry(entry);
67
+ }
68
+
69
+ /**
70
+ * Merge and persist project settings.
71
+ *
72
+ * Flag semantics for link:
73
+ * - originsFromFlags: when non-empty, merge into existing (deduped)
74
+ * - originsToRemove: when non-empty, remove matching stored origins (after merge)
75
+ * - allowAllOriginsFlag: true | false | undefined (undefined = keep existing / seed / default)
76
+ * - seed: when no projects.json entry exists, start from these values (e.g. Caddyfile marker)
77
+ * - isNew: when true and allowAllOriginsFlag is undefined, default allowAllOrigins to false
78
+ * - forceAllowAllOrigins: migration helper; force true once
79
+ *
80
+ * @param {string} domain
81
+ * @param {object} update
82
+ * @param {string} update.root
83
+ * @param {string[]} [update.originsFromFlags]
84
+ * @param {string[]} [update.originsToRemove]
85
+ * @param {boolean|undefined} [update.allowAllOriginsFlag]
86
+ * @param {{ origins?: string[], allowAllOrigins?: boolean }|null} [update.seed]
87
+ * @param {boolean} [update.isNew]
88
+ * @param {boolean} [update.forceAllowAllOrigins]
89
+ */
90
+ export async function upsertProject(domain, update, filePath = getProjectsPath()) {
91
+ const doc = await loadProjects(filePath);
92
+ const existing = doc.projects[domain]
93
+ ? normalizeProjectEntry(doc.projects[domain])
94
+ : update.seed
95
+ ? normalizeProjectEntry(update.seed)
96
+ : { origins: [], allowAllOrigins: false };
97
+
98
+ let origins = existing.origins;
99
+ if (Array.isArray(update.originsFromFlags) && update.originsFromFlags.length > 0) {
100
+ const merged = validateOriginList([...existing.origins, ...update.originsFromFlags]);
101
+ if (!merged.ok) {
102
+ throw new Error(merged.error);
103
+ }
104
+ origins = merged.origins;
105
+ }
106
+
107
+ if (Array.isArray(update.originsToRemove) && update.originsToRemove.length > 0) {
108
+ const toRemove = validateOriginList(update.originsToRemove);
109
+ if (!toRemove.ok) {
110
+ throw new Error(toRemove.error);
111
+ }
112
+ const removeSet = new Set(toRemove.origins);
113
+ origins = origins.filter((o) => !removeSet.has(o));
114
+ }
115
+
116
+ let allowAllOrigins = existing.allowAllOrigins;
117
+ if (update.isNew && update.allowAllOriginsFlag === undefined) {
118
+ allowAllOrigins = false;
119
+ }
120
+ if (update.allowAllOriginsFlag === true) allowAllOrigins = true;
121
+ if (update.allowAllOriginsFlag === false) allowAllOrigins = false;
122
+
123
+ if (update.forceAllowAllOrigins === true) {
124
+ allowAllOrigins = true;
125
+ }
126
+
127
+ doc.projects[domain] = {
128
+ root: update.root,
129
+ origins,
130
+ allowAllOrigins,
131
+ };
132
+
133
+ await saveProjects(doc, filePath);
134
+ return normalizeProjectEntry(doc.projects[domain]);
135
+ }
136
+
137
+ /**
138
+ * Ensure a projects.json entry exists after migrating a legacy Caddy block.
139
+ *
140
+ * Semantics:
141
+ * - Existing entry: leave unchanged (never drop stored origins; never force
142
+ * allowAllOrigins — the user may already have tightened CORS).
143
+ * - New entry from legacy migration: allowAllOrigins=true for compatibility,
144
+ * origins=[] until the user adds --origin.
145
+ *
146
+ * A migrated legacy project therefore keeps allowAllOrigins=true until the user
147
+ * turns it off; existing stored origins are never dropped by migration.
148
+ */
149
+ export async function ensureMigratedProject(domain, root, filePath = getProjectsPath()) {
150
+ const doc = await loadProjects(filePath);
151
+ const existing = doc.projects[domain];
152
+ if (existing) {
153
+ return normalizeProjectEntry(existing);
154
+ }
155
+ doc.projects[domain] = {
156
+ root,
157
+ origins: [],
158
+ allowAllOrigins: true,
159
+ };
160
+ await saveProjects(doc, filePath);
161
+ return normalizeProjectEntry(doc.projects[domain]);
162
+ }
163
+
164
+ export async function removeProject(domain, filePath = getProjectsPath()) {
165
+ const doc = await loadProjects(filePath);
166
+ if (doc.projects[domain]) {
167
+ delete doc.projects[domain];
168
+ await saveProjects(doc, filePath);
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+
174
+ function normalizeProjectEntry(entry) {
175
+ const originsResult = validateOriginList(entry.origins || []);
176
+ return {
177
+ root: entry.root,
178
+ origins: originsResult.ok ? originsResult.origins : [],
179
+ allowAllOrigins: entry.allowAllOrigins === true,
180
+ };
181
+ }
@@ -1,113 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { link } from '../link.js';
3
- import fs from 'fs-extra';
4
- import { execa } from 'execa';
5
- import os from 'os';
6
- import path from 'path';
7
-
8
- // Mock dependencies
9
- vi.mock('fs-extra');
10
- vi.mock('execa');
11
- vi.mock('ora', () => ({
12
- default: vi.fn(() => ({
13
- start: vi.fn(() => ({
14
- succeed: vi.fn(),
15
- fail: vi.fn(),
16
- warn: vi.fn(),
17
- })),
18
- })),
19
- }));
20
-
21
- describe('link command', () => {
22
- const mockCaddyDir = path.join(os.homedir(), '.stagepass');
23
- const mockCaddyFile = path.join(mockCaddyDir, 'Caddyfile');
24
- const originalCwd = process.cwd;
25
-
26
- beforeEach(() => {
27
- vi.clearAllMocks();
28
- process.cwd = vi.fn(() => '/test/project');
29
- });
30
-
31
- afterEach(() => {
32
- process.cwd = originalCwd;
33
- });
34
-
35
- it('should use current directory name as domain if not provided', async () => {
36
- fs.pathExists.mockResolvedValue(false);
37
- fs.ensureDir.mockResolvedValue();
38
- fs.writeFile.mockResolvedValue();
39
- execa.mockResolvedValue({});
40
-
41
- await link(undefined, {});
42
-
43
- expect(fs.writeFile).toHaveBeenCalled();
44
- const writtenContent = fs.writeFile.mock.calls[0][1];
45
- expect(writtenContent).toContain('project.sp');
46
- });
47
-
48
- it('should add .sp extension if missing', async () => {
49
- fs.pathExists.mockResolvedValue(false);
50
- fs.ensureDir.mockResolvedValue();
51
- fs.writeFile.mockResolvedValue();
52
- execa.mockResolvedValue({});
53
-
54
- await link('my-domain', {});
55
-
56
- const writtenContent = fs.writeFile.mock.calls[0][1];
57
- expect(writtenContent).toContain('my-domain.sp');
58
- });
59
-
60
- it('should replace existing domain block if already linked', async () => {
61
- const existingContent = `
62
- # START: test.sp
63
- test.sp {
64
- root * "/old/path"
65
- }
66
- # END: test.sp
67
- `;
68
-
69
- fs.pathExists.mockResolvedValue(true);
70
- fs.readFile.mockResolvedValue(existingContent);
71
- fs.ensureDir.mockResolvedValue();
72
- fs.writeFile.mockResolvedValue();
73
- execa.mockResolvedValue({});
74
-
75
- await link('test', {});
76
-
77
- expect(fs.writeFile).toHaveBeenCalled();
78
- const writtenContent = fs.writeFile.mock.calls[0][1];
79
- expect(writtenContent).toContain('test.sp');
80
- expect(writtenContent).toContain('/test/project');
81
- // Should not contain old path
82
- expect(writtenContent).not.toContain('/old/path');
83
- });
84
-
85
- it('should append new domain block if not exists', async () => {
86
- const existingContent = '# Some existing config';
87
-
88
- fs.pathExists.mockResolvedValue(true);
89
- fs.readFile.mockResolvedValue(existingContent);
90
- fs.ensureDir.mockResolvedValue();
91
- fs.writeFile.mockResolvedValue();
92
- execa.mockResolvedValue({});
93
-
94
- await link('new-domain', {});
95
-
96
- expect(fs.writeFile).toHaveBeenCalled();
97
- const writtenContent = fs.writeFile.mock.calls[0][1];
98
- expect(writtenContent).toContain('Some existing config');
99
- expect(writtenContent).toContain('new-domain.sp');
100
- });
101
-
102
- it('should handle Caddy reload failure gracefully', async () => {
103
- fs.pathExists.mockResolvedValue(false);
104
- fs.ensureDir.mockResolvedValue();
105
- fs.writeFile.mockResolvedValue();
106
- execa.mockRejectedValue(new Error('Caddy not running'));
107
-
108
- await link('test', {});
109
-
110
- // Should still write config even if reload fails
111
- expect(fs.writeFile).toHaveBeenCalled();
112
- });
113
- });
@@ -1,72 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { reload } from '../reload.js';
3
- import fs from 'fs-extra';
4
- import { execa } from 'execa';
5
- import os from 'os';
6
- import path from 'path';
7
-
8
- // Mock dependencies
9
- vi.mock('fs-extra');
10
- vi.mock('execa');
11
- vi.mock('ora', () => ({
12
- default: vi.fn(() => ({
13
- start: vi.fn(() => ({
14
- succeed: vi.fn(),
15
- fail: vi.fn(),
16
- })),
17
- })),
18
- }));
19
-
20
- describe('reload command', () => {
21
- const mockCaddyDir = path.join(os.homedir(), '.stagepass');
22
- const mockCaddyFile = path.join(mockCaddyDir, 'Caddyfile');
23
-
24
- beforeEach(() => {
25
- vi.clearAllMocks();
26
- });
27
-
28
- it('should reload Caddy when Caddyfile exists', async () => {
29
- fs.pathExists.mockResolvedValue(true);
30
- execa.mockResolvedValue({});
31
-
32
- await reload({});
33
-
34
- expect(execa).toHaveBeenCalledWith(
35
- 'caddy',
36
- ['reload', '--config', mockCaddyFile],
37
- expect.any(Object)
38
- );
39
- });
40
-
41
- it('should fail if Caddyfile does not exist', async () => {
42
- fs.pathExists.mockResolvedValue(false);
43
-
44
- await reload({});
45
-
46
- expect(execa).not.toHaveBeenCalled();
47
- });
48
-
49
- it('should fail if Caddy is not installed', async () => {
50
- fs.pathExists.mockResolvedValue(true);
51
- execa.mockRejectedValueOnce(new Error('caddy: command not found'));
52
-
53
- await reload({});
54
-
55
- // Should not attempt reload if version check fails
56
- expect(execa).toHaveBeenCalledTimes(1);
57
- expect(execa).toHaveBeenCalledWith('caddy', ['version'], expect.any(Object));
58
- });
59
-
60
- it('should use verbose stdio when verbose option is set', async () => {
61
- fs.pathExists.mockResolvedValue(true);
62
- execa.mockResolvedValue({});
63
-
64
- await reload({ verbose: true });
65
-
66
- expect(execa).toHaveBeenCalledWith(
67
- 'caddy',
68
- ['reload', '--config', mockCaddyFile],
69
- expect.objectContaining({ stdio: 'inherit' })
70
- );
71
- });
72
- });