diff --git a/.brain/data/git-snapshot.json b/.brain/data/git-snapshot.json index cc753148..e4c24237 100644 --- a/.brain/data/git-snapshot.json +++ b/.brain/data/git-snapshot.json @@ -176,7 +176,7 @@ "apps/site/src/events.ts": "320aaf33bcd4f1801f5f2ecb5b17cf417e78cd0917e19a57c5daae045f6da458", "apps/site/src/interest/interest-durable-object.ts": "110d38d7a92d5f4cc647dd6c3e12c2744566e0a9ab87fbd748a56517bf4ab390", "apps/site/src/interest/join-contact-cell.ts": "06e4de93ca209b7ecda32eb4ff491925e18d9ffb77f5b618418d97dd258104e8", - "apps/site/src/worker.ts": "3346d78a41d369a77e98cb173d1f701ab7bb05b728acda61ef03d09e1840702e", + "apps/site/src/worker.ts": "bf6a4ae3efc95153e64ecbd9355dbe7c87b25256bf793efed5ba61c95a081669", "apps/web/src/client/docs/command.ts": "858fb626d70610cf8ccb47a28128734aebe2845376941a78a94dcc6349c19275", "apps/web/src/client/docs/message.ts": "d345b21c25b00dcccd44f172a9d7487f265b932c285729da37eb6686ef20eeb0", "apps/web/src/client/docs/queries.ts": "bf531ec4f3abaf2b590c63772f8331e2fd9ae089ba02f0d74c7023f770b28347", @@ -606,7 +606,7 @@ "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/events.ts\"]": "export { events, memoryEvents } from \"@rat-stack/events/site\";\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/interest/interest-durable-object.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport { InterestStore, runInterestMachine } from \"@rat-stack/core/interest\";\nimport type { CaptureRequest, InterestRecord } from \"@rat-stack/core/interest\";\nimport type { SealedRow, TicketBinding } from \"@rat-stack/intake-live\";\nimport type { RuntimeContext } from \"alchemy/RuntimeContext\";\nimport * as Effect from \"effect/Effect\";\n\nimport { joinContactCell } from \"./join-contact-cell.js\";\n\nconst RECORD_KEY = \"record\";\n\nconst TICKET_KEY = \"ticket\";\n\nconst INTAKE_KEY = \"intake-key\";\n\nconst INTAKE_STATEMENT_PREFIX = \"intake-statement:\";\n\ninterface TicketHold {\n readonly expiresAt: number;\n readonly submissionId: string;\n}\n\nexport default class Interest extends Cloudflare.DurableObject()(\n \"Interest\",\n Effect.gen(function* makeInterest() {\n const state = yield* Cloudflare.DurableObjectState;\n\n // @effect-diagnostics-next-line returnEffectInGen:off -- Alchemy's DurableObject contract returns the per-instance Effect.\n return Effect.gen(function* makeInstance() {\n const runtime = yield* Effect.context();\n\n const store = {\n load: state.storage\n .get(RECORD_KEY)\n .pipe(Effect.provideContext(runtime)),\n save: (record: InterestRecord) =>\n state.storage\n .put(RECORD_KEY, record)\n .pipe(Effect.provideContext(runtime)),\n };\n\n const run = (\n address: string,\n command: \"confirm\" | \"mailFailed\" | \"register\",\n capture?: CaptureRequest\n ) =>\n runInterestMachine(address, command, capture).pipe(\n Effect.provideService(InterestStore, store)\n );\n\n const storage = (effect: Effect.Effect) =>\n effect.pipe(Effect.provideContext(runtime));\n\n const bindTicket = (submissionId: string, expiresAt: number) =>\n Effect.gen(function* bind() {\n const held = yield* storage(\n state.storage.get(TICKET_KEY)\n );\n\n if (held === undefined) {\n yield* storage(\n state.storage.put(TICKET_KEY, { expiresAt, submissionId })\n );\n\n return \"first\" satisfies TicketBinding;\n }\n\n return held.submissionId === submissionId ? \"same\" : \"other\";\n });\n\n const intakeKey = (candidate: string) =>\n Effect.gen(function* key() {\n const held = yield* storage(state.storage.get(INTAKE_KEY));\n\n if (held !== undefined) {\n return held;\n }\n\n yield* storage(state.storage.put(INTAKE_KEY, candidate));\n\n return candidate;\n });\n\n const intakeStore = (rows: readonly SealedRow[]) =>\n Effect.gen(function* storeRows() {\n for (const row of rows) {\n const key = `${INTAKE_STATEMENT_PREFIX}${row.id}`;\n const held = yield* storage(state.storage.get(key));\n\n if (held === undefined) {\n yield* storage(state.storage.put(key, row.sealed));\n }\n }\n });\n\n return {\n bindTicket,\n confirm: (address: string) => run(address, \"confirm\"),\n forget: () =>\n state.storage.delete(RECORD_KEY).pipe(Effect.provideContext(runtime)),\n intakeErase: () => storage(state.storage.deleteAll()),\n intakeKey,\n intakeRead: () =>\n Effect.all({\n key: storage(state.storage.get(INTAKE_KEY)),\n rows: storage(\n state.storage.list({ prefix: INTAKE_STATEMENT_PREFIX })\n ).pipe(\n Effect.map((entries) =>\n [...entries].map(([id, sealed]) => ({\n id: id.slice(INTAKE_STATEMENT_PREFIX.length),\n sealed,\n }))\n )\n ),\n }),\n intakeStore,\n ...joinContactCell({\n delete: (key) => storage(state.storage.delete(key)),\n get: (key) => storage(state.storage.get(key)),\n put: (key, value) => storage(state.storage.put(key, value)),\n setAlarm: (deadlineAt) => storage(state.storage.setAlarm(deadlineAt)),\n }),\n mailFailed: (address: string) => run(address, \"mailFailed\"),\n register: (address: string, capture?: CaptureRequest) =>\n run(address, \"register\", capture),\n };\n });\n })\n) {}\n", "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/interest/join-contact-cell.ts\"]": "import {\n JOIN_CONTACT_RETENTION_MILLIS,\n JoinErasureSchema,\n} from \"@rat-stack/core/join-interest\";\nimport { Clock, DateTime, Effect, Option, Schema } from \"effect\";\n\nexport const JOIN_CONTACT_KEY = \"join-contact\";\n\nexport const JOIN_ERASED_KEY = \"join-erased\";\n\nconst StoredContact = Schema.Struct({\n erase: Schema.Boolean,\n retentionDeadlineAt: Schema.optionalKey(Schema.Finite),\n sealed: Schema.String,\n});\n\nconst CONTACT_META_KEY = \"join-contact-meta\";\n\nconst ERASE_REQUEST_KEY = \"join-erase-request\";\n\nexport type JoinCellValue =\n | boolean\n | typeof StoredContact.Type\n | typeof JoinErasureSchema.Type;\n\nexport interface JoinCellStorage {\n readonly get: (key: string) => Effect.Effect;\n readonly put: (key: string, value: JoinCellValue) => Effect.Effect;\n readonly delete: (key: string) => Effect.Effect;\n readonly setAlarm: (deadlineAt: number) => Effect.Effect;\n}\n\nconst decodeStored = Schema.decodeUnknownOption(StoredContact);\n\nconst decodeLegacy = Schema.decodeUnknownOption(Schema.String);\n\nexport const joinContactCell = (storage: JoinCellStorage) => {\n const current = storage.get(JOIN_CONTACT_KEY).pipe(\n Effect.map((value) =>\n Option.orElse(decodeStored(value), () =>\n Option.orElse(\n Option.map(decodeLegacy(value), (sealed) => ({\n erase: false,\n retentionDeadlineAt: undefined,\n sealed,\n })),\n () =>\n value === undefined\n ? Option.none()\n : Option.some({\n erase: false,\n retentionDeadlineAt: undefined,\n sealed: \"\",\n })\n )\n )\n )\n );\n\n const metadata = storage\n .get(CONTACT_META_KEY)\n .pipe(Effect.map(Schema.decodeUnknownOption(JoinErasureSchema)));\n\n const readErasure = () =>\n storage\n .get(ERASE_REQUEST_KEY)\n .pipe(\n Effect.map(Schema.decodeUnknownOption(JoinErasureSchema)),\n Effect.map(Option.getOrUndefined)\n );\n\n const joinErase = () =>\n storage\n .put(JOIN_ERASED_KEY, true)\n .pipe(Effect.andThen(storage.delete(JOIN_CONTACT_KEY)), Effect.asVoid);\n\n const expire = Effect.gen(function* expireContact() {\n yield* joinErase();\n yield* Effect.logWarning(\"join contact erased at retention deadline\");\n });\n\n const readLive = Effect.gen(function* readLiveContact() {\n const contact = yield* current;\n\n if (Option.isNone(contact)) {\n return contact;\n }\n\n const now = yield* Clock.currentTimeMillis;\n const { retentionDeadlineAt } = contact.value;\n\n if (retentionDeadlineAt !== undefined && now >= retentionDeadlineAt) {\n yield* expire;\n\n return Option.none();\n }\n\n return contact;\n });\n\n return {\n alarm: () =>\n readLive.pipe(\n Effect.flatMap((contact) =>\n Option.isSome(contact) &&\n contact.value.retentionDeadlineAt !== undefined\n ? storage.setAlarm(contact.value.retentionDeadlineAt)\n : Effect.void\n )\n ),\n joinErase,\n joinReadSnapshot: () =>\n readLive.pipe(\n Effect.map(\n Option.map(({ sealed, retentionDeadlineAt }) =>\n retentionDeadlineAt === undefined\n ? { sealed }\n : { sealed, retentionDeadlineAt }\n )\n ),\n Effect.map(Option.getOrUndefined)\n ),\n joinReadRetentionDeadline: () =>\n current.pipe(\n Effect.map(\n Option.flatMap((contact) =>\n Option.fromUndefinedOr(contact.retentionDeadlineAt)\n )\n ),\n Effect.map(Option.getOrUndefined)\n ),\n joinReadErasure: readErasure,\n joinReadHandoff: () => metadata.pipe(Effect.map(Option.getOrUndefined)),\n joinRequestErase: () =>\n Effect.gen(function* requestErase() {\n const marker = yield* metadata;\n\n if (Option.isSome(marker)) {\n yield* storage.put(ERASE_REQUEST_KEY, marker.value);\n }\n\n yield* joinErase();\n\n return Option.getOrUndefined(marker);\n }),\n joinCompleteErasure: () =>\n storage.delete(ERASE_REQUEST_KEY).pipe(Effect.asVoid),\n joinMarkHandedToDrovr: (legacy = false) =>\n Effect.gen(function* markHandedToDrovr() {\n const marker = yield* metadata;\n\n if (Option.isNone(marker)) {\n return yield* Effect.die(\n new Error(\n \"Join contact handoff metadata is missing. Erasure forwarding needs a durable contact reference. Fix: call `joinRetentionBackfill` before retrying delivery.\"\n )\n );\n }\n\n const handedToDrovrAt =\n legacy || marker.value.handedToDrovr\n ? marker.value.handedToDrovrAt\n : DateTime.formatIso(yield* DateTime.now);\n\n const handed = {\n ...marker.value,\n handedToDrovr: true,\n handedToDrovrAt,\n };\n\n yield* storage.put(CONTACT_META_KEY, handed);\n\n if ((yield* readErasure()) !== undefined) {\n yield* storage.put(ERASE_REQUEST_KEY, handed);\n }\n\n return yield* Effect.void;\n }),\n joinRead: () =>\n readLive.pipe(\n Effect.map(Option.map(({ sealed }) => sealed)),\n Effect.map(Option.getOrUndefined)\n ),\n joinSave: (\n sealed: string,\n erase: boolean,\n deadlineAt?: number,\n contactRef?: string\n ) =>\n Effect.gen(function* saveUnlessErased() {\n if (contactRef !== undefined && Option.isNone(yield* metadata)) {\n const marker = yield* Schema.decodeEffect(JoinErasureSchema)({\n contactRef,\n handedToDrovr: false,\n handedToDrovrAt: null,\n pending: \"erase\",\n }).pipe(Effect.orDie);\n\n yield* storage.put(CONTACT_META_KEY, marker);\n }\n\n if (erase) {\n const marker = yield* metadata;\n\n if (Option.isSome(marker)) {\n yield* storage.put(ERASE_REQUEST_KEY, marker.value);\n }\n }\n\n const erased = yield* storage.get(JOIN_ERASED_KEY);\n\n if (erased === true) {\n return;\n }\n\n const held = yield* current;\n\n if (Option.isSome(held) && held.value.erase && !erase) {\n return;\n }\n\n const now = yield* Clock.currentTimeMillis;\n\n const retentionDeadlineAt = Math.min(\n Option.isSome(held)\n ? (held.value.retentionDeadlineAt ??\n now + JOIN_CONTACT_RETENTION_MILLIS)\n : now + JOIN_CONTACT_RETENTION_MILLIS,\n deadlineAt ?? now + JOIN_CONTACT_RETENTION_MILLIS\n );\n\n if (now >= retentionDeadlineAt) {\n yield* expire;\n\n return;\n }\n\n yield* storage.setAlarm(retentionDeadlineAt);\n yield* storage.put(JOIN_CONTACT_KEY, {\n erase,\n retentionDeadlineAt,\n sealed,\n });\n }),\n };\n};\n", - "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/worker.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport {\n Flags,\n eventsEnabled,\n eventsIdentityMode,\n} from \"@rat-stack/core/flags\";\nimport { InterestMode, InterestTokens } from \"@rat-stack/core/interest\";\nimport type { InterestDirectory } from \"@rat-stack/core/interest\";\nimport type { RequestCaptureSettings } from \"@rat-stack/core/request-capture\";\nimport { webCryptoLayer } from \"@rat-stack/core/web-crypto\";\nimport { intakeLiveLayer, intakeInstance } from \"@rat-stack/intake-live\";\nimport { subscriberDeliveryLayer } from \"@rat-stack/subscriber-delivery\";\nimport { Stage } from \"alchemy\";\nimport { Duration, Schema } from \"effect\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport * as HttpRouter from \"effect/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/http/HttpServerResponse\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\n\nimport { mischiefRoutes, readerResponseHeaders } from \"./app.js\";\nimport type { MischiefRouteOptions } from \"./app.js\";\nimport { contentAssetsForBuild } from \"./asset-deployment.js\";\nimport { feedbackGatewayBuild } from \"./auth/build-options.js\";\nimport type { feedbackAccess } from \"./auth/feedback-access.js\";\nimport { feedbackInfrastructure } from \"./auth/infrastructure.js\";\nimport { staticAssetGeneration } from \"./bundled-content.generated.js\";\nimport { mischiefConfigFingerprint } from \"./config-fingerprint.js\";\nimport { ContentStore } from \"./content-store.js\";\nimport CrashTail from \"./crash-tail.js\";\nimport { ErrorPageRenderer, websiteErrorPages } from \"./error-page-renderer.js\";\nimport { events as eventsFor } from \"./events.js\";\nimport { flagsLayer, liveFlagsLayer } from \"./flags.js\";\nimport { instituteStage, withInstitute } from \"./institute-mount.js\";\nimport { intakeApplicationsLayer } from \"./interest/applications.js\";\nimport { interestDirectoryLayer } from \"./interest/directory.js\";\nimport {\n SWEEP_PENDING_INTAKE_CRON,\n deliveryDeadlineLayer,\n scheduleIntakeSweep,\n} from \"./interest/intake-sweep.js\";\nimport Interest from \"./interest/interest-durable-object.js\";\nimport InterestIndex from \"./interest/interest-index-durable-object.js\";\nimport { agentSignupLayer } from \"./interest/join-layer.js\";\nimport type { AgentSignupOptions } from \"./interest/join-layer.js\";\nimport { interestOperatorOptions } from \"./interest/operator-options.js\";\nimport LegacyMcp from \"./legacy-mcp/durable-object.js\";\nimport { LEGACY_SESSION_HEADER } from \"./legacy-mcp/session.js\";\nimport {\n privateTelemetry,\n traceObservability,\n traceSettings,\n} from \"./observability.js\";\nimport { outerHttpPrivacyRegistration } from \"./outer-http-privacy.js\";\nimport { rateLimitsFrom, rateLimitDeclarations } from \"./rate-limits.js\";\nimport type { RateLimitBindings } from \"./rate-limits.js\";\nimport { withReaderWebsite } from \"./reader-website.js\";\nimport {\n logRequestIncident,\n observeRequestIncidents,\n} from \"./request-incidents.js\";\nimport { observeRequestLog } from \"./request-log.js\";\nimport { layerWorkerLoader, sandboxLimits } from \"./sandbox-loader.js\";\nimport type { WorkerLoaderBinding } from \"./sandbox-worker-loader.js\";\nimport { AssetBindingSchema, StaticAssets } from \"./static-assets.js\";\nimport {\n chromeWebMcpTrialToken,\n edgeWebMcpTrialToken,\n withWebMcpOriginTrials,\n} from \"./web-mcp-origin-trials.js\";\n\nconst cloudflareStaticCache = {\n match: (request: Request) => caches.default.match(request),\n put: (request: Request, response: Response) =>\n caches.default.put(request, response),\n};\n\nconst inBackground = (effect: Effect.Effect) =>\n Effect.gen(function* registerBackgroundWork() {\n const execution = yield* Cloudflare.WorkerExecutionContext;\n\n yield* execution.waitUntil(effect);\n });\n\nexport type RequestCapture = (\n settings: RequestCaptureSettings\n) => (\n app: Effect.Effect\n) => Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n E,\n R | RB | HttpServerRequest.HttpServerRequest\n>;\n\nexport const makeMischief = (\n legacyMcp: NonNullable,\n interestDirectory: Layer.Layer,\n capture?: RequestCapture,\n agentSignup?: AgentSignupOptions,\n feedback?: ReturnType,\n liveFlags?: Flags[\"Service\"]\n) =>\n Effect.gen(function* makeMischiefInit() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n const stageRateLimits = rateLimitDeclarations(yield* Stage);\n yield* Cloudflare.RateLimit(\"API_PER_IP\", stageRateLimits.API_PER_IP);\n yield* Cloudflare.RateLimit(\n \"EXECUTE_GLOBAL\",\n stageRateLimits.EXECUTE_GLOBAL\n );\n yield* Cloudflare.RateLimit(\n \"EXECUTE_PER_IP\",\n stageRateLimits.EXECUTE_PER_IP\n );\n yield* Cloudflare.RateLimit(\n \"INTEREST_PER_IP\",\n stageRateLimits.INTEREST_PER_IP\n );\n }\n\n const webBotAuthEnabled = yield* Config.Boolean(\n \"WEB_BOT_AUTH_ENABLED\"\n ).pipe(Config.withDefault(false));\n\n const webBotAuthPrivateJwk = yield* Config.option(\n Config.Redacted(\"WEB_BOT_AUTH_PRIVATE_JWK\")\n );\n\n const interestMode = yield* Config.schema(\n Schema.Literals([\"capture\", \"doi\", \"drovr\"]),\n \"INTEREST_MODE\"\n ).pipe(Config.withDefault(\"doi\" as const));\n\n const interestTokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const interestOperatorToken = yield* Config.option(\n Config.Redacted(\"INTEREST_OPERATOR_TOKEN\")\n );\n\n const drovrIntakeUrl = yield* Config.option(\n Config.String(\"DROVR_INTAKE_URL\")\n );\n\n const drovrIntakeTimeoutSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 60, minimum: 1 })),\n \"DROVR_INTAKE_TIMEOUT_SECONDS\"\n )\n );\n\n const joinDeliveryDeadlineSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 28, minimum: 5 })),\n \"JOIN_DELIVERY_DEADLINE_SECONDS\"\n )\n );\n\n const drovrApiBase = yield* Config.option(Config.String(\"DROVR_API_BASE\"));\n\n const drovrAgentIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_AGENT_INTAKE_CREDENTIAL\")\n );\n\n const drovrIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_INTAKE_CREDENTIAL\")\n );\n\n const identityMode = yield* Flags.use((flags) =>\n flags.get(eventsIdentityMode, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const environment = yield* Cloudflare.WorkerEnvironment;\n\n // SAFETY: these are the native runtime bindings declared above. Alchemy types the environment as a dictionary it fills in at runtime, so this is the one boundary cast.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Alchemy types the Worker environment as a dictionary, so the declared bindings need one boundary cast.\n const bindings = environment as RateLimitBindings & {\n readonly CODE_SANDBOX: WorkerLoaderBinding;\n };\n\n const loader = bindings.CODE_SANDBOX;\n\n const rateLimits = rateLimitsFrom({\n API_PER_IP: bindings.API_PER_IP,\n EXECUTE_GLOBAL: bindings.EXECUTE_GLOBAL,\n EXECUTE_PER_IP: bindings.EXECUTE_PER_IP,\n INTEREST_PER_IP: bindings.INTEREST_PER_IP,\n });\n\n const interestServices = Option.isNone(interestTokenSecret)\n ? undefined\n : yield* Layer.build(\n Layer.mergeAll(\n interestDirectory,\n InterestTokens.layer(interestTokenSecret.value),\n InterestMode.layer(interestMode),\n subscriberDeliveryLayer({\n agentIntake: {\n credential: drovrAgentIntakeCredential,\n url: drovrIntakeUrl,\n },\n confirm: {\n base: drovrApiBase,\n credential: drovrIntakeCredential,\n },\n intake: {\n credential: drovrIntakeCredential,\n url: drovrIntakeUrl,\n },\n intakeTimeout: drovrIntakeTimeoutSeconds.pipe(\n Option.map(Duration.seconds),\n Option.getOrUndefined\n ),\n })\n )\n );\n\n const interest =\n interestServices === undefined\n ? undefined\n : {\n operatorToken: interestOperatorToken.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n services: interestServices,\n };\n\n const joinServices =\n agentSignup !== undefined && interestServices !== undefined\n ? yield* Layer.build(\n agentSignupLayer(agentSignup, interestServices).pipe(\n Layer.provide(deliveryDeadlineLayer(joinDeliveryDeadlineSeconds))\n )\n )\n : undefined;\n\n yield* scheduleIntakeSweep(agentSignup, joinServices);\n\n const operatorOptions = yield* interestOperatorOptions(\n agentSignup,\n joinServices\n );\n\n const assetBinding = Schema.decodeUnknownOption(AssetBindingSchema)(\n environment.ASSETS\n );\n\n const assets = Option.isNone(assetBinding)\n ? undefined\n : yield* StaticAssets.pipe(\n Effect.provide(StaticAssets.layer(assetBinding.value))\n );\n\n const contentStore = yield* ContentStore.pipe(\n Effect.provide(\n ContentStore.layer.pipe(\n Layer.provide(\n Layer.succeed(\n StaticAssets,\n assets ??\n Option.getOrElse(\n yield* Effect.serviceOption(StaticAssets),\n () => StaticAssets.unavailable\n )\n )\n )\n )\n )\n );\n\n const workerRoutes = mischiefRoutes({\n assets,\n contentStore,\n feedback,\n flags: liveFlags,\n interest:\n interest === undefined\n ? undefined\n : { ...interest, ...operatorOptions },\n joinTokens: interestServices,\n legacyMcp,\n rateLimits,\n staticCache: cloudflareStaticCache,\n webBotAuth: {\n enabled: webBotAuthEnabled,\n privateJwk: webBotAuthPrivateJwk.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n },\n }).pipe(\n Layer.provide(layerWorkerLoader(loader, sandboxLimits)),\n Layer.provide(\n joinServices === undefined\n ? Layer.empty\n : Layer.succeedContext(joinServices)\n )\n );\n\n const website = Schema.decodeUnknownEffect(AssetBindingSchema)(\n environment.WEBSITE\n );\n\n const app = (yield* HttpRouter.toHttpEffect(workerRoutes).pipe(\n Effect.orDie\n )).pipe(\n Effect.provideService(ErrorPageRenderer, websiteErrorPages(website))\n );\n\n const chromeToken = yield* chromeWebMcpTrialToken;\n const edgeToken = yield* edgeWebMcpTrialToken;\n\n const readerApp = withInstitute({\n ALCHEMY_STAGE: environment.ALCHEMY_STAGE,\n INSTITUTE: environment.INSTITUTE,\n INSTITUTE_ENABLED: environment.INSTITUTE_ENABLED,\n })(\n withReaderWebsite(\n website.pipe(Effect.orDie),\n withWebMcpOriginTrials(\n [chromeToken, edgeToken],\n readerResponseHeaders(contentStore)\n )\n )(app)\n );\n\n return {\n fetch: observeRequestLog(\n observeRequestIncidents(\n capture === undefined\n ? readerApp\n : Effect.gen(function* captureWithLiveIdentity() {\n const currentIdentity =\n liveFlags === undefined\n ? identityMode\n : yield* liveFlags\n .get(eventsIdentityMode, {})\n .pipe(\n Effect.catch((error) =>\n Effect.logError(\n \"Flag read failed; using Config fallback.\",\n error\n ).pipe(Effect.andThen(Effect.succeed(identityMode)))\n )\n );\n\n return yield* capture({\n captureCity: true,\n identityMode: currentIdentity,\n runInBackground: inBackground,\n })(readerApp);\n })\n ).pipe(Effect.provide(webCryptoLayer))\n ),\n };\n });\n\nconst makeMischiefWorker = Effect.gen(function* makeMischiefWorker() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n yield* Cloudflare.WorkerLoader(\"CODE_SANDBOX\");\n }\n\n const feedback = (yield* feedbackInfrastructure).pipe(Option.getOrUndefined);\n const liveFlags = yield* Flags.pipe(Effect.provide(liveFlagsLayer));\n\n const legacyMcp = yield* LegacyMcp;\n const interests = yield* Interest;\n const interestIndex = yield* InterestIndex;\n const sweepCron = yield* Cloudflare.Workers.CronEventSource;\n\n const tokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const typesafeApiKey = yield* Config.option(\n Config.Redacted(\"TYPESAFE_API_KEY\")\n );\n\n const agentSignup = Option.isNone(tokenSecret)\n ? undefined\n : ({\n applications: intakeApplicationsLayer(\n () => interestIndex.getByName(\"index\").applicationIds(),\n (actor) => interests.getByName(intakeInstance(actor))\n ),\n applicationIds: () => interestIndex.getByName(\"index\").applicationIds(),\n contacts: (submissionId: string) =>\n interests.getByName(`join:${submissionId}`),\n intake: intakeLiveLayer({\n interests: (name) => interests.getByName(name),\n tokenSecret: tokenSecret.value,\n typesafeApiKey,\n }).pipe(Layer.provide(FetchHttpClient.layer)),\n markPending: (submissionId, pending) =>\n interestIndex.getByName(\"index\").markPending(submissionId, pending),\n noteApplication: (submissionId) =>\n interestIndex.getByName(\"index\").noteApplication(submissionId),\n sweep: {\n ids: () => interestIndex.getByName(\"index\").pendingIds(),\n schedule: (run) => sweepCron(SWEEP_PENDING_INTAKE_CRON, () => run),\n },\n } satisfies AgentSignupOptions | undefined);\n\n const enabled = yield* Flags.use((flags) =>\n flags.get(eventsEnabled, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const capture = yield* eventsFor({ enabled, id: \"Mischief\" });\n\n return yield* makeMischief(\n {\n forward: (session, request) => {\n const headers = new Headers(request.headers);\n headers.set(LEGACY_SESSION_HEADER, session);\n\n return legacyMcp\n .getByName(session)\n .fetch(HttpServerRequest.fromWeb(new Request(request, { headers })))\n .pipe(\n Effect.map((response) => HttpServerResponse.toWeb(response)),\n Effect.orDie\n );\n },\n },\n interestDirectoryLayer(\n (address) => interests.getByName(address),\n () => interestIndex.getByName(\"index\")\n ),\n capture,\n agentSignup,\n feedback,\n liveFlags\n );\n}).pipe(\n Effect.provide(\n Layer.mergeAll(\n Cloudflare.Workers.RateLimitBinding,\n Cloudflare.Workers.FetchBinding,\n Cloudflare.Workers.CronEventSourceLive,\n outerHttpPrivacyRegistration,\n privateTelemetry\n )\n ),\n Effect.tapCause((cause) =>\n logRequestIncident(cause, \"initialization\").pipe(\n Effect.provide(webCryptoLayer),\n Effect.asVoid\n )\n )\n);\n\nexport default class Mischief extends Cloudflare.Worker()(\n \"Mischief\",\n Effect.gen(function* mischiefProps() {\n const traces = yield* traceSettings.pipe(Effect.orDie);\n const stage = yield* Stage;\n\n const instituteEnabled = yield* Config.Boolean(\"INSTITUTE_ENABLED\").pipe(\n Config.withDefault(false)\n );\n\n const assets = yield* contentAssetsForBuild(\n new URL(\"../dist/content\", import.meta.url).pathname,\n staticAssetGeneration\n ).pipe(Effect.orDie);\n\n const env = {\n MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint,\n WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken,\n WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken,\n };\n\n return {\n assets,\n build: feedbackGatewayBuild,\n compatibility: { date: traces.enabled ? \"2026-07-28\" : \"2026-05-28\" },\n dev: { port: 1337 },\n ...(stage === instituteStage\n ? { workersDev: { enabled: false, previewsEnabled: false } }\n : { domain: { name: \"ratstack.sh\", redirects: [\"www.ratstack.sh\"] } }),\n env: instituteEnabled ? { ...env, INSTITUTE_ENABLED: \"true\" } : env,\n main: import.meta.url,\n observability: traceObservability(traces),\n tailConsumers: [yield* CrashTail],\n };\n }),\n makeMischiefWorker\n) {}\n", + "[\"rat-stack\",\"show\",\"HEAD:apps/site/src/worker.ts\"]": "import * as Cloudflare from \"@alchemy.run/cloudflare\";\nimport {\n Flags,\n eventsEnabled,\n eventsIdentityMode,\n} from \"@rat-stack/core/flags\";\nimport { InterestMode, InterestTokens } from \"@rat-stack/core/interest\";\nimport type { InterestDirectory } from \"@rat-stack/core/interest\";\nimport type { RequestCaptureSettings } from \"@rat-stack/core/request-capture\";\nimport { webCryptoLayer } from \"@rat-stack/core/web-crypto\";\nimport { intakeLiveLayer, intakeInstance } from \"@rat-stack/intake-live\";\nimport { subscriberDeliveryLayer } from \"@rat-stack/subscriber-delivery\";\nimport { Stage } from \"alchemy\";\nimport { Duration, Schema } from \"effect\";\nimport * as Config from \"effect/Config\";\nimport * as Effect from \"effect/Effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport * as HttpRouter from \"effect/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/http/HttpServerResponse\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\n\nimport { mischiefRoutes, readerResponseHeaders } from \"./app.js\";\nimport type { MischiefRouteOptions } from \"./app.js\";\nimport { contentAssetsForBuild } from \"./asset-deployment.js\";\nimport { feedbackGatewayBuild } from \"./auth/build-options.js\";\nimport type { feedbackAccess } from \"./auth/feedback-access.js\";\nimport { feedbackInfrastructure } from \"./auth/infrastructure.js\";\nimport { staticAssetGeneration } from \"./bundled-content.generated.js\";\nimport { mischiefConfigFingerprint } from \"./config-fingerprint.js\";\nimport { ContentStore } from \"./content-store.js\";\nimport CrashTail from \"./crash-tail.js\";\nimport { ErrorPageRenderer, websiteErrorPages } from \"./error-page-renderer.js\";\nimport { events as eventsFor } from \"./events.js\";\nimport { flagsLayer, liveFlagsLayer } from \"./flags.js\";\nimport { withInstituteNav } from \"./institute-discovery.js\";\nimport { instituteStage, withInstitute } from \"./institute-mount.js\";\nimport {\n instituteVisibilityConfig,\n instituteVisibilityFor,\n} from \"./institute-visibility.js\";\nimport { intakeApplicationsLayer } from \"./interest/applications.js\";\nimport { interestDirectoryLayer } from \"./interest/directory.js\";\nimport {\n SWEEP_PENDING_INTAKE_CRON,\n deliveryDeadlineLayer,\n scheduleIntakeSweep,\n} from \"./interest/intake-sweep.js\";\nimport Interest from \"./interest/interest-durable-object.js\";\nimport InterestIndex from \"./interest/interest-index-durable-object.js\";\nimport { agentSignupLayer } from \"./interest/join-layer.js\";\nimport type { AgentSignupOptions } from \"./interest/join-layer.js\";\nimport { interestOperatorOptions } from \"./interest/operator-options.js\";\nimport LegacyMcp from \"./legacy-mcp/durable-object.js\";\nimport { LEGACY_SESSION_HEADER } from \"./legacy-mcp/session.js\";\nimport {\n privateTelemetry,\n traceObservability,\n traceSettings,\n} from \"./observability.js\";\nimport { outerHttpPrivacyRegistration } from \"./outer-http-privacy.js\";\nimport { rateLimitsFrom, rateLimitDeclarations } from \"./rate-limits.js\";\nimport type { RateLimitBindings } from \"./rate-limits.js\";\nimport { withReaderWebsite } from \"./reader-website.js\";\nimport {\n logRequestIncident,\n observeRequestIncidents,\n} from \"./request-incidents.js\";\nimport { observeRequestLog } from \"./request-log.js\";\nimport { layerWorkerLoader, sandboxLimits } from \"./sandbox-loader.js\";\nimport type { WorkerLoaderBinding } from \"./sandbox-worker-loader.js\";\nimport { AssetBindingSchema, StaticAssets } from \"./static-assets.js\";\nimport {\n chromeWebMcpTrialToken,\n edgeWebMcpTrialToken,\n withWebMcpOriginTrials,\n} from \"./web-mcp-origin-trials.js\";\n\nconst cloudflareStaticCache = {\n match: (request: Request) => caches.default.match(request),\n put: (request: Request, response: Response) =>\n caches.default.put(request, response),\n};\n\nconst inBackground = (effect: Effect.Effect) =>\n Effect.gen(function* registerBackgroundWork() {\n const execution = yield* Cloudflare.WorkerExecutionContext;\n\n yield* execution.waitUntil(effect);\n });\n\nexport type RequestCapture = (\n settings: RequestCaptureSettings\n) => (\n app: Effect.Effect\n) => Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n E,\n R | RB | HttpServerRequest.HttpServerRequest\n>;\n\nexport const makeMischief = (\n legacyMcp: NonNullable,\n interestDirectory: Layer.Layer,\n capture?: RequestCapture,\n agentSignup?: AgentSignupOptions,\n feedback?: ReturnType,\n liveFlags?: Flags[\"Service\"]\n) =>\n Effect.gen(function* makeMischiefInit() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n const stageRateLimits = rateLimitDeclarations(yield* Stage);\n yield* Cloudflare.RateLimit(\"API_PER_IP\", stageRateLimits.API_PER_IP);\n yield* Cloudflare.RateLimit(\n \"EXECUTE_GLOBAL\",\n stageRateLimits.EXECUTE_GLOBAL\n );\n yield* Cloudflare.RateLimit(\n \"EXECUTE_PER_IP\",\n stageRateLimits.EXECUTE_PER_IP\n );\n yield* Cloudflare.RateLimit(\n \"INTEREST_PER_IP\",\n stageRateLimits.INTEREST_PER_IP\n );\n }\n\n const webBotAuthEnabled = yield* Config.Boolean(\n \"WEB_BOT_AUTH_ENABLED\"\n ).pipe(Config.withDefault(false));\n\n const webBotAuthPrivateJwk = yield* Config.option(\n Config.Redacted(\"WEB_BOT_AUTH_PRIVATE_JWK\")\n );\n\n const interestMode = yield* Config.schema(\n Schema.Literals([\"capture\", \"doi\", \"drovr\"]),\n \"INTEREST_MODE\"\n ).pipe(Config.withDefault(\"doi\" as const));\n\n const interestTokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const interestOperatorToken = yield* Config.option(\n Config.Redacted(\"INTEREST_OPERATOR_TOKEN\")\n );\n\n const drovrIntakeUrl = yield* Config.option(\n Config.String(\"DROVR_INTAKE_URL\")\n );\n\n const drovrIntakeTimeoutSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 60, minimum: 1 })),\n \"DROVR_INTAKE_TIMEOUT_SECONDS\"\n )\n );\n\n const joinDeliveryDeadlineSeconds = yield* Config.option(\n Config.schema(\n Schema.Int.check(Schema.isBetween({ maximum: 28, minimum: 5 })),\n \"JOIN_DELIVERY_DEADLINE_SECONDS\"\n )\n );\n\n const drovrApiBase = yield* Config.option(Config.String(\"DROVR_API_BASE\"));\n\n const drovrAgentIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_AGENT_INTAKE_CREDENTIAL\")\n );\n\n const drovrIntakeCredential = yield* Config.option(\n Config.Redacted(\"DROVR_INTAKE_CREDENTIAL\")\n );\n\n const identityMode = yield* Flags.use((flags) =>\n flags.get(eventsIdentityMode, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const environment = yield* Cloudflare.WorkerEnvironment;\n\n // SAFETY: these are the native runtime bindings declared above. Alchemy types the environment as a dictionary it fills in at runtime, so this is the one boundary cast.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Alchemy types the Worker environment as a dictionary, so the declared bindings need one boundary cast.\n const bindings = environment as RateLimitBindings & {\n readonly CODE_SANDBOX: WorkerLoaderBinding;\n };\n\n const loader = bindings.CODE_SANDBOX;\n\n const rateLimits = rateLimitsFrom({\n API_PER_IP: bindings.API_PER_IP,\n EXECUTE_GLOBAL: bindings.EXECUTE_GLOBAL,\n EXECUTE_PER_IP: bindings.EXECUTE_PER_IP,\n INTEREST_PER_IP: bindings.INTEREST_PER_IP,\n });\n\n const interestServices = Option.isNone(interestTokenSecret)\n ? undefined\n : yield* Layer.build(\n Layer.mergeAll(\n interestDirectory,\n InterestTokens.layer(interestTokenSecret.value),\n InterestMode.layer(interestMode),\n subscriberDeliveryLayer({\n agentIntake: {\n credential: drovrAgentIntakeCredential,\n url: drovrIntakeUrl,\n },\n confirm: {\n base: drovrApiBase,\n credential: drovrIntakeCredential,\n },\n intake: {\n credential: drovrIntakeCredential,\n url: drovrIntakeUrl,\n },\n intakeTimeout: drovrIntakeTimeoutSeconds.pipe(\n Option.map(Duration.seconds),\n Option.getOrUndefined\n ),\n })\n )\n );\n\n const interest =\n interestServices === undefined\n ? undefined\n : {\n operatorToken: interestOperatorToken.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n services: interestServices,\n };\n\n const joinServices =\n agentSignup !== undefined && interestServices !== undefined\n ? yield* Layer.build(\n agentSignupLayer(agentSignup, interestServices).pipe(\n Layer.provide(deliveryDeadlineLayer(joinDeliveryDeadlineSeconds))\n )\n )\n : undefined;\n\n yield* scheduleIntakeSweep(agentSignup, joinServices);\n\n const operatorOptions = yield* interestOperatorOptions(\n agentSignup,\n joinServices\n );\n\n const assetBinding = Schema.decodeUnknownOption(AssetBindingSchema)(\n environment.ASSETS\n );\n\n const assets = Option.isNone(assetBinding)\n ? undefined\n : yield* StaticAssets.pipe(\n Effect.provide(StaticAssets.layer(assetBinding.value))\n );\n\n const contentStore = yield* ContentStore.pipe(\n Effect.provide(\n ContentStore.layer.pipe(\n Layer.provide(\n Layer.succeed(\n StaticAssets,\n assets ??\n Option.getOrElse(\n yield* Effect.serviceOption(StaticAssets),\n () => StaticAssets.unavailable\n )\n )\n )\n )\n )\n );\n\n const { discoverable } = instituteVisibilityFor(environment);\n\n const workerRoutes = mischiefRoutes({\n assets,\n contentStore,\n feedback,\n flags: liveFlags,\n instituteDiscoverable: discoverable,\n interest:\n interest === undefined\n ? undefined\n : { ...interest, ...operatorOptions },\n joinTokens: interestServices,\n legacyMcp,\n rateLimits,\n staticCache: cloudflareStaticCache,\n webBotAuth: {\n enabled: webBotAuthEnabled,\n privateJwk: webBotAuthPrivateJwk.pipe(\n Option.map(Redacted.value),\n Option.getOrUndefined\n ),\n },\n }).pipe(\n Layer.provide(layerWorkerLoader(loader, sandboxLimits)),\n Layer.provide(\n joinServices === undefined\n ? Layer.empty\n : Layer.succeedContext(joinServices)\n )\n );\n\n const website = Schema.decodeUnknownEffect(AssetBindingSchema)(\n environment.WEBSITE\n );\n\n const app = (yield* HttpRouter.toHttpEffect(workerRoutes).pipe(\n Effect.orDie\n )).pipe(\n Effect.provideService(ErrorPageRenderer, websiteErrorPages(website))\n );\n\n const chromeToken = yield* chromeWebMcpTrialToken;\n const edgeToken = yield* edgeWebMcpTrialToken;\n\n const readerApp = withInstitute({\n ALCHEMY_STAGE: environment.ALCHEMY_STAGE,\n INSTITUTE: environment.INSTITUTE,\n INSTITUTE_ENABLED: environment.INSTITUTE_ENABLED,\n WEBSITE: environment.WEBSITE,\n })(\n withInstituteNav(discoverable)(\n withReaderWebsite(\n website.pipe(Effect.orDie),\n withWebMcpOriginTrials(\n [chromeToken, edgeToken],\n readerResponseHeaders(contentStore)\n )\n )(app)\n )\n );\n\n return {\n fetch: observeRequestLog(\n observeRequestIncidents(\n capture === undefined\n ? readerApp\n : Effect.gen(function* captureWithLiveIdentity() {\n const currentIdentity =\n liveFlags === undefined\n ? identityMode\n : yield* liveFlags\n .get(eventsIdentityMode, {})\n .pipe(\n Effect.catch((error) =>\n Effect.logError(\n \"Flag read failed; using Config fallback.\",\n error\n ).pipe(Effect.andThen(Effect.succeed(identityMode)))\n )\n );\n\n return yield* capture({\n captureCity: true,\n identityMode: currentIdentity,\n runInBackground: inBackground,\n })(readerApp);\n })\n ).pipe(Effect.provide(webCryptoLayer))\n ),\n };\n });\n\nconst makeMischiefWorker = Effect.gen(function* makeMischiefWorker() {\n if (globalThis.__ALCHEMY_RUNTIME__ !== true) {\n yield* Cloudflare.WorkerLoader(\"CODE_SANDBOX\");\n }\n\n const feedback = (yield* feedbackInfrastructure).pipe(Option.getOrUndefined);\n const liveFlags = yield* Flags.pipe(Effect.provide(liveFlagsLayer));\n\n const legacyMcp = yield* LegacyMcp;\n const interests = yield* Interest;\n const interestIndex = yield* InterestIndex;\n const sweepCron = yield* Cloudflare.Workers.CronEventSource;\n\n const tokenSecret = yield* Config.option(\n Config.Redacted(\"INTEREST_TOKEN_SECRET\")\n );\n\n const typesafeApiKey = yield* Config.option(\n Config.Redacted(\"TYPESAFE_API_KEY\")\n );\n\n const agentSignup = Option.isNone(tokenSecret)\n ? undefined\n : ({\n applications: intakeApplicationsLayer(\n () => interestIndex.getByName(\"index\").applicationIds(),\n (actor) => interests.getByName(intakeInstance(actor))\n ),\n applicationIds: () => interestIndex.getByName(\"index\").applicationIds(),\n contacts: (submissionId: string) =>\n interests.getByName(`join:${submissionId}`),\n intake: intakeLiveLayer({\n interests: (name) => interests.getByName(name),\n tokenSecret: tokenSecret.value,\n typesafeApiKey,\n }).pipe(Layer.provide(FetchHttpClient.layer)),\n markPending: (submissionId, pending) =>\n interestIndex.getByName(\"index\").markPending(submissionId, pending),\n noteApplication: (submissionId) =>\n interestIndex.getByName(\"index\").noteApplication(submissionId),\n sweep: {\n ids: () => interestIndex.getByName(\"index\").pendingIds(),\n schedule: (run) => sweepCron(SWEEP_PENDING_INTAKE_CRON, () => run),\n },\n } satisfies AgentSignupOptions | undefined);\n\n const enabled = yield* Flags.use((flags) =>\n flags.get(eventsEnabled, {}).pipe(Effect.orDie)\n ).pipe(Effect.provide(flagsLayer));\n\n const capture = yield* eventsFor({ enabled, id: \"Mischief\" });\n\n return yield* makeMischief(\n {\n forward: (session, request) => {\n const headers = new Headers(request.headers);\n headers.set(LEGACY_SESSION_HEADER, session);\n\n return legacyMcp\n .getByName(session)\n .fetch(HttpServerRequest.fromWeb(new Request(request, { headers })))\n .pipe(\n Effect.map((response) => HttpServerResponse.toWeb(response)),\n Effect.orDie\n );\n },\n },\n interestDirectoryLayer(\n (address) => interests.getByName(address),\n () => interestIndex.getByName(\"index\")\n ),\n capture,\n agentSignup,\n feedback,\n liveFlags\n );\n}).pipe(\n Effect.provide(\n Layer.mergeAll(\n Cloudflare.Workers.RateLimitBinding,\n Cloudflare.Workers.FetchBinding,\n Cloudflare.Workers.CronEventSourceLive,\n outerHttpPrivacyRegistration,\n privateTelemetry\n )\n ),\n Effect.tapCause((cause) =>\n logRequestIncident(cause, \"initialization\").pipe(\n Effect.provide(webCryptoLayer),\n Effect.asVoid\n )\n )\n);\n\nexport default class Mischief extends Cloudflare.Worker()(\n \"Mischief\",\n Effect.gen(function* mischiefProps() {\n const traces = yield* traceSettings.pipe(Effect.orDie);\n const stage = yield* Stage;\n\n const instituteVisibility = yield* instituteVisibilityConfig;\n\n const assets = yield* contentAssetsForBuild(\n new URL(\"../dist/content\", import.meta.url).pathname,\n staticAssetGeneration\n ).pipe(Effect.orDie);\n\n const env = {\n ...instituteVisibility,\n MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint,\n WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken,\n WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken,\n };\n\n return {\n assets,\n build: feedbackGatewayBuild,\n compatibility: { date: traces.enabled ? \"2026-07-28\" : \"2026-05-28\" },\n dev: { port: 1337 },\n ...(stage === instituteStage\n ? { workersDev: { enabled: false, previewsEnabled: false } }\n : { domain: { name: \"ratstack.sh\", redirects: [\"www.ratstack.sh\"] } }),\n env,\n main: import.meta.url,\n observability: traceObservability(traces),\n tailConsumers: [yield* CrashTail],\n };\n }),\n makeMischiefWorker\n) {}\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/command.ts\"]": "import { ResourceNotFound } from \"@rat-stack/core/contracts\";\nimport { Effect, Option, Schema } from \"effect\";\nimport { Command } from \"foldkit\";\nimport { load, pushUrl, replaceUrl } from \"foldkit/navigation\";\nimport { fromString } from \"foldkit/url\";\n\nimport { Message } from \"./message.js\";\nimport { DocumentQueries } from \"./queries.js\";\n\nexport const SearchDocs = Command.define(\"SearchDocs\", {\n args: { generation: Schema.Finite, query: Schema.String },\n execute: ({ query, generation }) =>\n DocumentQueries.use((queries) => queries.search(query)).pipe(\n Effect.map((result) => Message.SucceededSearch({ generation, result })),\n Effect.orElseSucceed(() => Message.FailedSearch({ generation }))\n ),\n messages: [Message.SucceededSearch, Message.FailedSearch],\n});\n\nexport const ReadDoc = Command.define(\"ReadDoc\", {\n args: { generation: Schema.Finite, id: Schema.String },\n execute: ({ id, generation }) =>\n DocumentQueries.use((queries) => queries.read(id)).pipe(\n Effect.match({\n onFailure: (error) =>\n Message.FailedRead({\n generation,\n message: Schema.is(ResourceNotFound)(error)\n ? error.message\n : \"The document could not be loaded. Try again in a moment.\",\n notFound: Schema.is(ResourceNotFound)(error),\n }),\n onSuccess: (document) =>\n Message.SucceededRead({ document, generation }),\n })\n ),\n messages: [Message.SucceededRead, Message.FailedRead],\n});\n\nexport const Navigate = Command.define(\"Navigate\", {\n args: { url: Schema.String },\n execute: ({ url }) =>\n pushUrl(url).pipe(\n Effect.andThen(\n Effect.sync(() => {\n window.scrollTo(0, 0);\n })\n ),\n Effect.as(Message.CompletedNavigate())\n ),\n messages: [Message.CompletedNavigate],\n});\n\nexport const ReadLocation = Command.define(\"ReadLocation\", {\n execute: Effect.sync(() =>\n Option.match(fromString(window.location.href), {\n onNone: () => Message.CompletedNavigate(),\n onSome: (url) => Message.ChangedUrl({ url }),\n })\n ),\n messages: [Message.ChangedUrl, Message.CompletedNavigate],\n});\n\nexport const ReplaceUrl = Command.define(\"ReplaceUrl\", {\n args: { url: Schema.String },\n execute: ({ url }) =>\n replaceUrl(url).pipe(Effect.as(Message.CompletedNavigate())),\n messages: [Message.CompletedNavigate],\n});\n\nexport const LoadExternal = Command.define(\"LoadExternal\", {\n args: { href: Schema.String },\n execute: ({ href }) =>\n load(href).pipe(Effect.as(Message.CompletedLoadExternal())),\n messages: [Message.CompletedLoadExternal],\n});\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/message.ts\"]": "import { ReadOutput, SearchOutput } from \"@rat-stack/core/contracts\";\nimport { Schema } from \"effect\";\nimport { defineMessageUnion } from \"foldkit/message\";\nimport { UrlRequest } from \"foldkit/navigation\";\nimport { Url } from \"foldkit/url\";\n\nexport const Message = defineMessageUnion({\n ChangedUrl: { url: Url },\n ClickedLink: { request: UrlRequest },\n CompletedLoadExternal: {},\n CompletedNavigate: {},\n FailedRead: {\n generation: Schema.Finite,\n message: Schema.String,\n notFound: Schema.Boolean,\n },\n FailedSearch: { generation: Schema.Finite },\n SubmittedSearch: {},\n SucceededRead: { document: ReadOutput, generation: Schema.Finite },\n SucceededSearch: { generation: Schema.Finite, result: SearchOutput },\n UpdatedQuery: { value: Schema.String },\n});\n\nexport type AppMessage = typeof Message.Type;\n", "[\"rat-stack\",\"show\",\"HEAD:apps/web/src/client/docs/queries.ts\"]": "import { toRpcGroup } from \"@rat-stack/capability/rpc-group\";\nimport { readContract, searchContract } from \"@rat-stack/core/contracts\";\nimport { Cache, Context, Effect, Layer } from \"effect\";\nimport { RpcClient } from \"effect/rpc\";\n\nimport { readerRpcProtocol } from \"../rpc.js\";\n\nconst { group } = toRpcGroup([searchContract, readContract]);\n\nconst make = Effect.gen(function* makeDocumentQueries() {\n const client = yield* RpcClient.make(group).pipe(\n Effect.provide(readerRpcProtocol)\n );\n\n const search = yield* Cache.make({\n capacity: Number.POSITIVE_INFINITY,\n lookup: (query: string) => client.search({ limit: 10, query }),\n timeToLive: \"30 seconds\",\n });\n\n const read = yield* Cache.make({\n capacity: Number.POSITIVE_INFINITY,\n lookup: (id: string) => client.read({ id }),\n });\n\n return {\n read: (id: string) => Cache.get(read, id),\n search: (query: string) => Cache.get(search, query),\n };\n});\n\nexport class DocumentQueries extends Context.Service<\n DocumentQueries,\n Effect.Success\n>()(\"@rat-stack/web/DocumentQueries\", { make }) {\n static readonly layer = Layer.effect(this, this.make);\n}\n", diff --git a/.env.schema b/.env.schema index 03fc8dba..329aa23c 100644 --- a/.env.schema +++ b/.env.schema @@ -113,11 +113,21 @@ AUTH_ENABLED=false # @sensitive=false INSTITUTE_ARTIFACT= -# Enable Mischief dispatch only if an Institute service binding is also present. +# Optional absolute path to the digest-pinned Institute dist for Website static content. +# @type=string +# @sensitive=false +INSTITUTE_CONTENT_ARTIFACT= + +# Enable serving the Institute. Off returns the site's normal not-found response. # @type=boolean # @sensitive=false INSTITUTE_ENABLED=false +# Make the enabled Institute discoverable through indexing, sitemaps, and site navigation. +# @type=boolean +# @sensitive=false +INSTITUTE_PUBLIC=false + # Native Effect tracing is opt-in. Cloudflare owns head sampling and export. # @type=boolean # @sensitive=false diff --git a/apps/infra/test/preview-stack.test.ts b/apps/infra/test/preview-stack.test.ts index b9d85df3..e979a42a 100644 --- a/apps/infra/test/preview-stack.test.ts +++ b/apps/infra/test/preview-stack.test.ts @@ -50,6 +50,8 @@ it.effect.prop( "/__error", "/__rat", "/__rat/*", + "/institute", + "/institute/*", "/prompts", "/prompts/*", ], diff --git a/apps/infra/test/website-build.test.ts b/apps/infra/test/website-build.test.ts index fb17a7c1..dc1ab3b2 100644 --- a/apps/infra/test/website-build.test.ts +++ b/apps/infra/test/website-build.test.ts @@ -30,6 +30,9 @@ const bindings = { BACKEND: { fetch: async () => new Response("private RPC binding", { status: 200 }) }, ASSETS: { fetch: async (request) => { const pathname = new URL(request.url).pathname; + if (pathname === "/institute" || pathname.startsWith("/institute/")) { + throw new Error("The disabled Institute must not read Website assets"); + } const base = payload.clientDirectory + (pathname === "/" ? "/index.html" : pathname); for (const file of [base, base + "/index.html"]) { try { return new Response(await readFile(file), { status: 200 }); } catch {} @@ -67,6 +70,20 @@ const ProbeResponses = Schema.fromJsonString( ) ); +const expectDisabledInstitute = (responses: typeof ProbeResponses.Type) => { + const outside = responses.find(({ path }) => path === "/outside-the-slice"); + + const institute = responses.filter(({ path }) => + path.startsWith("/institute") + ); + + expect(institute).toHaveLength(5); + + for (const response of institute) { + expect(response).toEqual({ ...outside, path: response.path }); + } +}; + it.layer(NodeServices.layer)((test) => { test.effect( "Alchemy selects the reader and RpcBackend evaluates without import.meta.url to serve native RPC", @@ -320,6 +337,11 @@ it.layer(NodeServices.layer)((test) => { "/rpc", "/__rat", "/outside-the-slice", + "/institute", + "/institute/chapters/one-contract?section=define-boundary", + "/institute/sitemap.xml", + "/institute/og/home.png", + "/institute/content/one-contract/define-boundary.4170eb40.webm", ], }) ) @@ -337,7 +359,11 @@ it.layer(NodeServices.layer)((test) => { const responses = yield* Schema.decodeEffect(ProbeResponses)(output); - for (const response of responses) { + expectDisabledInstitute(responses); + + for (const response of responses.filter( + ({ path: url }) => !url.startsWith("/institute") + )) { expect(response.commit).toBe(commit); expect(response.noindex).toBe("noindex"); expect(response.status).toBe( diff --git a/apps/infra/test/website-workerd.ts b/apps/infra/test/website-workerd.ts index 72fb3848..924cfca2 100644 --- a/apps/infra/test/website-workerd.ts +++ b/apps/infra/test/website-workerd.ts @@ -7,13 +7,28 @@ import { rpcContentDirectory } from "../../site/src/rpc-worker.js"; const nativeProbe = String.raw` import { Effect, Layer } from "effect"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientRequest, HttpClientResponse, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { withInstituteNav } from "../../../site/src/institute-discovery.js"; import { RpcClient, RpcSerialization } from "effect/rpc"; import { toRpcGroup } from "@rat-stack/capability/rpc-group"; import { searchContract, readContract } from "@rat-stack/core/contracts"; export default { async test(_controller, env) { + const request = new Request("https://pr-40.ratstack.sh/", { headers: { Accept: "text/html" } }); + const response = await env.WEBSITE.fetch(request); + const nav = (discoverable) => Effect.runPromise( + withInstituteNav(discoverable)(Effect.succeed(HttpServerResponse.fromWeb(response.clone()))).pipe( + Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), + Effect.map(HttpServerResponse.toWeb), + ) + ).then((value) => value.text()); + const [unlisted, publicHtml, original] = await Promise.all([nav(false), nav(true), response.text()]); + if (unlisted !== original || unlisted.includes('href="/institute"') || + !publicHtml.includes('
  • institute
  • ')) { + throw new Error("The public Institute switch did not preserve unlisted navigation and add the public link"); + } + const httpClient = HttpClient.make((request) => HttpClientRequest.toWeb(request).pipe( Effect.orDie, diff --git a/apps/site/scripts/smoke.sh b/apps/site/scripts/smoke.sh index 26a965c7..079863c1 100644 --- a/apps/site/scripts/smoke.sh +++ b/apps/site/scripts/smoke.sh @@ -87,8 +87,29 @@ for accept in text/html text/markdown; do grep -Eiq '^cache-control:.*no-store' "$tmp_dir/workshop.headers" || fail "workshop $accept lost no-store" printf 'workshop indexable: %s\n' "$accept" done -curl --fail --silent --show-error --max-time 20 "${base_url}/sitemap.xml" >"$tmp_dir/sitemap.xml" -grep -Fq "${base_url}/tokenmaxx" "$tmp_dir/sitemap.xml" || fail "workshop missing from sitemap" +curl --fail --silent --show-error --max-time 20 "${base_url}/sitemap.xml" >"$tmp_dir/sitemap.xml" || fail "GET ${base_url}/sitemap.xml did not complete" +site_sitemap_path=/sitemap.xml +if grep -Fq 'https://ratstack.sh/sitemap/site.xml' "$tmp_dir/sitemap.xml" || fail "${base_url}/sitemap.xml is missing the site child sitemap" + grep -Fq 'https://ratstack.sh/institute/sitemap.xml' "$tmp_dir/sitemap.xml" || fail "${base_url}/sitemap.xml is missing the Institute child sitemap" + site_sitemap_path=/sitemap/site.xml + curl --fail --silent --show-error --max-time 20 "${base_url}${site_sitemap_path}" >"$tmp_dir/sitemap.xml" || fail "GET ${base_url}${site_sitemap_path} did not complete" +else + if [[ "${INSTITUTE_ENABLED:-false}" == "true" && "${INSTITUTE_PUBLIC:-false}" == "true" ]]; then + fail "${base_url}/sitemap.xml is not an index with the public Institute enabled" + fi + if grep -Fiq 'institute' "$tmp_dir/sitemap.xml"; then + fail "${base_url}/sitemap.xml exposed the unlisted Institute" + fi + institute_status="$(curl --silent --show-error --max-time 20 --header 'accept: text/html' --dump-header "$tmp_dir/institute.headers" --output /dev/null --write-out '%{http_code}' "${base_url}/institute")" || fail "GET ${base_url}/institute did not complete" + case "$institute_status" in + 200) grep -Eiq '^x-robots-tag:.*noindex' "$tmp_dir/institute.headers" || fail "${base_url}/institute lost X-Robots-Tag: noindex while unlisted" ;; + 404) [[ "${INSTITUTE_ENABLED:-false}" != "true" ]] || fail "${base_url}/institute returned 404 with INSTITUTE_ENABLED on" ;; + *) fail "${base_url}/institute returned HTTP ${institute_status}; expected 200 unlisted or 404 disabled" ;; + esac +fi +grep -Fq "${base_url}/tokenmaxx" "$tmp_dir/sitemap.xml" || fail "workshop missing from ${base_url}${site_sitemap_path}" for route in '/tokenmaxx/confirm?token=invalid' '/tokenmaxx/unsubscribe?token=invalid' /tokenmaxx/interest /tokenmaxx/four-comma-club.jpg; do curl --silent --show-error --max-time 20 --dump-header "$tmp_dir/transaction.headers" --output /dev/null "${base_url}${route}" grep -Eiq '^x-robots-tag:.*noindex' "$tmp_dir/transaction.headers" || fail "$route lost noindex" diff --git a/apps/site/src/app.ts b/apps/site/src/app.ts index 035e67f4..ef27998e 100644 --- a/apps/site/src/app.ts +++ b/apps/site/src/app.ts @@ -68,6 +68,11 @@ import { } from "./executor-skills.js"; import { flagsLayer } from "./flags.js"; import { privateHttpTracingLayer } from "./http-privacy.js"; +import { + instituteRobotsDirective, + instituteSitemapIndex, + siteSitemapPath, +} from "./institute-discovery.js"; import { joinRequestMiddleware } from "./interest/join-request.js"; import { withAvailablePageTicket } from "./interest/page-ticket.js"; import { retiredInterestRoutes } from "./interest/retired-routes.js"; @@ -590,7 +595,48 @@ export const tokenmaxxResponse = Effect.gen(function* tokenmaxxPage() { }); }); -const contentRoutes = () => +const sitemapResponse = (body: string) => + HttpServerResponse.text(body, { + contentType: "application/xml; charset=utf-8", + }); + +const sitemapRoutes = ( + store: ContentStore["Service"], + discoverable: boolean +) => { + const site = (request: HttpServerRequest.HttpServerRequest) => + store.catalog.pipe( + Effect.map((catalog) => + sitemapResponse(sitemapXml(originOf(request), catalog)) + ) + ); + + const robots = discoverable + ? robotsText + instituteRobotsDirective + : robotsText; + + return Layer.mergeAll( + HttpRouter.add( + "GET", + "/robots.txt", + HttpServerResponse.text(robots, { + contentType: "text/plain; charset=utf-8", + }) + ), + discoverable + ? Layer.merge( + HttpRouter.add( + "GET", + "/sitemap.xml", + sitemapResponse(instituteSitemapIndex) + ), + HttpRouter.add("GET", siteSitemapPath, site) + ) + : HttpRouter.add("GET", "/sitemap.xml", site) + ); +}; + +const contentRoutes = (discoverable: boolean) => Layer.unwrap( Effect.gen(function* buildContentRoutes() { const tickets = yield* Effect.serviceOption(IntakeTicket); @@ -669,22 +715,7 @@ const contentRoutes = () => ) ), HttpRouter.add("GET", "/auth.md", markdown(authMarkdown)), - HttpRouter.add( - "GET", - "/robots.txt", - HttpServerResponse.text(robotsText, { - contentType: "text/plain; charset=utf-8", - }) - ), - HttpRouter.add("GET", "/sitemap.xml", (request) => - store.catalog.pipe( - Effect.map((catalog) => - HttpServerResponse.text(sitemapXml(originOf(request), catalog), { - contentType: "application/xml; charset=utf-8", - }) - ) - ) - ), + sitemapRoutes(store, discoverable), HttpRouter.add( "GET", "/.well-known/agent-skills/index.json", @@ -1140,6 +1171,7 @@ export interface MischiefRouteOptions { readonly feedback?: ReturnType | undefined; readonly contentStore?: ContentStore["Service"] | undefined; readonly assets?: StaticAssets["Service"] | undefined; + readonly instituteDiscoverable?: boolean; readonly interest?: Omit | undefined; readonly joinTokens?: Context.Context | undefined; readonly legacyMcp?: LegacyMcpRouter; @@ -1234,7 +1266,7 @@ export const mischiefRoutes = (options: MischiefRouteOptions = {}) => return Layer.mergeAll( unsubscribeRoutes, - contentRoutes(), + contentRoutes(options.instituteDiscoverable === true), retiredInterestRoutes, joinRequestMiddleware({ rateLimits: options.rateLimits, diff --git a/apps/site/src/institute-discovery.ts b/apps/site/src/institute-discovery.ts new file mode 100644 index 00000000..d3ccb27c --- /dev/null +++ b/apps/site/src/institute-discovery.ts @@ -0,0 +1,69 @@ +import { Effect } from "effect"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +import { institutePath, instituteSitemapPath } from "./institute-paths.js"; + +export const siteSitemapPath = "/sitemap/site.xml"; + +const origin = "https://ratstack.sh"; + +export const instituteRobotsDirective = `Sitemap: ${origin}${instituteSitemapPath}\n`; + +export const instituteSitemapIndex = ` + + ${origin}${siteSitemapPath} + ${origin}${instituteSitemapPath} + +`; + +declare class HTMLRewriter { + on( + selector: string, + handlers: { + readonly element: (element: { + readonly append: ( + markup: string, + options: { readonly html: boolean } + ) => void; + }) => void; + } + ): this; + transform(response: Response): Response; +} + +const primaryLinks = + 'nav[aria-label="Primary navigation"] > .site-links > ul:first-child'; + +export const withInstituteNav = + (discoverable: boolean) => + (app: Effect.Effect) => { + if (!discoverable) { + return app; + } + + return Effect.gen(function* instituteNav() { + const request = yield* HttpServerRequest.HttpServerRequest; + const response = yield* app; + + if ( + request.method !== "GET" || + response.status !== 200 || + response.headers["content-type"]?.startsWith("text/html") !== true + ) { + return response; + } + + const transformed = new HTMLRewriter() + .on(primaryLinks, { + element: (list) => { + list.append(`
  • institute
  • `, { + html: true, + }); + }, + }) + .transform(HttpServerResponse.toWeb(response)); + + return HttpServerResponse.fromWeb(transformed); + }); + }; diff --git a/apps/site/src/institute-mount.ts b/apps/site/src/institute-mount.ts index cc0eff0b..9b244ccf 100644 --- a/apps/site/src/institute-mount.ts +++ b/apps/site/src/institute-mount.ts @@ -2,6 +2,9 @@ import { Effect, Option, Schema } from "effect"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { isInstitutePath } from "./institute-paths.js"; +import { instituteVisibilityFor } from "./institute-visibility.js"; +import { instituteContentSecurityPolicy, secureResponse } from "./security.js"; import { AssetBindingSchema } from "./static-assets.js"; export const instituteStage = "institute-private"; @@ -10,12 +13,20 @@ export const withInstitute = (environment: { readonly ALCHEMY_STAGE?: unknown; readonly INSTITUTE?: unknown; readonly INSTITUTE_ENABLED?: unknown; + readonly WEBSITE?: unknown; }) => { - const binding = Schema.decodeUnknownOption(AssetBindingSchema)( + const { enabled } = instituteVisibilityFor(environment); + + const legacy = Schema.decodeUnknownOption(AssetBindingSchema)( environment.INSTITUTE ); - const enabled = environment.INSTITUTE_ENABLED === "true"; + const binding = legacy.pipe( + Option.orElse(() => + Schema.decodeUnknownOption(AssetBindingSchema)(environment.WEBSITE) + ) + ); + const privateStage = environment.ALCHEMY_STAGE === instituteStage; return ( @@ -37,10 +48,7 @@ export const withInstitute = (environment: { hostname === "ratstack.sh" || (privateStage && hostname !== "www.ratstack.sh"); - if ( - !allowedHost || - (pathname !== "/institute" && !pathname.startsWith("/institute/")) - ) { + if (!allowedHost || !isInstitutePath(pathname)) { return yield* fallback; } @@ -50,7 +58,11 @@ export const withInstitute = (environment: { institute.fetch.bind(institute, original) ); - return HttpServerResponse.fromWeb(response); + const web = HttpServerResponse.fromWeb(response); + + return Option.isSome(legacy) + ? web + : secureResponse(web, instituteContentSecurityPolicy); }); return privateStage diff --git a/apps/site/src/institute-paths.ts b/apps/site/src/institute-paths.ts new file mode 100644 index 00000000..0a47039a --- /dev/null +++ b/apps/site/src/institute-paths.ts @@ -0,0 +1,6 @@ +export const institutePath = "/institute"; + +export const instituteSitemapPath = `${institutePath}/sitemap.xml`; + +export const isInstitutePath = (path: string) => + path === institutePath || path.startsWith(`${institutePath}/`); diff --git a/apps/site/src/institute-visibility.ts b/apps/site/src/institute-visibility.ts new file mode 100644 index 00000000..0e99b6fb --- /dev/null +++ b/apps/site/src/institute-visibility.ts @@ -0,0 +1,33 @@ +import { Config, Effect } from "effect"; + +interface InstituteVisibilityBindings { + readonly INSTITUTE_ENABLED?: unknown; + readonly INSTITUTE_PUBLIC?: unknown; +} + +export const instituteVisibilityFor = ( + bindings: InstituteVisibilityBindings +) => { + const enabled = bindings.INSTITUTE_ENABLED === "true"; + + return { + enabled, + discoverable: enabled && bindings.INSTITUTE_PUBLIC === "true", + }; +}; + +export const instituteVisibilityConfig = Effect.gen( + function* instituteVisibilityConfig() { + const enabled = yield* Config.Boolean("INSTITUTE_ENABLED").pipe( + Config.withDefault(false) + ); + + const discoverable = yield* Config.Boolean("INSTITUTE_PUBLIC").pipe( + Config.withDefault(false) + ); + + return enabled + ? { INSTITUTE_ENABLED: "true", INSTITUTE_PUBLIC: String(discoverable) } + : {}; + } +); diff --git a/apps/site/src/security.ts b/apps/site/src/security.ts index 754dde04..efd4a2c7 100644 --- a/apps/site/src/security.ts +++ b/apps/site/src/security.ts @@ -7,10 +7,11 @@ const policy = (sources: { readonly formAction: string; readonly frames?: string; readonly images?: string; + readonly media?: string; readonly scripts: string; readonly styles: string; }) => - `default-src 'none'; style-src ${sources.styles}; img-src 'self' data:${sources.images === undefined ? "" : ` ${sources.images}`}; script-src ${sources.scripts}; connect-src 'self' https://cloudflareinsights.com; base-uri ${sources.base}; form-action ${sources.formAction}; frame-ancestors 'none'${sources.frames === undefined ? "" : `; frame-src ${sources.frames}`}`; + `default-src 'none'; style-src ${sources.styles}; img-src 'self' data:${sources.images === undefined ? "" : ` ${sources.images}`}; script-src ${sources.scripts}; connect-src 'self' https://cloudflareinsights.com; base-uri ${sources.base}; form-action ${sources.formAction}; frame-ancestors 'none'${sources.frames === undefined ? "" : `; frame-src ${sources.frames}`}${sources.media === undefined ? "" : `; media-src ${sources.media}`}`; export const contentSecurityPolicy = (formAction: "'none'" | "'self'") => policy({ @@ -29,6 +30,11 @@ const readerSources = { export const readerContentSecurityPolicy = policy(readerSources); +export const instituteContentSecurityPolicy = policy({ + ...readerSources, + media: "'self'", +}); + export const tubePagePath = "/tube"; export const tubeContentSecurityPolicy = policy({ diff --git a/apps/site/src/worker.ts b/apps/site/src/worker.ts index e7476cd8..9bda19b7 100644 --- a/apps/site/src/worker.ts +++ b/apps/site/src/worker.ts @@ -35,7 +35,12 @@ import CrashTail from "./crash-tail.js"; import { ErrorPageRenderer, websiteErrorPages } from "./error-page-renderer.js"; import { events as eventsFor } from "./events.js"; import { flagsLayer, liveFlagsLayer } from "./flags.js"; +import { withInstituteNav } from "./institute-discovery.js"; import { instituteStage, withInstitute } from "./institute-mount.js"; +import { + instituteVisibilityConfig, + instituteVisibilityFor, +} from "./institute-visibility.js"; import { intakeApplicationsLayer } from "./interest/applications.js"; import { interestDirectoryLayer } from "./interest/directory.js"; import { @@ -274,11 +279,14 @@ export const makeMischief = ( ) ); + const { discoverable } = instituteVisibilityFor(environment); + const workerRoutes = mischiefRoutes({ assets, contentStore, feedback, flags: liveFlags, + instituteDiscoverable: discoverable, interest: interest === undefined ? undefined @@ -320,14 +328,17 @@ export const makeMischief = ( ALCHEMY_STAGE: environment.ALCHEMY_STAGE, INSTITUTE: environment.INSTITUTE, INSTITUTE_ENABLED: environment.INSTITUTE_ENABLED, + WEBSITE: environment.WEBSITE, })( - withReaderWebsite( - website.pipe(Effect.orDie), - withWebMcpOriginTrials( - [chromeToken, edgeToken], - readerResponseHeaders(contentStore) - ) - )(app) + withInstituteNav(discoverable)( + withReaderWebsite( + website.pipe(Effect.orDie), + withWebMcpOriginTrials( + [chromeToken, edgeToken], + readerResponseHeaders(contentStore) + ) + )(app) + ) ); return { @@ -461,9 +472,7 @@ export default class Mischief extends Cloudflare.Worker()( const traces = yield* traceSettings.pipe(Effect.orDie); const stage = yield* Stage; - const instituteEnabled = yield* Config.Boolean("INSTITUTE_ENABLED").pipe( - Config.withDefault(false) - ); + const instituteVisibility = yield* instituteVisibilityConfig; const assets = yield* contentAssetsForBuild( new URL("../dist/content", import.meta.url).pathname, @@ -471,6 +480,7 @@ export default class Mischief extends Cloudflare.Worker()( ).pipe(Effect.orDie); const env = { + ...instituteVisibility, MISCHIEF_CONFIG_FINGERPRINT: mischiefConfigFingerprint, WEB_MCP_CHROME_TRIAL_TOKEN: chromeWebMcpTrialToken, WEB_MCP_EDGE_TRIAL_TOKEN: edgeWebMcpTrialToken, @@ -484,7 +494,7 @@ export default class Mischief extends Cloudflare.Worker()( ...(stage === instituteStage ? { workersDev: { enabled: false, previewsEnabled: false } } : { domain: { name: "ratstack.sh", redirects: ["www.ratstack.sh"] } }), - env: instituteEnabled ? { ...env, INSTITUTE_ENABLED: "true" } : env, + env, main: import.meta.url, observability: traceObservability(traces), tailConsumers: [yield* CrashTail], diff --git a/apps/site/test/institute-discovery.test.ts b/apps/site/test/institute-discovery.test.ts new file mode 100644 index 00000000..bcc528fd --- /dev/null +++ b/apps/site/test/institute-discovery.test.ts @@ -0,0 +1,96 @@ +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; + +import { mischiefRoutes } from "../src/app.js"; +import { ContentStore } from "../src/content-store.js"; +import { robotsText, sitemapXml } from "../src/content.js"; +import { withInstituteNav } from "../src/institute-discovery.js"; +import { instituteVisibilityFor } from "../src/institute-visibility.js"; +import { nodeAssetsLayer } from "../src/node-content.js"; +import { TestSandbox } from "./test-sandbox.js"; + +const request = (path: string) => + HttpServerRequest.fromWeb(new Request(`https://ratstack.sh${path}`)); + +it.layer(ContentStore.layer.pipe(Layer.provide(nodeAssetsLayer)))((test) => { + test.effect( + "only public Institute discovers the sitemap fragment in the site's sitemap index and robots", + () => + Effect.gen(function* discovery() { + const store = yield* ContentStore; + const catalog = yield* store.catalog; + const originalSitemap = sitemapXml("https://ratstack.sh", catalog); + + for (const bindings of [ + { INSTITUTE_ENABLED: "false", INSTITUTE_PUBLIC: "true" }, + { INSTITUTE_ENABLED: "true", INSTITUTE_PUBLIC: "false" }, + { INSTITUTE_ENABLED: "true", INSTITUTE_PUBLIC: "true" }, + ]) { + const { discoverable } = instituteVisibilityFor(bindings); + + const app = yield* HttpRouter.toHttpEffect( + mischiefRoutes({ + contentStore: store, + instituteDiscoverable: discoverable, + }).pipe(Layer.provide(TestSandbox)) + ); + + const fetch = (path: string) => + app.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + request(path) + ), + Effect.map(HttpServerResponse.toWeb), + Effect.flatMap((response) => + Effect.promise(response.text.bind(response)) + ) + ); + + const sitemap = yield* fetch("/sitemap.xml"); + const robots = yield* fetch("/robots.txt"); + + if (discoverable) { + expect(sitemap).toContain("https://ratstack.sh/institute/sitemap.xml" + ); + expect(sitemap).toContain( + "https://ratstack.sh/sitemap/site.xml" + ); + expect(yield* fetch("/sitemap/site.xml")).toBe(originalSitemap); + expect(robots).toBe( + `${robotsText}Sitemap: https://ratstack.sh/institute/sitemap.xml\n` + ); + } else { + expect(sitemap).toBe(originalSitemap); + expect(robots).toBe(robotsText); + expect(sitemap).not.toContain("institute"); + expect(robots).not.toContain("institute"); + } + } + }) + ); +}); + +it.effect("unlisted Institute leaves existing navigation byte-identical", () => + Effect.gen(function* unlistedNavigation() { + const nav = + ''; + + const original = HttpServerResponse.html(nav); + + const response = yield* withInstituteNav(false)( + Effect.succeed(original) + ).pipe( + Effect.provideService(HttpServerRequest.HttpServerRequest, request("/")) + ); + + expect(response).toBe(original); + const web = HttpServerResponse.toWeb(response); + const body = yield* Effect.promise(web.text.bind(web)); + expect(body).toBe(nav); + expect(body).not.toContain("institute"); + }) +); diff --git a/apps/site/test/institute-mount.test.ts b/apps/site/test/institute-mount.test.ts index 105aaf26..a4d8167d 100644 --- a/apps/site/test/institute-mount.test.ts +++ b/apps/site/test/institute-mount.test.ts @@ -80,6 +80,64 @@ it.effect.prop( }) ); +it.effect( + "forwards the original Range request to Website unless the legacy binding wins", + () => + Effect.gen(function* websiteFallback() { + const website = { + fetch: (forwarded: Request) => { + expect(forwarded.headers.get("range")).toBe("bytes=0-31"); + expect(forwarded.headers.get("accept")).toBe("audio/webm"); + expect(new URL(forwarded.url).search).toBe( + "?section=define-boundary" + ); + + return Promise.resolve(new Response("website", { status: 206 })); + }, + }; + + const legacy = { fetch: () => Promise.resolve(new Response("legacy")) }; + + const request = new Request( + "https://ratstack.sh/institute/content/one-contract/clip.webm?section=define-boundary", + { + headers: { accept: "audio/webm", range: "bytes=0-31" }, + } + ); + + for (const binding of [legacy, undefined]) { + const response = yield* dispatch(request, { + INSTITUTE: binding, + INSTITUTE_ENABLED: "true", + WEBSITE: website, + }); + + const web = HttpServerResponse.toWeb(response); + expect(yield* Effect.promise(web.text.bind(web))).toBe( + binding === undefined ? "website" : "legacy" + ); + expect(web.status).toBe(binding === undefined ? 206 : 200); + } + + for (const url of [ + "https://ratstack.sh/institutes", + "https://ratstack.sh/institute-x", + "https://www.ratstack.sh/institute", + ]) { + expect( + yield* dispatch(new Request(url), { + INSTITUTE_ENABLED: "true", + WEBSITE: website, + }) + ).toBe(fallback); + } + + expect( + yield* dispatch(request, { INSTITUTE: legacy, WEBSITE: website }) + ).toBe(fallback); + }) +); + it.effect( "keeps the stage noindex and passes the same request body to the service", () => diff --git a/apps/web/effect-ui.ts b/apps/web/effect-ui.ts index e4a9ce2b..755d85c3 100644 --- a/apps/web/effect-ui.ts +++ b/apps/web/effect-ui.ts @@ -4,6 +4,7 @@ import type { Plugin } from "vite"; const entries = { "all-stars-effect-ui": "src/client/all-stars-effect-ui/entry.ts", "directory-effect-ui": "src/client/directory-effect-ui/entry.ts", + "institute-effect-ui": "src/client/institute-entry.ts", "news-effect-ui": "src/client/news-effect-ui/entry.ts", "reader-effect-ui": "src/client/reader-effect-ui/entry.ts", }; diff --git a/apps/web/institute-assets.ts b/apps/web/institute-assets.ts new file mode 100644 index 00000000..15b17b06 --- /dev/null +++ b/apps/web/institute-assets.ts @@ -0,0 +1,30 @@ +import { NodeCrypto, NodeServices } from "@effect/platform-node"; +import { Effect, Path } from "effect"; +import type { Plugin } from "vite"; + +import { stageInstituteAssets } from "./src/institute/content/artifact.js"; + +export const instituteAssetsPlugin = (): Plugin => ({ + apply: "build", + buildApp: { + handler: (builder) => { + const { client } = builder.environments; + + if (client === undefined) { + return Promise.resolve(); + } + + return Effect.runPromise( + Effect.gen(function* stageForWebsite() { + const path = yield* Path.Path; + yield* stageInstituteAssets( + path.resolve(client.config.root, client.config.build.outDir) + ); + }).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layerDigest])) + ); + }, + order: "post", + }, + name: "institute-assets", + sharedDuringBuild: true, +}); diff --git a/apps/web/package.json b/apps/web/package.json index dbc43fa9..99d18e8c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,9 +34,11 @@ "@rat-stack/motion": "workspace:*", "@rat-stack/site": "workspace:*", "@stylexjs/stylex": "0.19.2", + "@xstate/effect": "1.0.0-beta.2", "alchemy": "2.0.0-beta.87", "effect": "4.1.4", - "foldkit": "0.170.0" + "foldkit": "0.170.0", + "xstate": "6.0.0-beta.3" }, "devDependencies": { "@effect/platform-node": "4.1.4", diff --git a/apps/web/src/client/institute-entry.ts b/apps/web/src/client/institute-entry.ts new file mode 100644 index 00000000..d23f7eaf --- /dev/null +++ b/apps/web/src/client/institute-entry.ts @@ -0,0 +1,19 @@ +import { Effect } from "effect"; + +import { hydrateInstitute } from "../institute/routes/hydration.js"; + +import "../../../site/src/rat.css"; +import "../institute/routes/institute.css"; + +Effect.runFork( + hydrateInstitute(document, (host, slot) => + Effect.tryPromise(() => import("./institute-playback.js")).pipe( + Effect.flatMap(({ mountChapter }) => mountChapter(host, slot)) + ) + ).pipe( + Effect.scoped, + Effect.tapCause((cause) => + Effect.logError("Institute hydration failed", cause) + ) + ) +); diff --git a/apps/web/src/client/institute-playback.ts b/apps/web/src/client/institute-playback.ts new file mode 100644 index 00000000..439b6bc3 --- /dev/null +++ b/apps/web/src/client/institute-playback.ts @@ -0,0 +1,91 @@ +import { Effect, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; + +import { + InstituteAssetError, + SectionSchema, +} from "../institute/content/index.js"; +import { mountControls } from "../institute/player/controls/index.js"; +import type { SectionNavigation } from "../institute/player/controls/index.js"; +import { mountInstitutePlayer } from "../institute/player/entry.js"; +import type { InstitutePlayerOptions } from "../institute/player/entry.js"; +import { preferredAudio } from "../institute/routes/audio-choice.js"; +import type { PlayerSlot } from "../institute/routes/hydration.js"; + +const decodeSection = Schema.decodeEffect(Schema.fromJsonString(SectionSchema)); + +const chapterAnchors = (host: HTMLElement): SectionNavigation => { + const page = host.ownerDocument; + + const sections = page.querySelectorAll( + "[data-institute-section-link]" + ); + + const links = [ + ["first", sections.item(0)], + ["home", page.querySelector("[data-institute-home]")], + ["last", sections.item(sections.length - 1)], + ["next", page.querySelector("[data-institute-next]")], + [ + "previous", + page.querySelector("[data-institute-previous]"), + ], + ] as const; + + const navigation: Partial void>> = {}; + + for (const [key, link] of links) { + if (link !== null) { + navigation[key] = link.click.bind(link); + } + } + + return navigation; +}; + +export const mountChapter = Effect.fn("institute.mountChapter")( + function* mountChapter(host: HTMLElement, slot: PlayerSlot) { + const path = slot.sectionUrl; + + const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); + const response = yield* client.get(new URL(path, host.ownerDocument.URL)); + const section = yield* response.text.pipe(Effect.flatMap(decodeSection)); + + if (section.id !== slot.sectionId) { + return yield* new InstituteAssetError({ + cause: `Expected section ${slot.sectionId}, got ${section.id}`, + path, + }); + } + + const navigation = chapterAnchors(host); + + const url = preferredAudio( + host.ownerDocument.createElement("audio"), + slot.audioUrl, + slot.audioFallbackUrl + ); + + const options: InstitutePlayerOptions = { + audioUrl: url, + chapterId: slot.chapterId, + mountControls: (controls, controller, keyboardScope) => + mountControls(controls, controller, { + chapterId: slot.chapterId, + keyboardScope, + navigation, + sectionId: slot.sectionId, + }), + section, + sectionId: slot.sectionId, + }; + + return mountInstitutePlayer( + host, + navigation.next === undefined + ? options + : { ...options, onEnded: navigation.next } + ); + }, + Effect.provide(FetchHttpClient.layer) +); diff --git a/apps/web/src/cloudflare-workers.d.ts b/apps/web/src/cloudflare-workers.d.ts index ec01b3c7..97994046 100644 --- a/apps/web/src/cloudflare-workers.d.ts +++ b/apps/web/src/cloudflare-workers.d.ts @@ -1,5 +1,10 @@ declare module "cloudflare:workers" { export const env: { + readonly ASSETS?: { + readonly fetch: (request: Request) => Promise; + }; + readonly INSTITUTE_ENABLED?: string; + readonly INSTITUTE_PUBLIC?: string; readonly BACKEND: { readonly fetch: (request: Request) => Promise; }; diff --git a/apps/web/src/entry.server.ts b/apps/web/src/entry.server.ts index 108fdaed..2698b9b9 100644 --- a/apps/web/src/entry.server.ts +++ b/apps/web/src/entry.server.ts @@ -1,5 +1,11 @@ import { Effect, Layer, Option, Schema } from "effect"; -import { Rendered, Responded } from "foldkit/experimental/server"; +import { + Rendered, + Responded, + handleRequest, + toResponse, +} from "foldkit/experimental/server"; +import type { DocumentRenderer } from "foldkit/experimental/server"; import effectUiAssetManifest from "virtual:reader-effect-ui-assets"; import { readerErrorTemplate } from "virtual:reader-error"; @@ -14,10 +20,12 @@ import { isWithinSection, loreRouter, } from "./features/site-route.js"; +import { isInstitutePath } from "./institute/routes/paths.js"; +import { instituteWebsiteRuntime } from "./institute/routes/website-runtime.js"; import type { ReaderSourcePage } from "./reader-cafe.js"; import { isWorkerFirstReaderRoute } from "./reader-routes.js"; import { readerPrerenderOrigin } from "./server/prerender-origin.js"; -import { EffectUiAssets } from "./server/reader-document.js"; +import { EffectUiAssets, renderDocument } from "./server/reader-document.js"; import { readerSupportsEffectUi } from "./server/reader-effect-ui-props.js"; import { ReaderErrorTemplate } from "./server/reader-error-template.js"; import { findPage } from "./server/reader-pages.js"; @@ -36,12 +44,13 @@ import { export { pagePaths as prerenderPaths } from "./server/reader-pages.js"; -export { renderDocument } from "./server/reader-document.js"; +export { renderDocument }; const effectUiAssets = Schema.decodeUnknownSync( Schema.Struct({ "all-stars-effect-ui": EffectUiAssets, "directory-effect-ui": EffectUiAssets, + "institute-effect-ui": EffectUiAssets, "news-effect-ui": EffectUiAssets, "reader-effect-ui": EffectUiAssets, }) @@ -79,7 +88,8 @@ const previewHeaders = Effect.fn("reader.previewHeaders")( const responded = Effect.fn("reader.responded")(function* responded( request: Request, - response: Response + response: Response, + noindex?: boolean ) { const headers = new Headers(response.headers); const preview = yield* previewHeaders(request); @@ -88,6 +98,10 @@ const responded = Effect.fn("reader.responded")(function* responded( headers.set(name, value); } + if (noindex === true) { + headers.set("X-Robots-Tag", "noindex"); + } + return Responded( new Response(response.body, { headers, @@ -183,6 +197,75 @@ const renderReaderHtml = (page: ReaderSourcePage) => { ); }; +const notFound = (request: Request, noindex = false) => + responded( + request, + new Response("This route is outside the reader preview slice", { + status: 404, + }), + noindex + ); + +const institutePage = Effect.fn("reader.institutePage")(function* institutePage( + request: Request +) { + const institute = yield* instituteWebsiteRuntime; + + if (institute === null) { + return yield* notFound(request); + } + + const { discoverable, fetchAsset } = institute; + + if (request.method !== "GET" && request.method !== "HEAD") { + return yield* responded( + request, + new Response("Institute pages accept GET or HEAD", { + headers: { Allow: "GET, HEAD" }, + status: 405, + }), + !discoverable + ); + } + + const { renderInstituteRequest } = yield* Effect.tryPromise( + () => import("./institute/routes/request.js") + ); + + const result = yield* renderInstituteRequest( + request, + fetchAsset, + effectUiAssets["institute-effect-ui"], + discoverable + ).pipe( + Effect.catch((error) => + Effect.logError("Institute published content unavailable", error).pipe( + Effect.as({ + response: new Response("Institute content is unavailable", { + status: 503, + }), + }) + ) + ) + ); + + if (result === null) { + return yield* notFound(request, !discoverable); + } + + if (result.response !== undefined) { + return yield* responded(request, result.response, !discoverable); + } + + const headers = yield* previewHeaders(request); + + if (!discoverable) { + headers.set("X-Robots-Tag", "noindex"); + } + + return Rendered(result.application, { headers, status: 200 }); +}); + export const renderReaderPage = Effect.fn("reader.renderPage")( function* renderReaderPage(request: Request) { const { pathname } = new URL(request.url); @@ -204,6 +287,10 @@ export const renderReaderPage = Effect.fn("reader.renderPage")( return yield* renderErrorRoute(request); } + if (isInstitutePath(pathname)) { + return yield* institutePage(request); + } + if (request.method !== "GET" && request.method !== "HEAD") { return yield* responded( request, @@ -218,12 +305,7 @@ export const renderReaderPage = Effect.fn("reader.renderPage")( const found = yield* findPage(route); if (Option.isNone(found)) { - return yield* responded( - request, - new Response("This route is outside the reader preview slice", { - status: 404, - }) - ); + return yield* notFound(request); } const page = found.value; @@ -277,3 +359,25 @@ export const renderPage = (request: Request) => ) ) ); + +export const renderWebsiteRequest = ( + request: Request, + assets: Parameters[1] +) => { + const document = (application: Parameters[0]) => + renderDocument(application, assets); + + if (!isInstitutePath(new URL(request.url).pathname)) { + return handleRequest(request, { renderDocument: document, renderPage }); + } + + return renderPage(request).then((result) => { + const response = toResponse(document, result); + + if (request.method !== "HEAD" || response.body === null) { + return response; + } + + return response.body.cancel().then(() => new Response(null, response)); + }); +}; diff --git a/apps/web/src/institute/content/PROVENANCE.md b/apps/web/src/institute/content/PROVENANCE.md new file mode 100644 index 00000000..ca20ab2a --- /dev/null +++ b/apps/web/src/institute/content/PROVENANCE.md @@ -0,0 +1,13 @@ +# Institute wire format + +`schema.ts` and `slideshow.ts` adapt Kit Langton's Effect Institute compiler schemas at `559b4ea0a1b3651705d4576de43505c2e0cb0250`: `src/lib/tooling/types.ts`, `src/lib/animated-code/slideshow.ts` and `src/lib/animated-code/annotations.ts`. The published filenames and optional narration come from `src/backend/services/course/builder.ts`. The adapted schemas use Effect 4 structs with finite numbers and constrain asset filenames to the compiler's hashed format. + +## MIT License + +Copyright (c) 2026 Kit Langton + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/apps/web/src/institute/content/README.md b/apps/web/src/institute/content/README.md new file mode 100644 index 00000000..7e54bc08 --- /dev/null +++ b/apps/web/src/institute/content/README.md @@ -0,0 +1,9 @@ +# Institute content + +The digest-verified fork artifact is the source of truth for lesson JSON and audio. `artifact.ts` owns the six-chapter Ratstack order and the artifact pin. Vite validates the input before copying only the selected chapter manifests, hashed section JSON, referenced WebM and optional AAC, and the home OG into Website static assets. The course manifest is derived from that selection. Kit's chapters are not copied. Nothing loads the fork's React bundle, includes lesson bytes in Worker JavaScript, or adds a storage service. + +For a local proof, set `INSTITUTE_CONTENT_ARTIFACT` to the output of the desk's `institute-artifact.sh path ` using the full SHA in `artifact.ts`. Run `pnpm --filter @rat-stack/web exec vitest run test/institute-content.test.ts` to check the pinned corpus; leave the variable unset for ordinary CI. To rotate the artifact, update the SHA and digest together and rerun the corpus check and Website build. The artifact build is not byte-reproducible, so the commit SHA alone is not a pin. + +Keep `INSTITUTE_CONTENT_ARTIFACT` unset on deployed builds until the `/institute` Worker-first routing gate lands. This variable is separate from the legacy `INSTITUTE_ARTIFACT` that provisions the fork Worker. The serving dispatcher forwards Range to the native `ASSETS` binding and preserves 206 and `Content-Range`. If `ASSETS` answers with a full 200, the dispatcher handles a single range on the bounded, hashed media only. Apply immutable cache headers to successful hashed JSON, WebM and AAC responses, never to manifests or 404s. On an enabled preview, fetch a `webm` with `Range: bytes=0-31` and check for 206, the matching `Content-Range`, and a 32-byte body. On a disabled preview, the same URL must return the site's normal 404, even when the asset exists. + +The current pin stages 71 files: 7,573,963 WebM bytes (largest file 518,262 bytes), 5,850,402 AAC bytes (largest file 390,738 bytes), 568,143 JSON bytes including the generated index, and a 50,675-byte OG PNG. Total: 14,043,183 bytes. No lesson bytes count toward Worker startup. The `InstituteContent` service reads through a caller-supplied asset adapter and returns `audioUrl(...) === undefined` when the section has no primary narration. When `audioFallbackFile` is set, `audioFallbackUrl(...)` derives the optional hashed AAC URL for playback as `audio/mp4`. diff --git a/apps/web/src/institute/content/artifact.ts b/apps/web/src/institute/content/artifact.ts new file mode 100644 index 00000000..365184f8 --- /dev/null +++ b/apps/web/src/institute/content/artifact.ts @@ -0,0 +1,226 @@ +import { Config, Effect, FileSystem, Option, Path, Schema } from "effect"; +import * as Digest from "effect/crypto/Digest"; + +import { InstituteAssetError } from "./institute-asset-error.js"; +import { + audioFallbackUrl, + audioUrl, + chapterAssetPath, + instituteManifestPath, + instituteOgPath, +} from "./paths.js"; +import { CourseManifestSchema } from "./schema.js"; +import { InstituteContent } from "./service.js"; + +export const instituteArtifactPin = { + sha: "ad383c832586b4d406d7495406a3c26f81fddc20", + digest: "cdba47941165c10e350040543124e86159a359a8622afb709e5e066096bb42ad", +}; + +export const instituteArtifactConfig = "INSTITUTE_CONTENT_ARTIFACT"; + +const chapterOrder = [ + "one-contract", + "one-boundary", + "effect-hard-parts", + "who-owns-state", + "cloud-as-code", + "the-fence", +]; + +class InstituteArtifactError extends Schema.TaggedError()( + "InstituteArtifactError", + { + directory: Schema.String, + reason: Schema.String, + } +) { + override get message() { + return `Invalid Institute artifact ${this.directory}: ${this.reason}. Fix: set ${instituteArtifactConfig} from \`institute-artifact.sh path ${instituteArtifactPin.sha}\` and rebuild.`; + } +} + +const verifyArtifact = Effect.fn("Institute.verifyArtifact")( + function* verifyArtifact(directory: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + if (!path.isAbsolute(directory)) { + return yield* new InstituteArtifactError({ + directory, + reason: "expected an absolute dist path", + }); + } + + const digest = yield* Digest.Digest; + const hashes: string[] = []; + + const paths = (yield* fs.readDirectory(directory, { + recursive: true, + })).toSorted(); + + for (const entry of paths) { + if ( + entry === "server/wrangler.json" || + entry.startsWith("server/.wrangler/") + ) { + continue; + } + + const fullPath = path.join(directory, entry); + const stat = yield* fs.stat(fullPath); + + if (stat.type === "File") { + const bytes = yield* fs.readFile(fullPath); + const hash = yield* digest.digestHex(Digest.sha256, bytes); + hashes.push(`${hash} ./${entry}\n`); + } + } + + const actual = yield* digest.digestHex( + Digest.sha256, + new TextEncoder().encode(hashes.join("")) + ); + + if (actual !== instituteArtifactPin.digest) { + return yield* new InstituteArtifactError({ + directory, + reason: `expected digest ${instituteArtifactPin.digest}, got ${actual}`, + }); + } + + return actual; + } +); + +export const stageInstituteAssets = Effect.fn("Institute.stageAssets")( + function* stageInstituteAssets(clientDirectory: string) { + const configured = yield* Config.option( + Config.String(instituteArtifactConfig) + ); + + if (Option.isNone(configured) || configured.value === "") { + return; + } + + const directory = configured.value; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* verifyArtifact(directory).pipe( + Effect.catchTag( + "PlatformError", + (error) => + new InstituteArtifactError({ directory, reason: error.message }) + ) + ); + + const fromAsset = (asset: string) => path.join(directory, "client", asset); + + const readAsset = (asset: string) => + fs + .readFileString(fromAsset(asset)) + .pipe( + Effect.mapError( + (cause) => new InstituteAssetError({ path: asset, cause }) + ) + ); + + const upstream = yield* InstituteContent.make(readAsset); + const course = yield* upstream.manifest; + const files = [instituteOgPath]; + + const chapters = yield* Effect.forEach((chapterId: string, index) => + Effect.gen(function* stageChapter() { + const metadata = course.chapters.find(({ id }) => id === chapterId); + + if ( + metadata === undefined || + metadata.draft === true || + metadata.comingSoon === true + ) { + return yield* new InstituteArtifactError({ + directory, + reason: `chapter ${chapterId} is not published`, + }); + } + + const chapter = yield* upstream.chapter(chapterId); + + if (chapter.sections.length === 0 || chapter.draft === true) { + return yield* new InstituteArtifactError({ + directory, + reason: `chapter ${chapterId} has no published sections`, + }); + } + + const chapterFiles = yield* Effect.forEach( + (entry: (typeof chapter.sections)[number]) => + Effect.gen(function* stageSection() { + const section = yield* upstream.section(chapterId, entry.id); + + const urls = [ + chapterAssetPath(chapterId, entry.file), + audioUrl(chapterId, section), + audioFallbackUrl(chapterId, section), + ].filter((asset) => asset !== undefined); + + for (const asset of urls) { + const info = yield* fs + .stat(fromAsset(asset)) + .pipe( + Effect.mapError( + (cause) => new InstituteAssetError({ path: asset, cause }) + ) + ); + + if ( + info.type !== "File" || + info.size === 0n || + info.size > 25n * 1024n * 1024n + ) { + return yield* new InstituteArtifactError({ + directory, + reason: `asset ${asset} must be a nonempty file within the 25 MiB static asset limit`, + }); + } + } + + return urls; + }) + )(chapter.sections); + + files.push( + chapterAssetPath(chapterId, "manifest.json"), + ...chapterFiles.flat() + ); + + return { + ...metadata, + order: index + 1, + sectionsCount: chapter.sections.length, + }; + }) + )(chapterOrder); + + for (const asset of files) { + const output = path.join(clientDirectory, asset); + yield* fs.makeDirectory(path.dirname(output), { recursive: true }); + yield* fs + .copyFile(fromAsset(asset), output) + .pipe( + Effect.mapError( + (cause) => new InstituteAssetError({ path: asset, cause }) + ) + ); + } + + const manifest = yield* Schema.encodeEffect( + Schema.fromJsonString(CourseManifestSchema) + )({ chapters }); + + yield* fs.writeFileString( + path.join(clientDirectory, instituteManifestPath), + manifest + ); + } +); diff --git a/apps/web/src/institute/content/index.ts b/apps/web/src/institute/content/index.ts new file mode 100644 index 00000000..5f5c22e4 --- /dev/null +++ b/apps/web/src/institute/content/index.ts @@ -0,0 +1,17 @@ +export { audioFallbackUrl, audioUrl } from "./paths.js"; + +export { + AudioFallbackFile, + AudioFile, + ChapterManifestSchema, + CourseManifestSchema, + SectionSchema, +} from "./schema.js"; + +export { InstituteAssetError } from "./institute-asset-error.js"; + +export { InstituteContent } from "./service.js"; + +export type { ReadInstituteAsset } from "./service.js"; + +export type { ChapterManifest, CourseManifest, Section } from "./schema.js"; diff --git a/apps/web/src/institute/content/institute-asset-error.ts b/apps/web/src/institute/content/institute-asset-error.ts new file mode 100644 index 00000000..483c9445 --- /dev/null +++ b/apps/web/src/institute/content/institute-asset-error.ts @@ -0,0 +1,13 @@ +import { Schema } from "effect"; + +export class InstituteAssetError extends Schema.TaggedError()( + "InstituteAssetError", + { + path: Schema.String, + cause: Schema.Unknown, + } +) { + override get message() { + return `Cannot read Institute asset ${this.path}: ${String(this.cause)}. Fix: verify the pinned Institute artifact and rebuild Website assets.`; + } +} diff --git a/apps/web/src/institute/content/institute-chapter-not-found.ts b/apps/web/src/institute/content/institute-chapter-not-found.ts new file mode 100644 index 00000000..b32947bc --- /dev/null +++ b/apps/web/src/institute/content/institute-chapter-not-found.ts @@ -0,0 +1,12 @@ +import { Schema } from "effect"; + +export class InstituteChapterNotFound extends Schema.TaggedError()( + "InstituteChapterNotFound", + { + chapterId: Schema.String, + } +) { + override get message() { + return `Institute chapter ${this.chapterId} is not in the course manifest. Fix: use a chapter id from the course manifest.`; + } +} diff --git a/apps/web/src/institute/content/institute-content-invalid.ts b/apps/web/src/institute/content/institute-content-invalid.ts new file mode 100644 index 00000000..ac5d4256 --- /dev/null +++ b/apps/web/src/institute/content/institute-content-invalid.ts @@ -0,0 +1,13 @@ +import { Schema } from "effect"; + +export class InstituteContentInvalid extends Schema.TaggedError()( + "InstituteContentInvalid", + { + path: Schema.String, + reason: Schema.String, + } +) { + override get message() { + return `Invalid Institute asset ${this.path}: ${this.reason}. Fix: rebuild the pinned Institute artifact with the published content compiler.`; + } +} diff --git a/apps/web/src/institute/content/institute-section-not-found.ts b/apps/web/src/institute/content/institute-section-not-found.ts new file mode 100644 index 00000000..f0d92e4d --- /dev/null +++ b/apps/web/src/institute/content/institute-section-not-found.ts @@ -0,0 +1,13 @@ +import { Schema } from "effect"; + +export class InstituteSectionNotFound extends Schema.TaggedError()( + "InstituteSectionNotFound", + { + chapterId: Schema.String, + sectionId: Schema.String, + } +) { + override get message() { + return `Institute section ${this.chapterId}/${this.sectionId} is not in its chapter manifest. Fix: use a section id from the chapter manifest.`; + } +} diff --git a/apps/web/src/institute/content/paths.ts b/apps/web/src/institute/content/paths.ts new file mode 100644 index 00000000..bb6d2893 --- /dev/null +++ b/apps/web/src/institute/content/paths.ts @@ -0,0 +1,26 @@ +import type { Section } from "./schema.js"; + +export const instituteContentPath = "/institute/content"; + +export const instituteManifestPath = `${instituteContentPath}/manifest.json`; + +export const instituteOgPath = "/institute/og/home.png"; + +export const chapterAssetPath = (chapterId: string, file: string): string => + `${instituteContentPath}/${encodeURIComponent(chapterId)}/${file}`; + +export const audioUrl = ( + chapterId: string, + section: Section +): string | undefined => + section.audioFile === undefined + ? undefined + : chapterAssetPath(chapterId, section.audioFile); + +export const audioFallbackUrl = ( + chapterId: string, + section: Section +): string | undefined => + section.audioFallbackFile === undefined + ? undefined + : chapterAssetPath(chapterId, section.audioFallbackFile); diff --git a/apps/web/src/institute/content/schema.ts b/apps/web/src/institute/content/schema.ts new file mode 100644 index 00000000..2bf80fd9 --- /dev/null +++ b/apps/web/src/institute/content/schema.ts @@ -0,0 +1,118 @@ +import { Schema } from "effect"; + +import { AnimationSoundName, CodeSlideshow } from "./slideshow.js"; + +const Id = Schema.String.check(Schema.isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)); + +const SectionFile = Schema.String.check( + Schema.isPattern(/^[a-z0-9-]+\.[0-9a-f]{8}\.json$/u) +); + +export const AudioFile = Schema.String.check( + Schema.isPattern(/^[a-z0-9-]+\.[0-9a-f]{8}\.webm$/u) +); + +export const AudioFallbackFile = Schema.String.check( + Schema.isPattern(/^[a-z0-9-]+\.[0-9a-f]{8}\.m4a$/u) +); + +export const CourseManifestSchema = Schema.Struct({ + chapters: Schema.Array( + Schema.Struct({ + id: Id, + title: Schema.String, + description: Schema.optionalKey(Schema.String), + order: Schema.Finite, + draft: Schema.optionalKey(Schema.Boolean), + comingSoon: Schema.optionalKey(Schema.Boolean), + sectionsCount: Schema.optionalKey(Schema.Finite), + }) + ), +}); + +export type CourseManifest = typeof CourseManifestSchema.Type; + +export const ChapterManifestSchema = Schema.Struct({ + id: Id, + title: Schema.String, + description: Schema.optionalKey(Schema.String), + sections: Schema.Array(Schema.Struct({ id: Id, file: SectionFile })), + groups: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + id: Id, + title: Schema.String, + sectionIds: Schema.Array(Id), + }) + ) + ), + draft: Schema.optionalKey(Schema.Boolean), + draftGroups: Schema.optionalKey(Schema.Array(Id)), +}); + +export type ChapterManifest = typeof ChapterManifestSchema.Type; + +const WordTiming = Schema.Struct({ + word: Schema.String, + start: Schema.Finite, + end: Schema.Finite, + style: Schema.optionalKey( + Schema.Struct({ + bold: Schema.optionalKey(Schema.Boolean), + italic: Schema.optionalKey(Schema.Boolean), + code: Schema.optionalKey(Schema.Boolean), + }) + ), + paragraphBreak: Schema.optionalKey(Schema.Boolean), + listItem: Schema.optionalKey(Schema.Boolean), + definition: Schema.optionalKey(Schema.String), + link: Schema.optionalKey(Schema.String), + suffix: Schema.optionalKey(Schema.String), +}); + +const Step = Schema.Struct({ + name: Schema.optionalKey(Schema.String), + at: Schema.String, + nth: Schema.optionalKey(Schema.Finite), + after: Schema.optionalKey(Schema.String), + offset: Schema.optionalKey(Schema.Finite), +}); + +export const SectionSchema = Schema.Struct({ + id: Id, + text: Schema.String, + code: Schema.String, + contentHash: Schema.String, + wordTimings: Schema.Array(WordTiming), + componentFlow: Schema.optionalKey( + Schema.Struct({ + name: Schema.String, + steps: Schema.Array(Step), + snapshots: Schema.Array( + Schema.Struct({ + state: Schema.Record(Schema.String, Schema.Unknown), + sound: Schema.optionalKey(AnimationSoundName), + }) + ), + }) + ), + slideshowData: Schema.optionalKey(CodeSlideshow), + steps: Schema.optionalKey(Schema.Array(Step)), + stepTimes: Schema.optionalKey(Schema.Array(Schema.Finite)), + componentStepTimes: Schema.optionalKey(Schema.Array(Schema.Finite)), + _debug: Schema.optionalKey( + Schema.Struct({ + timingsStatus: Schema.Literals(["none", "matched", "mismatched"]), + dslWordCount: Schema.Finite, + message: Schema.optionalKey(Schema.String), + }) + ), + groupId: Schema.optionalKey(Id), + groupTitle: Schema.optionalKey(Schema.String), + isFirstInGroup: Schema.optionalKey(Schema.Boolean), + groupDraft: Schema.optionalKey(Schema.Boolean), + audioFile: Schema.optionalKey(AudioFile), + audioFallbackFile: Schema.optionalKey(AudioFallbackFile), +}); + +export type Section = typeof SectionSchema.Type; diff --git a/apps/web/src/institute/content/service.ts b/apps/web/src/institute/content/service.ts new file mode 100644 index 00000000..c31888a3 --- /dev/null +++ b/apps/web/src/institute/content/service.ts @@ -0,0 +1,106 @@ +import { Context, Effect, Layer, Schema } from "effect"; + +import type { InstituteAssetError } from "./institute-asset-error.js"; +import { InstituteChapterNotFound } from "./institute-chapter-not-found.js"; +import { InstituteContentInvalid } from "./institute-content-invalid.js"; +import { InstituteSectionNotFound } from "./institute-section-not-found.js"; +import { chapterAssetPath, instituteManifestPath } from "./paths.js"; +import { + ChapterManifestSchema, + CourseManifestSchema, + SectionSchema, +} from "./schema.js"; + +export type ReadInstituteAsset = ( + path: string +) => Effect.Effect; + +const decodeAsset = >( + schema: S, + path: string, + readAsset: ReadInstituteAsset +) => + readAsset(path).pipe( + Effect.flatMap((raw) => + Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( + Effect.mapError( + (cause) => + new InstituteContentInvalid({ path, reason: cause.message }) + ) + ) + ) + ); + +export class InstituteContent extends Context.Service()( + "@rat-stack/web/InstituteContent", + { + make: (readAsset: ReadInstituteAsset) => + Effect.sync(() => { + const manifest = Effect.suspend(() => + decodeAsset(CourseManifestSchema, instituteManifestPath, readAsset) + ); + + const chapter = Effect.fn("InstituteContent.chapter")(function* chapter( + id: string + ) { + const course = yield* manifest; + + if (!course.chapters.some((entry) => entry.id === id)) { + return yield* new InstituteChapterNotFound({ chapterId: id }); + } + + const path = chapterAssetPath(id, "manifest.json"); + + const decoded = yield* decodeAsset( + ChapterManifestSchema, + path, + readAsset + ); + + if (decoded.id !== id) { + return yield* new InstituteContentInvalid({ + path, + reason: `expected chapter id ${id}, got ${decoded.id}`, + }); + } + + return decoded; + }); + + const section = Effect.fn("InstituteContent.section")(function* section( + chapterId: string, + sectionId: string + ) { + const chapterManifest = yield* chapter(chapterId); + + const entry = chapterManifest.sections.find( + ({ id }) => id === sectionId + ); + + if (entry === undefined) { + return yield* new InstituteSectionNotFound({ + chapterId, + sectionId, + }); + } + + const path = chapterAssetPath(chapterId, entry.file); + const decoded = yield* decodeAsset(SectionSchema, path, readAsset); + + if (decoded.id !== sectionId) { + return yield* new InstituteContentInvalid({ + path, + reason: `expected section id ${sectionId}, got ${decoded.id}`, + }); + } + + return decoded; + }); + + return { manifest, chapter, section }; + }), + } +) { + static readonly layer = (readAsset: ReadInstituteAsset) => + Layer.effect(this, this.make(readAsset)); +} diff --git a/apps/web/src/institute/content/slideshow.ts b/apps/web/src/institute/content/slideshow.ts new file mode 100644 index 00000000..9ef66689 --- /dev/null +++ b/apps/web/src/institute/content/slideshow.ts @@ -0,0 +1,155 @@ +import { Schema } from "effect"; + +const StatusKind = Schema.Literals([ + "running", + "success", + "error", + "interrupted", + "die", +]); + +const CursorType = Schema.Literals(["pointer", "hand", "thumbsDown"]); + +const LineBackground = Schema.Literals(["success", "error", "warning", "info"]); + +export const AnimationSoundName = Schema.Literals([ + "tick", + "pop", + "whoosh", + "sad", + "celebrate", + "chime", + "success", + "error", + "alarm", + "doom", + "spooky", + "press", + "fail", + "succeed", + "ping1", + "ping2", + "ping3", + "derp", + "skip", +]); + +const Token = Schema.Struct({ + text: Schema.String, + type: Schema.Literals([ + "keyword", + "type", + "string", + "number", + "operator", + "comment", + "identifier", + "punctuation", + "default", + ]), + + color: Schema.optionalKey(Schema.String), +}); + +const TemplatePart = Schema.Struct({ + tokens: Schema.Array(Token), + + animateEntry: Schema.Boolean, + + crossfade: Schema.Boolean, + + inline: Schema.optionalKey(Schema.String), + + versions: Schema.optionalKey( + Schema.Record(Schema.String, Schema.Array(Token)) + ), +}); + +const CharRange = Schema.Struct({ start: Schema.Finite, end: Schema.Finite }); + +const TemplateLine = Schema.Struct({ + parts: Schema.Record(Schema.String, TemplatePart), + + partOrder: Schema.Array(Schema.String), + + brightBoundaries: Schema.optionalKey(Schema.Array(CharRange)), +}); + +const Template = Schema.Struct({ + lines: Schema.Record(Schema.String, TemplateLine), +}); + +const LineState = Schema.Struct({ + parts: Schema.Record( + Schema.String, + Schema.Union([Schema.Boolean, Schema.String]) + ), + entering: Schema.optionalKey(Schema.Boolean), + dimmed: Schema.optionalKey(Schema.Boolean), + background: Schema.optionalKey(LineBackground), +}); + +const StatusRange = Schema.Struct({ + start: Schema.Finite, + end: Schema.Finite, + status: StatusKind, +}); + +const Overlay = Schema.Struct({ + lineIndex: Schema.Finite, + start: Schema.Finite, + end: Schema.Finite, + color: Schema.optionalKey(Schema.String), +}); + +const CursorTarget = Schema.Struct({ + lineIndex: Schema.Finite, + charOffset: Schema.Finite, + textLength: Schema.Finite, + type: Schema.optionalKey(CursorType), +}); + +const BurstTarget = Schema.Struct({ + lineIndex: Schema.Finite, + charOffset: Schema.Finite, + textLength: Schema.Finite, + emoji: Schema.Array(Schema.String), + count: Schema.Finite, +}); + +const Spotlight = Schema.Struct({ + ranges: Schema.Record(Schema.String, Schema.Array(CharRange)), + + allRanges: Schema.Record(Schema.String, Schema.Array(CharRange)), + dim: Schema.Finite, + glow: Schema.Boolean, +}); + +const StatusIndicators = Schema.Struct({ + ranges: Schema.Record(Schema.String, Schema.Array(StatusRange)), + + allRanges: Schema.Record(Schema.String, Schema.Array(CharRange)), +}); + +const FrameState = Schema.Struct({ + id: Schema.Finite, + + lineOrder: Schema.Array(Schema.String), + state: Schema.Record(Schema.String, LineState), + marks: Schema.Array(Overlay), + glows: Schema.Array(Overlay), + squiggles: Schema.Array(Overlay), + brightRanges: Schema.Array(Overlay), + spotlight: Schema.optionalKey(Spotlight), + status: Schema.optionalKey(StatusIndicators), + cursor: Schema.optionalKey(CursorTarget), + bursts: Schema.Array(BurstTarget), + sound: Schema.optionalKey(AnimationSoundName), + + say: Schema.optionalKey(Schema.String), +}); + +export const CodeSlideshow = Schema.Struct({ + template: Template, + frames: Schema.Array(FrameState), +}); diff --git a/apps/web/src/institute/player/code-frame.ts b/apps/web/src/institute/player/code-frame.ts new file mode 100644 index 00000000..2267ba07 --- /dev/null +++ b/apps/web/src/institute/player/code-frame.ts @@ -0,0 +1,73 @@ +import { Predicate } from "effect"; + +import type { CodeFrame, CodeLine, CodeToken } from "./section.js"; + +interface CharacterRange { + readonly start: number; + readonly end: number; +} + +const visibleTokens = (line: CodeLine, frame: CodeFrame, id: string) => + line.partOrder.flatMap((part) => { + const visibility = frame.state[id]?.parts[part]; + const template = line.parts[part]; + + if (Predicate.isString(visibility)) { + return template?.versions?.[visibility] ?? []; + } + + return visibility === true ? (template?.tokens ?? []) : []; + }); + +export const codeRuns = ( + line: CodeLine, + frame: CodeFrame, + id: string, + bright: readonly CharacterRange[] +) => { + let from = 0; + + const runs: (CodeToken & { + readonly bright: boolean; + readonly start: number; + })[] = []; + + const boundaries = new Set( + [...(line.brightBoundaries ?? []), ...bright].flatMap(({ start, end }) => [ + start, + end, + ]) + ); + + for (const token of visibleTokens(line, frame, id)) { + const offset = from; + const to = offset + token.text.length; + + const cuts = [...boundaries] + .filter((pos) => pos > offset && pos < to) + .toSorted((a, b) => a - b); + + let start = offset; + + for (const end of [...cuts, to]) { + const spanStart = start; + + if (end > spanStart) { + runs.push({ + ...token, + bright: bright.some( + (range) => range.start <= spanStart && end <= range.end + ), + start: spanStart, + text: token.text.slice(spanStart - offset, end - offset), + }); + } + + start = end; + } + + from = to; + } + + return runs; +}; diff --git a/apps/web/src/institute/player/controller.ts b/apps/web/src/institute/player/controller.ts new file mode 100644 index 00000000..3764bf77 --- /dev/null +++ b/apps/web/src/institute/player/controller.ts @@ -0,0 +1,28 @@ +export type PlayerState = + | "loading" + | "ready" + | "playing" + | "paused" + | "seeking" + | "ended" + | "unavailable" + | "failed"; + +export interface PlayerSnapshot { + readonly state: PlayerState; + readonly currentMs: number; + readonly durationMs: number | undefined; + readonly rate: number; + readonly seeking: boolean; +} + +export interface PlayerController { + readonly play: () => void; + readonly pause: () => void; + readonly seek: (ms: number) => void; + readonly setRate: (rate: number) => void; + readonly getSnapshot: () => PlayerSnapshot; + readonly subscribe: ( + listener: (snapshot: PlayerSnapshot) => void + ) => () => void; +} diff --git a/apps/web/src/institute/player/controls/component.ts b/apps/web/src/institute/player/controls/component.ts new file mode 100644 index 00000000..be4de97e --- /dev/null +++ b/apps/web/src/institute/player/controls/component.ts @@ -0,0 +1,136 @@ +import { Command } from "@effect/ui"; +import { Html } from "@effect/ui/html"; +import { Match, Option, Schema } from "effect"; + +import type { ControlsAction } from "./transport.js"; +import { + ControlsActionSchema, + decodeRate, + hasTransport, + muteAction, + PlaybackSchema, + rates, + TransportAction, +} from "./transport.js"; + +export const ControlsModel = Schema.Struct({ + playback: PlaybackSchema, + muted: Schema.Boolean, + completed: Schema.Boolean, +}); + +export const Message = Schema.TaggedUnion({ + Changed: { model: ControlsModel }, + Action: { action: ControlsActionSchema }, + ActionSent: {}, +}); + +// @effect-diagnostics-next-line experimentalApiUsage:off -- Bind the command to the transport of this player mount. +export class RunAction extends Command.Service()( + "institute/RunControl", + { + args: { action: ControlsActionSchema }, + mode: "concurrent", + success: Message.cases.ActionSent, + } +) {} + +const send = (action: ControlsAction) => Message.cases.Action.make({ action }); + +const displayTime = (ms: number) => { + const seconds = Math.floor(ms / 1000); + + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; +}; + +const announceTime = (ms: number) => { + const seconds = Math.floor(ms / 1000); + + return `${Math.floor(seconds / 60)} min ${seconds % 60} sec`; +}; + +export const Controls = Html.component({ + name: "InstituteControls", + props: ControlsModel, + model: ControlsModel, + message: Message, +}).make({ + init: ({ props }) => props, + update: ($, message) => + Match.value(message).pipe( + Match.tagsExhaustive({ + Changed: ({ model }) => model, + Action: ({ action }) => $.run(RunAction.make({ action })), + ActionSent: () => $.model, + }) + ), + view: (h, { playback, completed, muted }) => { + const { currentMs, durationMs, state, rate } = playback; + const time = `${displayTime(currentMs)} / ${durationMs === undefined ? "–:––" : displayTime(durationMs)}`; + const disabled = !hasTransport(playback); + const playLabel = state === "playing" ? "Pause" : "Play"; + + const mediaStatus = Match.value(state).pipe( + Match.when("unavailable", () => "Playback unavailable"), + Match.when("failed", () => "Playback failed"), + Match.orElse(() => (completed ? "Section completed" : "")) + ); + + return h.div + .class("institute-controls") + .attrs({ role: "group", "aria-label": "Playback controls" }) + .children( + h.div.class("institute-controls__actions").children( + h.button + .attr("type", "button") + .disabled(disabled) + .on("click", send(TransportAction.cases.Toggle.make({}))) + .children(playLabel), + h.button + .attrs({ type: "button", "aria-keyshortcuts": "R" }) + .disabled(disabled) + .on("click", send(TransportAction.cases.Replay.make({}))) + .children("Replay"), + h.select + .attr("aria-label", "Playback speed") + .disabled(disabled) + .value(String(rate)) + .on("change", ({ value }) => { + const parsed = decodeRate(Number(value)); + + return Option.isSome(parsed) + ? send(TransportAction.cases.Rate.make({ rate: parsed.value })) + : undefined; + }) + .children( + ...rates.map((speed) => + h.option.attr("value", String(speed)).children(`${speed}×`) + ) + ), + h.button + .attrs({ type: "button", "aria-pressed": String(muted) }) + .on("click", send(muteAction.make({}))) + .children("Mute cues"), + h.span.class("institute-controls__time").children(time) + ), + h.input + .attrs({ + "aria-label": "Seek", + "aria-valuetext": + durationMs === undefined + ? "Duration unknown" + : `${announceTime(currentMs)} of ${announceTime(durationMs)}`, + max: String(durationMs ?? 0), + min: "0", + step: "any", + type: "range", + }) + .disabled(disabled || (durationMs ?? 0) <= 0) + .value(String(currentMs)) + .on("input", ({ value }) => + send(TransportAction.cases.Seek.make({ ms: Number(value) })) + ), + h.span.attr("role", "status").children(mediaStatus) + ); + }, +}); diff --git a/apps/web/src/institute/player/controls/cues.ts b/apps/web/src/institute/player/controls/cues.ts new file mode 100644 index 00000000..1ae88e4f --- /dev/null +++ b/apps/web/src/institute/player/controls/cues.ts @@ -0,0 +1,174 @@ +import { Effect, Fiber, Schema } from "effect"; + +class CueUnavailable extends Schema.TaggedError< + CueUnavailable, + { readonly brand: unique symbol } +>()("CueUnavailable", { cause: Schema.Defect() }) {} + +const tickEnvelope = { attack: 0.001, decay: 0.03, sustain: 0, release: 0.02 }; + +const presets = { + click: { hz: 783.991, beats: 1 / 8, velocity: 0.25, envelope: tickEnvelope }, + skip: { hz: 1046.502, beats: 1 / 16, velocity: 0.09, envelope: tickEnvelope }, + complete: { + hz: 523.251, + beats: 1, + velocity: 0.4, + envelope: { attack: 0.02, decay: 0.5, sustain: 0.1, release: 0.4 }, + }, +} as const; + +type Cue = keyof typeof presets; + +const playCue = (output: GainNode, cue: Cue) => { + const ctx = output.context; + + const { + hz, + beats, + velocity, + envelope: { attack, decay, sustain, release }, + } = presets[cue]; + + const start = ctx.currentTime; + const attackEnd = start + attack; + const noteOff = start + beats * 0.5; + const decayConstant = decay / Math.log(1000); + const sustainGain = velocity * sustain; + + const offGain = + sustainGain + + (velocity - sustainGain) * Math.exp(-(noteOff - attackEnd) / decayConstant); + + const oscillator = new OscillatorNode(ctx, { type: "sine", frequency: hz }); + const amp = new GainNode(ctx, { gain: 0 }); + + const filters = + cue === "complete" + ? [ + new BiquadFilterNode(ctx, { type: "lowpass", frequency: 1200, Q: 1 }), + new BiquadFilterNode(ctx, { type: "lowpass", frequency: 1200, Q: 1 }), + ] + : []; + + oscillator.connect(amp); + let upstream: AudioNode = amp; + + for (const filter of filters) { + upstream.connect(filter); + upstream = filter; + } + + upstream.connect(output); + amp.gain.setValueAtTime(0, start); + amp.gain.linearRampToValueAtTime(velocity, attackEnd); + amp.gain.setTargetAtTime(sustainGain, attackEnd, decayConstant); + amp.gain.setValueAtTime(offGain, noteOff); + amp.gain.setTargetAtTime(0, noteOff, release / Math.log(1000)); + oscillator.addEventListener( + "ended", + () => { + oscillator.disconnect(); + amp.disconnect(); + + for (const filter of filters) { + filter.disconnect(); + } + }, + { once: true } + ); + oscillator.start(start); + oscillator.stop(noteOff + release); +}; + +const resume = (ctx: AudioContext) => + Effect.tryPromise({ + try: () => ctx.resume(), + catch: (cause) => new CueUnavailable({ cause }), + }); + +export const createCueBank = (doc: Document, muted: () => boolean) => { + let audio: AudioContext | undefined; + let output: GainNode | undefined; + let pending: Fiber.Fiber | undefined; + let lastClickMs = Number.NEGATIVE_INFINITY; + + return { + unlock: () => { + const browser = doc.defaultView; + + if (muted() || browser?.AudioContext === undefined) { + return; + } + + if (audio === undefined) { + try { + const ctx = new browser.AudioContext(); + output = ctx.createGain(); + output.connect(ctx.destination); + audio = ctx; + } catch { + return; + } + } + + if (audio.state === "suspended" && pending === undefined) { + pending = Effect.runFork(resume(audio)); + } + }, + setMuted: (value: boolean) => { + if (output !== undefined) { + output.gain.value = value ? 0 : 1; + } + }, + play: (cue: Cue) => { + if (output === undefined || muted()) { + return; + } + + const now = output.context.currentTime * 1000; + + if (cue === "click" && now - lastClickMs < 150) { + return; + } + + if (cue === "click") { + lastClickMs = now; + } + + const trigger = Effect.sync(() => { + if (output !== undefined && !muted()) { + playCue(output, cue); + } + }); + + Effect.runFork( + (pending === undefined + ? trigger + : Fiber.join(pending).pipe(Effect.andThen(trigger)) + ).pipe(Effect.ignore) + ); + }, + dispose: () => { + const ctx = audio; + const resumeFiber = pending; + output?.disconnect(); + output = undefined; + + if (ctx !== undefined) { + const close = Effect.tryPromise({ + try: () => ctx.close(), + catch: (cause) => new CueUnavailable({ cause }), + }); + + Effect.runFork( + resumeFiber === undefined + ? Effect.ignore(close) + : Fiber.interrupt(resumeFiber).pipe( + Effect.andThen(Effect.ignore(close)) + ) + ); + } + }, + }; +}; diff --git a/apps/web/src/institute/player/controls/hotkeys.ts b/apps/web/src/institute/player/controls/hotkeys.ts new file mode 100644 index 00000000..eb1e64cd --- /dev/null +++ b/apps/web/src/institute/player/controls/hotkeys.ts @@ -0,0 +1,211 @@ +import type { ControlsAction } from "./transport.js"; +import { TransportAction } from "./transport.js"; + +export interface SectionNavigation { + readonly previous?: () => void; + readonly next?: () => void; + readonly first?: () => void; + readonly last?: () => void; + readonly home?: () => void; + readonly continuePlaying?: () => void; +} + +const ignoresKey = ( + event: KeyboardEvent, + scope: HTMLElement, + target: Element +) => + event.defaultPrevented || + event.isComposing || + event.ctrlKey || + event.metaKey || + event.altKey || + !scope.contains(target) || + target.closest( + "select, textarea, [contenteditable]:not([contenteditable=false]), [role=textbox], input:not([type=range])" + ) !== null; + +const runKey = ( + event: KeyboardEvent, + handle: (() => void) | null | undefined, + repeat = false +) => { + if (handle !== null && handle !== undefined) { + event.preventDefault(); + + if (repeat || !event.repeat) { + handle(); + } + } +}; + +const navigationKey = ( + key: string, + range: boolean, + navigation?: SectionNavigation +) => { + switch (key) { + case "Home": { + return range ? undefined : navigation?.first; + } + + case "End": { + return range ? undefined : navigation?.last; + } + + case "ArrowDown": { + return range ? undefined : navigation?.next; + } + + case "ArrowUp": { + return range ? undefined : navigation?.previous; + } + + case "G": { + return navigation?.last; + } + + case "j": { + return navigation?.next; + } + + case "k": { + return navigation?.previous; + } + + default: { + return null; + } + } +}; + +const transportKey = (key: string, shiftKey: boolean) => { + const distanceMs = shiftKey ? 5000 : 2000; + + switch (key) { + case "ArrowLeft": + case "h": { + return TransportAction.cases.SeekBy.make({ ms: -distanceMs }); + } + + case "ArrowRight": + case "l": { + return TransportAction.cases.SeekBy.make({ ms: distanceMs }); + } + + case "<": { + return TransportAction.cases.StepRate.make({ direction: -1 }); + } + + case ">": { + return TransportAction.cases.StepRate.make({ direction: 1 }); + } + + case "r": { + return TransportAction.cases.Replay.make({}); + } + + default: { + return null; + } + } +}; + +const chapterKey = ({ key, shiftKey }: KeyboardEvent) => { + const normalized = /^[a-z]$/iu.test(key) ? key.toLowerCase() : key; + + return normalized === "g" && shiftKey ? "G" : normalized; +}; + +export const attachHotkeys = ( + scope: HTMLElement, + act: (action: ControlsAction) => void, + navigation: SectionNavigation | undefined, + ended: () => boolean +) => { + let gAt = Number.NEGATIVE_INFINITY; + + const reset = () => { + gAt = Number.NEGATIVE_INFINITY; + }; + + const toggle = () => { + act(TransportAction.cases.Toggle.make({})); + }; + + const keydown = (event: KeyboardEvent) => { + const target = scope.ownerDocument.activeElement; + const key = chapterKey(event); + const awaitedG = event.timeStamp - gAt <= 500; + + reset(); + + if (target === null || ignoresKey(event, scope, target)) { + return; + } + + if (key === "g" && (navigation?.first || navigation?.home)) { + runKey(event, () => { + if (awaitedG && navigation.first !== undefined) { + navigation.first(); + } else { + gAt = event.timeStamp; + } + }); + + return; + } + + if (key === "h" && awaitedG && navigation?.home !== undefined) { + runKey(event, navigation.home); + + return; + } + + if ( + key === " " && + target.closest("button, a[href], input, summary") === null + ) { + runKey(event, ended() ? (navigation?.continuePlaying ?? toggle) : toggle); + + return; + } + + const navigate = navigationKey( + key, + target.matches("input[type=range]"), + navigation + ); + + const action = transportKey(key, event.shiftKey); + + if (navigate !== null && navigate !== undefined) { + runKey(event, navigate); + } else if (action !== null) { + runKey( + event, + () => { + act(action); + }, + key !== "r" + ); + } + }; + + const focusout = (event: FocusEvent) => { + if ( + !(event.relatedTarget instanceof Node) || + !scope.contains(event.relatedTarget) + ) { + reset(); + } + }; + + scope.addEventListener("keydown", keydown); + scope.addEventListener("focusout", focusout); + + return () => { + scope.removeEventListener("keydown", keydown); + scope.removeEventListener("focusout", focusout); + }; +}; diff --git a/apps/web/src/institute/player/controls/index.ts b/apps/web/src/institute/player/controls/index.ts new file mode 100644 index 00000000..82ba0892 --- /dev/null +++ b/apps/web/src/institute/player/controls/index.ts @@ -0,0 +1,218 @@ +import { BrowserHost } from "@effect/ui/html"; +import { Effect, Fiber, Option, Predicate, Schema } from "effect"; + +import { Controls, Message, RunAction } from "./component.js"; +import { createCueBank } from "./cues.js"; +import { attachHotkeys } from "./hotkeys.js"; +import type { SectionNavigation } from "./hotkeys.js"; +import { + readPreferences, + readSectionProgress, + savePreferences, + saveSectionProgress, +} from "./progress.js"; +import { + applyTransportAction, + decodeRate, + hasTransport, + muteAction, + seekTo, +} from "./transport.js"; +import type { + ControlsAction, + ControlsTransport, + Playback, +} from "./transport.js"; + +import "./styles.css"; + +export { readSectionProgress } from "./progress.js"; + +export type { SectionNavigation } from "./hotkeys.js"; + +interface ControlsOptions { + readonly chapterId: string; + readonly sectionId: string; + readonly keyboardScope?: HTMLElement; + readonly navigation?: SectionNavigation; +} + +const isMute = Schema.is(muteAction); + +export const mountControls = ( + host: HTMLElement, + controller: ControlsTransport, + { chapterId, sectionId, keyboardScope = host, navigation }: ControlsOptions +): (() => void) => { + const doc = host.ownerDocument; + const browser = doc.defaultView; + let preferences = readPreferences(doc); + let progress = readSectionProgress(doc, chapterId, sectionId); + let playback = controller.getSnapshot(); + let restored = false; + let dirty = false; + let savedSecond = Math.floor(progress.positionMs / 1000); + + const cues = createCueBank(doc, () => preferences.muted); + + const model = () => ({ + completed: progress.completed, + muted: preferences.muted, + playback, + }); + + const save = () => { + if (dirty) { + saveSectionProgress(doc, chapterId, sectionId, progress); + savedSecond = Math.floor(progress.positionMs / 1000); + dirty = false; + } + }; + + const mount = Effect.scoped( + Effect.gen(function* mountPlayerControls() { + const dispatch = (action: ControlsAction): void => { + if (isMute(action)) { + preferences = { ...preferences, muted: !preferences.muted }; + savePreferences(doc, preferences); + cues.setMuted(preferences.muted); + cues.unlock(); + publishModel(); + + return; + } + + if (!hasTransport(controller.getSnapshot())) { + return; + } + + const before = controller.getSnapshot().rate; + cues.unlock(); + applyTransportAction(controller, action); + const rate = decodeRate(controller.getSnapshot().rate); + + if (Option.isSome(rate) && rate.value !== preferences.rate) { + preferences = { ...preferences, rate: rate.value }; + savePreferences(doc, preferences); + } + + if (Predicate.isTagged(action, "SeekBy")) { + cues.play("skip"); + } else if ( + Predicate.isTagged(action, "Toggle") || + Predicate.isTagged(action, "Replay") || + controller.getSnapshot().rate !== before + ) { + cues.play("click"); + } + }; + + const commands = RunAction.toLayer(({ action }) => + Effect.sync(() => { + dispatch(action); + + return Message.cases.ActionSent.make({}); + }) + ); + + // @effect-diagnostics-next-line experimentalApiUsage:off -- Embedded mount shares the parent player lifetime via Scope. + const root = yield* BrowserHost.mountEffect(Controls, model(), host, { + head: false, + }).pipe(Effect.provide(commands)); + + const publishModel = (): void => { + root.send(Message.cases.Changed.make({ model: model() })); + }; + + const update = (snapshot: Playback) => { + const previous = playback; + playback = snapshot; + + if ( + !restored && + hasTransport(snapshot) && + snapshot.durationMs !== undefined + ) { + restored = true; + const { positionMs } = progress; + + if (positionMs > 0 && positionMs < snapshot.durationMs) { + seekTo(controller, positionMs); + } + + controller.setRate(preferences.rate); + publishModel(); + + return; + } + + const positionChanged = snapshot.currentMs !== previous.currentMs; + + if ( + restored && + hasTransport(snapshot) && + (!snapshot.seeking || positionChanged) + ) { + const ended = snapshot.state === "ended"; + const firstCompletion = ended && !progress.completed; + const positionMs = ended ? 0 : snapshot.currentMs; + + if (firstCompletion || progress.positionMs !== positionMs) { + progress = { completed: progress.completed || ended, positionMs }; + dirty = true; + } + + if ( + firstCompletion || + (previous.state !== snapshot.state && dirty) || + savedSecond !== Math.floor(positionMs / 1000) + ) { + save(); + } + + if (firstCompletion) { + cues.play("complete"); + } + } + + publishModel(); + }; + + const unsubscribe = controller.subscribe(update); + + const detachKeys = attachHotkeys( + keyboardScope, + dispatch, + navigation, + () => playback.state === "ended" + ); + + const onVisibility = () => { + if (doc.visibilityState === "hidden") { + save(); + } + }; + + browser?.addEventListener("pagehide", save); + doc.addEventListener("visibilitychange", onVisibility); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + unsubscribe(); + detachKeys(); + browser?.removeEventListener("pagehide", save); + doc.removeEventListener("visibilitychange", onVisibility); + save(); + cues.dispose(); + }) + ); + + return yield* Effect.never; + }) + ); + + const fiber = Effect.runFork(mount); + + return () => { + Effect.runFork(Fiber.interrupt(fiber)); + }; +}; diff --git a/apps/web/src/institute/player/controls/progress.ts b/apps/web/src/institute/player/controls/progress.ts new file mode 100644 index 00000000..2b6f5acd --- /dev/null +++ b/apps/web/src/institute/player/controls/progress.ts @@ -0,0 +1,87 @@ +import { Option, Schema } from "effect"; + +import { Rate } from "./transport.js"; + +const prefix = "ratstack-institute:"; + +const SectionProgressSchema = Schema.Struct({ + completed: Schema.Boolean, + positionMs: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type SectionProgress = typeof SectionProgressSchema.Type; + +const ProgressJson = Schema.fromJsonString(SectionProgressSchema); + +const PreferencesSchema = Schema.Struct({ muted: Schema.Boolean, rate: Rate }); + +export type Preferences = typeof PreferencesSchema.Type; + +const PreferencesJson = Schema.fromJsonString(PreferencesSchema); + +const sectionKey = (chapterId: string, sectionId: string) => + `${prefix}section:${encodeURIComponent(chapterId)}:${encodeURIComponent(sectionId)}`; + +const preferencesKey = `${prefix}player-preferences`; + +const read = (doc: Document, key: string) => { + try { + return doc.defaultView?.localStorage.getItem(key); + } catch { + return null; + } +}; + +const write = (doc: Document, key: string, value: string) => { + try { + doc.defaultView?.localStorage.setItem(key, value); + } catch { + return false; + } + + return true; +}; + +export const readSectionProgress = ( + doc: Document, + chapterId: string, + sectionId: string +): SectionProgress => + Option.getOrElse( + Schema.decodeUnknownOption(ProgressJson)( + read(doc, sectionKey(chapterId, sectionId)) + ), + () => ({ completed: false, positionMs: 0 }) + ); + +export const saveSectionProgress = ( + doc: Document, + chapterId: string, + sectionId: string, + progress: SectionProgress +) => { + const persisted = readSectionProgress(doc, chapterId, sectionId); + + const encoded = Schema.encodeOption(ProgressJson)({ + completed: persisted.completed || progress.completed, + positionMs: progress.positionMs, + }); + + if (Option.isSome(encoded)) { + write(doc, sectionKey(chapterId, sectionId), encoded.value); + } +}; + +export const readPreferences = (doc: Document): Preferences => + Option.getOrElse( + Schema.decodeUnknownOption(PreferencesJson)(read(doc, preferencesKey)), + () => ({ muted: false, rate: 1 }) + ); + +export const savePreferences = (doc: Document, value: Preferences) => { + const encoded = Schema.encodeOption(PreferencesJson)(value); + + if (Option.isSome(encoded)) { + write(doc, preferencesKey, encoded.value); + } +}; diff --git a/apps/web/src/institute/player/controls/styles.css b/apps/web/src/institute/player/controls/styles.css new file mode 100644 index 00000000..0cd8758d --- /dev/null +++ b/apps/web/src/institute/player/controls/styles.css @@ -0,0 +1,45 @@ +.institute-controls { + display: grid; + gap: 0.25rem; + min-width: 0; +} + +.institute-controls__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +.institute-controls :is(button, select, input) { + min-height: 44px; +} + +.institute-controls :is(button, select) { + min-width: 44px; + border: 1px solid currentcolor; + border-radius: 0.375rem; + padding: 0.35rem 0.625rem; + background: transparent; + color: inherit; + font: inherit; +} + +.institute-controls :is(button, select):disabled { + opacity: 0.55; +} + +.institute-controls input[type="range"] { + width: 100%; + margin: 0; + touch-action: pan-y; +} + +.institute-controls :is(button, select, input, [tabindex]):focus-visible { + outline: 2px solid var(--accent, currentcolor); + outline-offset: 2px; +} + +.institute-controls__time { + font-variant-numeric: tabular-nums; +} diff --git a/apps/web/src/institute/player/controls/transport.ts b/apps/web/src/institute/player/controls/transport.ts new file mode 100644 index 00000000..91281611 --- /dev/null +++ b/apps/web/src/institute/player/controls/transport.ts @@ -0,0 +1,125 @@ +import { Match, Option, Schema } from "effect"; + +export const rates = [0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3] as const; + +export const Rate = Schema.Literals(rates); + +export const decodeRate = Schema.decodeUnknownOption(Rate); + +export const PlaybackSchema = Schema.Struct({ + state: Schema.Literals([ + "loading", + "ready", + "playing", + "paused", + "seeking", + "ended", + "unavailable", + "failed", + ]), + currentMs: Schema.Finite, + durationMs: Schema.UndefinedOr(Schema.Finite), + rate: Schema.Finite, + seeking: Schema.Boolean, +}); + +export type Playback = typeof PlaybackSchema.Type; + +export interface ControlsTransport { + readonly play: () => void; + readonly pause: () => void; + readonly seek: (ms: number) => void; + readonly setRate: (rate: number) => void; + readonly getSnapshot: () => Playback; + readonly subscribe: (listener: (snapshot: Playback) => void) => () => void; +} + +export const TransportAction = Schema.TaggedUnion({ + Toggle: {}, + Replay: {}, + Seek: { ms: Schema.Finite }, + SeekBy: { ms: Schema.Finite }, + Rate: { rate: Rate }, + StepRate: { direction: Schema.Literals([-1, 1]) }, +}); + +export const ControlsActionSchema = Schema.Union([ + TransportAction, + Schema.TaggedStruct("Mute", {}), +]); + +export type ControlsAction = typeof ControlsActionSchema.Type; + +export const muteAction = Schema.TaggedStruct("Mute", {}); + +export const hasTransport = ({ state }: Playback) => + state !== "failed" && state !== "unavailable" && state !== "loading"; + +export const seekTo = (transport: ControlsTransport, positionMs: number) => { + const snapshot = transport.getSnapshot(); + + if ( + hasTransport(snapshot) && + snapshot.durationMs !== undefined && + Number.isFinite(positionMs) + ) { + transport.seek(Math.max(0, Math.min(positionMs, snapshot.durationMs))); + } +}; + +export const applyTransportAction = ( + transport: ControlsTransport, + action: typeof TransportAction.Type +) => { + const snapshot = transport.getSnapshot(); + + if (!hasTransport(snapshot)) { + return; + } + + const execute = Match.value(action).pipe( + Match.tagsExhaustive({ + Toggle: () => () => { + if (snapshot.state === "playing") { + transport.pause(); + } else { + transport.play(); + } + }, + Replay: () => () => { + seekTo(transport, 0); + transport.play(); + }, + Seek: + ({ ms }) => + () => { + seekTo(transport, ms); + }, + SeekBy: + ({ ms }) => + () => { + seekTo(transport, snapshot.currentMs + ms * snapshot.rate); + }, + Rate: + ({ rate }) => + () => { + transport.setRate(rate); + }, + StepRate: + ({ direction }) => + () => { + const current = decodeRate(snapshot.rate); + + if (Option.isSome(current)) { + const rate = rates[rates.indexOf(current.value) + direction]; + + if (rate !== undefined) { + transport.setRate(rate); + } + } + }, + }) + ); + + execute(); +}; diff --git a/apps/web/src/institute/player/entry.ts b/apps/web/src/institute/player/entry.ts new file mode 100644 index 00000000..e8a04c28 --- /dev/null +++ b/apps/web/src/institute/player/entry.ts @@ -0,0 +1,120 @@ +import { BrowserHost } from "@effect/ui/html"; +import { Effect, Fiber } from "effect"; +import { constVoid } from "effect/Function"; + +import type { PlayerController } from "./controller.js"; +import { openPlayback, unavailableController } from "./playback.js"; +import type { PlayerSection } from "./section.js"; +import { PlayerView, Tick } from "./view.js"; + +import "./player.css"; + +export interface InstitutePlayerOptions { + readonly chapterId: string; + readonly sectionId: string; + readonly section: PlayerSection; + readonly audioUrl: string | undefined; + readonly onEnded?: () => void; + readonly mountControls?: ( + host: HTMLElement, + controller: PlayerController, + keyboardScope: HTMLElement + ) => () => void; +} + +export const mountInstitutePlayer = ( + host: HTMLElement, + options: InstitutePlayerOptions +): (() => void) => { + const page = host.ownerDocument; + const shell = page.createElement("section"); + shell.className = "institute-player"; + shell.tabIndex = 0; + shell.setAttribute("aria-label", "Lesson player"); + const controls = page.createElement("div"); + controls.className = "institute-controls"; + const content = page.createElement("div"); + const audio = page.createElement("audio"); + shell.append(controls, content, audio); + host.replaceChildren(shell); + + let disposed = false; + + const session = Effect.runFork( + Effect.scoped( + Effect.gen(function* session() { + // @effect-diagnostics-next-line experimentalApiUsage:off -- The pinned Effect UI browser host owns the player view scope. + const root = yield* BrowserHost.mountEffect( + PlayerView, + { + narrated: options.audioUrl !== undefined, + section: options.section, + }, + content + ); + + const controller = + options.audioUrl === undefined + ? unavailableController + : yield* openPlayback(audio, options.audioUrl, options.onEnded); + + const stop = controller.subscribe((snapshot) => { + shell.dataset.state = snapshot.state; + root.send(Tick.make({ seconds: snapshot.currentMs / 1000 })); + }); + + yield* Effect.addFinalizer(() => Effect.sync(stop)); + + if (options.mountControls !== undefined) { + const activeController: PlayerController = { + getSnapshot: controller.getSnapshot, + pause: () => { + if (!disposed) { + controller.pause(); + } + }, + play: () => { + if (!disposed) { + controller.play(); + } + }, + seek: (ms) => { + if (!disposed) { + controller.seek(ms); + } + }, + setRate: (rate) => { + if (!disposed) { + controller.setRate(rate); + } + }, + subscribe: (listener) => + disposed + ? constVoid + : controller.subscribe((snapshot) => { + if (!disposed) { + listener(snapshot); + } + }), + }; + + const unmountControls = options.mountControls( + controls, + activeController, + shell + ); + + yield* Effect.addFinalizer(() => Effect.sync(unmountControls)); + } + + return yield* Effect.never; + }) + ) + ); + + return () => { + disposed = true; + Effect.runFork(Fiber.interrupt(session)); + shell.remove(); + }; +}; diff --git a/apps/web/src/institute/player/playback.ts b/apps/web/src/institute/player/playback.ts new file mode 100644 index 00000000..88cddad0 --- /dev/null +++ b/apps/web/src/institute/player/playback.ts @@ -0,0 +1,322 @@ +import { watchActor } from "@rat-stack/capability/actor-watch"; +import { + createEffectActor, + createEffectLogic, + sendAndAwait, + setupEffect, +} from "@xstate/effect"; +import type { EffectActor } from "@xstate/effect"; +import { Effect, Schema } from "effect"; +import { constVoid } from "effect/Function"; +import { types } from "xstate"; + +import type { + PlayerController, + PlayerSnapshot, + PlayerState, +} from "./controller.js"; + +const signal = Schema.Struct({}); + +interface MetadataSource extends EventTarget { + readonly HAVE_METADATA: number; + readonly readyState: number; + readonly error: MediaError | null; +} + +const loadMetadata = createEffectLogic( + ({ input }: { readonly input: MetadataSource }) => + Effect.callback((resume) => { + if (input.readyState >= input.HAVE_METADATA) { + resume(Effect.undefined); + + return Effect.void; + } + + if (input.error !== null) { + resume(Effect.fail("metadata")); + + return Effect.void; + } + + const cleanup = () => { + input.removeEventListener("loadedmetadata", loaded); + input.removeEventListener("error", failed); + }; + + const loaded = () => { + cleanup(); + resume(Effect.undefined); + }; + + const failed = () => { + cleanup(); + resume(Effect.fail("metadata")); + }; + + input.addEventListener("loadedmetadata", loaded); + input.addEventListener("error", failed); + + return Effect.sync(cleanup); + }) +); + +export const playbackMachine = setupEffect({ + actors: { loadMetadata }, + schemas: { + events: { + ENDED: signal, + FAILED: signal, + PAUSED: signal, + PLAYING: signal, + SEEKED_PAUSED: signal, + SEEKED_PLAYING: signal, + SEEKING: signal, + }, + context: types<{ readonly audio: MetadataSource }>(), + input: types(), + }, +}).createMachine({ + context: ({ input }) => ({ audio: input }), + initial: "loading", + states: { + ended: { + on: { PLAYING: { target: "playing" }, SEEKING: { target: "seeking" } }, + }, + failed: { type: "final" }, + loading: { + invoke: { + input: ({ context }) => context.audio, + onDone: { target: "ready" }, + onError: { target: "failed" }, + src: "loadMetadata", + }, + }, + paused: { + on: { PLAYING: { target: "playing" }, SEEKING: { target: "seeking" } }, + }, + playing: { + on: { + ENDED: { target: "ended" }, + PAUSED: { target: "paused" }, + SEEKING: { target: "seeking" }, + }, + }, + ready: { + on: { PLAYING: { target: "playing" }, SEEKING: { target: "seeking" } }, + }, + seeking: { + on: { + ENDED: { target: "ended" }, + SEEKED_PAUSED: { target: "paused" }, + SEEKED_PLAYING: { target: "playing" }, + }, + }, + }, + on: { FAILED: { target: ".failed" } }, +}); + +export const unavailableController: PlayerController = { + getSnapshot: () => ({ + currentMs: 0, + durationMs: undefined, + rate: 1, + seeking: false, + state: "unavailable", + }), + pause: constVoid, + play: constVoid, + seek: constVoid, + setRate: constVoid, + subscribe: (listener) => { + listener(unavailableController.getSnapshot()); + + return constVoid; + }, +}; + +const playMedia = (audio: HTMLAudioElement, onRejected: () => void) => { + Effect.runFork( + Effect.tryPromise(() => audio.play()).pipe( + Effect.matchEffect({ + onFailure: () => Effect.sync(onRejected), + onSuccess: () => Effect.void, + }) + ) + ); +}; + +const seekMedia = ( + actor: EffectActor, + apply: () => void +) => { + Effect.runFork( + sendAndAwait(actor, { type: "SEEKING" }).pipe( + Effect.matchEffect({ + onFailure: () => Effect.void, + onSuccess: ({ value }) => + value === "seeking" ? Effect.sync(apply) : Effect.void, + }) + ) + ); +}; + +export const openPlayback = Effect.fnUntraced(function* openPlayback( + audio: HTMLAudioElement, + url: string, + onEnded: (() => void) | undefined +) { + const actor = yield* createEffectActor(playbackMachine, { input: audio }); + yield* watchActor("institutePlayback", actor); + const view = audio.ownerDocument.defaultView; + const events = new AbortController(); + const listeners = new Set<(snapshot: PlayerSnapshot) => void>(); + let state: PlayerState = "loading"; + let animation: number | undefined; + let seekRequest = 0; + + const getSnapshot = (): PlayerSnapshot => ({ + currentMs: audio.currentTime * 1000, + durationMs: Number.isFinite(audio.duration) + ? audio.duration * 1000 + : undefined, + rate: audio.playbackRate, + seeking: state === "seeking", + state, + }); + + const publish = () => { + const snapshot = getSnapshot(); + + for (const listener of listeners) { + listener(snapshot); + } + }; + + const tick = () => { + publish(); + animation = + state === "playing" ? view?.requestAnimationFrame(tick) : undefined; + }; + + const cancelFrame = () => { + if (animation !== undefined) { + view?.cancelAnimationFrame(animation); + animation = undefined; + } + }; + + const subscription = actor.subscribe((snapshot) => { + const before = state; + state = snapshot.value; + + if (state === "playing") { + animation ??= view?.requestAnimationFrame(tick); + } else { + cancelFrame(); + } + + if (before !== state) { + publish(); + + if (state === "ended") { + onEnded?.(); + } + } + }); + + const listen = (event: string, f: () => void) => { + audio.addEventListener(event, f, { signal: events.signal }); + }; + + listen("playing", () => { + actor.send({ type: "PLAYING" }); + }); + listen("pause", () => { + if (!audio.ended) { + actor.send({ type: "PAUSED" }); + } + }); + listen("seeking", () => { + actor.send({ type: "SEEKING" }); + }); + listen("seeked", () => { + actor.send({ type: audio.paused ? "SEEKED_PAUSED" : "SEEKED_PLAYING" }); + }); + listen("ended", () => { + actor.send({ type: "ENDED" }); + }); + listen("error", () => { + actor.send({ type: "FAILED" }); + }); + listen("ratechange", publish); + listen("durationchange", publish); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + events.abort(); + cancelFrame(); + subscription.unsubscribe(); + listeners.clear(); + audio.pause(); + audio.removeAttribute("src"); + audio.load(); + }) + ); + audio.preload = "auto"; + audio.src = url; + + const controller: PlayerController = { + getSnapshot, + pause: () => { + if (!events.signal.aborted) { + audio.pause(); + } + }, + play: () => { + if (events.signal.aborted || state === "loading" || state === "failed") { + return; + } + + playMedia(audio, () => { + actor.send({ type: "PAUSED" }); + }); + }, + seek: (ms) => { + if ( + !events.signal.aborted && + Number.isFinite(audio.duration) && + Number.isFinite(ms) + ) { + const seconds = Math.min(audio.duration, Math.max(0, ms / 1000)); + + if (seconds !== audio.currentTime) { + seekRequest += 1; + const revision = seekRequest; + seekMedia(actor, () => { + if (!events.signal.aborted && revision === seekRequest) { + audio.currentTime = seconds; + publish(); + } + }); + } + } + }, + setRate: (rate) => { + if (!events.signal.aborted && rate >= 0.5 && rate <= 3) { + audio.playbackRate = rate; + } + }, + subscribe: (listener) => { + if (!events.signal.aborted) { + listeners.add(listener); + listener(getSnapshot()); + } + + return () => { + listeners.delete(listener); + }; + }, + }; + + return controller; +}); diff --git a/apps/web/src/institute/player/player.css b/apps/web/src/institute/player/player.css new file mode 100644 index 00000000..17264eec --- /dev/null +++ b/apps/web/src/institute/player/player.css @@ -0,0 +1,220 @@ +.institute-player { + color: #ebe9ef; + background: #080809; + font: + 1rem/1.55 ui-monospace, + monospace; + border-block: 1px solid #303034; +} + +.institute-player-layout { + display: grid; + grid-template-columns: minmax(15rem, 2fr) minmax(0, 3fr); + min-block-size: clamp(22rem, 74vh, 56rem); +} + +.institute-transcript { + font-size: clamp(0.95rem, 1.3vw, 1.25rem); + align-content: center; + border-inline-end: 1px solid #303034; + padding: clamp(1rem, 2.4vw, 2.5rem); +} + +.institute-transcript-card { + border-block: 1px solid #303034; + padding-block: 1.35rem; +} +.institute-transcript-card p { + margin: 0; +} +.institute-transcript-card p + p { + margin-block-start: 1.1em; +} +.institute-transcript [data-phase="upcoming"] { + opacity: 0.54; +} +.institute-transcript [data-phase="past"] { + opacity: 0.68; +} +.institute-player[data-state="playing"] [data-phase="upcoming"] { + opacity: 0.51; +} +.institute-player[data-state="playing"] [data-phase="past"] { + opacity: 0.6; +} +.institute-transcript [data-phase="active"] { + color: #fff; +} +.institute-player[data-state="playing"] [data-phase="active"] { + text-shadow: 0 0 0.5em #f5efd0; +} +.institute-bold { + font-weight: 700; +} +.institute-italic { + font-style: italic; +} +.institute-inline-code { + font-family: ui-monospace, monospace; +} + +.institute-code-panel { + align-content: center; + min-inline-size: 0; + padding: clamp(1rem, 2.4vw, 2.5rem); +} + +.institute-player pre { + margin: 0; + overflow: auto; + font: + clamp(0.78rem, 1.2vw, 1.25rem)/1.65 ui-monospace, + monospace; +} + +.institute-player pre code { + display: block; + position: relative; + block-size: calc(var(--line-count) * 1.65em + 1.6em); + font: inherit; + transition: block-size 260ms cubic-bezier(0.2, 0.7, 0.25, 1); +} + +.institute-code-line { + position: absolute; + inset-inline-start: 0; + inset-block-start: 0; + inline-size: max-content; + min-block-size: 1.65em; + white-space: pre; + font-variant-ligatures: none; + isolation: isolate; + transform: translateY(calc(var(--line-index) * 1.65em)); + transition: + opacity 220ms ease-out, + transform 260ms cubic-bezier(0.2, 0.7, 0.25, 1); +} + +.institute-code-line[data-dimmed="true"] { + opacity: 0.4; +} + +.institute-code-line [data-bright] { + transition: text-shadow 240ms ease-out; +} + +.institute-code-line [data-bright="true"] { + text-shadow: + 0 0 6px currentColor, + 0 0 16px color-mix(in srgb, currentColor 50%, transparent); +} +.institute-code-line[data-entering="true"] { + animation: institute-line-in 260ms ease-out both; +} + +.institute-code-cursor, +.institute-code-mark { + position: absolute; + pointer-events: none; + box-sizing: border-box; +} + +.institute-code-cursor { + inset-inline-start: 0; + inset-block-start: 0; + inline-size: clamp(1rem, 1.5vw, 1.5rem); + block-size: clamp(1rem, 1.5vw, 1.5rem); + opacity: 0; + color: #fff; + transform: translate( + calc(var(--cursor-col, 0) * 1ch - 50%), + calc(var(--cursor-row, 0) * 1.65em - 0.16em) + ); + transition: + transform 300ms cubic-bezier(0.18, 0.72, 0.25, 1.12), + opacity 200ms ease-out; +} +.institute-code-cursor[data-target="true"] { + opacity: 1; +} +.institute-code-cursor svg { + display: block; + inline-size: 100%; + block-size: 100%; +} +.institute-code-mark { + inset-block: 0; + margin-inline: -0.28em; + padding-inline-end: 0.56em; + box-sizing: content-box; + z-index: -1; + border: 1px solid rgb(234 179 8 / 0.64); + background: rgb(234 179 8 / 0.24); + animation: institute-mark-in 250ms ease-out both; +} +.institute-controls:not(:empty), +.institute-code-controls { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; + padding: 0.5rem clamp(1rem, 2.4vw, 2.5rem); +} +.institute-controls:not(:empty) { + border-block-end: 1px solid #303034; +} +.institute-code-controls { + padding-inline: 0; +} + +.institute-player button { + min-block-size: 2.75rem; + color: inherit; + background: #27272a; + border: 1px solid #626268; + border-radius: 0.25rem; + padding-inline: 0.75rem; +} +.institute-player button:disabled { + opacity: 0.5; +} + +@keyframes institute-line-in { + from { + opacity: 0; + filter: blur(4px); + } +} + +@media (max-width: 48rem) { + .institute-player-layout { + grid-template-columns: minmax(0, 1fr); + min-block-size: 0; + } + .institute-transcript { + border-inline-end: 0; + } + .institute-code-panel { + padding-block-start: 0; + } +} + +@keyframes institute-mark-in { + from { + opacity: 0; + filter: blur(5px); + transform: scale(0.3); + } +} + +@media (prefers-reduced-motion: reduce) { + .institute-player pre code, + .institute-code-line, + .institute-code-line [data-bright], + .institute-code-cursor { + transition: none; + } + .institute-code-line[data-entering="true"], + .institute-code-mark { + animation: none; + } +} diff --git a/apps/web/src/institute/player/section.ts b/apps/web/src/institute/player/section.ts new file mode 100644 index 00000000..811f5be6 --- /dev/null +++ b/apps/web/src/institute/player/section.ts @@ -0,0 +1,91 @@ +import { Schema } from "effect"; + +const Token = Schema.Struct({ + color: Schema.optionalKey(Schema.String), + text: Schema.String, +}); + +const CharRange = Schema.Struct({ end: Schema.Finite, start: Schema.Finite }); + +const Line = Schema.Struct({ + brightBoundaries: Schema.optionalKey(Schema.Array(CharRange)), + partOrder: Schema.Array(Schema.String), + parts: Schema.Record( + Schema.String, + Schema.Struct({ + tokens: Schema.Array(Token), + versions: Schema.optionalKey( + Schema.Record(Schema.String, Schema.Array(Token)) + ), + }) + ), +}); + +const Range = Schema.Struct({ + end: Schema.Finite, + lineIndex: Schema.Int, + start: Schema.Finite, +}); + +const Frame = Schema.Struct({ + brightRanges: Schema.optionalKey(Schema.Array(Range)), + cursor: Schema.optionalKey( + Schema.Struct({ + charOffset: Schema.Finite, + lineIndex: Schema.Int, + textLength: Schema.Finite, + }) + ), + id: Schema.Int, + lineOrder: Schema.Array(Schema.String), + marks: Schema.optionalKey(Schema.Array(Range)), + state: Schema.Record( + Schema.String, + Schema.Struct({ + dimmed: Schema.optionalKey(Schema.Boolean), + entering: Schema.optionalKey(Schema.Boolean), + parts: Schema.Record( + Schema.String, + Schema.Union([Schema.Boolean, Schema.String]) + ), + }) + ), +}); + +const Word = Schema.Struct({ + end: Schema.Finite, + paragraphBreak: Schema.optionalKey(Schema.Boolean), + start: Schema.Finite, + suffix: Schema.optionalKey(Schema.String), + style: Schema.optionalKey( + Schema.Struct({ + bold: Schema.optionalKey(Schema.Boolean), + code: Schema.optionalKey(Schema.Boolean), + italic: Schema.optionalKey(Schema.Boolean), + }) + ), + word: Schema.String, +}); + +export const PlayerSectionSchema = Schema.Struct({ + id: Schema.String, + slideshowData: Schema.optionalKey( + Schema.Struct({ + frames: Schema.Array(Frame), + template: Schema.Struct({ lines: Schema.Record(Schema.String, Line) }), + }) + ), + stepTimes: Schema.optionalKey(Schema.Array(Schema.Finite)), + text: Schema.String, + wordTimings: Schema.optionalKey(Schema.Array(Word)), +}); + +export type PlayerSection = typeof PlayerSectionSchema.Type; + +export type CodeFrame = typeof Frame.Type; + +export type CodeLine = typeof Line.Type; + +export type CodeToken = typeof Token.Type; + +export type WordTiming = typeof Word.Type; diff --git a/apps/web/src/institute/player/spike.html b/apps/web/src/institute/player/spike.html new file mode 100644 index 00000000..02c9c671 --- /dev/null +++ b/apps/web/src/institute/player/spike.html @@ -0,0 +1,20 @@ + + + + + + Institute player spike + + +
    +

    Define the boundary

    +
    Loading sample…
    +
    + + + diff --git a/apps/web/src/institute/player/spike.ts b/apps/web/src/institute/player/spike.ts new file mode 100644 index 00000000..2fb76589 --- /dev/null +++ b/apps/web/src/institute/player/spike.ts @@ -0,0 +1,113 @@ +import { Effect, Schema } from "effect"; + +import type { PlayerController } from "./controller.js"; +import { mountInstitutePlayer } from "./entry.js"; +import { PlayerSectionSchema } from "./section.js"; + +const chapter = "/one-contract"; + +const Manifest = Schema.Struct({ + sections: Schema.Array( + Schema.Struct({ + file: Schema.String.check( + Schema.isPattern( + /^define-boundary\.[a-f0-9]+\.json$|^[a-z0-9-]+\.[a-f0-9]+\.json$/u + ) + ), + id: Schema.String, + }) + ), +}); + +const DraftSection = Schema.Struct({ + ...PlayerSectionSchema.fields, + audioFile: Schema.String.check( + Schema.isPattern(/^define-boundary\.[a-f0-9]+\.webm$/u) + ), +}); + +const readFixture = Effect.fnUntraced(function* readFixture( + view: Window, + name: string +) { + const response = yield* Effect.tryPromise((signal) => + view.fetch(`${chapter}/${name}`, { signal }) + ); + + if (!response.ok) { + return yield* Effect.fail("draft section HTTP failure"); + } + + return yield* Effect.tryPromise(() => response.text()); +}); + +const mountSpikeControls = (host: HTMLElement, player: PlayerController) => { + const button = host.ownerDocument.createElement("button"); + button.type = "button"; + button.addEventListener("click", () => { + if (player.getSnapshot().state === "playing") { + player.pause(); + } else { + player.play(); + } + }); + host.append(button); + + return player.subscribe(({ state }) => { + button.textContent = state === "playing" ? "Pause" : "Play"; + button.disabled = state === "loading" || state === "failed"; + }); +}; + +const start = Effect.fnUntraced(function* start(host: HTMLElement) { + const view = host.ownerDocument.defaultView; + + if (view === null) { + return yield* Effect.void; + } + + const manifestJson = yield* readFixture(view, "manifest.json"); + + const manifest = yield* Schema.decodeEffect(Schema.fromJsonString(Manifest))( + manifestJson + ); + + const source = manifest.sections.find(({ id }) => id === "define-boundary"); + + if (source === undefined) { + return yield* Effect.fail("draft manifest omitted define-boundary"); + } + + const sectionJson = yield* readFixture(view, source.file); + + const section = yield* Schema.decodeEffect( + Schema.fromJsonString(DraftSection) + )(sectionJson); + + mountInstitutePlayer(host, { + audioUrl: `${chapter}/${section.audioFile}`, + chapterId: "one-contract", + mountControls: mountSpikeControls, + section, + sectionId: section.id, + }); + + return yield* Effect.void; +}); + +export const mountSpike = (host: HTMLElement) => { + if (import.meta.env.DEV) { + Effect.runFork( + start(host).pipe( + Effect.matchEffect({ + onSuccess: () => Effect.void, + onFailure: () => + Effect.sync(() => { + host.textContent = + "Sample unavailable. Start the spike with the compiled draft assets."; + }), + }) + ) + ); + } +}; diff --git a/apps/web/src/institute/player/timeline.ts b/apps/web/src/institute/player/timeline.ts new file mode 100644 index 00000000..1df0b6d0 --- /dev/null +++ b/apps/web/src/institute/player/timeline.ts @@ -0,0 +1,49 @@ +import type { WordTiming } from "./section.js"; + +export const wordLeadSeconds = 0.18; + +export const wordParagraphs = (words: readonly WordTiming[]) => { + const paragraphs: { readonly word: WordTiming; readonly index: number }[][] = + []; + + let paragraph: (typeof paragraphs)[number] = []; + + for (const [index, word] of words.entries()) { + if (paragraph.length === 0 || word.paragraphBreak === true) { + paragraph = []; + paragraphs.push(paragraph); + } + + paragraph.push({ index, word }); + } + + return paragraphs; +}; + +export const chooseStep = (stepTimes: readonly number[], seconds: number) => { + for (let index = stepTimes.length - 1; index >= 0; index -= 1) { + const time = stepTimes[index]; + + if (time !== undefined && seconds >= time) { + return index; + } + } + + return 0; +}; + +export const wordPhase = ( + word: WordTiming, + seconds: number, + first: boolean +) => { + if ( + seconds >= word.start - wordLeadSeconds && + seconds <= word.end && + !(first && seconds < 0.1) + ) { + return "active"; + } + + return seconds > word.end ? "past" : "upcoming"; +}; diff --git a/apps/web/src/institute/player/view.ts b/apps/web/src/institute/player/view.ts new file mode 100644 index 00000000..51c64e8a --- /dev/null +++ b/apps/web/src/institute/player/view.ts @@ -0,0 +1,192 @@ +import { Html } from "@effect/ui/html"; +import { Predicate, Schema } from "effect"; + +import { codeRuns } from "./code-frame.js"; +import { PlayerSectionSchema } from "./section.js"; +import { chooseStep, wordParagraphs, wordPhase } from "./timeline.js"; + +const Props = Schema.Struct({ + narrated: Schema.Boolean, + section: PlayerSectionSchema, +}); + +const Model = Schema.Struct({ seconds: Schema.Finite, step: Schema.Finite }); + +export const Tick = Schema.TaggedStruct("Tick", { seconds: Schema.Finite }); + +const Step = Schema.TaggedStruct("Step", { step: Schema.Finite }); + +const Message = Schema.Union([Tick, Step]); + +const handOutline = + "M8 13V4a1.65 1.65 0 0 1 3.3 0v6.5h.4a1.55 1.55 0 0 1 2.9 0h.4a1.55 1.55 0 0 1 2.9.5h.4a1.6 1.6 0 0 1 2.2 1.5V16c0 4-2.55 6-6 6h-1c-2.3 0-3.9-1-5.1-2.6l-3.6-4.6a1.6 1.6 0 0 1 2.2-2.3L8 13Z"; + +const wordClass = ( + style: + | { + readonly bold?: boolean; + readonly code?: boolean; + readonly italic?: boolean; + } + | undefined +) => + [ + style?.bold === true ? "institute-bold" : "", + style?.code === true ? "institute-inline-code" : "", + style?.italic === true ? "institute-italic" : "", + ].join(" "); + +export const PlayerView = Html.component({ + message: Message, + model: Model, + name: "InstitutePlayerView", + props: Props, +}).make({ + init: () => ({ seconds: 0, step: 0 }), + update: ({ model, props }, msg) => + Predicate.isTagged(msg, "Tick") + ? { + seconds: msg.seconds, + step: chooseStep(props.section.stepTimes ?? [], msg.seconds), + } + : { ...model, step: msg.step }, + view: (h, model) => { + const { narrated, section } = h.props; + const data = section.slideshowData; + const frame = data?.frames[model.step]; + const lines = data?.template.lines; + const words = section.wordTimings; + const next = data?.frames[model.step + 1]; + const actualStep = frame === undefined ? 0 : model.step; + const cursor = frame?.cursor; + + return h.div.class("institute-player-layout").children( + h.div + .class("institute-transcript") + .attr("aria-label", "Transcript") + .children( + h.div.class("institute-transcript-card").children( + words !== undefined && words.length > 0 + ? wordParagraphs(words).map((paragraph) => + h.p.children( + paragraph.map(({ word, index }, offset) => + h.span + .class(wordClass(word.style)) + .attrs({ + "data-phase": narrated + ? wordPhase(word, model.seconds, offset === 0) + : "static", + "data-word": String(index), + }) + .children(`${word.word}${word.suffix ?? " "}`) + ) + ) + ) + : section.text + .split(/\n\n+/u) + .map((paragraph) => h.p.children(paragraph)) + ) + ), + frame !== undefined && lines !== undefined + ? h.div.class("institute-code-panel").children( + h.pre + .attr("data-step", String(actualStep)) + .attr("aria-label", "Code walkthrough") + .children( + h.code + .attr("style", `--line-count:${frame.lineOrder.length}`) + .children( + frame.lineOrder.map((id, index) => { + const line = lines[id]; + + const marks = + frame.marks?.filter( + (mark) => mark.lineIndex === index + ) ?? []; + + const bright = + frame.brightRanges?.filter( + (range) => range.lineIndex === index + ) ?? []; + + const runs = + line === undefined + ? [] + : codeRuns(line, frame, id, bright); + + return h.span + .key(id) + .class("institute-code-line") + .attrs({ + "data-dimmed": String( + frame.state[id]?.dimmed === true + ), + "data-entering": String( + frame.state[id]?.entering === true + ), + "data-line": id, + style: `--line-index:${index}`, + }) + .children( + ...runs.map((token) => + h.span + .key(String(token.start)) + .attrs({ + "data-bright": String(token.bright), + style: `color:${token.color ?? "inherit"}`, + }) + .children(token.text) + ), + ...marks.map((mark) => + h.span + .class("institute-code-mark") + .attrs({ + "aria-hidden": "true", + style: `left:${mark.start}ch;width:${mark.end - mark.start}ch`, + }) + .children() + ) + ); + }), + h.span + .key("cursor") + .class("institute-code-cursor") + .attrs({ + "aria-hidden": "true", + "data-target": String(cursor !== undefined), + style: + cursor === undefined + ? undefined + : `--cursor-col:${cursor.charOffset + cursor.textLength / 2};--cursor-row:${cursor.lineIndex + 1}`, + }) + .children( + h + .el("svg") + .attrs({ + viewBox: "0 0 24 24", + fill: "currentColor", + focusable: "false", + }) + .children(h.el("path").attr("d", handOutline)) + ) + ) + ), + narrated + ? null + : h.div.class("institute-code-controls").children( + h.button + .attr("type", "button") + .attr("disabled", actualStep === 0 ? "" : undefined) + .on("click", Step.make({ step: actualStep - 1 })) + .children("Previous code step"), + h.button + .attr("type", "button") + .attr("disabled", next === undefined ? "" : undefined) + .on("click", Step.make({ step: actualStep + 1 })) + .children("Next code step") + ) + ) + : null + ); + }, +}); diff --git a/apps/web/src/institute/routes/PARITY.md b/apps/web/src/institute/routes/PARITY.md new file mode 100644 index 00000000..ed58f3fd --- /dev/null +++ b/apps/web/src/institute/routes/PARITY.md @@ -0,0 +1,48 @@ +# Institute route parity + +Inventory: the pinned fork's `src/routes`, `src/worker.ts`, `src/lib/hotkeys/registry.ts`, `src/hooks/useChapterControls.ts`, `src/authoring/client/logic.ts`, and chapter/home link components. Fork routes below are relative to `/institute`. + +## Routes and queries + +| Fork surface | Status in the port | +| --- | --- | +| `/` (bare prefix and trailing slash) | Done. Effect UI course home, published Ratstack chapters only. The two Kit chapters are outbound prerequisites, not local lesson routes. | +| `/chapters/:chapter` | Done. SSR chapter overview, section list and transcript; native section/previous/next/home links; chapter-level canonical and share card. The chapter-only player and controls mount after hydration; the transcript and links work without JavaScript. | +| `/chapters/:chapter?section=:id` | Done. Selects by manifest ID; missing/unknown IDs fall back to the first section. Copy the native section link to share it. | +| `?fresh=1` | Dropped as a query: a request without `section` already selects the first section. The controls save and restore section position and playback preferences. | +| `/chapters/` redirect and `/content` → `intro` | Dropped. Home is the chapter index; Kit’s intro is on Effect Institute. | +| `/sitemap` | Replaced by the gated `/sitemap.xml` fragment at `/institute/sitemap.xml`. When public it also appears in the site sitemap index and `robots.txt`. | +| `/content/*` static manifests, hashed section JSON, WebM and timing JSON | Done for published Ratstack hashed JSON/WebM/M4A via Website assets. The loader reads manifests server-side; raw manifests and separate timing JSON are not public routes. No Kit payloads are staged or served. | +| `/og/home` and `/og/chapter?title=&description=&chapter=` | Dropped: these are authoring templates. Reuse the built `og/home.png` for the Ratstack home, chapter and credit cards. The upstream `og/intro.png` and `og/basics.png` stay with Kit’s chapters. | +| `/hotkeys` | Dropped as a separate shortcut editor; scoped player shortcuts are owned by `instcontrols`. | +| `/changelog` | Dropped: fork-specific log; rat-stack has its own site log. | +| `/debug/components`, `/debug/pixi-comparison`, `/debug/sounds` | Dropped: dev-only diagnostics for the old player. | +| `__authoring`, development HMR and authoring HTTP params `chapter`, `section`, `take` | Dropped from the Website: recording/editing stays in the private fork. | +| Fork favicon, touch icons, webmanifest, font, `robots.txt`, and `/sounds/scroll-jacked.webm` | Dropped as mounted assets: use site chrome/icons and site robots; no scroll-jacking cue. | +| `/credits` | New. Original Effect Institute and Kit attribution, MIT notice, and narration library credit. | + +## Links and controls + +| Fork link or action | Status in the port | +| --- | --- | +| Institute brand, back/home, chapter cards, section outline and next chapter | Home, chapter and section links work without JS. Narration completion follows the in-chapter next link. The final section links to the next chapter without navigating automatically. | +| Resume from last chapter/section, go to next on completion, replay, progress | The player and controls implement playback, replay, and saved per-section progress. Reloading a section restores its position without autoplay. | +| “By Kit Langton” on intro/basics, original Institute footer, and ratstack.sh footer/logo | Done as credited upstream chapter links, exact section prerequisites where applicable, and persistent footer/site links. No local Kit chapter views. | +| GitHub repository source and Ratstack sample’s historical source pin | Repository links done. Per-chapter source pins belong with lesson source provenance; the historical tree link is not the default for the new course. | +| Copy code, feedback/new GitHub issue form, hotkeys settings, and changelog footer/inline links | Copy code left for the player; old feedback, settings and changelog UI dropped with the fork chrome. No Discord link. | +| Alt-click copy section permalink; Shift-click copy local source path | Native shareable `?section=` anchor replaces special clipboard gesture. Local source-path clipboard dropped as author-only. | + +## Hotkeys + +| Context and fork bindings | Status in the port | +| --- | --- | +| Chapter Space (play/pause or continue), `r` (restart), ←/`h`, →/`l` (seek, with Shift for larger jumps), `<`/`>` (rate) | Mounted on the focused player through the controls integration. Space toggles playback. | +| Chapter ↓/`j`, ↑/`k`, Home/`gg`, End/Shift+`G`, `gh` | Focused player controls call the route-owned section and home anchors. Mouse, touch, Tab and Enter work on the native links. | +| Alt+←/→ (animation step) | Left for `instcore`/`instcontrols`; animation-step support needs a player controller, not route keyboard interception. | +| Chapter Ctrl+D; authoring Ctrl+R, Enter, Escape | Dropped: inspect or record only in the private dev fork. | +| Home ↓/`j`, ↑/`k`, Enter, Escape | Native Tab/Shift+Tab and Enter replace keyboard interception and the transient selected-card model. | +| Changelog `gh` | Dropped with the changelog route. | +| Debug Pixi ←/`a`, →/`d`; OG generator ←/`a`, →/`d` | Dropped with their debug/authoring routes. | +| Modal Escape | Left for player dialogs if needed. No route modal. | + +The Website gate owns HTTP exposure. `InstituteContent.layer` reads the approved six-chapter manifest and validates chapter and section assets served by ASSETS. After adoption the chapter entry loads the player, controls, and the selected hashed section. The mount owns the inside of `#institute-player` and chooses WebM/Opus if the browser supports it, otherwise AAC. The course home does not load player code. The gateway prefers the legacy binding where one already exists. diff --git a/apps/web/src/institute/routes/artifact.ts b/apps/web/src/institute/routes/artifact.ts new file mode 100644 index 00000000..a700c4c8 --- /dev/null +++ b/apps/web/src/institute/routes/artifact.ts @@ -0,0 +1,26 @@ +import { Effect } from "effect"; + +import { InstituteAssetError, InstituteContent } from "../content/index.js"; + +export type AssetFetch = (request: Request) => Promise; + +export const instituteContentLayer = (fetchAsset: AssetFetch, origin: string) => + InstituteContent.layer((path) => { + const failed = (cause: unknown) => new InstituteAssetError({ cause, path }); + + return Effect.gen(function* readWebsiteAsset() { + const response = yield* Effect.tryPromise({ + catch: failed, + try: () => fetchAsset(new Request(new URL(path, origin))), + }); + + if (!response.ok) { + return yield* failed(response.status); + } + + return yield* Effect.tryPromise({ + catch: failed, + try: () => response.text(), + }); + }); + }); diff --git a/apps/web/src/institute/routes/audio-choice.ts b/apps/web/src/institute/routes/audio-choice.ts new file mode 100644 index 00000000..e555bdad --- /dev/null +++ b/apps/web/src/institute/routes/audio-choice.ts @@ -0,0 +1,8 @@ +export const preferredAudio = ( + audio: Pick, + webm: string | undefined, + aac?: string +): string | undefined => + webm !== undefined && audio.canPlayType('audio/webm; codecs="opus"') !== "" + ? webm + : aac; diff --git a/apps/web/src/institute/routes/component.ts b/apps/web/src/institute/routes/component.ts new file mode 100644 index 00000000..f66117fb --- /dev/null +++ b/apps/web/src/institute/routes/component.ts @@ -0,0 +1,190 @@ +import { Html } from "@effect/ui/html"; +import { Schema } from "effect"; + +import { mitNotice, narrationCredit } from "./credits.js"; +import { + InstitutePageProps, + instituteDescription, + institutePlayerId, + instituteTitle, +} from "./model.js"; +import { + chapterPath, + instituteOriginal, + instituteCreditsPath, + institutePath, + sectionPath, +} from "./paths.js"; +import { effectChapters, effectPrerequisites } from "./prerequisites.js"; + +export const InstitutePage = Html.component({ + message: Schema.Never, + model: Schema.Null, + name: "InstitutePage", + props: InstitutePageProps, +}).make({ + init: () => null, + update: ($) => $.model, + view: (h) => { + const { props } = h; + + const link = (href: string, label: string) => + h.a.attr("href", href).children(label); + + const kitLinks = ( + title: string, + links: readonly { readonly href: string; readonly title: string }[] + ) => + h.section( + h.h2(title), + h.p(link(instituteOriginal, "By Kit Langton")), + h.ul(...links.map((item) => h.li(link(item.href, item.title)))) + ); + + const footer = h.footer( + h.p( + "Based on the ", + link(instituteOriginal, "Effect Institute"), + ". ", + link(instituteCreditsPath, "Credits") + ) + ); + + const header = h.nav + .attr("aria-label", "Ratstack Institute") + .children( + link("/", "ratstack.sh"), + " / ", + h.a + .attrs({ href: institutePath, "data-institute-home": "" }) + .children(instituteTitle), + " / ", + link("https://github.com/joelhooks/rat-stack", "Source") + ); + + if (props.kind === "credits") { + return h.main + .attr("class", "institute-page") + .children( + header, + h.h1("Credits"), + h.p( + "Based on the ", + link(instituteOriginal, "Effect Institute"), + " by Kit Langton." + ), + h.p(narrationCredit), + h.h2("MIT license"), + h.pre.attr("class", "institute-license").children(mitNotice), + footer + ); + } + + if (props.kind === "home") { + return h.main + .attr("class", "institute-page") + .children( + header, + h.h1(instituteTitle), + h.p(instituteDescription), + h.section( + h.h2("Chapters"), + props.chapters.length === 0 + ? h.p("No rat-stack chapters are published yet.") + : h.ol( + ...props.chapters.map((chapter) => + h.li( + link(chapterPath(chapter.id), chapter.title), + h.p(chapter.description) + ) + ) + ) + ), + kitLinks("Start with Effect", effectChapters), + footer + ); + } + + const prerequisites = effectPrerequisites(props.section.id); + + return h.main.attr("class", "institute-page").children( + header, + h.h1(props.chapter.title), + h.p(props.chapter.description), + h.p( + link( + "https://github.com/joelhooks/rat-stack", + "By rat-stack contributors" + ) + ), + h.div.attr("class", "institute-chapter").children( + h.article.attr("aria-label", "Lesson").children( + h.div + .attrs({ + "data-chapter": props.chapter.id, + "data-section": props.section.id, + "data-section-url": props.sectionUrl, + id: institutePlayerId, + "data-audio-url": props.audioUrl, + }) + .children(h.h2(props.section.title), h.p(props.text)), + ...(props.next === undefined + ? [] + : [ + h.p( + h.a + .attrs({ + href: sectionPath(props.chapter.id, props.next.id), + "data-institute-next": "", + }) + .children(`Next: ${props.next.title}`) + ), + ]), + ...(props.nextChapter === undefined + ? [] + : [ + h.p( + link( + chapterPath(props.nextChapter.id), + `Next chapter: ${props.nextChapter.title}` + ) + ), + ]), + ...(prerequisites.length === 0 + ? [] + : [kitLinks("Prerequisites", prerequisites)]) + ), + h.nav.attr("aria-label", "Chapter sections").children( + h.h2("Sections"), + h.ol( + ...props.sections.map((section) => + h.li( + h.a + .attrs({ + href: sectionPath(props.chapter.id, section.id), + "data-institute-section-link": "", + "aria-current": + section.id === props.section.id ? "page" : undefined, + }) + .children(section.title) + ) + ) + ), + ...(props.previous === undefined + ? [] + : [ + h.p( + h.a + .attrs({ + href: sectionPath(props.chapter.id, props.previous.id), + "data-institute-previous": "", + }) + .children(`Previous: ${props.previous.title}`) + ), + ]) + ) + ), + footer + ); + }, +}); diff --git a/apps/web/src/institute/routes/credits.ts b/apps/web/src/institute/routes/credits.ts new file mode 100644 index 00000000..eab506cd --- /dev/null +++ b/apps/web/src/institute/routes/credits.ts @@ -0,0 +1,24 @@ +export const narrationCredit = + "Narration voice: Tom - Conversations & Books, from the ElevenLabs Voice Library"; + +export const mitNotice = `MIT License + +Copyright (c) 2026 Kit Langton + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.`; diff --git a/apps/web/src/institute/routes/fetch-plugin.ts b/apps/web/src/institute/routes/fetch-plugin.ts new file mode 100644 index 00000000..264bc2df --- /dev/null +++ b/apps/web/src/institute/routes/fetch-plugin.ts @@ -0,0 +1,29 @@ +import type { Plugin } from "vite"; + +const foldkitFetchModule = "\0virtual:foldkit/fetch"; + +const generatedFetch = `return handleRequest(request, { + renderPage: server.renderPage, + renderDocument: application => renderDocument(application, assets), + })`; + +export const instituteFetchPlugin = (): Plugin => ({ + enforce: "post", + name: "institute-fetch-boundary", + transform(source, id) { + if (id !== foldkitFetchModule) { + return null; + } + + if (!source.includes(generatedFetch)) { + return this.error( + "Unknown Foldkit fetch entry. Institute media and XML require dispatch before Foldkit's asset classifier. Fix: update `instituteFetchPlugin` for the pinned Foldkit fetch template." + ); + } + + return source.replace( + generatedFetch, + "return server.renderWebsiteRequest(request, assets)" + ); + }, +}); diff --git a/apps/web/src/institute/routes/hydration.ts b/apps/web/src/institute/routes/hydration.ts new file mode 100644 index 00000000..822b8efd --- /dev/null +++ b/apps/web/src/institute/routes/hydration.ts @@ -0,0 +1,69 @@ +import { HtmlHydrate } from "@effect/ui/html"; +import { Effect, Schema } from "effect"; + +import { InstitutePage } from "./component.js"; +import { + InstituteHandoff, + instituteHandoffId, + institutePlayerId, + instituteRootId, +} from "./model.js"; + +const decodeHandoff = Schema.decodeEffect( + Schema.fromJsonString(InstituteHandoff) +); + +export interface PlayerSlot { + readonly audioUrl: string | undefined; + readonly audioFallbackUrl: string | undefined; + readonly chapterId: string; + readonly sectionId: string; + readonly sectionUrl: string; +} + +type MountChapterPlayer = ( + host: HTMLElement, + slot: PlayerSlot +) => Effect.Effect<() => void, E>; + +export const hydrateInstitute = Effect.fn("institute.hydrate")( + function* hydrateInstitute(page: Document, mount: MountChapterPlayer) { + const container = page.querySelector(`#${instituteRootId}`); + const payload = page.querySelector(`#${instituteHandoffId}`); + + if (container === null || payload === null) { + return null; + } + + const { props, state } = yield* decodeHandoff(payload.textContent ?? ""); + + const root = yield* HtmlHydrate.hydrateEffect( + InstitutePage, + props, + container, + state + ); + + yield* root.adopted; + container.dataset.hydrated = "true"; + + if (props.kind === "chapter") { + const host = page.querySelector(`#${institutePlayerId}`); + + if (host !== null) { + yield* Effect.acquireRelease( + mount(host, { + audioUrl: props.audioUrl, + audioFallbackUrl: props.audioFallbackUrl, + chapterId: props.chapter.id, + sectionId: props.section.id, + sectionUrl: props.sectionUrl, + }), + (dispose) => Effect.sync(dispose) + ); + } + } + + return yield* Effect.never; + } +); diff --git a/apps/web/src/institute/routes/institute.css b/apps/web/src/institute/routes/institute.css new file mode 100644 index 00000000..ec0d7acf --- /dev/null +++ b/apps/web/src/institute/routes/institute.css @@ -0,0 +1,31 @@ +.institute-page { + overflow-wrap: anywhere; +} + +.institute-license { + white-space: pre-wrap; +} + +.institute-page nav a { + display: inline-block; + padding-block: 0.35rem; +} + +.institute-page nav a[aria-current="page"] { + font-weight: 700; +} + +.institute-chapter { + display: grid; + gap: 2rem; +} + +.institute-chapter > * { + min-width: 0; +} + +@media (min-width: 54rem) { + .institute-chapter { + grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); + } +} diff --git a/apps/web/src/institute/routes/media.ts b/apps/web/src/institute/routes/media.ts new file mode 100644 index 00000000..6dbdf0f4 --- /dev/null +++ b/apps/web/src/institute/routes/media.ts @@ -0,0 +1,119 @@ +import { Effect } from "effect"; + +import type { AssetFetch } from "./artifact.js"; + +const byteRange = (header: string, size: number) => { + const range = /^bytes=(?\d*)-(?\d*)$/iu.exec( + header.trim() + )?.groups; + + if (range === undefined || (range.start === "" && range.end === "")) { + return null; + } + + const start = + range.start === "" + ? Math.max(0, size - Number(range.end)) + : Number(range.start); + + const end = + range.start === "" || range.end === "" + ? size - 1 + : Math.min(size - 1, Number(range.end)); + + return { end, start }; +}; + +const rangeResponse = Effect.fn("institute.rangeResponse")( + function* rangeResponse(response: Response, headers: Headers, range: string) { + const bytes = yield* Effect.tryPromise(() => response.bytes()); + const interval = byteRange(range, bytes.byteLength); + + if (interval === null) { + return new Response(bytes, { headers, status: 200 }); + } + + const { end, start } = interval; + + if (start > end) { + headers.delete("Content-Length"); + headers.set("Cache-Control", "no-store"); + headers.set("Content-Range", `bytes */${bytes.byteLength}`); + + return new Response(null, { headers, status: 416 }); + } + + const slice = bytes.subarray(start, end + 1); + headers.set("Content-Length", String(slice.byteLength)); + headers.set("Content-Range", `bytes ${start}-${end}/${bytes.byteLength}`); + + return new Response(slice, { headers, status: 206 }); + } +); + +const audioType = (pathname: string) => { + if (pathname.endsWith(".webm")) { + return "audio/webm"; + } + + return pathname.endsWith(".m4a") ? "audio/mp4" : null; +}; + +const matchesIfRange = (request: Request, response: Response) => { + const validator = request.headers.get("If-Range"); + + return ( + validator === null || + (!validator.startsWith("W/") && + (validator === response.headers.get("ETag") || + validator === response.headers.get("Last-Modified"))) + ); +}; + +export const serveHashedAsset = Effect.fn("institute.hashedAsset")( + function* serveHashedAsset( + request: Request, + fetchAsset: AssetFetch, + discoverable: boolean + ) { + const response = yield* Effect.tryPromise(() => fetchAsset(request)); + + if ( + response.status !== 200 && + response.status !== 206 && + response.status !== 304 + ) { + return response; + } + + const headers = new Headers(response.headers); + headers.set( + "Cache-Control", + discoverable ? "public, max-age=31536000, immutable" : "no-store" + ); + const mediaType = audioType(new URL(request.url).pathname); + + if (mediaType !== null) { + headers.set("Accept-Ranges", "bytes"); + headers.set("Content-Type", mediaType); + } + + const range = request.headers.get("Range"); + + if ( + mediaType !== null && + response.status === 200 && + request.method === "GET" && + range !== null && + matchesIfRange(request, response) + ) { + return yield* rangeResponse(response, headers, range); + } + + return new Response(response.body, { + headers, + status: response.status, + statusText: response.statusText, + }); + } +); diff --git a/apps/web/src/institute/routes/model.ts b/apps/web/src/institute/routes/model.ts new file mode 100644 index 00000000..a4ed594a --- /dev/null +++ b/apps/web/src/institute/routes/model.ts @@ -0,0 +1,47 @@ +import { Schema } from "effect"; + +import { effectUiHandoff } from "../../client/effect-ui-handoff.js"; + +const ChapterLink = Schema.Struct({ + id: Schema.String, + title: Schema.String, + description: Schema.String, +}); + +const SectionLink = Schema.Struct({ id: Schema.String, title: Schema.String }); + +export const InstitutePageProps = Schema.Union([ + Schema.Struct({ kind: Schema.Literal("credits") }), + Schema.Struct({ + kind: Schema.Literal("home"), + chapters: Schema.Array(ChapterLink), + }), + Schema.Struct({ + kind: Schema.Literal("chapter"), + chapter: ChapterLink, + section: SectionLink, + sectionUrl: Schema.String, + sections: Schema.Array(SectionLink), + text: Schema.String, + audioUrl: Schema.optional(Schema.String), + audioFallbackUrl: Schema.optional(Schema.String), + nextChapter: Schema.optional(ChapterLink), + next: Schema.optional(SectionLink), + previous: Schema.optional(SectionLink), + }), +]); + +export type InstituteProps = typeof InstitutePageProps.Type; + +export const InstituteHandoff = effectUiHandoff(InstitutePageProps); + +export const instituteRootId = "institute-effect-ui"; + +export const instituteHandoffId = "institute-effect-ui-handoff"; + +export const institutePlayerId = "institute-player"; + +export const instituteTitle = "Ratstack Institute"; + +export const instituteDescription = + "Learn how rat-stack puts Effect, Alchemy, and the fence to work."; diff --git a/apps/web/src/institute/routes/paths.ts b/apps/web/src/institute/routes/paths.ts new file mode 100644 index 00000000..173b9309 --- /dev/null +++ b/apps/web/src/institute/routes/paths.ts @@ -0,0 +1,33 @@ +import { institutePath } from "../../../../site/src/institute-paths.js"; + +export { + institutePath, + instituteSitemapPath, + isInstitutePath, +} from "../../../../site/src/institute-paths.js"; + +export const instituteCreditsPath = `${institutePath}/credits`; + +export const instituteOrigin = "https://ratstack.sh"; + +export const instituteOriginal = "https://www.effect.institute"; + +export const chapterPath = (chapter: string) => + `${institutePath}/chapters/${encodeURIComponent(chapter)}`; + +export const sectionPath = (chapter: string, section: string) => + `${chapterPath(chapter)}?${new URLSearchParams({ section })}`; + +export const chapterIdFrom = (path: string) => + /^\/institute\/chapters\/(?[a-z0-9]+(?:-[a-z0-9]+)*)$/u.exec(path)?.groups + ?.id; + +export const isKitChapter = (chapter: string) => + chapter === "intro" || chapter === "basics"; + +export const ogPath = `${institutePath}/og/home.png`; + +export const contentAssetChapter = (path: string) => + /^\/institute\/content\/(?[a-z0-9-]+)\/[a-z0-9-]+\.[a-f0-9]{8}\.(?:json|webm|m4a)$/u.exec( + path + )?.groups?.id; diff --git a/apps/web/src/institute/routes/prerequisites.ts b/apps/web/src/institute/routes/prerequisites.ts new file mode 100644 index 00000000..4aa19cb7 --- /dev/null +++ b/apps/web/src/institute/routes/prerequisites.ts @@ -0,0 +1,72 @@ +import { instituteOriginal } from "./paths.js"; + +const originalChapter = (chapter: string) => + `${instituteOriginal}/chapters/${chapter}`; + +export const effectChapters = [ + { href: originalChapter("intro"), title: "Introduction to Effect" }, + { href: originalChapter("basics"), title: "Effect Basics" }, +]; + +const lesson = (chapter: string, section: string, title: string) => ({ + href: `${originalChapter(chapter)}?${new URLSearchParams({ section })}`, + title, +}); + +const showsErrors = lesson( + "intro", + "effect-shows-errors", + "Effect shows errors" +); + +const errorsCompose = lesson("intro", "errors-compose", "Errors compose"); + +const typesCaptureRuntime = lesson( + "basics", + "types-capture-runtime", + "Types capture runtime" +); + +const errorsShortCircuit = lesson( + "basics", + "errors-short-circuit", + "Errors short circuit" +); + +const effectIsADescription = lesson( + "basics", + "effect-is-a-description", + "Effect is a description" +); + +const runningEffects = lesson("basics", "running-effects", "Running Effects"); + +const effectGenSyntax = lesson( + "basics", + "effect-gen-syntax", + "Effect gen syntax" +); + +const structuredConcurrency = lesson( + "intro", + "effect-structured-concurrency", + "Effect structured concurrency" +); + +const prerequisites = new Map([ + ["bind-behavior", [typesCaptureRuntime]], + ["decode-a-match", [showsErrors, errorsCompose]], + ["define-boundary", [showsErrors, typesCaptureRuntime]], + ["follow-the-states", [structuredConcurrency]], + ["from-read-to-cli", [runningEffects]], + ["keep-the-schema", [typesCaptureRuntime]], + ["name-the-job", [effectIsADescription]], + ["people-surfaces", [showsErrors]], + ["program-surfaces", [errorsCompose]], + ["put-the-read-in-an-actor", [effectGenSyntax, structuredConcurrency]], + ["say-how-to-fix-it", [showsErrors, errorsShortCircuit]], + ["supply-an-adapter", [effectGenSyntax]], +]); + +export const effectPrerequisites = (section: string) => + prerequisites.get(section) ?? []; diff --git a/apps/web/src/institute/routes/render.ts b/apps/web/src/institute/routes/render.ts new file mode 100644 index 00000000..e870da51 --- /dev/null +++ b/apps/web/src/institute/routes/render.ts @@ -0,0 +1,89 @@ +import { HtmlServer } from "@effect/ui/html"; +import { Effect, Schema } from "effect"; + +import { readerMetadataHead } from "../../reader-metadata.js"; +import type { EffectUiAssets } from "../../server/reader-document.js"; +import { effectUiDocument } from "../../server/reader-effect-ui.js"; +import { InstitutePage } from "./component.js"; +import { + InstituteHandoff, + instituteDescription, + instituteHandoffId, + instituteRootId, + instituteTitle, +} from "./model.js"; +import type { InstituteProps } from "./model.js"; +import { + chapterPath, + instituteCreditsPath, + instituteOrigin, + institutePath, + ogPath, +} from "./paths.js"; + +const institutePageMetadata = (props: InstituteProps) => { + if (props.kind === "chapter") { + return { + canonicalPath: chapterPath(props.chapter.id), + description: props.chapter.description, + title: `${props.chapter.title} | ${instituteTitle}`, + }; + } + + if (props.kind === "credits") { + return { + canonicalPath: instituteCreditsPath, + description: "Credits for the Ratstack Institute.", + title: `Credits | ${instituteTitle}`, + }; + } + + return { + canonicalPath: institutePath, + description: instituteDescription, + title: instituteTitle, + }; +}; + +export const renderInstitute = Effect.fn("institute.render")( + function* renderInstitute( + props: InstituteProps, + assets: typeof EffectUiAssets.Type, + discoverable: boolean + ) { + const rendered = yield* HtmlServer.renderToHtml(InstitutePage, props); + + const handoff = yield* Schema.encodeEffect(InstituteHandoff)({ + props, + state: rendered.state, + }); + + const { canonicalPath, description, title } = institutePageMetadata(props); + + const canonical = `${instituteOrigin}${canonicalPath}`; + + const metadata = readerMetadataHead( + { + canonicalPath, + description, + discoveryLinks: [], + jsonLd: "none", + ogImagePath: ogPath, + robots: "index", + title, + }, + instituteOrigin + ); + + return { + canonical, + html: `
    ${rendered.html}
    `, + ogUrl: canonical, + readerHead: discoverable + ? metadata + : `${metadata}\n`, + title, + ...effectUiDocument(assets, instituteHandoffId, handoff), + }; + } +); diff --git a/apps/web/src/institute/routes/request.ts b/apps/web/src/institute/routes/request.ts new file mode 100644 index 00000000..44aadc52 --- /dev/null +++ b/apps/web/src/institute/routes/request.ts @@ -0,0 +1,194 @@ +import { Effect } from "effect"; + +import type { EffectUiAssets } from "../../server/reader-document.js"; +import { + audioFallbackUrl, + audioUrl, + InstituteContent, +} from "../content/index.js"; +import { chapterAssetPath } from "../content/paths.js"; +import { instituteContentLayer } from "./artifact.js"; +import type { AssetFetch } from "./artifact.js"; +import { serveHashedAsset } from "./media.js"; +import type { InstituteProps } from "./model.js"; +import { + chapterIdFrom, + chapterPath, + contentAssetChapter, + instituteCreditsPath, + instituteOrigin, + institutePath, + instituteSitemapPath, + isKitChapter, + ogPath, +} from "./paths.js"; +import { renderInstitute } from "./render.js"; + +const sitemap = (chapters: readonly { readonly id: string }[]) => { + const urls = [ + institutePath, + ...chapters.map((chapter) => chapterPath(chapter.id)), + ]; + + return `\n\n${urls.map((path) => ` ${instituteOrigin}${path}`).join("\n")}\n\n`; +}; + +const sectionLink = ({ id }: { readonly id: string }) => ({ + id, + title: id.charAt(0).toUpperCase() + id.slice(1).replaceAll("-", " "), +}); + +const chapterPage = Effect.fn("institute.chapterPage")(function* chapterPage( + reader: InstituteContent["Service"], + chapter: Extract["chapter"], + nextChapter: Extract< + InstituteProps, + { readonly kind: "chapter" } + >["nextChapter"], + sectionId: string | null +) { + const manifest = yield* reader.chapter(chapter.id); + + const selected = manifest.sections.findIndex( + (section) => section.id === sectionId + ); + + const index = Math.max(0, selected); + const entry = manifest.sections[index]; + + if (manifest.id !== chapter.id || entry === undefined) { + return null; + } + + const section = yield* reader.section(chapter.id, entry.id); + + const next = manifest.sections[index + 1]; + const previous = manifest.sections[index - 1]; + + return { + chapter, + kind: "chapter", + section: sectionLink(entry), + sectionUrl: chapterAssetPath(chapter.id, entry.file), + sections: manifest.sections.map(sectionLink), + text: section.text, + audioUrl: audioUrl(chapter.id, section), + audioFallbackUrl: audioFallbackUrl(chapter.id, section), + nextChapter: next === undefined ? nextChapter : undefined, + next: next === undefined ? undefined : sectionLink(next), + previous: previous === undefined ? undefined : sectionLink(previous), + } satisfies InstituteProps; +}); + +export const renderInstituteRequest = Effect.fn("institute.request")( + function* renderInstituteRequest( + request: Request, + fetchAsset: AssetFetch, + assets: typeof EffectUiAssets.Type, + discoverable: boolean + ) { + const url = new URL(request.url); + const path = url.pathname.replace(/\/$/u, ""); + const chapterId = chapterIdFrom(path); + const assetChapter = contentAssetChapter(path); + + if (path === instituteSitemapPath && !discoverable) { + return null; + } + + if (path === instituteCreditsPath) { + return { + application: yield* renderInstitute( + { kind: "credits" }, + assets, + discoverable + ), + }; + } + + if (path === ogPath) { + return { response: yield* Effect.tryPromise(() => fetchAsset(request)) }; + } + + if ( + path !== institutePath && + path !== instituteSitemapPath && + (chapterId === undefined || isKitChapter(chapterId)) && + (assetChapter === undefined || isKitChapter(assetChapter)) + ) { + return null; + } + + const reader = yield* InstituteContent; + const course = yield* reader.manifest; + + const chapters = course.chapters + .filter( + ({ id, draft, comingSoon }) => + !isKitChapter(id) && draft !== true && comingSoon !== true + ) + .toSorted((left, right) => left.order - right.order) + .map(({ id, title, description }) => ({ + id, + title, + description: description ?? "", + })); + + if (path === instituteSitemapPath) { + return { + response: new Response( + request.method === "HEAD" ? null : sitemap(chapters), + { + headers: { "Content-Type": "application/xml; charset=utf-8" }, + } + ), + }; + } + + if (path === institutePath) { + return { + application: yield* renderInstitute( + { chapters, kind: "home" }, + assets, + discoverable + ), + }; + } + + if (assetChapter !== undefined) { + return chapters.some((chapter) => chapter.id === assetChapter) + ? { + response: yield* serveHashedAsset( + request, + fetchAsset, + discoverable + ), + } + : null; + } + + const chapterIndex = chapters.findIndex((item) => item.id === chapterId); + const chapter = chapters[chapterIndex]; + + if (chapter === undefined) { + return null; + } + + const props = yield* chapterPage( + reader, + chapter, + chapters[chapterIndex + 1], + url.searchParams.get("section") + ); + + return props === null + ? null + : { application: yield* renderInstitute(props, assets, discoverable) }; + }, + (effect, request, fetchAsset) => + effect.pipe( + Effect.provide( + instituteContentLayer(fetchAsset, new URL(request.url).origin) + ) + ) +); diff --git a/apps/web/src/institute/routes/website-runtime.ts b/apps/web/src/institute/routes/website-runtime.ts new file mode 100644 index 00000000..a99bda2e --- /dev/null +++ b/apps/web/src/institute/routes/website-runtime.ts @@ -0,0 +1,22 @@ +import { Effect } from "effect"; + +import { instituteVisibilityFor } from "../../../../site/src/institute-visibility.js"; +import type { AssetFetch } from "./artifact.js"; + +export const instituteWebsiteRuntime = Effect.tryPromise( + () => import("cloudflare:workers") +).pipe( + Effect.map(({ env }) => { + const { enabled, discoverable } = instituteVisibilityFor(env); + const binding = env.ASSETS; + + if (!enabled || binding === undefined) { + return null; + } + + const fetchAsset: AssetFetch = (request) => binding.fetch(request); + + return { discoverable, fetchAsset }; + }), + Effect.orElseSucceed(() => null) +); diff --git a/apps/web/src/website.ts b/apps/web/src/website.ts index fb663d84..f0bc1ee3 100644 --- a/apps/web/src/website.ts +++ b/apps/web/src/website.ts @@ -9,6 +9,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; +import { instituteVisibilityConfig } from "../../site/src/institute-visibility.js"; import { traceObservability, traceSettings, @@ -48,6 +49,10 @@ export class Website extends Cloudflare.Website.Foldkit()( const generation = yield* contentGeneration; const preview = /^pr-[1-9][0-9]*$/u.test(stage); + const instituteVisibility = yield* instituteVisibilityConfig.pipe( + Effect.orDie + ); + const props = { assets: { htmlHandling: "drop-trailing-slash", @@ -57,6 +62,8 @@ export class Website extends Cloudflare.Website.Foldkit()( "/__error", "/__rat", "/__rat/*", + "/institute", + "/institute/*", "/prompts", "/prompts/*", ], @@ -64,6 +71,7 @@ export class Website extends Cloudflare.Website.Foldkit()( env: { BACKEND: preview ? PreviewRpcBackend : RpcBackend, CONTENT_GENERATION: generation, + ...instituteVisibility, }, observability: traceObservability(traces), rootDir: "../web", diff --git a/apps/web/test/effect-ui-assets.test.ts b/apps/web/test/effect-ui-assets.test.ts index 819f3328..2f1ff828 100644 --- a/apps/web/test/effect-ui-assets.test.ts +++ b/apps/web/test/effect-ui-assets.test.ts @@ -46,6 +46,8 @@ const allStarsEntry = "src/client/all-stars-effect-ui/entry.ts"; const directoryEntry = "src/client/directory-effect-ui/entry.ts"; +const instituteEntry = "src/client/institute-entry.ts"; + const newsEntry = "src/client/news-effect-ui/entry.ts"; const readerEntry = "src/client/reader-effect-ui/entry.ts"; @@ -65,9 +67,13 @@ const fixture = (overrideManifest?: ManifestFixture): Plugin => ({ } if ( - [allStarsEntry, directoryEntry, newsEntry, readerEntry].some((entry) => - id.endsWith(entry) - ) + [ + allStarsEntry, + directoryEntry, + instituteEntry, + newsEntry, + readerEntry, + ].some((entry) => id.endsWith(entry)) ) { return `export default ${JSON.stringify(id)}`; } @@ -137,6 +143,7 @@ it.effect("loads dev source URLs without a client build", () => const entries = { "all-stars-effect-ui": allStarsEntry, "directory-effect-ui": directoryEntry, + "institute-effect-ui": instituteEntry, "news-effect-ui": newsEntry, "reader-effect-ui": readerEntry, }; @@ -165,7 +172,7 @@ it.effect( } const names = client.output.map(({ fileName }) => fileName); - expect(names).toHaveLength(4); + expect(names).toHaveLength(5); expect(names).not.toContain(".vite/manifest.json"); const server = yield* buildEnvironment(builder, "ssr"); diff --git a/apps/web/test/institute-content.test.ts b/apps/web/test/institute-content.test.ts new file mode 100644 index 00000000..bf07a91a --- /dev/null +++ b/apps/web/test/institute-content.test.ts @@ -0,0 +1,240 @@ +import { NodeCrypto, NodeServices } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { + Config, + ConfigProvider, + Effect, + FileSystem, + Option, + Path, + Schema, +} from "effect"; +import * as Arbitrary from "effect/Arbitrary"; + +import { + instituteArtifactConfig, + stageInstituteAssets, +} from "../src/institute/content/artifact.js"; +import { + audioFallbackUrl, + audioUrl, + InstituteAssetError, + InstituteContent, +} from "../src/institute/content/index.js"; +import { + chapterAssetPath, + instituteManifestPath, + instituteOgPath, +} from "../src/institute/content/paths.js"; + +const chapterId = "chapter"; + +const hasAudio = Arbitrary.schema(Schema.Boolean); + +const lessonNumber = Arbitrary.schema( + Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThan(1000)) +); + +it.effect.prop( + "resolves a manifest's hashed lesson, not arbitrary file names, and accepts no narration", + { narrated: hasAudio, fallback: hasAudio, index: lessonNumber }, + ({ narrated, fallback, index }) => + Effect.gen(function* resolveLesson() { + const id = `lesson-${index}`; + const narration = `lesson-${index}.a982ba54.webm`; + const alternate = `lesson-${index}.badf0151.m4a`; + const file = `lesson-${index}.1234abcd.json`; + + const base = { + id, + text: "Start here.", + code: "", + contentHash: "0123456789abcdef", + wordTimings: [{ word: "Start", start: 0, end: 0.25 }], + }; + + const primary = narrated ? { ...base, audioFile: narration } : base; + + const lesson = + narrated && fallback + ? { ...primary, audioFallbackFile: alternate } + : primary; + + const assets = new Map([ + [ + instituteManifestPath, + JSON.stringify({ + chapters: [{ id: chapterId, title: "Chapter", order: 1 }], + }), + ], + [ + chapterAssetPath(chapterId, "manifest.json"), + JSON.stringify({ + id: chapterId, + title: "Chapter", + sections: [{ id, file }], + }), + ], + [chapterAssetPath(chapterId, file), JSON.stringify(lesson)], + ]); + + const content = yield* InstituteContent.make((path) => { + const document = assets.get(path); + + return document === undefined + ? Effect.fail( + new InstituteAssetError({ path, cause: "missing from fixture" }) + ) + : Effect.succeed(document); + }); + + const section = yield* content.section(chapterId, id); + expect(section).toEqual(lesson); + expect(audioUrl(chapterId, section)).toBe( + narrated ? chapterAssetPath(chapterId, narration) : undefined + ); + + expect(audioFallbackUrl(chapterId, section)).toBe( + narrated && fallback + ? chapterAssetPath(chapterId, alternate) + : undefined + ); + + const missingSection = yield* Effect.flip( + content.section(chapterId, `${id}-other`) + ); + + expect(missingSection._tag).toBe("InstituteSectionNotFound"); + + const missingChapter = yield* Effect.flip( + content.section(`${chapterId}-other`, id) + ); + + expect(missingChapter._tag).toBe("InstituteChapterNotFound"); + }) +); + +it.effect( + "leaves the Website output untouched with no artifact configured", + () => + Effect.gen(function* emptyWebsite() { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* stageInstituteAssets(directory).pipe( + Effect.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({}))) + ); + expect(yield* fs.readDirectory(directory)).toEqual([]); + }).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layerDigest])) +); + +it.effect("rejects an unpinned artifact before emitting assets", () => + Effect.gen(function* unpinnedArtifact() { + const fs = yield* FileSystem.FileSystem; + const artifact = yield* fs.makeTempDirectoryScoped(); + const output = yield* fs.makeTempDirectoryScoped(); + + const failure = yield* stageInstituteAssets(output).pipe( + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromUnknown({ [instituteArtifactConfig]: artifact }) + ) + ), + Effect.flip + ); + + expect(failure._tag).toBe("InstituteArtifactError"); + expect(failure.message).toContain("expected digest"); + expect(yield* fs.readDirectory(output)).toEqual([]); + }).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layerDigest])) +); + +it.effect( + "stages and decodes every published rat-stack lesson when the pinned artifact is configured", + () => + Effect.gen(function* pinnedWebsite() { + const artifact = yield* Config.option( + Config.String(instituteArtifactConfig) + ); + + if (Option.isNone(artifact) || artifact.value === "") { + return; + } + + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const output = yield* fs.makeTempDirectoryScoped(); + yield* stageInstituteAssets(output); + + const content = yield* InstituteContent.make((asset) => + fs + .readFileString(path.join(output, asset)) + .pipe( + Effect.mapError( + (cause) => new InstituteAssetError({ path: asset, cause }) + ) + ) + ); + + const course = yield* content.manifest; + expect(course.chapters.map(({ id }) => id)).toEqual([ + "one-contract", + "one-boundary", + "effect-hard-parts", + "who-owns-state", + "cloud-as-code", + "the-fence", + ]); + + const expectedFallbacks: string[] = []; + + const assetCount = yield* Effect.forEach( + ({ id: chapter }: (typeof course.chapters)[number]) => + Effect.gen(function* countLessons() { + const manifest = yield* content.chapter(chapter); + yield* Effect.forEach( + ({ id, file }: (typeof manifest.sections)[number]) => + Effect.gen(function* checkNarration() { + const section = yield* content.section(chapter, id); + const audio = audioUrl(chapter, section); + expect(audio).toBeDefined(); + expect(section.wordTimings.length).toBeGreaterThan(0); + expect(section._debug?.timingsStatus).toBe("matched"); + const json = chapterAssetPath(chapter, file); + const fallback = audioFallbackUrl(chapter, section); + expect(fallback).toBeDefined(); + + if (fallback !== undefined) { + expectedFallbacks.push(fallback); + } + + for (const asset of [json, audio, fallback].filter( + (url) => url !== undefined + )) { + const original = yield* fs.readFile( + path.join(artifact.value, "client", asset) + ); + + const staged = yield* fs.readFile(path.join(output, asset)); + expect(staged).toEqual(original); + } + }) + )(manifest.sections); + + return manifest.sections.length; + }) + )(course.chapters); + + expect(assetCount).toEqual([4, 2, 4, 5, 2, 4]); + expect(yield* fs.exists(path.join(output, instituteOgPath))).toBe(true); + const emitted = yield* fs.readDirectory(output, { recursive: true }); + expect(emitted.filter((file) => file.endsWith(".json"))).toHaveLength(28); + expect(emitted.filter((file) => file.endsWith(".webm"))).toHaveLength(21); + expect( + emitted + .filter((file) => file.endsWith(".m4a")) + .map((file) => `/${file}`) + .toSorted() + ).toEqual(expectedFallbacks.toSorted()); + expect(emitted.some((file) => file.endsWith(".js"))).toBe(false); + }).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layerDigest])) +); diff --git a/apps/web/test/institute-controls.model.test.ts b/apps/web/test/institute-controls.model.test.ts new file mode 100644 index 00000000..7bd1b374 --- /dev/null +++ b/apps/web/test/institute-controls.model.test.ts @@ -0,0 +1,210 @@ +import { describe, expect, it } from "@effect/vitest"; +import { Schema } from "effect"; +import * as Arbitrary from "effect/Arbitrary"; + +import type { + ControlsTransport, + Playback, +} from "../src/institute/player/controls/transport.js"; +import { + applyTransportAction, + TransportAction, +} from "../src/institute/player/controls/transport.js"; + +const Command = Schema.Struct({ + kind: Schema.Literals(["play", "pause", "seek", "end", "replay"]), + positionMs: Schema.Int.check( + Schema.isBetween({ minimum: -10_000, maximum: 20_000 }) + ), +}); + +type CommandKind = typeof Command.Type.kind; + +type Mode = "ready" | "playing" | "paused" | "ended"; + +interface ReferenceMachine { + mode: Mode; +} + +const transitions = { + ready: { + play: "playing", + pause: "ready", + seek: "paused", + end: "ready", + replay: "playing", + }, + playing: { + play: "playing", + pause: "paused", + seek: "playing", + end: "ended", + replay: "playing", + }, + paused: { + play: "playing", + pause: "paused", + seek: "paused", + end: "paused", + replay: "playing", + }, + ended: { + play: "playing", + pause: "ended", + seek: "paused", + end: "ended", + replay: "playing", + }, +} as const satisfies Record>; + +const durationMs = 9000; + +const recordingTransport = () => { + let state: Mode = "ready"; + let currentMs = 0; + const seeks: number[] = []; + + const transport: ControlsTransport = { + getSnapshot: (): Playback => ({ + currentMs, + durationMs, + state, + rate: 1, + seeking: false, + }), + pause: () => { + state = "paused"; + }, + play: () => { + if (state === "ended") { + currentMs = 0; + } + + state = "playing"; + }, + seek: (positionMs) => { + seeks.push(positionMs); + currentMs = positionMs; + + if (state !== "playing") { + state = "paused"; + } + }, + setRate: (rate) => { + expect(rate).toBe(1); + }, + subscribe: (listener) => { + listener({ currentMs, durationMs, state, rate: 1, seeking: false }); + + return () => { + seeks.length = 0; + }; + }, + }; + + return { + transport, + seeks, + end: () => { + if (state === "playing") { + currentMs = durationMs; + state = "ended"; + } + }, + }; +}; + +const toggle = TransportAction.cases.Toggle.make({}); + +const replay = TransportAction.cases.Replay.make({}); + +const commands = Arbitrary.array(Arbitrary.schema(Command), { + minLength: 5, + maxLength: 60, +}); + +describe("institute controls transport", () => { + it.prop( + "keeps controller interactions in bounds over mixed playback histories", + { history: commands }, + ({ history }) => { + const { transport, seeks, end } = recordingTransport(); + const model: ReferenceMachine = { mode: "ready" }; + let expectedMs = 0; + const expectedSeeks: number[] = []; + + const boundary = { kind: "seek", positionMs: durationMs + 1 } as const; + + for (const { kind, positionMs } of [...history, boundary]) { + const before = model.mode; + model.mode = transitions[before][kind]; + + switch (kind) { + case "play": { + if (before !== "playing") { + applyTransportAction(transport, toggle); + } + + if (before === "ended") { + expectedMs = 0; + } + + break; + } + + case "pause": { + if (before === "playing") { + applyTransportAction(transport, toggle); + } + + break; + } + + case "seek": { + applyTransportAction( + transport, + TransportAction.cases.Seek.make({ ms: positionMs }) + ); + expectedMs = positionMs; + + if (positionMs < 0) { + expectedMs = 0; + } else if (positionMs > durationMs) { + expectedMs = durationMs; + } + + expectedSeeks.push(expectedMs); + break; + } + + case "end": { + end(); + + if (before === "playing") { + expectedMs = durationMs; + } + + break; + } + + case "replay": { + applyTransportAction(transport, replay); + expectedMs = 0; + expectedSeeks.push(expectedMs); + break; + } + + default: { + kind satisfies never; + } + } + + expect(transport.getSnapshot()).toMatchObject({ + currentMs: expectedMs, + state: model.mode, + }); + expect(seeks).toStrictEqual(expectedSeeks); + } + } + ); +}); diff --git a/apps/web/test/institute-effect-ui.test.ts b/apps/web/test/institute-effect-ui.test.ts new file mode 100644 index 00000000..bc386f3c --- /dev/null +++ b/apps/web/test/institute-effect-ui.test.ts @@ -0,0 +1,287 @@ +import { ssr } from "@effect/ui/html/testing"; +import { TestHost } from "@effect/ui/testing"; +import { expect, it } from "@effect/vitest"; +import { Effect, Schema } from "effect"; + +import { preferredAudio } from "../src/institute/routes/audio-choice.js"; +import { InstitutePage } from "../src/institute/routes/component.js"; +import { + InstituteHandoff, + instituteHandoffId, +} from "../src/institute/routes/model.js"; +import { renderInstituteRequest } from "../src/institute/routes/request.js"; +import { renderDocument } from "../src/server/reader-document.js"; + +it("chooses WebM when supported and the AAC rendition otherwise", () => { + const webm = "/lesson.01234567.webm"; + const aac = "/lesson.01234567.m4a"; + + const supported = { + canPlayType: (type: string): CanPlayTypeResult => + type === 'audio/webm; codecs="opus"' ? "maybe" : "", + }; + + const unsupported = { canPlayType: (): CanPlayTypeResult => "" }; + expect(preferredAudio(supported, webm, aac)).toBe(webm); + expect(preferredAudio(unsupported, webm, aac)).toBe(aac); + expect(preferredAudio(unsupported, webm)).toBeUndefined(); + expect(preferredAudio(supported, undefined, aac)).toBe(aac); +}); + +const assets = { + entryScript: "/assets/institute-test.js", + modulePreloads: [], + stylesheets: [], +}; + +const summary = (id: string, title: string, order: number) => ({ + description: title, + id, + order, + title, +}); + +const published = summary("one-contract", "One contract, every surface", 3); + +const transcript = "A boundary keeps in the transcript."; + +const files = new Map([ + [ + "/institute/content/manifest.json", + { + chapters: [ + summary("intro", "Introduction to Effect", 1), + { ...summary("one-boundary", "Unpublished", 2), draft: true }, + published, + { ...summary("the-fence", "Not ready", 4), comingSoon: true }, + ], + }, + ], + [ + "/institute/content/one-contract/manifest.json", + { + id: "one-contract", + title: published.title, + sections: [ + { file: "bind-behavior.01234567.json", id: "bind-behavior" }, + { file: "define-boundary.12345678.json", id: "define-boundary" }, + { file: "people-surfaces.23456789.json", id: "people-surfaces" }, + ], + }, + ], + [ + "/institute/content/one-contract/define-boundary.12345678.json", + { + audioFile: "define-boundary.01234567.webm", + audioFallbackFile: "define-boundary.12345678.m4a", + code: "", + contentHash: "section-fixture", + id: "define-boundary", + text: transcript, + wordTimings: [], + }, + ], + [ + "/institute/content/one-contract/bind-behavior.01234567.json", + { + code: "", + contentHash: "silent-fixture", + id: "bind-behavior", + text: "This section has no narration yet.", + wordTimings: [], + }, + ], +]); + +const read = (path: string, discoverable = true) => + renderInstituteRequest( + new Request(`https://preview.test${path}`), + (request) => { + const file = files.get(new URL(request.url).pathname); + + return Promise.resolve( + file === undefined + ? new Response(null, { status: 404 }) + : Response.json(file) + ); + }, + assets, + discoverable + ); + +const documentFor = (path: string, discoverable = true) => + read(path, discoverable).pipe( + Effect.map((result) => { + if (result?.application === undefined) { + throw new Error(`Expected Institute HTML at ${path}`); + } + + return new DOMParser().parseFromString( + renderDocument(result.application, assets), + "text/html" + ); + }) + ); + +it.effect( + "publishes only Ratstack chapters and gives Kit's chapters outbound credit", + () => + Effect.gen(function* courseHome() { + const home = yield* documentFor("/institute"); + + const listing = [...home.querySelectorAll("ol a")].map((link) => + link.getAttribute("href") + ); + + expect(listing).toEqual(["/institute/chapters/one-contract"]); + expect( + home.querySelector( + 'a[href="https://www.effect.institute/chapters/basics"]' + )?.textContent + ).toBe("Effect Basics"); + expect( + home.querySelector('link[rel="canonical"]')?.getAttribute("href") + ).toBe("https://ratstack.sh/institute"); + expect( + home + .querySelector('meta[name="twitter:image"]') + ?.getAttribute("content") + ).toBe("https://ratstack.sh/institute/og/home.png"); + expect(yield* read("/institute/chapters/intro")).toBeNull(); + expect(yield* read("/institute/chapters/one-boundary")).toBeNull(); + expect( + yield* read("/institute/content/intro/welcome.12345678.json") + ).toBeNull(); + + const fragment = yield* read("/institute/sitemap.xml"); + + const response = fragment?.response; + + if (response === undefined) { + throw new Error("Expected an Institute sitemap response"); + } + + const xml = yield* Effect.tryPromise(() => response.text()); + + const links = [ + ...new DOMParser() + .parseFromString(xml, "application/xml") + .querySelectorAll("loc"), + ].map((loc) => loc.textContent); + + expect(links).toEqual([ + "https://ratstack.sh/institute", + "https://ratstack.sh/institute/chapters/one-contract", + ]); + }) +); + +it.effect( + "a deep link renders and hydrates the selected section without losing its fallback", + () => + Effect.gen(function* chapterHydration() { + const chapter = yield* documentFor( + "/institute/chapters/one-contract?section=define-boundary" + ); + + const canonical = "https://ratstack.sh/institute/chapters/one-contract"; + expect( + chapter.querySelector('link[rel="canonical"]')?.getAttribute("href") + ).toBe(canonical); + expect( + chapter + .querySelector('meta[property="og:url"]') + ?.getAttribute("content") + ).toBe(canonical); + expect(chapter.querySelector("#institute-player p")?.textContent).toBe( + transcript + ); + expect(chapter.querySelector("#institute-player mark")).toBeNull(); + expect( + chapter.querySelector('a[aria-current="page"]')?.getAttribute("href") + ).toBe("/institute/chapters/one-contract?section=define-boundary"); + expect( + chapter.querySelector( + 'a[href="https://www.effect.institute/chapters/intro?section=effect-shows-errors"]' + )?.textContent + ).toBe("Effect shows errors"); + + const handoff = yield* Schema.decodeEffect( + Schema.fromJsonString(InstituteHandoff) + )(chapter.querySelector(`#${instituteHandoffId}`)?.textContent ?? ""); + + expect( + handoff.props.kind === "chapter" && handoff.props.audioFallbackUrl + ).toBe("/institute/content/one-contract/define-boundary.12345678.m4a"); + + const hydrated = yield* ssr(InstitutePage, handoff.props).pipe( + Effect.provide(TestHost.layer()) + ); + + expect(hydrated.adopted).toEqual(["/InstitutePage"]); + expect( + hydrated.container.querySelector("#institute-player") + ?.dataset.audioUrl + ).toBe("/institute/content/one-contract/define-boundary.01234567.webm"); + }) +); + +it.effect( + "unlisted pages carry noindex without changing canonical URLs or cards", + () => + Effect.gen(function* unlistedInstitute() { + for (const path of [ + "/institute", + "/institute/credits", + "/institute/chapters/one-contract?section=define-boundary", + ]) { + const unlisted = yield* documentFor(path, false); + const discoverable = yield* documentFor(path); + const robots = 'meta[name="robots"]'; + expect(unlisted.querySelector(robots)?.getAttribute("content")).toBe( + "noindex, nofollow" + ); + expect(discoverable.querySelector(robots)).toBeNull(); + + for (const name of [ + 'link[rel="canonical"]', + 'meta[property="og:url"]', + 'meta[name="twitter:image"]', + ]) { + expect(unlisted.querySelector(name)?.outerHTML).toBe( + discoverable.querySelector(name)?.outerHTML + ); + } + } + + expect(yield* read("/institute/sitemap.xml", false)).toBeNull(); + const credits = yield* documentFor("/institute/credits"); + expect(credits.querySelector("main")?.textContent).toContain( + "Narration voice: Tom - Conversations & Books, from the ElevenLabs Voice Library" + ); + expect(credits.querySelector("pre")?.textContent).toContain( + "Copyright (c) 2026 Kit Langton" + ); + }) +); + +it.effect( + "absent and unknown section IDs both use the first section, even without narration", + () => + Effect.gen(function* firstSection() { + for (const search of ["", "?section=unknown&fresh=1"]) { + const document = yield* documentFor( + `/institute/chapters/one-contract${search}` + ); + + const player = + document.querySelector("#institute-player"); + + expect(player?.dataset.section).toBe("bind-behavior"); + expect(player?.dataset.audioUrl).toBeUndefined(); + expect(player?.textContent).toContain( + "This section has no narration yet." + ); + } + }) +); diff --git a/apps/web/test/institute-media.test.ts b/apps/web/test/institute-media.test.ts new file mode 100644 index 00000000..8772a151 --- /dev/null +++ b/apps/web/test/institute-media.test.ts @@ -0,0 +1,102 @@ +import { expect, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import { serveHashedAsset } from "../src/institute/routes/media.js"; + +const media = + "https://ratstack.sh/institute/content/one-contract/lesson.01234567.webm"; + +it.effect( + "supplies single and suffix ranges when ASSETS returns the full WebM", + () => + Effect.gen(function* rangeFallback() { + for (const [range, status, contentRange, body] of [ + ["bytes=1-2", 206, "bytes 1-2/5", "bc"], + ["bytes=-2", 206, "bytes 3-4/5", "de"], + ["bytes=3-", 206, "bytes 3-4/5", "de"], + ["bytes=0-1,3-4", 200, null, "abcde"], + ["bytes=5-", 416, "bytes */5", ""], + ] as const) { + const request = new Request(media, { headers: { range } }); + + const response = yield* serveHashedAsset( + request, + (forwarded) => { + expect(forwarded).toBe(request); + + return Promise.resolve( + new Response("abcde", { + headers: { "Content-Type": "audio/webm" }, + }) + ); + }, + true + ); + + expect(response.status).toBe(status); + expect(response.headers.get("accept-ranges")).toBe("bytes"); + expect(response.headers.get("content-range")).toBe(contentRange); + expect(response.headers.get("cache-control")).toBe( + status === 416 ? "no-store" : "public, max-age=31536000, immutable" + ); + expect(yield* Effect.promise(response.text.bind(response))).toBe(body); + } + }) +); + +it.effect("AAC uses audio/mp4 and the same range fallback", () => + Effect.gen(function* aacRange() { + const request = new Request(media.replace(/\.webm$/u, ".m4a"), { + headers: { Range: "bytes=0-1" }, + }); + + const response = yield* serveHashedAsset( + request, + () => + Promise.resolve( + new Response("abcd", { + headers: { "Content-Type": "application/octet-stream" }, + }) + ), + true + ); + + expect(response.status).toBe(206); + expect(response.headers.get("content-type")).toBe("audio/mp4"); + expect(response.headers.get("content-range")).toBe("bytes 0-1/4"); + }) +); + +it.effect( + "preserves ASSETS's range response, without caching when unlisted", + () => + Effect.gen(function* providerRange() { + const request = new Request(media, { headers: { Range: "bytes=0-1" } }); + + const partial = yield* serveHashedAsset( + request, + () => + Promise.resolve( + new Response("ab", { + headers: { "Content-Range": "bytes 0-1/5" }, + status: 206, + }) + ), + false + ); + + expect(partial.status).toBe(206); + expect(partial.headers.get("content-range")).toBe("bytes 0-1/5"); + expect(partial.headers.get("cache-control")).toBe("no-store"); + expect(yield* Effect.promise(partial.text.bind(partial))).toBe("ab"); + + const refused = new Response(null, { + headers: { "Content-Range": "bytes */5" }, + status: 416, + }); + + expect( + yield* serveHashedAsset(request, () => Promise.resolve(refused), true) + ).toBe(refused); + }) +); diff --git a/apps/web/test/institute-player.model.test.ts b/apps/web/test/institute-player.model.test.ts new file mode 100644 index 00000000..9fed4151 --- /dev/null +++ b/apps/web/test/institute-player.model.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "@effect/vitest"; +import { createEffectActor, sendAndAwait, waitFor } from "@xstate/effect"; +import { Effect, Schema } from "effect"; +import * as Arbitrary from "effect/Arbitrary"; + +import { playbackMachine } from "../src/institute/player/playback.js"; +import { chooseStep } from "../src/institute/player/timeline.js"; + +class Media extends EventTarget { + readonly HAVE_METADATA = 1; + readonly error = null; + readyState = 0; + + loadMetadata() { + this.readyState = this.HAVE_METADATA; + this.dispatchEvent(new Event("loadedmetadata")); + } +} + +const EventName = Schema.Literals([ + "PLAYING", + "PAUSED", + "SEEKING", + "SEEKED_PLAYING", + "SEEKED_PAUSED", + "ENDED", + "FAILED", +]); + +type MediaEventName = typeof EventName.Type; + +type PlaybackMode = + | "ready" + | "playing" + | "paused" + | "seeking" + | "ended" + | "failed"; + +const expectedAfter = ( + state: PlaybackMode, + event: MediaEventName +): PlaybackMode => { + if (state === "failed" || event === "FAILED") { + return "failed"; + } + + if (state === "seeking") { + if (event === "ENDED") { + return "ended"; + } + + if (event === "SEEKED_PAUSED") { + return "paused"; + } + + if (event === "SEEKED_PLAYING") { + return "playing"; + } + + return state; + } + + if (event === "SEEKING") { + return "seeking"; + } + + if (event === "PLAYING") { + return "playing"; + } + + if (state === "playing") { + if (event === "ENDED") { + return "ended"; + } + + if (event === "PAUSED") { + return "paused"; + } + } + + return state; +}; + +const histories = Arbitrary.array(Arbitrary.schema(EventName), { + maxLength: 30, +}); + +describe("Institute playback", () => { + it.effect.prop( + "tracks native readiness and generated playback histories", + [histories], + ([history]) => + Effect.scoped( + Effect.gen(function* replayPlayback() { + const media = new Media(); + + const actor = yield* createEffectActor(playbackMachine, { + input: media, + }); + + expect(actor.getSnapshot().value).toBe("loading"); + media.loadMetadata(); + yield* waitFor(actor, (snapshot) => snapshot.value === "ready"); + + let expected: PlaybackMode = "ready"; + + for (const event of history) { + if (expected === "failed") { + actor.send({ type: event }); + expect(actor.getSnapshot().value).toBe("failed"); + } else { + expected = expectedAfter(expected, event); + const snapshot = yield* sendAndAwait(actor, { type: event }); + + expect(snapshot.value).toBe(expected); + } + } + }) + ) + ); + + it.prop( + "the last due frame wins at its boundary and after a rewind", + [ + Arbitrary.array(Arbitrary.schema(Schema.Int), { maxLength: 30 }), + Arbitrary.schema(Schema.Int), + ], + ([times, sample]) => { + const ordered = [0, ...times.map(Math.abs)].toSorted( + (left, right) => left - right + ); + + const t = Math.abs(sample); + const due = ordered.filter((time) => time <= t); + + expect(chooseStep(ordered, t)).toBe(due.length - 1); + expect(chooseStep(ordered, 0)).toBe( + ordered.filter((time) => time === 0).length - 1 + ); + } + ); +}); diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 3026c00c..087a3d77 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -33,7 +33,10 @@ } }, { - "include": ["test/all-stars-effect-ui.test.ts"], + "include": [ + "test/all-stars-effect-ui.test.ts", + "test/institute-effect-ui.test.ts" + ], "options": { "allowedExperimentalApis": [ "@effect/ui/html/testing#ssr", @@ -116,6 +119,7 @@ "effect/ai/McpServer", "effect/crypto/Digest", "effect/http/FetchHttpClient", + "effect/http/HttpClient", "effect/http/HttpRouter", "effect/http/HttpServerRequest", "effect/http/HttpServerResponse", diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index a571721a..412655a3 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -5,8 +5,10 @@ import { Predicate, Schema } from "effect"; import { defineConfig } from "vite"; import { effectUiPlugin } from "./effect-ui.js"; +import { instituteAssetsPlugin } from "./institute-assets.js"; import { readerFinalizationPlugin } from "./reader-finalization.js"; import { readerPagesPlugin } from "./reader-pages.js"; +import { instituteFetchPlugin } from "./src/institute/routes/fetch-plugin.js"; import { readerPrerenderOrigin } from "./src/server/prerender-origin.js"; import type { BackendFetch } from "./src/server/rpc.js"; import { stylexPlugin } from "./stylex.js"; @@ -29,7 +31,9 @@ export default defineConfig({ }, }), effectUiPlugin(), + instituteFetchPlugin(), readerFinalizationPlugin(), + instituteAssetsPlugin(), { apply: "build", config: (config, environment) => { diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts index 301ece95..bda496e9 100644 --- a/apps/web/vitest.config.ts +++ b/apps/web/vitest.config.ts @@ -14,6 +14,7 @@ export default defineConfig({ "test/all-stars-effect-ui.test.ts", "test/app.test.ts", "test/directory-effect-ui.test.ts", + "test/institute-effect-ui.test.ts", "test/news-effect-ui.test.ts", "test/overlay.test.ts", "test/reader-csp.test.ts", @@ -30,6 +31,7 @@ export default defineConfig({ "test/all-stars-effect-ui.test.ts", "test/app.test.ts", "test/directory-effect-ui.test.ts", + "test/institute-effect-ui.test.ts", "test/news-effect-ui.test.ts", "test/overlay.test.ts", "test/reader-csp.test.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f9c4b400..f5d81c62 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -520,6 +520,9 @@ importers: '@stylexjs/stylex': specifier: 0.19.2 version: 0.19.2 + '@xstate/effect': + specifier: 1.0.0-beta.2 + version: 1.0.0-beta.2(@oxlint/plugins@1.93.0)(effect@4.1.4)(xstate@6.0.0-beta.3) alchemy: specifier: 2.0.0-beta.87 version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(effect@4.1.4)(vite@8.3.8(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.1) @@ -529,6 +532,9 @@ importers: foldkit: specifier: 0.170.0 version: 0.170.0(@effect/platform-browser@4.1.4(effect@4.1.4))(effect@4.1.4) + xstate: + specifier: 6.0.0-beta.3 + version: 6.0.0-beta.3 devDependencies: '@effect/platform-node': specifier: 4.1.4 diff --git a/scripts/turbo-inputs-source.ts b/scripts/turbo-inputs-source.ts index b35d0c69..0a15b815 100644 --- a/scripts/turbo-inputs-source.ts +++ b/scripts/turbo-inputs-source.ts @@ -143,8 +143,15 @@ const parameterizedReadBoundaries = new Map( ...hashed("apps/site/dist/content/**"), ...temporary("/**"), ], + "apps/web/src/institute/content/artifact.ts": temporary( + "/**" + ), "apps/web/test/accent.test.ts": hashed("apps/web/src/**"), "apps/web/test/built-images.test.ts": hashed("apps/web/dist/**"), + "apps/web/test/institute-content.test.ts": [ + ...temporary(), + ...temporary("/**"), + ], "apps/web/test/news-effect-ui.test.ts": hashed( "apps/web/dist/client/assets/**" ), diff --git a/turbo.json b/turbo.json index d22ae575..6617dec6 100644 --- a/turbo.json +++ b/turbo.json @@ -249,6 +249,11 @@ "$TURBO_ROOT$/apps/site/src/rpc-worker.ts" ] }, + "@rat-stack/web#build": { + "dependsOn": ["^build"], + "env": ["INSTITUTE_CONTENT_ARTIFACT"], + "outputs": ["dist/**"] + }, "@rat-stack/web#typecheck": { "dependsOn": ["^build", "^typecheck"], "outputs": []