feat: install.sh + auto-update checker for CLI
- tools/install.sh: standalone installer/upgrader, curl-pipe safe (main() wrapper, process.argv instead of stdin, mkdir -p prefix) - packages/mosaic/src/runtime/update-checker.ts: version check module with 1h cache at ~/.cache/mosaic/update-check.json - CLI startup: non-blocking background update check on every invocation - 'mosaic update' command: explicit check + install (--check for CI) - session-start.sh: warns agents when CLI is outdated - Proper semver comparison including pre-release precedence - eslint: allow __tests__ in packages/mosaic for projectService
This commit is contained in:
@@ -10,6 +10,14 @@ import { registerPrdyCommand } from './commands/prdy.js';
|
||||
const _require = createRequire(import.meta.url);
|
||||
const CLI_VERSION: string = (_require('../package.json') as { version: string }).version;
|
||||
|
||||
// Fire-and-forget update check at startup (non-blocking, cached 1h)
|
||||
try {
|
||||
const { backgroundUpdateCheck } = await import('@mosaic/mosaic');
|
||||
backgroundUpdateCheck();
|
||||
} catch {
|
||||
// Silently ignore — update check is best-effort
|
||||
}
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program.name('mosaic').description('Mosaic Stack CLI').version(CLI_VERSION);
|
||||
@@ -297,6 +305,52 @@ if (qrCmd !== undefined) {
|
||||
program.addCommand(qrCmd as unknown as Command);
|
||||
}
|
||||
|
||||
// ─── update ─────────────────────────────────────────────────────────────
|
||||
|
||||
program
|
||||
.command('update')
|
||||
.description('Check for and install Mosaic CLI updates')
|
||||
.option('--check', 'Check only, do not install')
|
||||
.action(async (opts: { check?: boolean }) => {
|
||||
const { checkForUpdate, formatUpdateNotice } = await import('@mosaic/mosaic');
|
||||
const { execSync } = await import('node:child_process');
|
||||
|
||||
console.log('Checking for updates…');
|
||||
const result = checkForUpdate({ skipCache: true });
|
||||
|
||||
if (!result.latest) {
|
||||
console.error('Could not reach the Mosaic registry.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(` Installed: ${result.current || '(none)'}`);
|
||||
console.log(` Latest: ${result.latest}`);
|
||||
|
||||
if (!result.updateAvailable) {
|
||||
console.log('\n✔ Up to date.');
|
||||
return;
|
||||
}
|
||||
|
||||
const notice = formatUpdateNotice(result);
|
||||
if (notice) console.log(notice);
|
||||
|
||||
if (opts.check) {
|
||||
process.exit(2); // Signal to callers that an update exists
|
||||
}
|
||||
|
||||
console.log('Installing update…');
|
||||
try {
|
||||
execSync(
|
||||
'npm install -g @mosaic/cli@latest --registry=https://git.mosaicstack.dev/api/packages/mosaic/npm/',
|
||||
{ stdio: 'inherit', timeout: 60_000 },
|
||||
);
|
||||
console.log('\n✔ Updated successfully.');
|
||||
} catch {
|
||||
console.error('\nUpdate failed. Try manually: bash tools/install.sh');
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── wizard ─────────────────────────────────────────────────────────────
|
||||
|
||||
program
|
||||
|
||||
52
packages/mosaic/__tests__/update-checker.test.ts
Normal file
52
packages/mosaic/__tests__/update-checker.test.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { semverLt, formatUpdateNotice } from '../src/runtime/update-checker.js';
|
||||
import type { UpdateCheckResult } from '../src/runtime/update-checker.js';
|
||||
|
||||
describe('semverLt', () => {
|
||||
it('returns true when a < b', () => {
|
||||
expect(semverLt('0.0.1', '0.0.2')).toBe(true);
|
||||
expect(semverLt('0.1.0', '0.2.0')).toBe(true);
|
||||
expect(semverLt('1.0.0', '2.0.0')).toBe(true);
|
||||
expect(semverLt('0.0.1-alpha.1', '0.0.1-alpha.2')).toBe(true);
|
||||
expect(semverLt('0.0.1-alpha.1', '0.0.1')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when a >= b', () => {
|
||||
expect(semverLt('0.0.2', '0.0.1')).toBe(false);
|
||||
expect(semverLt('1.0.0', '1.0.0')).toBe(false);
|
||||
expect(semverLt('2.0.0', '1.0.0')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for empty strings', () => {
|
||||
expect(semverLt('', '1.0.0')).toBe(false);
|
||||
expect(semverLt('1.0.0', '')).toBe(false);
|
||||
expect(semverLt('', '')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatUpdateNotice', () => {
|
||||
it('returns empty string when up to date', () => {
|
||||
const result: UpdateCheckResult = {
|
||||
current: '1.0.0',
|
||||
latest: '1.0.0',
|
||||
updateAvailable: false,
|
||||
checkedAt: new Date().toISOString(),
|
||||
registry: 'https://example.com',
|
||||
};
|
||||
expect(formatUpdateNotice(result)).toBe('');
|
||||
});
|
||||
|
||||
it('returns a notice when update is available', () => {
|
||||
const result: UpdateCheckResult = {
|
||||
current: '0.0.1',
|
||||
latest: '0.1.0',
|
||||
updateAvailable: true,
|
||||
checkedAt: new Date().toISOString(),
|
||||
registry: 'https://example.com',
|
||||
};
|
||||
const notice = formatUpdateNotice(result);
|
||||
expect(notice).toContain('0.0.1');
|
||||
expect(notice).toContain('0.1.0');
|
||||
expect(notice).toContain('Update available');
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,15 @@ import type { CommunicationStyle } from './types.js';
|
||||
|
||||
export { VERSION, DEFAULT_MOSAIC_HOME };
|
||||
export { runWizard } from './wizard.js';
|
||||
export {
|
||||
checkForUpdate,
|
||||
backgroundUpdateCheck,
|
||||
formatUpdateNotice,
|
||||
getInstalledVersion,
|
||||
getLatestVersion,
|
||||
semverLt,
|
||||
} from './runtime/update-checker.js';
|
||||
export type { UpdateCheckResult } from './runtime/update-checker.js';
|
||||
export { ClackPrompter } from './prompter/clack-prompter.js';
|
||||
export { HeadlessPrompter } from './prompter/headless-prompter.js';
|
||||
export { createConfigService } from './config/config-service.js';
|
||||
|
||||
238
packages/mosaic/src/runtime/update-checker.ts
Normal file
238
packages/mosaic/src/runtime/update-checker.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* Mosaic update checker — compares installed @mosaic/cli version against the
|
||||
* Gitea npm registry and reports when an upgrade is available.
|
||||
*
|
||||
* Used by:
|
||||
* - CLI startup (non-blocking background check)
|
||||
* - session-start.sh (via `mosaic update --check`)
|
||||
* - install.sh (direct invocation)
|
||||
*
|
||||
* Design:
|
||||
* - Result is cached to ~/.cache/mosaic/update-check.json for 1 hour
|
||||
* - Network call is fire-and-forget with a 5 s timeout
|
||||
* - Never throws on failure — returns stale/unknown result
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface UpdateCheckResult {
|
||||
/** Currently installed version (empty if not found) */
|
||||
current: string;
|
||||
/** Latest published version (empty if check failed) */
|
||||
latest: string;
|
||||
/** True when a newer version is available */
|
||||
updateAvailable: boolean;
|
||||
/** ISO timestamp of this check */
|
||||
checkedAt: string;
|
||||
/** Where the latest version was resolved from */
|
||||
registry: string;
|
||||
}
|
||||
|
||||
// ─── Constants ──────────────────────────────────────────────────────────────
|
||||
|
||||
const REGISTRY = 'https://git.mosaicstack.dev/api/packages/mosaic/npm/';
|
||||
const CLI_PKG = '@mosaic/cli';
|
||||
const CACHE_DIR = join(homedir(), '.cache', 'mosaic');
|
||||
const CACHE_FILE = join(CACHE_DIR, 'update-check.json');
|
||||
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
const NETWORK_TIMEOUT_MS = 5_000;
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function npmExec(args: string, timeoutMs = NETWORK_TIMEOUT_MS): string {
|
||||
try {
|
||||
return execSync(`npm ${args}`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: timeoutMs,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rudimentary semver "a < b" — handles pre-release tags.
|
||||
* Per semver spec: 1.0.0-alpha.1 < 1.0.0 (pre-release has lower precedence).
|
||||
*/
|
||||
export function semverLt(a: string, b: string): boolean {
|
||||
if (!a || !b) return false;
|
||||
|
||||
const stripped = (v: string) => v.replace(/^v/, '');
|
||||
const splitPre = (v: string): [string, string | null] => {
|
||||
const idx = v.indexOf('-');
|
||||
return idx === -1 ? [v, null] : [v.slice(0, idx), v.slice(idx + 1)];
|
||||
};
|
||||
|
||||
const sa = stripped(a);
|
||||
const sb = stripped(b);
|
||||
const [coreA, preA] = splitPre(sa);
|
||||
const [coreB, preB] = splitPre(sb);
|
||||
|
||||
// Compare core version (major.minor.patch)
|
||||
const partsA = coreA.split('.').map(Number);
|
||||
const partsB = coreB.split('.').map(Number);
|
||||
const len = Math.max(partsA.length, partsB.length);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
const va = partsA[i] ?? 0;
|
||||
const vb = partsB[i] ?? 0;
|
||||
if (va < vb) return true;
|
||||
if (va > vb) return false;
|
||||
}
|
||||
|
||||
// Core versions are equal — compare pre-release
|
||||
// No pre-release > any pre-release (1.0.0 > 1.0.0-alpha)
|
||||
if (preA !== null && preB === null) return true;
|
||||
if (preA === null && preB !== null) return false;
|
||||
if (preA === null && preB === null) return false;
|
||||
|
||||
// Both have pre-release — compare dot-separated identifiers
|
||||
const idsA = preA!.split('.');
|
||||
const idsB = preB!.split('.');
|
||||
const preLen = Math.max(idsA.length, idsB.length);
|
||||
|
||||
for (let i = 0; i < preLen; i++) {
|
||||
const ia = idsA[i];
|
||||
const ib = idsB[i];
|
||||
// Fewer fields = lower precedence
|
||||
if (ia === undefined && ib !== undefined) return true;
|
||||
if (ia !== undefined && ib === undefined) return false;
|
||||
const na = /^\d+$/.test(ia!) ? parseInt(ia!, 10) : null;
|
||||
const nb = /^\d+$/.test(ib!) ? parseInt(ib!, 10) : null;
|
||||
// Numeric vs string: numeric < string
|
||||
if (na !== null && nb !== null) {
|
||||
if (na < nb) return true;
|
||||
if (na > nb) return false;
|
||||
continue;
|
||||
}
|
||||
if (na !== null && nb === null) return true;
|
||||
if (na === null && nb !== null) return false;
|
||||
// Both strings
|
||||
if (ia! < ib!) return true;
|
||||
if (ia! > ib!) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Cache ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function readCache(): UpdateCheckResult | null {
|
||||
try {
|
||||
if (!existsSync(CACHE_FILE)) return null;
|
||||
const raw = JSON.parse(readFileSync(CACHE_FILE, 'utf-8')) as UpdateCheckResult;
|
||||
const age = Date.now() - new Date(raw.checkedAt).getTime();
|
||||
if (age > CACHE_TTL_MS) return null;
|
||||
return raw;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(result: UpdateCheckResult): void {
|
||||
try {
|
||||
mkdirSync(CACHE_DIR, { recursive: true });
|
||||
writeFileSync(CACHE_FILE, JSON.stringify(result, null, 2) + '\n', 'utf-8');
|
||||
} catch {
|
||||
// Best-effort — cache is not critical
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Public API ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get the currently installed version of @mosaic/cli.
|
||||
* Returns empty string if not installed.
|
||||
*/
|
||||
export function getInstalledVersion(): string {
|
||||
// Fast path: check via package.json require chain
|
||||
try {
|
||||
const raw = npmExec(`ls -g --depth=0 --json 2>/dev/null`, 3000);
|
||||
if (raw) {
|
||||
const data = JSON.parse(raw) as {
|
||||
dependencies?: Record<string, { version?: string }>;
|
||||
};
|
||||
return data?.dependencies?.[CLI_PKG]?.version ?? '';
|
||||
}
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the latest published version from the Gitea npm registry.
|
||||
* Returns empty string on failure.
|
||||
*/
|
||||
export function getLatestVersion(): string {
|
||||
return npmExec(`view ${CLI_PKG} version --registry=${REGISTRY}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform an update check — uses cache when fresh, otherwise hits registry.
|
||||
* Never throws.
|
||||
*/
|
||||
export function checkForUpdate(options?: { skipCache?: boolean }): UpdateCheckResult {
|
||||
if (!options?.skipCache) {
|
||||
const cached = readCache();
|
||||
if (cached) return cached;
|
||||
}
|
||||
|
||||
const current = getInstalledVersion();
|
||||
const latest = getLatestVersion();
|
||||
const updateAvailable = !!(current && latest && semverLt(current, latest));
|
||||
|
||||
const result: UpdateCheckResult = {
|
||||
current,
|
||||
latest,
|
||||
updateAvailable,
|
||||
checkedAt: new Date().toISOString(),
|
||||
registry: REGISTRY,
|
||||
};
|
||||
|
||||
writeCache(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a human-readable update notice. Returns empty string if up-to-date.
|
||||
*/
|
||||
export function formatUpdateNotice(result: UpdateCheckResult): string {
|
||||
if (!result.updateAvailable) return '';
|
||||
|
||||
const lines = [
|
||||
'',
|
||||
'╭─────────────────────────────────────────────────╮',
|
||||
'│ │',
|
||||
`│ Update available: ${result.current} → ${result.latest}`.padEnd(50) + '│',
|
||||
'│ │',
|
||||
'│ Run: bash tools/install.sh │',
|
||||
'│ Or: npm i -g @mosaic/cli@latest │',
|
||||
'│ │',
|
||||
'╰─────────────────────────────────────────────────╯',
|
||||
'',
|
||||
];
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-blocking update check that prints a notice to stderr if an update
|
||||
* is available. Designed to be called at CLI startup without delaying
|
||||
* the user.
|
||||
*/
|
||||
export function backgroundUpdateCheck(): void {
|
||||
try {
|
||||
const result = checkForUpdate();
|
||||
const notice = formatUpdateNotice(result);
|
||||
if (notice) {
|
||||
process.stderr.write(notice);
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — never block the user
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user