feat: resolve Phase 1 contract requests and compose every feature

Contracts and core:
- Feature gains auth and stop; FeatureFactory; core composeServer builds the
  context, runs the factories, then the job queue from the union of their jobs
  (R8/R14). startServer uses it; main.ts composes learner, import, studio, AI.
- AppConfig/loadConfig own the layout and settings: courseDirs include
  <dataDir>/courses and <dataDir>/worktrees, studioReposDir, cacheDir,
  importRoots, uploadMaxMb, aiAllowedBaseUrls, transcribeUrl, python.
  resolveConfig derives the same for tests; cachePaths shares the importer's
  cache layout.
- canView: the global author role views every course (R14); the learner,
  studio and AI packages all call it.
- migrate(db, packages): core first, then packages in name order.
- Media: nosniff on every response, a sandbox CSP on svg/html/js; a Range on
  an empty file is 416.
- courseUrl/lessonUrl and the lesson route patterns live in @stc/contracts.

Packages:
- import, studio and AI read AppConfig instead of process.env; the importer
  refuses ids used by studio/repos.
- learner migrations run through core migrate; library covers fall back to
  the importer's cached candidate behind a canView-checked route.
- studio preview renders through the learner LessonView (anchors honoured,
  draft URLs); AI drafts go to the studio draft branch for studio courses (as
  the requesting user) and to <dataDir>/drafts otherwise, and the generator
  page says which.

Web: tsconfig paths for @stc/<feature>/web browser entries; features.ts
imports them by package name; nav.roles hides links by role.

