mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-25 08:48:08 +02:00
feat: add GitHub star nudges to CLI build view and docs sidebar (#271)
* feat: load star count during context builds * docs: document star prompt opt-out * fix: initialize demo context star count * feat(docs-site): add GitHub star count widget to docs sidebar * test: isolate star-prompt build-view tests from ambient CI env
This commit is contained in:
parent
5232578d44
commit
795a97485a
15 changed files with 928 additions and 12 deletions
|
|
@ -12,6 +12,13 @@ import { buildPublicIngestPlan, executePublicIngestTarget, publicProgressMessage
|
|||
import { createAggregateProgressPort } from './progress-port-adapter.js';
|
||||
import { formatDuration } from './demo-metrics.js';
|
||||
import { profileMark } from './startup-profile.js';
|
||||
import {
|
||||
isFreshStarCountCache,
|
||||
readStarCountCache,
|
||||
writeStarCountCache,
|
||||
} from './star-prompt/cache.js';
|
||||
import { fetchGitHubStarCount as defaultFetchGitHubStarCount } from './star-prompt/star-count.js';
|
||||
import { renderStarPromptLine } from './star-prompt/star-line.js';
|
||||
|
||||
profileMark('module:context-build-view');
|
||||
|
||||
|
|
@ -79,6 +86,7 @@ export interface ContextBuildViewState {
|
|||
frame: number;
|
||||
startedAt: number | null;
|
||||
totalElapsedMs: number;
|
||||
starCount: number | null;
|
||||
}
|
||||
|
||||
export interface ContextBuildArgs {
|
||||
|
|
@ -121,6 +129,8 @@ interface CompletedItemName {
|
|||
interface ContextBuildRenderOptions {
|
||||
styled?: boolean;
|
||||
showHint?: boolean;
|
||||
showStarPrompt?: boolean;
|
||||
columns?: number;
|
||||
hintText?: string;
|
||||
projectDir?: string;
|
||||
title?: string;
|
||||
|
|
@ -138,6 +148,15 @@ export interface ContextBuildDeps {
|
|||
now?: () => number;
|
||||
onSourceProgress?: (sources: ContextBuildSourceProgressUpdate[]) => void;
|
||||
sourceProgressThrottleMs?: number;
|
||||
fetchStarCount?: typeof defaultFetchGitHubStarCount;
|
||||
starPromptEnv?: StarPromptEnv;
|
||||
starPromptHomeDir?: string;
|
||||
}
|
||||
|
||||
interface StarPromptEnv extends NodeJS.ProcessEnv {
|
||||
CI?: string;
|
||||
DO_NOT_TRACK?: string;
|
||||
KTX_NO_STAR?: string;
|
||||
}
|
||||
|
||||
// --- Rendering ---
|
||||
|
|
@ -427,6 +446,14 @@ export function renderContextBuildView(
|
|||
lines.push('');
|
||||
}
|
||||
|
||||
if (options.showStarPrompt && hasActive) {
|
||||
const starPrompt = renderStarPromptLine({
|
||||
count: state.starCount,
|
||||
columns: options.columns ?? 80,
|
||||
});
|
||||
lines.push(styled ? dim(starPrompt) : starPrompt);
|
||||
}
|
||||
|
||||
if (options.showHint && hasActive) {
|
||||
const hintContent = options.hintText ?? 'Ctrl+C to stop';
|
||||
const hint = ` ${hintContent}`;
|
||||
|
|
@ -584,6 +611,7 @@ export function viewStateFromSourceProgress(
|
|||
frame: 0,
|
||||
startedAt: startedAtMs ?? null,
|
||||
totalElapsedMs: startedAtMs ? now - startedAtMs : 0,
|
||||
starCount: null,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -631,6 +659,9 @@ export function createRepainter(io: KtxCliIo) {
|
|||
hasPainted = true;
|
||||
lastCursorUpRows = cursorUpRowsAfterWrite(content);
|
||||
},
|
||||
columns() {
|
||||
return terminalColumns();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -806,6 +837,7 @@ export function initViewState(targets: KtxPublicIngestPlanTarget[]): ContextBuil
|
|||
frame: 0,
|
||||
startedAt: null,
|
||||
totalElapsedMs: 0,
|
||||
starCount: null,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -817,6 +849,50 @@ function formatProgressDetail(
|
|||
return `[${percent}%] ${publicProgressMessage(update.message, target)}`;
|
||||
}
|
||||
|
||||
const STAR_COUNT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
function envFlag(value: string | undefined): boolean {
|
||||
return value !== undefined && value !== '' && value !== '0' && value !== 'false';
|
||||
}
|
||||
|
||||
function shouldSuppressStarPrompt(env: StarPromptEnv): boolean {
|
||||
return envFlag(env.CI) || envFlag(env.DO_NOT_TRACK) || envFlag(env.KTX_NO_STAR);
|
||||
}
|
||||
|
||||
function startStarPromptCountRefresh(input: {
|
||||
fetchStarCount: typeof defaultFetchGitHubStarCount;
|
||||
homeDir?: string;
|
||||
now: () => number;
|
||||
paint: () => void;
|
||||
state: ContextBuildViewState;
|
||||
}): void {
|
||||
const cached = readStarCountCache({ homeDir: input.homeDir });
|
||||
if (cached) {
|
||||
input.state.starCount = cached.count;
|
||||
}
|
||||
|
||||
if (isFreshStarCountCache(cached, new Date(input.now()), STAR_COUNT_CACHE_TTL_MS)) {
|
||||
return;
|
||||
}
|
||||
|
||||
void input.fetchStarCount()
|
||||
.then((count) => {
|
||||
if (typeof count !== 'number' || !Number.isFinite(count)) {
|
||||
return;
|
||||
}
|
||||
input.state.starCount = count;
|
||||
input.paint();
|
||||
void writeStarCountCache(
|
||||
{
|
||||
count,
|
||||
fetchedAt: new Date(input.now()).toISOString(),
|
||||
},
|
||||
{ homeDir: input.homeDir },
|
||||
);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
export async function runContextBuild(
|
||||
project: KtxPublicIngestProject,
|
||||
args: ContextBuildArgs,
|
||||
|
|
@ -838,13 +914,31 @@ export async function runContextBuild(
|
|||
state.startedAt = nowFn();
|
||||
|
||||
const repainter = isTTY ? createRepainter(io) : null;
|
||||
const starPromptEnabled = repainter !== null && !shouldSuppressStarPrompt(deps.starPromptEnv ?? process.env);
|
||||
const viewOpts = {
|
||||
styled: true,
|
||||
projectDir: args.projectDir,
|
||||
notices: plan.notices ?? [],
|
||||
warnings: plan.warnings,
|
||||
};
|
||||
const paint = (hint: boolean) => repainter?.paint(renderContextBuildView(state, { ...viewOpts, showHint: hint }));
|
||||
const paint = (hint: boolean) =>
|
||||
repainter?.paint(
|
||||
renderContextBuildView(state, {
|
||||
...viewOpts,
|
||||
showHint: hint,
|
||||
showStarPrompt: starPromptEnabled && hint,
|
||||
columns: repainter.columns(),
|
||||
}),
|
||||
);
|
||||
if (starPromptEnabled) {
|
||||
startStarPromptCountRefresh({
|
||||
fetchStarCount: deps.fetchStarCount ?? defaultFetchGitHubStarCount,
|
||||
homeDir: deps.starPromptHomeDir,
|
||||
now: nowFn,
|
||||
paint: () => paint(true),
|
||||
state,
|
||||
});
|
||||
}
|
||||
paint(true);
|
||||
|
||||
let spinnerInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ const unicode = detectUnicodeSupport();
|
|||
export const SYMBOLS = {
|
||||
middot: unicode ? '·' : '-',
|
||||
emDash: unicode ? '—' : '--',
|
||||
star: unicode ? '★' : '*',
|
||||
rightArrow: unicode ? '→' : '->',
|
||||
} as const;
|
||||
|
||||
export function dim(text: string): string {
|
||||
|
|
|
|||
|
|
@ -259,6 +259,7 @@ async function runDemoContextReplay(
|
|||
frame: 0,
|
||||
startedAt: Date.now(),
|
||||
totalElapsedMs: 0,
|
||||
starCount: null,
|
||||
};
|
||||
|
||||
const allTargets = [...allPrimary, ...allContext];
|
||||
|
|
|
|||
50
packages/cli/src/star-prompt/cache.ts
Normal file
50
packages/cli/src/star-prompt/cache.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
|
||||
const starCountCacheSchema = z
|
||||
.object({
|
||||
count: z.number().int().nonnegative(),
|
||||
fetchedAt: z.string(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type StarCountCache = z.infer<typeof starCountCacheSchema>;
|
||||
|
||||
/** @internal */
|
||||
export function starCountCachePath(homeDir = homedir()): string {
|
||||
return join(homeDir, '.ktx', 'star-count.json');
|
||||
}
|
||||
|
||||
export function readStarCountCache(options: { homeDir?: string } = {}): StarCountCache | null {
|
||||
try {
|
||||
return starCountCacheSchema.parse(JSON.parse(readFileSync(starCountCachePath(options.homeDir), 'utf-8')));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeStarCountCache(value: StarCountCache, options: { homeDir?: string } = {}): Promise<void> {
|
||||
try {
|
||||
const path = starCountCachePath(options.homeDir);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
|
||||
writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
|
||||
renameSync(tempPath, path);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function isFreshStarCountCache(cache: StarCountCache | null, now: Date, ttlMs: number): boolean {
|
||||
if (!cache) {
|
||||
return false;
|
||||
}
|
||||
const fetchedAtMs = Date.parse(cache.fetchedAt);
|
||||
if (Number.isNaN(fetchedAtMs)) {
|
||||
return false;
|
||||
}
|
||||
return now.getTime() - fetchedAtMs < ttlMs;
|
||||
}
|
||||
76
packages/cli/src/star-prompt/star-count.ts
Normal file
76
packages/cli/src/star-prompt/star-count.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { request as httpsRequest } from 'node:https';
|
||||
import { URL } from 'node:url';
|
||||
import { z } from 'zod';
|
||||
|
||||
const GITHUB_REPO_URL = new URL('https://api.github.com/repos/Kaelio/ktx');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
const githubRepoSchema = z.object({
|
||||
stargazers_count: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
type HttpsRequest = typeof httpsRequest;
|
||||
|
||||
function parseStarCount(raw: string): number {
|
||||
return githubRepoSchema.parse(JSON.parse(raw)).stargazers_count;
|
||||
}
|
||||
|
||||
export function fetchGitHubStarCount(options: { request?: HttpsRequest; timeoutMs?: number } = {}): Promise<number | null> {
|
||||
const requestImpl = options.request ?? httpsRequest;
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (count: number | null): void => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
resolve(count);
|
||||
};
|
||||
|
||||
try {
|
||||
const request = requestImpl(
|
||||
GITHUB_REPO_URL,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
accept: 'application/vnd.github+json',
|
||||
'user-agent': 'ktx-star-prompt',
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
response.on('data', (chunk: Buffer | string) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
response.on('end', () => {
|
||||
const statusCode = response.statusCode ?? 0;
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
finish(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
finish(parseStarCount(Buffer.concat(chunks).toString('utf8')));
|
||||
} catch {
|
||||
finish(null);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
request.on('socket', (socket) => {
|
||||
socket.unref();
|
||||
});
|
||||
request.on('error', () => {
|
||||
finish(null);
|
||||
});
|
||||
request.setTimeout(timeoutMs, () => {
|
||||
request.destroy(new Error('GitHub star count request timed out'));
|
||||
finish(null);
|
||||
});
|
||||
request.end();
|
||||
} catch {
|
||||
finish(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
42
packages/cli/src/star-prompt/star-line.ts
Normal file
42
packages/cli/src/star-prompt/star-line.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { SYMBOLS } from '../io/symbols.js';
|
||||
|
||||
const STAR_PROMPT_URL = 'github.com/Kaelio/ktx';
|
||||
const STAR_PROMPT_TEXT = 'This takes a few minutes - mind giving ktx a star while you wait?';
|
||||
|
||||
interface StarPromptSymbols {
|
||||
star: string;
|
||||
middot: string;
|
||||
rightArrow: string;
|
||||
}
|
||||
|
||||
export interface RenderStarPromptLineOptions {
|
||||
columns: number;
|
||||
count?: number | null;
|
||||
symbols?: StarPromptSymbols;
|
||||
}
|
||||
|
||||
function usableColumns(columns: number): number {
|
||||
return Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : 80;
|
||||
}
|
||||
|
||||
function starCountSegment(count: number | null | undefined, symbols: StarPromptSymbols): string {
|
||||
if (typeof count !== 'number' || !Number.isFinite(count)) {
|
||||
return '';
|
||||
}
|
||||
const formatted = new Intl.NumberFormat('en-US').format(count);
|
||||
return ` ${symbols.middot} ${formatted} ${symbols.star}`;
|
||||
}
|
||||
|
||||
export function renderStarPromptLine(options: RenderStarPromptLineOptions): string {
|
||||
const symbols = options.symbols ?? SYMBOLS;
|
||||
const columns = usableColumns(options.columns);
|
||||
const base = ` ${symbols.star} ${STAR_PROMPT_TEXT} ${STAR_PROMPT_URL}`;
|
||||
const withCount = `${base}${starCountSegment(options.count, symbols)}`;
|
||||
if (withCount.length <= columns) {
|
||||
return withCount;
|
||||
}
|
||||
if (base.length <= columns) {
|
||||
return base;
|
||||
}
|
||||
return ` ${symbols.star} Star ktx ${symbols.rightArrow} ${STAR_PROMPT_URL}`;
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { buildDefaultKtxProjectConfig, type KtxProjectConfig } from '../src/context/project/config.js';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { KtxPublicIngestProject, KtxPublicIngestTargetResult } from '../src/public-ingest.js';
|
||||
import {
|
||||
type ContextBuildTargetState,
|
||||
|
|
@ -12,6 +15,7 @@ import {
|
|||
runContextBuild,
|
||||
viewStateFromSourceProgress,
|
||||
} from '../src/context-build-view.js';
|
||||
import { writeStarCountCache } from '../src/star-prompt/cache.js';
|
||||
|
||||
function makeIo(options: { isTTY?: boolean; columns?: number } = {}) {
|
||||
let stdout = '';
|
||||
|
|
@ -426,6 +430,64 @@ describe('renderContextBuildView', () => {
|
|||
expect(rendered).not.toContain('resume');
|
||||
});
|
||||
|
||||
it('renders the star prompt directly above the stop hint while active', () => {
|
||||
const state = initViewState([
|
||||
{ connectionId: 'warehouse', driver: 'postgres', operation: 'database-ingest', debugCommand: '', steps: ['database-schema'] },
|
||||
]);
|
||||
state.primarySources[0].status = 'running';
|
||||
state.starCount = 1234;
|
||||
|
||||
const rendered = renderContextBuildView(state, {
|
||||
styled: false,
|
||||
showHint: true,
|
||||
showStarPrompt: true,
|
||||
columns: 120,
|
||||
});
|
||||
|
||||
expect(rendered).toContain(
|
||||
' ★ This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx · 1,234 ★',
|
||||
);
|
||||
expect(rendered.indexOf('mind giving ktx a star')).toBeLessThan(rendered.indexOf('Ctrl+C to stop'));
|
||||
});
|
||||
|
||||
it('renders the star prompt without a count while active', () => {
|
||||
const state = initViewState([
|
||||
{ connectionId: 'warehouse', driver: 'postgres', operation: 'database-ingest', debugCommand: '', steps: ['database-schema'] },
|
||||
]);
|
||||
state.primarySources[0].status = 'running';
|
||||
|
||||
const rendered = renderContextBuildView(state, {
|
||||
styled: false,
|
||||
showHint: true,
|
||||
showStarPrompt: true,
|
||||
columns: 120,
|
||||
});
|
||||
|
||||
expect(rendered).toContain(
|
||||
' ★ This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx',
|
||||
);
|
||||
expect(rendered).not.toContain('1,234');
|
||||
});
|
||||
|
||||
it('omits the star prompt after the build finishes', () => {
|
||||
const state = initViewState([
|
||||
{ connectionId: 'warehouse', driver: 'postgres', operation: 'database-ingest', debugCommand: '', steps: ['database-schema'] },
|
||||
]);
|
||||
state.primarySources[0].status = 'done';
|
||||
state.totalElapsedMs = 5000;
|
||||
state.starCount = 1234;
|
||||
|
||||
const rendered = renderContextBuildView(state, {
|
||||
styled: false,
|
||||
showHint: true,
|
||||
showStarPrompt: true,
|
||||
columns: 120,
|
||||
});
|
||||
|
||||
expect(rendered).not.toContain('mind giving ktx a star');
|
||||
expect(rendered).not.toContain('Ctrl+C to stop');
|
||||
});
|
||||
|
||||
it('omits detach hint when all targets are done', () => {
|
||||
const state = initViewState([
|
||||
{ connectionId: 'warehouse', driver: 'postgres', operation: 'database-ingest', debugCommand: '', steps: ['database-schema'] },
|
||||
|
|
@ -608,9 +670,140 @@ describe('createRepainter', () => {
|
|||
const cursorMoves = [...io.stdout().matchAll(/\[(\d+)A/g)].map((m) => Number(m[1]));
|
||||
expect(cursorMoves).toEqual([2]);
|
||||
});
|
||||
|
||||
it('exposes the same terminal columns used for visual row calculations', () => {
|
||||
const io = makeIo({ isTTY: true, columns: 44 });
|
||||
const repainter = createRepainter(io.io);
|
||||
|
||||
expect(repainter.columns()).toBe(44);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runContextBuild', () => {
|
||||
let starPromptHomeDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
starPromptHomeDir = await mkdtemp(join(tmpdir(), 'ktx-star-prompt-run-'));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(starPromptHomeDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('seeds the interactive star prompt from a fresh cached count without fetching', async () => {
|
||||
await writeStarCountCache(
|
||||
{ count: 1234, fetchedAt: '2026-06-08T10:00:00.000Z' },
|
||||
{ homeDir: starPromptHomeDir },
|
||||
);
|
||||
const io = makeIo({ isTTY: true, columns: 120 });
|
||||
const project = projectWithConnections({ warehouse: { driver: 'postgres' } });
|
||||
const fetchStarCount = vi.fn(async () => 9999);
|
||||
const executeTarget = vi.fn(async (target) => successResult(target.connectionId, target.driver, target.operation));
|
||||
|
||||
await runContextBuild(
|
||||
project,
|
||||
{ projectDir: '/tmp/project', inputMode: 'disabled' },
|
||||
io.io,
|
||||
{
|
||||
executeTarget,
|
||||
fetchStarCount,
|
||||
now: () => Date.parse('2026-06-08T11:00:00.000Z'),
|
||||
starPromptEnv: {},
|
||||
starPromptHomeDir,
|
||||
},
|
||||
);
|
||||
|
||||
expect(fetchStarCount).not.toHaveBeenCalled();
|
||||
expect(io.stdout()).toContain('mind giving ktx a star');
|
||||
expect(io.stdout()).toContain('1,234 ★');
|
||||
});
|
||||
|
||||
it('refreshes a stale cached count while the interactive build is active', async () => {
|
||||
await writeStarCountCache(
|
||||
{ count: 1234, fetchedAt: '2026-06-06T10:00:00.000Z' },
|
||||
{ homeDir: starPromptHomeDir },
|
||||
);
|
||||
const io = makeIo({ isTTY: true, columns: 120 });
|
||||
const project = projectWithConnections({ warehouse: { driver: 'postgres' } });
|
||||
const fetchStarCount = vi.fn(async () => 5678);
|
||||
let finishTarget!: () => void;
|
||||
const targetFinished = new Promise<KtxPublicIngestTargetResult>((resolve) => {
|
||||
finishTarget = () => {
|
||||
resolve(successResult('warehouse', 'postgres', 'database-ingest'));
|
||||
};
|
||||
});
|
||||
const executeTarget = vi.fn(async () => targetFinished);
|
||||
|
||||
const run = runContextBuild(
|
||||
project,
|
||||
{ projectDir: '/tmp/project', inputMode: 'disabled' },
|
||||
io.io,
|
||||
{
|
||||
executeTarget,
|
||||
fetchStarCount,
|
||||
now: () => Date.parse('2026-06-08T11:00:00.000Z'),
|
||||
starPromptEnv: {},
|
||||
starPromptHomeDir,
|
||||
},
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchStarCount).toHaveBeenCalledTimes(1);
|
||||
expect(io.stdout()).toContain('5,678 ★');
|
||||
});
|
||||
finishTarget();
|
||||
await expect(run).resolves.toMatchObject({ exitCode: 0 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['DO_NOT_TRACK', { DO_NOT_TRACK: '1' }],
|
||||
['KTX_NO_STAR', { KTX_NO_STAR: '1' }],
|
||||
['CI', { CI: '1' }],
|
||||
])('suppresses the star prompt and fetch for %s', async (_name, starPromptEnv) => {
|
||||
const io = makeIo({ isTTY: true, columns: 120 });
|
||||
const project = projectWithConnections({ warehouse: { driver: 'postgres' } });
|
||||
const fetchStarCount = vi.fn(async () => 1234);
|
||||
const executeTarget = vi.fn(async (target) => successResult(target.connectionId, target.driver, target.operation));
|
||||
|
||||
await runContextBuild(
|
||||
project,
|
||||
{ projectDir: '/tmp/project', inputMode: 'disabled' },
|
||||
io.io,
|
||||
{
|
||||
executeTarget,
|
||||
fetchStarCount,
|
||||
now: () => Date.parse('2026-06-08T11:00:00.000Z'),
|
||||
starPromptEnv,
|
||||
starPromptHomeDir,
|
||||
},
|
||||
);
|
||||
|
||||
expect(fetchStarCount).not.toHaveBeenCalled();
|
||||
expect(io.stdout()).not.toContain('mind giving ktx a star');
|
||||
});
|
||||
|
||||
it('suppresses the star prompt and fetch for non-TTY output', async () => {
|
||||
const io = makeIo({ isTTY: false, columns: 120 });
|
||||
const project = projectWithConnections({ warehouse: { driver: 'postgres' } });
|
||||
const fetchStarCount = vi.fn(async () => 1234);
|
||||
const executeTarget = vi.fn(async (target) => successResult(target.connectionId, target.driver, target.operation));
|
||||
|
||||
await runContextBuild(
|
||||
project,
|
||||
{ projectDir: '/tmp/project', inputMode: 'disabled' },
|
||||
io.io,
|
||||
{
|
||||
executeTarget,
|
||||
fetchStarCount,
|
||||
now: () => Date.parse('2026-06-08T11:00:00.000Z'),
|
||||
starPromptHomeDir,
|
||||
},
|
||||
);
|
||||
|
||||
expect(fetchStarCount).not.toHaveBeenCalled();
|
||||
expect(io.stdout()).not.toContain('mind giving ktx a star');
|
||||
});
|
||||
|
||||
it('executes scan targets before source-ingest targets', async () => {
|
||||
const io = makeIo();
|
||||
const project = projectWithConnections({
|
||||
|
|
|
|||
73
packages/cli/test/star-prompt/cache.test.ts
Normal file
73
packages/cli/test/star-prompt/cache.test.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
isFreshStarCountCache,
|
||||
readStarCountCache,
|
||||
starCountCachePath,
|
||||
writeStarCountCache,
|
||||
} from '../../src/star-prompt/cache.js';
|
||||
|
||||
describe('star prompt cache', () => {
|
||||
let homeDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
homeDir = await mkdtemp(join(tmpdir(), 'ktx-star-count-cache-'));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(homeDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('uses ~/.ktx/star-count.json', () => {
|
||||
expect(starCountCachePath(homeDir)).toBe(join(homeDir, '.ktx', 'star-count.json'));
|
||||
});
|
||||
|
||||
it('round-trips strict cache data', async () => {
|
||||
await writeStarCountCache({ count: 1234, fetchedAt: '2026-06-08T10:00:00.000Z' }, { homeDir });
|
||||
|
||||
expect(readStarCountCache({ homeDir })).toEqual({
|
||||
count: 1234,
|
||||
fetchedAt: '2026-06-08T10:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null for missing, corrupt, or unknown-field cache files', async () => {
|
||||
expect(readStarCountCache({ homeDir })).toBeNull();
|
||||
|
||||
await mkdir(join(homeDir, '.ktx'), { recursive: true });
|
||||
await writeFile(starCountCachePath(homeDir), '{bad json', 'utf-8');
|
||||
expect(readStarCountCache({ homeDir })).toBeNull();
|
||||
|
||||
await writeFile(
|
||||
starCountCachePath(homeDir),
|
||||
JSON.stringify({ count: 1234, fetchedAt: '2026-06-08T10:00:00.000Z', extra: true }),
|
||||
'utf-8',
|
||||
);
|
||||
expect(readStarCountCache({ homeDir })).toBeNull();
|
||||
});
|
||||
|
||||
it('writes formatted JSON with a trailing newline', async () => {
|
||||
await writeStarCountCache({ count: 9876, fetchedAt: '2026-06-08T10:00:00.000Z' }, { homeDir });
|
||||
|
||||
const raw = await readFile(starCountCachePath(homeDir), 'utf-8');
|
||||
expect(raw).toContain('"count": 9876');
|
||||
expect(raw.endsWith('\n')).toBe(true);
|
||||
});
|
||||
|
||||
it('detects fresh and stale cache entries', () => {
|
||||
const now = new Date('2026-06-08T12:00:00.000Z');
|
||||
const ttlMs = 24 * 60 * 60 * 1000;
|
||||
|
||||
expect(
|
||||
isFreshStarCountCache({ count: 1, fetchedAt: '2026-06-07T12:00:01.000Z' }, now, ttlMs),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isFreshStarCountCache({ count: 1, fetchedAt: '2026-06-07T11:59:59.000Z' }, now, ttlMs),
|
||||
).toBe(false);
|
||||
expect(isFreshStarCountCache({ count: 1, fetchedAt: 'not-a-date' }, now, ttlMs)).toBe(false);
|
||||
expect(isFreshStarCountCache(null, now, ttlMs)).toBe(false);
|
||||
});
|
||||
});
|
||||
90
packages/cli/test/star-prompt/star-count.test.ts
Normal file
90
packages/cli/test/star-prompt/star-count.test.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('node:https', () => ({
|
||||
request: requestMock,
|
||||
}));
|
||||
|
||||
type MockResponse = EventEmitter & { statusCode?: number };
|
||||
type MockRequest = EventEmitter & {
|
||||
destroy: ReturnType<typeof vi.fn>;
|
||||
end: () => void;
|
||||
setTimeout: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function mockHttpsResponse(statusCode: number, body: string): { socket: { unref: ReturnType<typeof vi.fn> } } {
|
||||
const socket = { unref: vi.fn() };
|
||||
requestMock.mockImplementation((_url: unknown, _options: unknown, callback: (response: MockResponse) => void) => {
|
||||
const request = new EventEmitter() as MockRequest;
|
||||
request.destroy = vi.fn();
|
||||
request.setTimeout = vi.fn();
|
||||
request.end = () => {
|
||||
request.emit('socket', socket);
|
||||
const response = new EventEmitter() as MockResponse;
|
||||
response.statusCode = statusCode;
|
||||
callback(response);
|
||||
response.emit('data', Buffer.from(body));
|
||||
response.emit('end');
|
||||
};
|
||||
return request;
|
||||
});
|
||||
return { socket };
|
||||
}
|
||||
|
||||
describe('fetchGitHubStarCount', () => {
|
||||
beforeEach(() => {
|
||||
requestMock.mockReset();
|
||||
});
|
||||
|
||||
it('fetches the Kaelio/ktx repository star count and unrefs the socket', async () => {
|
||||
const { socket } = mockHttpsResponse(200, JSON.stringify({ stargazers_count: 1234, name: 'ktx' }));
|
||||
const { fetchGitHubStarCount } = await import('../../src/star-prompt/star-count.js');
|
||||
|
||||
await expect(fetchGitHubStarCount()).resolves.toBe(1234);
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
accept: 'application/vnd.github+json',
|
||||
'user-agent': 'ktx-star-prompt',
|
||||
}),
|
||||
}),
|
||||
expect.any(Function),
|
||||
);
|
||||
const [url] = requestMock.mock.calls[0] as [URL];
|
||||
expect(url.toString()).toBe('https://api.github.com/repos/Kaelio/ktx');
|
||||
expect(socket.unref).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns null for non-2xx, invalid JSON, and invalid payloads', async () => {
|
||||
const { fetchGitHubStarCount } = await import('../../src/star-prompt/star-count.js');
|
||||
|
||||
mockHttpsResponse(503, 'GitHub unavailable');
|
||||
await expect(fetchGitHubStarCount()).resolves.toBeNull();
|
||||
|
||||
mockHttpsResponse(200, '{bad json');
|
||||
await expect(fetchGitHubStarCount()).resolves.toBeNull();
|
||||
|
||||
mockHttpsResponse(200, JSON.stringify({ stargazers_count: '1234' }));
|
||||
await expect(fetchGitHubStarCount()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('destroys the request and returns null on timeout', async () => {
|
||||
const request = new EventEmitter() as MockRequest;
|
||||
request.destroy = vi.fn();
|
||||
request.end = vi.fn();
|
||||
request.setTimeout = vi.fn((_ms: number, callback: () => void) => {
|
||||
callback();
|
||||
return request;
|
||||
});
|
||||
requestMock.mockReturnValue(request);
|
||||
const { fetchGitHubStarCount } = await import('../../src/star-prompt/star-count.js');
|
||||
|
||||
await expect(fetchGitHubStarCount({ timeoutMs: 5 })).resolves.toBeNull();
|
||||
expect(request.destroy).toHaveBeenCalledWith(expect.any(Error));
|
||||
});
|
||||
});
|
||||
47
packages/cli/test/star-prompt/star-line.test.ts
Normal file
47
packages/cli/test/star-prompt/star-line.test.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { renderStarPromptLine } from '../../src/star-prompt/star-line.js';
|
||||
|
||||
const unicodeSymbols = {
|
||||
star: '★',
|
||||
middot: '·',
|
||||
rightArrow: '→',
|
||||
};
|
||||
|
||||
const asciiSymbols = {
|
||||
star: '*',
|
||||
middot: '-',
|
||||
rightArrow: '->',
|
||||
};
|
||||
|
||||
describe('renderStarPromptLine', () => {
|
||||
it('renders the full prompt with a formatted count when it fits', () => {
|
||||
expect(renderStarPromptLine({ count: 1234, columns: 120, symbols: unicodeSymbols })).toBe(
|
||||
' ★ This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx · 1,234 ★',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the full prompt without a count when the count is unavailable', () => {
|
||||
expect(renderStarPromptLine({ count: null, columns: 120, symbols: unicodeSymbols })).toBe(
|
||||
' ★ This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the count segment before shortening the sentence', () => {
|
||||
expect(renderStarPromptLine({ count: 1234, columns: 102, symbols: unicodeSymbols })).toBe(
|
||||
' ★ This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the narrow fallback on compact terminals', () => {
|
||||
expect(renderStarPromptLine({ count: 1234, columns: 92, symbols: unicodeSymbols })).toBe(
|
||||
' ★ Star ktx → github.com/Kaelio/ktx',
|
||||
);
|
||||
});
|
||||
|
||||
it('supports ASCII fallback symbols', () => {
|
||||
expect(renderStarPromptLine({ count: 1234, columns: 120, symbols: asciiSymbols })).toBe(
|
||||
' * This takes a few minutes - mind giving ktx a star while you wait? github.com/Kaelio/ktx - 1,234 *',
|
||||
);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue