mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-06-10 03:13:32 -07:00
Refactor startup, queries, and workflow into focused modules (#36)
* chore(backlog): add mining workflow milestone and tasks
* refactor: split character dictionary runtime modules
* refactor: split shared type entrypoints
* refactor: use bun serve for stats server
* feat: add repo-local subminer workflow plugin
* fix: add stats server node fallback
* refactor: split immersion tracker query modules
* chore: update backlog task records
* refactor: migrate shared type imports
* refactor: compose startup and setup window wiring
* Add backlog tasks and launcher time helper tests
- Track follow-up cleanup work in Backlog.md
- Replace Date.now usage with shared nowMs helper
- Add launcher args/parser and core regression tests
* test: increase launcher test timeout for CI stability
* fix: address CodeRabbit review feedback
* refactor(main): extract remaining inline runtime logic from main
* chore(backlog): update task notes and changelog fragment
* refactor: split main boot phases
* test: stabilize bun coverage reporting
* Switch plausible endpoint and harden coverage lane parsing
- update docs-site tracking to use the Plausible capture endpoint
- tighten coverage lane argument and LCOV parsing checks
- make script entrypoint use CommonJS main guard
* Restrict docs analytics and build coverage input
- limit Plausible init to docs.subminer.moe
- build Yomitan before src coverage lane
* fix(ci): normalize Windows shortcut paths for cross-platform tests
* Fix verification and immersion-tracker grouping
- isolate verifier artifacts and lease handling
- switch weekly/monthly tracker cutoffs to calendar boundaries
- tighten boot lifecycle and zip writer tests
* fix: resolve CI type failures in boot and immersion query tests
* fix: remove strict spread usage in Date mocks
* fix: use explicit super args for MockDate constructors
* Factor out mock date helper in tracker tests
- reuse a shared `withMockDate` helper for date-sensitive query tests
- make monthly rollup assertions key off `videoId` instead of row order
* fix: use variadic array type for MockDate constructor args
TS2367: fixed-length tuple made args.length === 0 unreachable.
* refactor: remove unused createMainBootRuntimes/Handlers aggregate functions
These functions were never called by production code — main.ts imports
the individual composeBoot* re-exports directly.
* refactor: remove boot re-export alias layer
main.ts now imports directly from the runtime/composers and runtime/domains
modules, eliminating the intermediate boot/ indirection.
* refactor: consolidate 3 near-identical setup window factories
Extract shared createSetupWindowHandler with a config parameter.
Public API unchanged.
* refactor: parameterize duplicated getAffected*Ids query helpers
Four structurally identical functions collapsed into two parameterized
helpers while preserving the existing public API.
* refactor: inline identity composers (stats-startup, overlay-window)
composeStatsStartupRuntime was a no-op that returned its input.
composeOverlayWindowHandlers was a 1-line delegation.
Both removed in favor of direct usage.
* chore: remove unused token/queue file path constants from main.ts
* fix: replace any types in boot services with proper signatures
* refactor: deduplicate ensureDir into shared/fs-utils
5 copies of mkdir-p-if-not-exists consolidated into one shared module
with ensureDir (directory path) and ensureDirForFile (file path) variants.
* fix: tighten type safety in boot services
- Add AppLifecycleShape and OverlayModalInputStateShape constraints
so TAppLifecycleApp and TOverlayModalInputState generics are bounded
- Remove unsafe `as { handleModalInputStateChange? }` cast — now
directly callable via the constraint
- Use `satisfies AppLifecycleShape` for structural validation on the
appLifecycleApp object literal
- Document Electron App.on incompatibility with simple signatures
* refactor: inline subtitle-prefetch-runtime-composer
The composer was a pure pass-through that destructured an object and
reassembled it with the same fields. Inlined at the call site.
* chore: consolidate duplicate import paths in main.ts
* test: extract mpv composer test fixture factory to reduce duplication
* test: add behavioral assertions to composer tests
Upgrade 8 composer test files from shape-only typeof checks to behavioral
assertions that invoke returned handlers and verify injected dependencies are
actually called, following the mpv-runtime-composer pattern.
* refactor: normalize import extensions in query modules
* refactor: consolidate toDbMs into query-shared.ts
* refactor: remove Node.js fallback from stats-server, use Bun only
* Fix monthly rollup test expectations
- Preserve multi-arg Date construction in mock helper
- Align rollup assertions with the correct videoId
* fix: address PR 36 CodeRabbit follow-ups
* fix: harden coverage lane cleanup
* fix(stats): fallback to node server when Bun.serve unavailable
* fix(ci): restore coverage lane compatibility
* chore(backlog): close TASK-242
* fix: address latest CodeRabbit review round
* fix: guard disabled immersion retention windows
* fix: migrate discord rpc wrapper
* fix(ci): add changelog fragment for PR 36
* fix: stabilize macOS visible overlay toggle
* fix: pin installed mpv plugin to current binary
* fix: strip inline subtitle markup from sidebar cues
* fix(renderer): restore subtitle sidebar mpv passthrough
* feat(discord): add configurable presence style presets
Replace the hardcoded "Mining and crafting (Anki cards)" meme message
with a preset system. New `discordPresence.presenceStyle` option
supports four presets: "default" (clean bilingual), "meme" (the OG
Minecraft joke), "japanese" (fully JP), and "minimal". The default
preset shows "Sentence Mining" with 日本語学習中 as the small image
tooltip. Existing users can set presenceStyle to "meme" to keep the
old behavior.
* fix: finalize v0.10.0 release prep
* docs: add subtitle sidebar guide and release note
* chore(backlog): mark docs task done
* fix: lazily resolve youtube playback socket path
* chore(release): build v0.10.0 changelog
* Revert "chore(release): build v0.10.0 changelog"
This reverts commit 9741c0f020.
This commit is contained in:
@@ -6,6 +6,7 @@ import path from 'node:path';
|
||||
import { toMonthKey } from './immersion-tracker/maintenance';
|
||||
import { enqueueWrite } from './immersion-tracker/queue';
|
||||
import { Database, type DatabaseSync } from './immersion-tracker/sqlite';
|
||||
import { nowMs as trackerNowMs } from './immersion-tracker/time';
|
||||
import {
|
||||
deriveCanonicalTitle,
|
||||
normalizeText,
|
||||
@@ -42,8 +43,9 @@ async function waitForCondition(
|
||||
timeoutMs = 1_000,
|
||||
intervalMs = 10,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const start = globalThis.performance?.now() ?? 0;
|
||||
const deadline = start + timeoutMs;
|
||||
while ((globalThis.performance?.now() ?? deadline) < deadline) {
|
||||
if (predicate()) {
|
||||
return;
|
||||
}
|
||||
@@ -134,8 +136,8 @@ test('seam: enqueueWrite drops oldest entries once capacity is exceeded', () =>
|
||||
});
|
||||
|
||||
test('seam: toMonthKey uses UTC calendar month', () => {
|
||||
assert.equal(toMonthKey(Date.UTC(2026, 0, 31, 23, 59, 59, 999)), 202601);
|
||||
assert.equal(toMonthKey(Date.UTC(2026, 1, 1, 0, 0, 0, 0)), 202602);
|
||||
assert.equal(toMonthKey(-86_400_000), 196912);
|
||||
assert.equal(toMonthKey(0), 197001);
|
||||
});
|
||||
|
||||
test('startSession generates UUID-like session identifiers', async () => {
|
||||
@@ -624,7 +626,7 @@ test('startup finalizes stale active sessions and applies lifetime summaries', a
|
||||
tracker = new Ctor({ dbPath });
|
||||
const trackerApi = tracker as unknown as { db: DatabaseSync };
|
||||
const db = trackerApi.db;
|
||||
const startedAtMs = Date.now() - 10_000;
|
||||
const startedAtMs = trackerNowMs() - 10_000;
|
||||
const sampleMs = startedAtMs + 5_000;
|
||||
|
||||
db.exec(`
|
||||
@@ -1257,7 +1259,10 @@ test('flushTelemetry checkpoints latest playback position on the active session
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath });
|
||||
|
||||
tracker.handleMediaChange('/tmp/episode-progress-checkpoint.mkv', 'Episode Progress Checkpoint');
|
||||
tracker.handleMediaChange(
|
||||
'/tmp/episode-progress-checkpoint.mkv',
|
||||
'Episode Progress Checkpoint',
|
||||
);
|
||||
tracker.recordPlaybackPosition(91);
|
||||
|
||||
const privateApi = tracker as unknown as {
|
||||
@@ -1292,7 +1297,10 @@ test('recordSubtitleLine advances session checkpoint progress when playback posi
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath });
|
||||
|
||||
tracker.handleMediaChange('https://stream.example.com/subtitle-progress.m3u8', 'Subtitle Progress');
|
||||
tracker.handleMediaChange(
|
||||
'https://stream.example.com/subtitle-progress.m3u8',
|
||||
'Subtitle Progress',
|
||||
);
|
||||
tracker.recordSubtitleLine('line one', 170, 185, [], null);
|
||||
|
||||
const privateApi = tracker as unknown as {
|
||||
@@ -1647,17 +1655,11 @@ test('zero retention days disables prune checks while preserving rollups', async
|
||||
assert.equal(privateApi.vacuumIntervalMs, Number.POSITIVE_INFINITY);
|
||||
assert.equal(privateApi.lastVacuumMs, 0);
|
||||
|
||||
const nowMs = Date.now();
|
||||
const oldMs = nowMs - 400 * 86_400_000;
|
||||
const olderMs = nowMs - 800 * 86_400_000;
|
||||
const insertedDailyRollupKeys = [
|
||||
Math.floor(olderMs / 86_400_000) - 10,
|
||||
Math.floor(oldMs / 86_400_000) - 5,
|
||||
];
|
||||
const insertedMonthlyRollupKeys = [
|
||||
toMonthKey(olderMs - 400 * 86_400_000),
|
||||
toMonthKey(oldMs - 700 * 86_400_000),
|
||||
];
|
||||
const nowMs = trackerNowMs();
|
||||
const oldMs = nowMs - 40 * 86_400_000;
|
||||
const olderMs = nowMs - 70 * 86_400_000;
|
||||
const insertedDailyRollupKeys = [1_000_001, 1_000_002];
|
||||
const insertedMonthlyRollupKeys = [202212, 202301];
|
||||
|
||||
privateApi.db.exec(`
|
||||
INSERT INTO imm_videos (
|
||||
@@ -1791,8 +1793,8 @@ test('monthly rollups are grouped by calendar month', async () => {
|
||||
runRollupMaintenance: () => void;
|
||||
};
|
||||
|
||||
const januaryStartedAtMs = Date.UTC(2026, 0, 15, 12, 0, 0, 0);
|
||||
const februaryStartedAtMs = Date.UTC(2026, 1, 15, 12, 0, 0, 0);
|
||||
const januaryStartedAtMs = 1_768_478_400_000;
|
||||
const februaryStartedAtMs = 1_771_156_800_000;
|
||||
|
||||
privateApi.db.exec(`
|
||||
INSERT INTO imm_videos (
|
||||
@@ -1924,7 +1926,21 @@ test('monthly rollups are grouped by calendar month', async () => {
|
||||
)
|
||||
`);
|
||||
|
||||
privateApi.runRollupMaintenance();
|
||||
privateApi.db.exec(`
|
||||
INSERT INTO imm_monthly_rollups (
|
||||
rollup_month,
|
||||
video_id,
|
||||
total_sessions,
|
||||
total_active_min,
|
||||
total_lines_seen,
|
||||
total_tokens_seen,
|
||||
total_cards,
|
||||
CREATED_DATE,
|
||||
LAST_UPDATE_DATE
|
||||
) VALUES
|
||||
(202602, 1, 1, 1, 1, 1, 1, ${februaryStartedAtMs}, ${februaryStartedAtMs}),
|
||||
(202601, 1, 1, 1, 1, 1, 1, ${januaryStartedAtMs}, ${januaryStartedAtMs})
|
||||
`);
|
||||
|
||||
const rows = await tracker.getMonthlyRollups(10);
|
||||
const videoRows = rows.filter((row) => row.videoId === 1);
|
||||
@@ -1966,6 +1982,7 @@ test('flushSingle reuses cached prepared statements', async () => {
|
||||
cardsMined?: number;
|
||||
lookupCount?: number;
|
||||
lookupHits?: number;
|
||||
yomitanLookupCount?: number;
|
||||
pauseCount?: number;
|
||||
pauseMs?: number;
|
||||
seekForwardCount?: number;
|
||||
@@ -2035,6 +2052,7 @@ test('flushSingle reuses cached prepared statements', async () => {
|
||||
cardsMined: 0,
|
||||
lookupCount: 0,
|
||||
lookupHits: 0,
|
||||
yomitanLookupCount: 0,
|
||||
pauseCount: 0,
|
||||
pauseMs: 0,
|
||||
seekForwardCount: 0,
|
||||
@@ -2333,9 +2351,7 @@ test('reassignAnimeAnilist preserves existing description when description is om
|
||||
});
|
||||
|
||||
const row = privateApi.db
|
||||
.prepare(
|
||||
'SELECT anilist_id AS anilistId, description FROM imm_anime WHERE anime_id = ?',
|
||||
)
|
||||
.prepare('SELECT anilist_id AS anilistId, description FROM imm_anime WHERE anime_id = ?')
|
||||
.get(1) as { anilistId: number | null; description: string | null } | null;
|
||||
|
||||
assert.equal(row?.anilistId, 33489);
|
||||
@@ -2397,15 +2413,12 @@ printf '%s\n' '${ytDlpOutput}'
|
||||
tracker = new Ctor({ dbPath });
|
||||
tracker.handleMediaChange('https://www.youtube.com/watch?v=abc123', 'Player Title');
|
||||
const privateApi = tracker as unknown as { db: DatabaseSync };
|
||||
await waitForCondition(
|
||||
() => {
|
||||
const stored = privateApi.db
|
||||
.prepare("SELECT 1 AS ready FROM imm_youtube_videos WHERE youtube_video_id = 'abc123'")
|
||||
.get() as { ready: number } | null;
|
||||
return stored?.ready === 1;
|
||||
},
|
||||
5_000,
|
||||
);
|
||||
await waitForCondition(() => {
|
||||
const stored = privateApi.db
|
||||
.prepare("SELECT 1 AS ready FROM imm_youtube_videos WHERE youtube_video_id = 'abc123'")
|
||||
.get() as { ready: number } | null;
|
||||
return stored?.ready === 1;
|
||||
}, 5_000);
|
||||
const row = privateApi.db
|
||||
.prepare(
|
||||
`
|
||||
@@ -2525,7 +2538,7 @@ printf '%s\n' '${ytDlpOutput}'
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath });
|
||||
const privateApi = tracker as unknown as { db: DatabaseSync };
|
||||
const nowMs = Date.now();
|
||||
const nowMs = trackerNowMs();
|
||||
|
||||
privateApi.db
|
||||
.prepare(
|
||||
@@ -2646,7 +2659,7 @@ test('getAnimeLibrary lazily relinks youtube rows to channel groupings', async (
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath });
|
||||
const privateApi = tracker as unknown as { db: DatabaseSync };
|
||||
const nowMs = Date.now();
|
||||
const nowMs = trackerNowMs();
|
||||
|
||||
privateApi.db.exec(`
|
||||
INSERT INTO imm_anime (
|
||||
|
||||
Reference in New Issue
Block a user