Tests: compose, config, canView, media headers, migrations order, covers,
preview, nav, SPA bundle without server code, and an end-to-end flow on
SQLite and Postgres.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Lucas Winther
2026-10-30 15:02:46 +01:00
co-authored by Claude Opus 5.5
parent 427eda6e93
commit 777ae2cc37
72 changed files with 1066 additions and 244 deletions
+44
View File
@@ -0,0 +1,44 @@
import type { FeatureFactory, ServerContext } from "@stc/contracts";
import type { PackageMigrations } from "@stc/db";
import { aiFeature, createFsDraftSink, migrationsDirs as aiMigrations, type DraftSink } from "@stc/feature-ai";
import { importFeature, migrationsDirs as importMigrations } from "@stc/feature-import";
import { learnerFeature, migrationsDirs as learnerMigrations, userIdentity } from "@stc/feature-learner";
import { createDraftWriter, migrationsDirs as studioMigrations, studioFeature, type StudioFeature } from "@stc/feature-studio";
/** Every package's migration folders, keyed by package name (core runs first, then these in name order). */
export const packageMigrations: PackageMigrations = {
"feature-ai": aiMigrations,
"feature-import": importMigrations,
"feature-learner": learnerMigrations,
"feature-studio": studioMigrations,
};
/**
* Where the AI generator writes drafts: studio-managed courses get a commit on the requesting author's
* `draft/<userId>` branch, authored as that user's name and email; overlay and imported courses (which the studio
* does not manage) fall back to files under `<dataDir>/drafts/<courseId>/<run>/`. The generator page says which.
*/
export function aiDraftSink(ctx: ServerContext, studio: Pick<StudioFeature, "store">): DraftSink {
const writer = createDraftWriter(ctx, { identity: (userId) => userIdentity(ctx.db, userId) });
const files = createFsDraftSink(ctx.config.dataDir);
return {
writeDraftFiles: (courseId, authorId, list, message) =>
(studio.store.isManaged(courseId) ? writer : files).writeDraftFiles(courseId, authorId, list, message),
};
}
export interface FeatureSetOptions {
/** Studio published-worktree polling (default on). */
studioWatch?: boolean;
}
/** The product: learner (auth, library, reader), importer, studio and AI, in that order. */
export function productFeatures(opts: FeatureSetOptions = {}): FeatureFactory[] {
let studio: StudioFeature | null = null;
return [
learnerFeature,
(ctx) => importFeature(ctx),
(ctx) => (studio = studioFeature(ctx, { watch: opts.studioWatch ?? true })),
(ctx) => aiFeature(ctx, { draftSink: aiDraftSink(ctx, studio!) }),
];
}
+26 -46
View File
@@ -1,62 +1,42 @@
import type { AppConfig, AuthService, Feature, JobHandler, JobQueue, ServerContext } from "@stc/contracts";
import { createApp, createJobQueue, loadConfig } from "@stc/core";
import { createCourseRepository } from "@stc/course-format";
import { connect, migrate } from "@stc/db";
import { importFeature } from "@stc/feature-import";
import { learnerFeature } from "@stc/feature-learner";
import { resolve } from "node:path";
import type { AppConfig, Feature, FeatureFactory } from "@stc/contracts";
import { composeServer, loadConfig, type ComposeOptions } from "@stc/core";
import indexHtml from "../../web/index.html";
import { packageMigrations, productFeatures } from "./features";
// Used until a feature supplies an `auth` service (the learner package does).
const anonymousAuth: AuthService = { userFromRequest: async () => null };
export interface StartOptions extends ComposeOptions {}
/** A feature, or a factory that needs the server context. A feature may carry the `AuthService`. */
export type FeatureEntry = (Feature & { auth?: AuthService }) | ((ctx: ServerContext) => Feature & { auth?: AuthService });
export async function startServer(
config: AppConfig,
features: FeatureEntry[],
_webFeatures?: unknown,
): Promise<{ server: Bun.Server<undefined>; stop(): Promise<void> }> {
const db = await connect(config.databaseUrl);
await migrate(db);
const courses = await createCourseRepository(config.courseDirs);
const handlers: Record<string, JobHandler> = {};
// Factories get the context before the job queue exists; ctx.jobs is set right after they run.
const ctx: ServerContext = { config, db, courses, jobs: null as unknown as JobQueue, auth: anonymousAuth };
const built = features.map((f) => (typeof f === "function" ? f(ctx) : f));
for (const f of built) {
Object.assign(handlers, f.jobs);
if (f.auth) ctx.auth = f.auth;
/**
* Composes the features (core `composeServer`) and serves them with the SPA. Bun routes win over `fetch`;
* "/api/*" falls through to the composed app, so unknown API paths are 404 rather than the SPA.
*/
export async function startServer(config: AppConfig, features: (Feature | FeatureFactory)[], opts: StartOptions = {}) {
const composed = await composeServer(config, features, opts);
const { app } = composed;
let server: Bun.Server<undefined>;
try {
server = Bun.serve({
port: config.port,
routes: { ...app.routes, "/api/*": (req) => app.fetch(req), "/*": indexHtml },
fetch: (req) => app.fetch(req),
// Production (NODE_ENV=production, as in the Docker image) bundles the SPA once, minified, without HMR.
development: process.env.NODE_ENV !== "production",
});
} catch (e) {
await composed.stop();
throw e;
}
const jobs = createJobQueue(db, handlers);
ctx.jobs = jobs;
const app = createApp(ctx, built);
jobs.start();
const server = Bun.serve({
port: config.port,
// Bun routes win over fetch; "/api/*" falls through to the composed app (404 for unknown API paths).
routes: { ...app.routes, "/api/*": (req) => app.fetch(req), "/*": indexHtml },
fetch: (req) => app.fetch(req),
});
return {
server,
ctx: composed.ctx,
async stop() {
await server.stop(true);
await jobs.stop();
await db.close();
await composed.stop();
},
};
}
if (import.meta.main) {
const config = loadConfig();
// Contract request (import.md): core config should include <dataDir>/courses itself.
const generated = resolve(config.dataDir, "courses");
if (!config.courseDirs.some((c) => resolve(c) === generated)) config.courseDirs.push(generated);
const { server } = await startServer(config, [
learnerFeature,
(ctx) => importFeature(ctx),
]);
const { server } = await startServer(config, productFeatures(), { migrations: packageMigrations });
console.log(`STCourses listening on ${server.url}`);
}