diff --git a/apps/site-e2e/tests/features/todo/__fixtures__/mcp.fixture.ts b/apps/site-e2e/tests/features/todo/__fixtures__/mcp.fixture.ts new file mode 100644 index 000000000..e9fdc762e --- /dev/null +++ b/apps/site-e2e/tests/features/todo/__fixtures__/mcp.fixture.ts @@ -0,0 +1,67 @@ +import { Config, ConfigProvider, Effect, Layer, Option } from 'effect' +import * as McpClient from 'effect/ai/McpClient' +import * as McpProtocol from 'effect/ai/McpProtocol' +import { FetchHttpClient } from 'effect/http' +import * as S from 'effect/Schema' + +const siteUrl = Effect.orDie( + Config.String('SITE_URL').pipe( + Config.withDefault('http://localhost:1337'), + (config) => config.parse(ConfigProvider.fromEnv()), + ), +) + +export const McpClientLive = Layer.unwrap( + Effect.map(siteUrl, (origin) => + McpClient.layerHttp({ + name: 'todo-agent', + version: '1.0.0', + protocol: McpProtocol.v2026_07_28, + url: `${origin}/mcp`, + })), +).pipe(Layer.provide(FetchHttpClient.layer), Layer.orDie) + +const TodoShape = S.Struct({ + id: S.String, + text: S.String, + done: S.Boolean, + position: S.Int, + version: S.Int, + createdAt: S.Int, +}) + +const AddedShape = S.Struct({ todo: TodoShape }) + +const ListedShape = S.Array(TodoShape) + +export interface ToolOutcome { + readonly tools: ReadonlyArray + readonly added: S.Schema.Type + readonly listed: S.Schema.Type +} + +export const credential = (): string => `${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().slice(0, 11)}` + +const callTool = (name: string, args: { readonly credential: string; readonly text?: string }) => + Effect.gen(function*() { + const client = yield* McpClient.McpClient + const tools = yield* client.listTools() + const tool = Option.fromNullishOr(tools.find((candidate) => candidate.name === name)) + return yield* Option.match(tool, { + onNone: () => Effect.die(new Error(`the server does not offer ${name}`)), + onSome: (found) => client.callTool({ tool: found, arguments: args }), + }) + }) + +export const throughTheTools: Effect.Effect = Effect.gen(function*() { + const client = yield* McpClient.McpClient + const tools = yield* client.listTools() + const key = credential() + const added = yield* callTool('todo_add', { credential: key, text: 'buy milk' }) + const listed = yield* callTool('todo_list', { credential: key }) + return { + tools: tools.map((tool) => tool.name), + added: yield* S.decodeUnknownEffect(AddedShape)(added.structuredContent), + listed: yield* S.decodeUnknownEffect(ListedShape)(listed.structuredContent), + } +}).pipe(Effect.orDie) diff --git a/apps/site-e2e/tests/features/todo/__fixtures__/todo.fixture.ts b/apps/site-e2e/tests/features/todo/__fixtures__/todo.fixture.ts new file mode 100644 index 000000000..d19b13f47 --- /dev/null +++ b/apps/site-e2e/tests/features/todo/__fixtures__/todo.fixture.ts @@ -0,0 +1,122 @@ +import { Config, ConfigProvider, Effect } from 'effect' +import type { Page } from 'playwright' + +import { Chromium } from '../../../__fixtures__/browser.fixture' + +const siteUrl = Effect.orDie( + Config.String('SITE_URL').pipe( + Config.withDefault('http://localhost:1337'), + (config) => config.parse(ConfigProvider.fromEnv()), + ), +) + +export interface TodoVisit { + readonly todos: ReadonlyArray + readonly notice: string +} + +export interface TwoPersons { + readonly first: ReadonlyArray + readonly second: ReadonlyArray +} + +const composerReady = (): boolean => { + const button = document.querySelector('button.todo__add') + return button !== null && !button.hasAttribute('disabled') +} + +const todoLines = (page: Page): Promise> => + page.locator('ol.todo__list li .todo__text').allTextContents() + +const noticeOf = (page: Page): Promise => page.locator('.todo__notice').textContent().then((text) => text ?? '') + +const rpcAnswered = (page: Page, procedure: string) => + page.waitForResponse((response) => + response.url().endsWith('/api/rpc') && response.request().postData()?.includes(`"tag":"${procedure}"`) === true + ) + +const visitOf = (page: Page) => + Effect.gen(function*() { + const todos = yield* Effect.promise(() => todoLines(page)) + const notice = yield* Effect.promise(() => noticeOf(page)) + return { todos, notice } satisfies TodoVisit + }) + +const opened = async (page: Page, origin: string): Promise => { + await page.goto(`${origin}/todo`) + await page.waitForFunction(composerReady) +} + +const addTodo = async (page: Page, text: string): Promise => { + const answered = rpcAnswered(page, 'todo_add') + await page.locator('#todo-new').fill(text) + await page.getByRole('button', { name: 'Add' }).click() + await answered +} + +const inFreshContext = ( + use: (page: Page, origin: string) => Effect.Effect, +): Effect.Effect => + Effect.gen(function*() { + const origin = yield* siteUrl + const browser = yield* Chromium + return yield* Effect.acquireUseRelease( + Effect.promise(() => browser.newContext()), + (context) => Effect.flatMap(Effect.promise(() => context.newPage()), (page) => use(page, origin)), + (context) => Effect.promise(() => context.close()), + ) + }) + +export const addedAndReloaded = (text: string): Effect.Effect => + inFreshContext((page, origin) => + Effect.gen(function*() { + yield* Effect.promise(() => opened(page, origin)) + yield* Effect.promise(() => addTodo(page, text)) + yield* Effect.promise(() => page.reload()) + yield* Effect.promise(() => page.waitForFunction(composerReady)) + yield* Effect.promise(() => page.waitForFunction(() => document.querySelectorAll('ol.todo__list li').length > 0)) + return yield* visitOf(page) + }) + ) + +export const workedThroughTheList: Effect.Effect = inFreshContext((page, origin) => + Effect.gen(function*() { + yield* Effect.promise(() => opened(page, origin)) + yield* Effect.promise(async () => { + await addTodo(page, 'first task') + await addTodo(page, 'second task') + + const completed = rpcAnswered(page, 'todo_complete') + await page.getByRole('button', { name: 'Mark first task done' }).click() + await completed + + const renamed = rpcAnswered(page, 'todo_rename') + await page.getByRole('button', { name: 'Rename second task' }).click() + await page.getByLabel('Rename second task').fill('renamed task') + await page.getByLabel('Rename second task').press('Enter') + await renamed + + const moved = rpcAnswered(page, 'todo_reorder') + await page.getByRole('button', { name: 'Move renamed task up' }).click() + await moved + + const removed = rpcAnswered(page, 'todo_remove') + await page.getByRole('button', { name: 'Delete first task' }).click() + await removed + }) + return yield* visitOf(page) + }) +) + +export const twoPersonsLists: Effect.Effect = inFreshContext((firstPage, origin) => + inFreshContext((secondPage) => + Effect.gen(function*() { + yield* Effect.promise(() => opened(firstPage, origin)) + yield* Effect.promise(() => addTodo(firstPage, 'a private task')) + yield* Effect.promise(() => opened(secondPage, origin)) + const first = yield* Effect.promise(() => todoLines(firstPage)) + const second = yield* Effect.promise(() => todoLines(secondPage)) + return { first, second } satisfies TwoPersons + }) + ) +) diff --git a/apps/site-e2e/tests/features/todo/mcp.integration.test.ts b/apps/site-e2e/tests/features/todo/mcp.integration.test.ts new file mode 100644 index 000000000..c9df6fb3d --- /dev/null +++ b/apps/site-e2e/tests/features/todo/mcp.integration.test.ts @@ -0,0 +1,55 @@ +import { Gherkin, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' + +import { McpClientLive, throughTheTools } from './__fixtures__/mcp.fixture' + +const Feature = makeFeature({ it }) + +const MCP_TIMEOUT_MS = 60_000 + +Feature('Working with the todos over the MCP surface', { timeout: MCP_TIMEOUT_MS }) + .withLayer(McpClientLive) + .live('the running Worker serves the todo tools it derives from the todo contract') + .body(({ scenario }) => { + scenario( + 'An agent lists the todo tools and adds a todo it can then list', + Gherkin.Do.pipe( + When('the agent calls the todo tools')('outcome', () => throughTheTools), + Then('the todo tools are offered and the added todo comes back from the list')((s, expect) => + expect({ + tools: s.outcome.tools, + added: s.outcome.added, + listed: s.outcome.listed, + }).toEqual({ + tools: [ + 'todo_list', + 'todo_add', + 'todo_complete', + 'todo_rename', + 'todo_reorder', + 'todo_remove', + ], + added: { + todo: { + id: expect.any(String), + text: 'buy milk', + done: false, + position: 0, + version: 1, + createdAt: expect.any(Number), + }, + }, + listed: [ + { + id: expect.any(String), + text: 'buy milk', + done: false, + position: 0, + version: 1, + createdAt: expect.any(Number), + }, + ], + }) + ), + ), + ) + }) diff --git a/apps/site-e2e/tests/features/todo/todo.integration.test.ts b/apps/site-e2e/tests/features/todo/todo.integration.test.ts new file mode 100644 index 000000000..0ed4fc517 --- /dev/null +++ b/apps/site-e2e/tests/features/todo/todo.integration.test.ts @@ -0,0 +1,43 @@ +import { Gherkin, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' + +import { ChromiumLive } from '../../__fixtures__/browser.fixture' +import { addedAndReloaded, twoPersonsLists, workedThroughTheList } from './__fixtures__/todo.fixture' + +const Feature = makeFeature({ it }) + +const CHROMIUM_TIMEOUT_MS = 60_000 + +Feature('Keeping a list of todos in the browser', { timeout: CHROMIUM_TIMEOUT_MS }) + .withLayer(ChromiumLive) + .live('a real Chromium drives the todo page the running Worker serves, over its own local D1 database') + .body(({ scenario }) => { + scenario( + 'A visitor adds a todo and finds it again after a reload', + Gherkin.Do.pipe( + When('a visitor adds a todo and reloads the page')('visit', () => addedAndReloaded('buy milk')), + Then('the todo is still on the list, with no notice')((s, expect) => + expect(s.visit).toEqual({ todos: ['buy milk'], notice: '' }) + ), + ), + ) + + scenario( + 'A visitor completes, renames, moves and deletes todos', + Gherkin.Do.pipe( + When('a visitor works through the list')('visit', () => workedThroughTheList), + Then('the renamed todo is first and the completed one is gone')((s, expect) => + expect(s.visit).toEqual({ todos: ['renamed task'], notice: '' }) + ), + ), + ) + + scenario( + "One person never sees another person's todos", + Gherkin.Do.pipe( + When('two people open their own lists')('lists', () => twoPersonsLists), + Then('the first person sees their todo and the second sees none')((s, expect) => + expect(s.lists).toEqual({ first: ['a private task'], second: [] }) + ), + ), + ) + }) diff --git a/apps/site/alchemy.run.ts b/apps/site/alchemy.run.ts index ce46e2b7a..9af681618 100644 --- a/apps/site/alchemy.run.ts +++ b/apps/site/alchemy.run.ts @@ -16,6 +16,8 @@ const productionDomain = (stage: string): { readonly domain?: string } => { export const Database = Cloudflare.D1.Database('Database', { migrations: 'src/features/guestbook/migrations' }) +export const TodoDatabase = Cloudflare.D1.Database('TodoDatabase', { migrations: 'src/features/todo/migrations' }) + export const Site = Cloudflare.Website.Vite( 'Site', Effect.gen(function*() { @@ -25,7 +27,11 @@ export const Site = Cloudflare.Website.Vite( compatibility: { date: siteWorker.compatibilityDate, flags: [...siteWorker.compatibilityFlags] }, assets: { runWorkerFirst: ['/app', '/app/*'] }, dev: { port: 1337, strictPort: true }, - env: { DB: yield* Database }, + env: { + DB: yield* Database, + TODO_DB: yield* TodoDatabase, + OTEL_EXPORTER_OTLP_ENDPOINT: process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '', + }, ...productionDomain(stage), } }), diff --git a/apps/site/fakes/clock.fake.ts b/apps/site/fakes/clock.fake.ts new file mode 100644 index 000000000..49e6bb1b6 --- /dev/null +++ b/apps/site/fakes/clock.fake.ts @@ -0,0 +1,29 @@ +import * as Clock from 'effect/Clock' +import * as Duration from 'effect/Duration' +import * as Effect from 'effect/Effect' + +export interface FakeClock extends Clock.Clock { + readonly set: (millis: number) => void + readonly advance: (millis: number) => void +} + +const NANOS_PER_MILLI = 1_000_000n + +export const make = (start: number = 1_700_000_000_000): FakeClock => { + let now = start + return { + currentTimeMillisUnsafe: () => now, + currentTimeMillis: Effect.sync(() => now), + currentTimeNanosUnsafe: () => BigInt(now) * NANOS_PER_MILLI, + currentTimeNanos: Effect.sync(() => BigInt(now) * NANOS_PER_MILLI), + monotonicTimeNanosUnsafe: () => BigInt(now) * NANOS_PER_MILLI, + monotonicTimeNanos: Effect.sync(() => BigInt(now) * NANOS_PER_MILLI), + sleep: (duration: Duration.Duration) => Effect.sleep(duration), + set: (millis: number) => { + now = millis + }, + advance: (millis: number) => { + now = now + millis + }, + } +} diff --git a/apps/site/fakes/todo-store.fake.ts b/apps/site/fakes/todo-store.fake.ts new file mode 100644 index 000000000..9f02b5d8c --- /dev/null +++ b/apps/site/fakes/todo-store.fake.ts @@ -0,0 +1,109 @@ +import * as Effect from 'effect/Effect' +import * as Layer from 'effect/Layer' + +import { + type PersonId, + Todo, + TodoMove, + TodoNotFound, + Todos, + TodoStore, + TodoVersionConflict, + type Uuid, +} from '@endgame/site/todo' + +interface Row { + readonly person: PersonId + readonly todo: Todo +} + +export interface TodoStoreFake { + readonly layer: Layer.Layer + readonly todosOf: (person: PersonId) => Effect.Effect +} + +const keyOf = (person: PersonId, id: Uuid): string => `${person}/${id}` + +const listOf = (rows: Map, person: PersonId): Todos => + [...rows.values()] + .filter((row) => row.person === person) + .map((row) => row.todo) + .sort((left, right) => left.position - right.position) + +const storedOf = ( + rows: Map, + person: PersonId, + id: Uuid, +): Effect.Effect => + Effect.suspend((): Effect.Effect => { + const row = rows.get(keyOf(person, id)) + return row === undefined ? Effect.fail(new TodoNotFound({ id })) : Effect.succeed(row.todo) + }) + +const versionGuard = (todo: Todo, expectedVersion: number): Effect.Effect => + Effect.suspend((): Effect.Effect => + todo.version === expectedVersion + ? Effect.succeed(todo) + : Effect.fail(new TodoVersionConflict({ id: todo.id, expected: expectedVersion, actual: todo.version })) + ) + +const placed = (todo: Todo, move: TodoMove): Todo => ({ + id: todo.id, + text: todo.text, + done: todo.done, + position: move.position, + version: move.version, + createdAt: todo.createdAt, +}) + +export const make = (): TodoStoreFake => { + const rows = new Map() + + const layer = Layer.succeed(TodoStore, { + list: (person) => Effect.succeed(listOf(rows, person)), + todo: (person, id) => storedOf(rows, person, id), + add: (person, todo) => + Effect.sync(() => { + rows.set(keyOf(person, todo.id), { person, todo }) + return todo + }), + update: (person, todo, expectedVersion) => + Effect.flatMap( + storedOf(rows, person, todo.id), + (stored) => + Effect.flatMap(versionGuard(stored, expectedVersion), () => + Effect.sync(() => { + rows.set(keyOf(person, todo.id), { person, todo }) + return todo + })), + ), + remove: (person, id, expectedVersion) => + Effect.flatMap( + storedOf(rows, person, id), + (stored) => + Effect.flatMap(versionGuard(stored, expectedVersion), () => + Effect.sync(() => { + rows.delete(keyOf(person, id)) + return id + })), + ), + reorder: (person, first, second) => + Effect.flatMap( + storedOf(rows, person, first.id), + (storedFirst) => + Effect.flatMap(storedOf(rows, person, second.id), (storedSecond) => + Effect.flatMap(versionGuard(storedFirst, first.expectedVersion), () => + Effect.flatMap(versionGuard(storedSecond, second.expectedVersion), () => + Effect.sync(() => { + rows.set(keyOf(person, first.id), { person, todo: placed(storedFirst, first) }) + rows.set(keyOf(person, second.id), { person, todo: placed(storedSecond, second) }) + return listOf(rows, person) + })))), + ), + }) + + return { + layer, + todosOf: (person) => Effect.succeed(listOf(rows, person)), + } +} diff --git a/apps/site/oxlint.config.ts b/apps/site/oxlint.config.ts index 74f63702a..1abb75010 100644 --- a/apps/site/oxlint.config.ts +++ b/apps/site/oxlint.config.ts @@ -1,4 +1,17 @@ import { defineConfig } from 'oxlint' import shared from '../../oxlint.shared.ts' -export default defineConfig({ extends: [shared] }) +export default defineConfig({ + extends: [shared], + overrides: [ + { + files: ['**/todo-ids.ts'], + rules: { + '@systemfsoftware/effect-platform/no-unported-time-source': [ + 'error', + { ports: ['apps/site/src/features/todo/todo-ids.ts'] }, + ], + }, + }, + ], +}) diff --git a/apps/site/package.json b/apps/site/package.json index 174150fd7..f81246b92 100644 --- a/apps/site/package.json +++ b/apps/site/package.json @@ -1,6 +1,9 @@ { "author": "TODO ", "description": "The one Worker: the starter's TanStack Start site", + "exports": { + "./todo": "./src/features/todo/index.ts" + }, "dependencies": { "@systemfsoftware/effect-cell-types": "^12.1.4", "@systemfsoftware/xstate": "^6.0.0-beta.65", diff --git a/apps/site/src/api/site-mcp-server.ts b/apps/site/src/api/site-mcp-server.ts new file mode 100644 index 000000000..c440daa83 --- /dev/null +++ b/apps/site/src/api/site-mcp-server.ts @@ -0,0 +1,26 @@ +import { McpProtocol, McpServer } from 'effect/ai' +import * as Effect from 'effect/Effect' +import { HttpServer } from 'effect/http' +import * as Layer from 'effect/Layer' + +import { TodoHandlers, TodoTools } from '@endgame/site/todo' + +import { todoCells } from './site-todo-cells' + +export const SITE_MCP_PATH = '/mcp' + +const TodoRegistrationsLive = Layer.effectDiscard( + Effect.gen(function*() { + const cells = yield* todoCells + const handlers = TodoHandlers(cells) + yield* Layer.build(McpServer.toolkit(TodoTools).pipe(Layer.provide(TodoTools.toLayer(handlers)))) + }), +) + +export const SiteMcpLive = McpServer.layerHttpRequestScoped({ + name: 'todo-app', + version: '1.0.0', + path: SITE_MCP_PATH, + protocols: [McpProtocol.v2026_07_28], + registrations: TodoRegistrationsLive, +}).pipe(Layer.provideMerge(HttpServer.layerServices)) diff --git a/apps/site/src/api/site-rpc-server.ts b/apps/site/src/api/site-rpc-server.ts index 26b429a8b..1b845b696 100644 --- a/apps/site/src/api/site-rpc-server.ts +++ b/apps/site/src/api/site-rpc-server.ts @@ -10,9 +10,12 @@ import { GuestbookHandlers } from '../features/guestbook/guestbook-handlers' import { listGuestbookEntriesCell } from '../features/guestbook/list-guestbook-entries.cell' import { moderateGuestbookEntryCell } from '../features/guestbook/moderate-guestbook-entry.cell' import { signGuestbookCell } from '../features/guestbook/sign-guestbook.cell' +import { TodoHandlers } from '../features/todo/todo-handlers' import { SiteDatabase } from '../site-database.service' import { checkHealthCell } from './check-health.cell' import { SITE_RPC_PATH, SiteRpcs } from './site-rpcs' +import { telemetryLayer } from './site-telemetry' +import { todoCells } from './site-todo-cells' const SiteDatabaseLive = Layer.succeed(SiteDatabase, env.DB) @@ -27,7 +30,8 @@ const SiteHandlers = SiteRpcs.toLayer( list: Cell.provideContext(listGuestbookEntriesCell, context), moderate: Cell.provideContext(moderateGuestbookEntryCell, context), }) - return { health: () => health.run(undefined), ...guestbook } + const todo = TodoHandlers(yield* todoCells) + return { health: () => health.run(undefined), ...guestbook, ...todo } }), ) @@ -35,4 +39,5 @@ export const SiteRpcLive = RpcServer.layerHttp({ group: SiteRpcs, path: SITE_RPC Layer.provide(SiteHandlers), Layer.provide(RpcSerialization.layerJson), Layer.provide(HttpServer.layerServices), + Layer.provideMerge(telemetryLayer(env.OTEL_EXPORTER_OTLP_ENDPOINT)), ) diff --git a/apps/site/src/api/site-rpcs.ts b/apps/site/src/api/site-rpcs.ts index 2308d59bf..8451e717e 100644 --- a/apps/site/src/api/site-rpcs.ts +++ b/apps/site/src/api/site-rpcs.ts @@ -1,6 +1,7 @@ import { Rpc, RpcGroup } from 'effect/rpc' import { GuestbookRpcs } from '../features/guestbook/guestbook-rpcs' +import { TodoRpcs } from '../features/todo/todo.contract' import { DatabaseUnreachable } from './check-health.workflow' import { Health } from './health.schema' @@ -8,4 +9,4 @@ export const SITE_RPC_PATH = '/api/rpc' export const HealthRpcs = RpcGroup.make(Rpc.make('health', { success: Health, error: DatabaseUnreachable })) -export const SiteRpcs = HealthRpcs.merge(GuestbookRpcs) +export const SiteRpcs = HealthRpcs.merge(GuestbookRpcs).merge(TodoRpcs) diff --git a/apps/site/src/api/site-telemetry.ts b/apps/site/src/api/site-telemetry.ts new file mode 100644 index 000000000..198d6b5f5 --- /dev/null +++ b/apps/site/src/api/site-telemetry.ts @@ -0,0 +1,15 @@ +import { FetchHttpClient } from 'effect/http' +import * as Layer from 'effect/Layer' +import * as Otlp from 'effect/observability/Otlp' + +export const SITE_SERVICE_NAME = 'endgame-site' + +const isConfigured = (endpoint: string): boolean => endpoint !== '' + +export const telemetryLayer = (endpoint: string): Layer.Layer => + isConfigured(endpoint) + ? Otlp.layerJson({ + baseUrl: endpoint, + resource: { serviceName: SITE_SERVICE_NAME }, + }).pipe(Layer.provide(FetchHttpClient.layer)) + : Layer.empty diff --git a/apps/site/src/api/site-todo-cells.ts b/apps/site/src/api/site-todo-cells.ts new file mode 100644 index 000000000..430fd978e --- /dev/null +++ b/apps/site/src/api/site-todo-cells.ts @@ -0,0 +1,21 @@ +import { env } from 'cloudflare:workers' +import * as Effect from 'effect/Effect' +import * as Layer from 'effect/Layer' + +import { todoCellsOf, TodoHandlers } from '@endgame/site/todo' + +import * as D1TodoStore from '../features/todo/d1-todo-store' + +export const TodoStoreLive = D1TodoStore.layer(env.TODO_DB) + +export const TodoContextLive = Layer.mergeAll(TodoStoreLive) + +export const todoCells = Effect.gen(function*() { + const context = yield* Layer.build(TodoContextLive) + return todoCellsOf(context) +}) + +export const todoHandlers = Effect.gen(function*() { + const cells = yield* todoCells + return TodoHandlers(cells) +}) diff --git a/apps/site/src/cloudflare-env.d.ts b/apps/site/src/cloudflare-env.d.ts index 66873f9af..1a556b334 100644 --- a/apps/site/src/cloudflare-env.d.ts +++ b/apps/site/src/cloudflare-env.d.ts @@ -4,6 +4,8 @@ import type { Site } from '../alchemy.run' declare global { namespace Cloudflare { - interface Env extends Alchemy.InferEnv {} + interface Env extends Alchemy.InferEnv { + readonly OTEL_EXPORTER_OTLP_ENDPOINT: string + } } } diff --git a/apps/site/src/features/todo/__tests__/add-todo.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/add-todo.workflow.property.test.ts new file mode 100644 index 000000000..22a755dab --- /dev/null +++ b/apps/site/src/features/todo/__tests__/add-todo.workflow.property.test.ts @@ -0,0 +1,159 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Match from 'effect/Match' +import * as Num from 'effect/Number' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + AddTodo, + addTodo, + type AddTodoRefusal, + PersonId, + type Todo, + TodoAdded, + TodoRateLimited, + Todos, + TodosRead, + TodoTextMissing, + TodoTextTooLong, + Uuid, +} from '@endgame/site/todo' + +const CREATES_PER_MINUTE = 30 +const CREATES_WINDOW_MS = 60_000 +const TEXT_CAP = 280 +const ONE_NON_WHITESPACE_CODE_UNIT = /^\S$/ + +type Added = Result.Result + +const sameTodo = (todo: Todo, other: Todo): boolean => + todo.id === other.id && + todo.text === other.text && + todo.done === other.done && + todo.position === other.position && + todo.version === other.version && + todo.createdAt === other.createdAt + +const addedAs = (outcome: Added, expected: Todo): boolean => + Result.match(outcome, { + onSuccess: (added) => sameTodo(added.todo, expected), + onFailure: () => false, + }) + +const refusedAs = (outcome: Added, isRefusal: (refused: AddTodoRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +const staleOf = (todos: Todos, now: number): Todos => + todos.map((todo) => ({ ...todo, createdAt: now - CREATES_WINDOW_MS })) + +const uuidOf = (index: number): string => `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}` + +const recentOf = (now: number, count: number): Todos => + Array.from({ length: count }, (_, index) => ({ + id: uuidOf(index), + text: `todo ${index}`, + done: false, + position: index, + version: 1, + createdAt: now, + })) + +const nextPositionOf = (todos: Todos): number => + todos.reduce((highest, todo) => Num.max(highest, todo.position), -1) + 1 + +describe('Feature: a todo is added trimmed at the next position, or the add is refused for its first fault', () => { + it.prop( + '∀d_Outcome_=TrimmedTextOrItsRefusal', + { of: { todos: Todos, text: S.String, now: S.Int, id: Uuid, person: PersonId }, subject: addTodo }, + (subject, { todos, text, now, id, person }) => { + const stale = staleOf(todos, now) + const outcome = subject(new AddTodo({ person, text, id, now, probe: new TodosRead({ todos: stale }) })) + const trimmed = text.trim() + return Match.value(trimmed.length).pipe( + Match.when(0, () => refusedAs(outcome, S.is(TodoTextMissing))), + Match.when((length) => length > TEXT_CAP, () => refusedAs(outcome, S.is(TodoTextTooLong))), + Match.orElse(() => + addedAs(outcome, { + id, + text: trimmed, + done: false, + position: nextPositionOf(stale), + version: 1, + createdAt: now, + }) + ), + ) + }, + ) + + it.prop( + '∀d_Refusal_=TextTooLongPastTheCap', + { + of: { + todos: Todos, + glyph: S.String.check(S.isPattern(ONE_NON_WHITESPACE_CODE_UNIT)), + now: S.Int, + id: Uuid, + person: PersonId, + }, + subject: addTodo, + }, + (subject, { todos, glyph, now, id, person }) => { + const stale = staleOf(todos, now) + const outcome = subject( + new AddTodo({ person, text: glyph.repeat(TEXT_CAP + 1), id, now, probe: new TodosRead({ todos: stale }) }), + ) + return refusedAs(outcome, S.is(TodoTextTooLong)) + }, + ) + + it.prop( + '∀d_Refusal_=RateLimitedAtTheCap', + { + of: { + text: S.String.check(S.isPattern(ONE_NON_WHITESPACE_CODE_UNIT)), + now: S.Int, + id: Uuid, + person: PersonId, + }, + subject: addTodo, + }, + (subject, { text, now, id, person }) => { + const outcome = subject( + new AddTodo({ person, text, id, now, probe: new TodosRead({ todos: recentOf(now, CREATES_PER_MINUTE) }) }), + ) + return refusedAs(outcome, S.is(TodoRateLimited)) + }, + ) + + it.prop( + '∀d_Accepted_=CreateOutsideTheWindow', + { + of: { + text: S.String.check(S.isPattern(ONE_NON_WHITESPACE_CODE_UNIT)), + now: S.Int, + id: Uuid, + person: PersonId, + }, + subject: addTodo, + }, + (subject, { text, now, id, person }) => { + const outside = recentOf(now, CREATES_PER_MINUTE).map((todo) => ({ + ...todo, + createdAt: now - CREATES_WINDOW_MS, + })) + const outcome = subject(new AddTodo({ person, text, id, now, probe: new TodosRead({ todos: outside }) })) + return addedAs(outcome, { + id, + text, + done: false, + position: nextPositionOf(outside), + version: 1, + createdAt: now, + }) + }, + ) +}) diff --git a/apps/site/src/features/todo/__tests__/complete-todo.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/complete-todo.workflow.property.test.ts new file mode 100644 index 000000000..e58d35c36 --- /dev/null +++ b/apps/site/src/features/todo/__tests__/complete-todo.workflow.property.test.ts @@ -0,0 +1,91 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + CompleteTodo, + completeTodo, + type CompleteTodoRefusal, + PersonId, + Todo, + TodoCompleted, + TodoFound, + TodoMissing, + TodoNotFound, + TodoStoreFailed, + TodoStoreUnavailable, + Uuid, +} from '@endgame/site/todo' + +type Completed = Result.Result + +const sameTodo = (todo: Todo, other: Todo): boolean => + todo.id === other.id && + todo.text === other.text && + todo.done === other.done && + todo.position === other.position && + todo.version === other.version && + todo.createdAt === other.createdAt + +const completedAs = (outcome: Completed, expected: Todo): boolean => + Result.match(outcome, { + onSuccess: (completed) => sameTodo(completed.todo, expected), + onFailure: () => false, + }) + +const conflictAs = (outcome: Completed, expected: number, actual: number): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => + Match.value(refused).pipe( + Match.tag('TodoVersionConflict', (conflict) => conflict.expected === expected && conflict.actual === actual), + Match.orElse(() => false), + ), + }) + +const refusedAs = (outcome: Completed, isRefusal: (refused: CompleteTodoRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +describe('Feature: a todo is marked done or not done at the next version, or the mark is refused', () => { + it.prop( + '∀d_Completed_=DoneStateAtTheNextVersion', + { of: { todo: Todo, version: S.Int, done: S.Boolean, person: PersonId }, subject: completeTodo }, + (subject, { todo, version, done, person }) => { + const outcome = subject( + new CompleteTodo({ person, id: todo.id, version, done, probe: new TodoFound({ todo }) }), + ) + return Match.value(todo.version === version).pipe( + Match.when(true, () => completedAs(outcome, { ...todo, done, version: todo.version + 1 })), + Match.when(false, () => conflictAs(outcome, version, todo.version)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotFoundOnMissingTodo', + { of: { id: Uuid, version: S.Int, done: S.Boolean, person: PersonId }, subject: completeTodo }, + (subject, { id, version, done, person }) => + refusedAs( + subject(new CompleteTodo({ person, id, version, done, probe: new TodoMissing({ id }) })), + S.is(TodoNotFound), + ), + ) + + it.prop( + '∀d_Refusal_=StoreUnavailableOnFailedRead', + { + of: { id: Uuid, version: S.Int, done: S.Boolean, person: PersonId, detail: S.String }, + subject: completeTodo, + }, + (subject, { id, version, done, person, detail }) => + refusedAs( + subject(new CompleteTodo({ person, id, version, done, probe: new TodoStoreFailed({ detail }) })), + S.is(TodoStoreUnavailable), + ), + ) +}) diff --git a/apps/site/src/features/todo/__tests__/list-todos.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/list-todos.workflow.property.test.ts new file mode 100644 index 000000000..c75a134ee --- /dev/null +++ b/apps/site/src/features/todo/__tests__/list-todos.workflow.property.test.ts @@ -0,0 +1,61 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + ListTodos, + listTodos, + type ListTodosRefusal, + PersonId, + type Todo, + TodoListed, + Todos, + TodosRead, + TodoStoreFailed, + TodoStoreUnavailable, +} from '@endgame/site/todo' + +type Listed = Result.Result + +const sameTodo = (todo: Todo, other: Todo | undefined): boolean => + other !== undefined && + todo.id === other.id && + todo.text === other.text && + todo.done === other.done && + todo.position === other.position && + todo.version === other.version && + todo.createdAt === other.createdAt + +const sameTodos = (left: Todos, right: Todos): boolean => + left.length === right.length && left.every((todo, index) => sameTodo(todo, right[index])) + +const listedAs = (outcome: Listed, todos: Todos): boolean => + Result.match(outcome, { + onSuccess: (listed) => sameTodos(listed.todos, todos), + onFailure: () => false, + }) + +const refusedAs = (outcome: Listed, isRefusal: (refused: ListTodosRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +describe('Feature: the todo list is read whole for the person who asks, or the read is refused', () => { + it.prop( + '∀d_List_=ProbeTodos', + { of: { todos: Todos, person: PersonId }, subject: listTodos }, + (subject, { todos, person }) => + listedAs(subject(new ListTodos({ person, probe: new TodosRead({ todos }) })), todos), + ) + + it.prop( + '∀d_Refusal_=StoreUnavailableOnFailedRead', + { of: { person: PersonId, detail: S.String }, subject: listTodos }, + (subject, { person, detail }) => + refusedAs( + subject(new ListTodos({ person, probe: new TodoStoreFailed({ detail }) })), + S.is(TodoStoreUnavailable), + ), + ) +}) diff --git a/apps/site/src/features/todo/__tests__/remove-todo.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/remove-todo.workflow.property.test.ts new file mode 100644 index 000000000..7b52df76c --- /dev/null +++ b/apps/site/src/features/todo/__tests__/remove-todo.workflow.property.test.ts @@ -0,0 +1,88 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + PersonId, + RemoveTodo, + removeTodo, + type RemoveTodoRefusal, + Todo, + TodoFound, + TodoMissing, + TodoNotFound, + TodoRemoved, + TodoStoreFailed, + TodoStoreUnavailable, + Uuid, +} from '@endgame/site/todo' + +type Removed = Result.Result + +const sameTodo = (todo: Todo, other: Todo): boolean => + todo.id === other.id && + todo.text === other.text && + todo.done === other.done && + todo.position === other.position && + todo.version === other.version && + todo.createdAt === other.createdAt + +const removedAs = (outcome: Removed, expected: Todo): boolean => + Result.match(outcome, { + onSuccess: (removed) => sameTodo(removed.todo, expected), + onFailure: () => false, + }) + +const conflictAs = (outcome: Removed, expected: number, actual: number): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => + Match.value(refused).pipe( + Match.tag('TodoVersionConflict', (conflict) => conflict.expected === expected && conflict.actual === actual), + Match.orElse(() => false), + ), + }) + +const refusedAs = (outcome: Removed, isRefusal: (refused: RemoveTodoRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +describe('Feature: a todo is removed at the version the reader saw, or the removal is refused', () => { + it.prop( + '∀d_Removed_=TheFoundTodo', + { of: { todo: Todo, version: S.Int, person: PersonId }, subject: removeTodo }, + (subject, { todo, version, person }) => { + const outcome = subject( + new RemoveTodo({ person, id: todo.id, version, probe: new TodoFound({ todo }) }), + ) + return Match.value(todo.version === version).pipe( + Match.when(true, () => removedAs(outcome, todo)), + Match.when(false, () => conflictAs(outcome, version, todo.version)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotFoundOnMissingTodo', + { of: { id: Uuid, version: S.Int, person: PersonId }, subject: removeTodo }, + (subject, { id, version, person }) => + refusedAs( + subject(new RemoveTodo({ person, id, version, probe: new TodoMissing({ id }) })), + S.is(TodoNotFound), + ), + ) + + it.prop( + '∀d_Refusal_=StoreUnavailableOnFailedRead', + { of: { id: Uuid, version: S.Int, person: PersonId, detail: S.String }, subject: removeTodo }, + (subject, { id, version, person, detail }) => + refusedAs( + subject(new RemoveTodo({ person, id, version, probe: new TodoStoreFailed({ detail }) })), + S.is(TodoStoreUnavailable), + ), + ) +}) diff --git a/apps/site/src/features/todo/__tests__/rename-todo.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/rename-todo.workflow.property.test.ts new file mode 100644 index 000000000..102b16f6d --- /dev/null +++ b/apps/site/src/features/todo/__tests__/rename-todo.workflow.property.test.ts @@ -0,0 +1,161 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + PersonId, + RenameTodo, + renameTodo, + type RenameTodoRefusal, + Todo, + TodoFound, + TodoMissing, + TodoNotFound, + TodoRenamed, + TodoStoreFailed, + TodoStoreUnavailable, + TodoTextMissing, + TodoTextTooLong, + Uuid, +} from '@endgame/site/todo' + +const TEXT_CAP = 280 +const ONLY_WHITESPACE = /^\s*$/ +const ONE_NON_WHITESPACE_CODE_UNIT = /^\S$/ + +type Renamed = Result.Result + +const sameTodo = (todo: Todo, other: Todo): boolean => + todo.id === other.id && + todo.text === other.text && + todo.done === other.done && + todo.position === other.position && + todo.version === other.version && + todo.createdAt === other.createdAt + +const renamedAs = (outcome: Renamed, expected: Todo): boolean => + Result.match(outcome, { + onSuccess: (renamed) => sameTodo(renamed.todo, expected), + onFailure: () => false, + }) + +const conflictAs = (outcome: Renamed, expected: number, actual: number): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => + Match.value(refused).pipe( + Match.tag('TodoVersionConflict', (conflict) => conflict.expected === expected && conflict.actual === actual), + Match.orElse(() => false), + ), + }) + +const refusedAs = (outcome: Renamed, isRefusal: (refused: RenameTodoRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +describe('Feature: a todo is renamed with its text trimmed at the next version, or the rename is refused', () => { + it.prop( + '∀d_Renamed_=TrimmedTextAtTheNextVersion', + { + of: { + todo: Todo, + version: S.Int, + lead: S.String.check(S.isPattern(ONLY_WHITESPACE)), + trail: S.String.check(S.isPattern(ONLY_WHITESPACE)), + person: PersonId, + }, + subject: renameTodo, + }, + (subject, { todo, version, lead, trail, person }) => { + const outcome = subject( + new RenameTodo({ + person, + id: todo.id, + version, + text: `${lead}buy milk${trail}`, + probe: new TodoFound({ todo }), + }), + ) + return Match.value(todo.version === version).pipe( + Match.when(true, () => renamedAs(outcome, { ...todo, text: 'buy milk', version: todo.version + 1 })), + Match.when(false, () => conflictAs(outcome, version, todo.version)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=TextMissingForBlankText', + { + of: { + todo: Todo, + version: S.Int, + blank: S.String.check(S.isPattern(ONLY_WHITESPACE)), + person: PersonId, + }, + subject: renameTodo, + }, + (subject, { todo, version, blank, person }) => { + const outcome = subject( + new RenameTodo({ person, id: todo.id, version, text: blank, probe: new TodoFound({ todo }) }), + ) + return Match.value(todo.version === version).pipe( + Match.when(true, () => refusedAs(outcome, S.is(TodoTextMissing))), + Match.when(false, () => conflictAs(outcome, version, todo.version)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=TextTooLongPastTheCap', + { + of: { + todo: Todo, + version: S.Int, + glyph: S.String.check(S.isPattern(ONE_NON_WHITESPACE_CODE_UNIT)), + person: PersonId, + }, + subject: renameTodo, + }, + (subject, { todo, version, glyph, person }) => { + const outcome = subject( + new RenameTodo({ + person, + id: todo.id, + version, + text: glyph.repeat(TEXT_CAP + 1), + probe: new TodoFound({ todo }), + }), + ) + return Match.value(todo.version === version).pipe( + Match.when(true, () => refusedAs(outcome, S.is(TodoTextTooLong))), + Match.when(false, () => conflictAs(outcome, version, todo.version)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotFoundOnMissingTodo', + { of: { id: Uuid, version: S.Int, person: PersonId }, subject: renameTodo }, + (subject, { id, version, person }) => + refusedAs( + subject(new RenameTodo({ person, id, version, text: 'buy milk', probe: new TodoMissing({ id }) })), + S.is(TodoNotFound), + ), + ) + + it.prop( + '∀d_Refusal_=StoreUnavailableOnFailedRead', + { of: { id: Uuid, version: S.Int, person: PersonId, detail: S.String }, subject: renameTodo }, + (subject, { id, version, person, detail }) => + refusedAs( + subject(new RenameTodo({ person, id, version, text: 'buy milk', probe: new TodoStoreFailed({ detail }) })), + S.is(TodoStoreUnavailable), + ), + ) +}) diff --git a/apps/site/src/features/todo/__tests__/reorder-todo.workflow.property.test.ts b/apps/site/src/features/todo/__tests__/reorder-todo.workflow.property.test.ts new file mode 100644 index 000000000..726971f4e --- /dev/null +++ b/apps/site/src/features/todo/__tests__/reorder-todo.workflow.property.test.ts @@ -0,0 +1,180 @@ +import { describe, it } from '@systemfsoftware/vitest' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + PersonId, + ReorderTodo, + reorderTodo, + type ReorderTodoRefusal, + TodoMove, + TodoNotFound, + TodoReordered, + Todos, + TodosRead, + TodoStoreFailed, + TodoStoreUnavailable, + Uuid, +} from '@endgame/site/todo' + +type Reordered = Result.Result + +const uuidOf = (index: number): string => `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}` + +const listOf = (size: number): Todos => + Array.from({ length: size }, (_, index) => ({ + id: uuidOf(index), + text: `todo ${index}`, + done: false, + position: index, + version: 1, + createdAt: index, + })) + +const sameMove = (move: TodoMove, expected: TodoMove): boolean => + move.id === expected.id && + move.position === expected.position && + move.version === expected.version && + move.expectedVersion === expected.expectedVersion + +const reorderedAs = ( + outcome: Reordered, + expected: { readonly first: TodoMove; readonly second: TodoMove }, +): boolean => + Result.match(outcome, { + onSuccess: (reordered) => sameMove(reordered.first, expected.first) && sameMove(reordered.second, expected.second), + onFailure: () => false, + }) + +const conflictAs = (outcome: Reordered, expected: number, actual: number): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => + Match.value(refused).pipe( + Match.tag('TodoVersionConflict', (conflict) => conflict.expected === expected && conflict.actual === actual), + Match.orElse(() => false), + ), + }) + +const notMovableAs = (outcome: Reordered, id: string, edge: 'top' | 'bottom'): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => + Match.value(refused).pipe( + Match.tag('TodoNotMovable', (refusal) => refusal.id === id && refusal.edge === edge), + Match.orElse(() => false), + ), + }) + +const refusedAs = (outcome: Reordered, isRefusal: (refused: ReorderTodoRefusal) => boolean): boolean => + Result.match(outcome, { + onSuccess: () => false, + onFailure: (refused) => isRefusal(refused) && refused.message !== '', + }) + +describe('Feature: a todo moves one place up or down the list, or the move is refused at its edge', () => { + it.prop( + '∀d_Reordered_=SwappedNeighbour', + { + of: { size: S.Int.check(S.isBetween({ minimum: 2, maximum: 5 })), version: S.Int, person: PersonId }, + subject: reorderTodo, + }, + (subject, { size, version, person }) => { + const todos = listOf(size) + const outcome = subject( + new ReorderTodo({ person, id: uuidOf(1), version, direction: 'up', probe: new TodosRead({ todos }) }), + ) + return Match.value(version === 1).pipe( + Match.when( + true, + () => + reorderedAs(outcome, { + first: { id: uuidOf(1), position: 0, version: 2, expectedVersion: 1 }, + second: { id: uuidOf(0), position: 1, version: 2, expectedVersion: 1 }, + }), + ), + Match.when(false, () => conflictAs(outcome, version, 1)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotMovableAtTheTopEdge', + { + of: { size: S.Int.check(S.isBetween({ minimum: 1, maximum: 5 })), version: S.Int, person: PersonId }, + subject: reorderTodo, + }, + (subject, { size, version, person }) => { + const todos = listOf(size) + const outcome = subject( + new ReorderTodo({ person, id: uuidOf(0), version, direction: 'up', probe: new TodosRead({ todos }) }), + ) + return Match.value(version === 1).pipe( + Match.when(true, () => notMovableAs(outcome, uuidOf(0), 'top')), + Match.when(false, () => conflictAs(outcome, version, 1)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotMovableAtTheBottomEdge', + { + of: { size: S.Int.check(S.isBetween({ minimum: 1, maximum: 5 })), version: S.Int, person: PersonId }, + subject: reorderTodo, + }, + (subject, { size, version, person }) => { + const todos = listOf(size) + const last = uuidOf(size - 1) + const outcome = subject( + new ReorderTodo({ person, id: last, version, direction: 'down', probe: new TodosRead({ todos }) }), + ) + return Match.value(version === 1).pipe( + Match.when(true, () => notMovableAs(outcome, last, 'bottom')), + Match.when(false, () => conflictAs(outcome, version, 1)), + Match.exhaustive, + ) + }, + ) + + it.prop( + '∀d_Refusal_=NotFoundOnMissingTodo', + { + of: { index: S.Int.check(S.isBetween({ minimum: 0, maximum: 1000 })), version: S.Int, person: PersonId }, + subject: reorderTodo, + }, + (subject, { index, version, person }) => + refusedAs( + subject( + new ReorderTodo({ + person, + id: uuidOf(1000 + index), + version, + direction: 'up', + probe: new TodosRead({ todos: listOf(1) }), + }), + ), + S.is(TodoNotFound), + ), + ) + + it.prop( + '∀d_Refusal_=StoreUnavailableOnFailedRead', + { of: { id: Uuid, version: S.Int, person: PersonId, detail: S.String }, subject: reorderTodo }, + (subject, { id, version, person, detail }) => + refusedAs( + subject( + new ReorderTodo({ + person, + id, + version, + direction: 'up', + probe: new TodoStoreFailed({ detail }), + }), + ), + S.is(TodoStoreUnavailable), + ), + ) +}) diff --git a/apps/site/src/features/todo/add-todo.cell.ts b/apps/site/src/features/todo/add-todo.cell.ts new file mode 100644 index 000000000..112dcc90f --- /dev/null +++ b/apps/site/src/features/todo/add-todo.cell.ts @@ -0,0 +1,38 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Clock from 'effect/Clock' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { addTodo } from './add-todo.workflow' +import { personOf } from './todo-credential' +import { newId } from './todo-ids' +import { readTodos } from './todo-probe' +import { TodoStore } from './todo-store.service' +import { AddTodoRequest, TodoRateLimited, TodoStoreUnavailable, TodoTextMissing, TodoTextTooLong } from './todo.schema' + +export const addTodoCell = Sandwich.named('todo.add')((request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const now = yield* Clock.currentTimeMillis + const probe = yield* readTodos(person) + return { + person, + text: request.text, + id: newId(), + now, + probe, + } + }) +) + .decide(addTodo) + .write({ + TodoAdded: (decision, command) => + Effect.flatMap(TodoStore, (store) => store.add(command.person, decision.todo)).pipe( + Effect.map((todo) => ({ todo })), + ), + TodoTextMissing: () => Effect.fail(new TodoTextMissing({})), + TodoTextTooLong: () => Effect.fail(new TodoTextTooLong({})), + TodoRateLimited: (failure) => Effect.fail(new TodoRateLimited({ limit: failure.limit })), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/add-todo.workflow.ts b/apps/site/src/features/todo/add-todo.workflow.ts new file mode 100644 index 000000000..f15169096 --- /dev/null +++ b/apps/site/src/features/todo/add-todo.workflow.ts @@ -0,0 +1,91 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Num from 'effect/Number' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' +import * as Str from 'effect/String' + +import { + AddTodoRefusal, + PersonId, + Todo, + TodoRateLimited, + Todos, + TodosRead, + TodoStoreFailed, + TodoStoreUnavailable, + TodoText, + TodoTextMissing, + TodoTextTooLong, + Uuid, +} from './todo.schema.ts' + +const AddTodoTypeId: unique symbol = Symbol.for('site/AddTodo') + +const CREATES_PER_MINUTE = 30 +const CREATES_WINDOW_MS = 60_000 + +export class AddTodo extends S.Class('AddTodo')({ + person: PersonId, + text: S.String, + id: Uuid, + now: S.Int, + probe: S.Union([TodosRead, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoAdded extends S.TaggedClass()('TodoAdded', { + todo: Todo, +}) { + readonly [AddTodoTypeId] = AddTodoTypeId +} + +const textOf = (raw: string): Result.Result => { + const text = Str.trim(raw) + return Match.value(Str.isEmpty(text)).pipe( + Match.when(true, () => Result.fail(new TodoTextMissing({}))), + Match.when(false, () => Result.mapError(S.decodeResult(TodoText)(text), () => new TodoTextTooLong({}))), + Match.exhaustive, + ) +} + +const rateLimitOf = (creates: number): Result.Result => + Match.value(creates >= CREATES_PER_MINUTE).pipe( + Match.when(true, () => Result.fail(new TodoRateLimited({ limit: CREATES_PER_MINUTE }))), + Match.when(false, () => Result.succeed(creates)), + Match.exhaustive, + ) + +const nextPosition = (todos: Todos): number => todos.reduce((highest, todo) => Num.max(highest, todo.position), -1) + 1 + +const addedOf = ( + command: AddTodo, + todos: Todos, +): Result.Result => + Result.gen(function*() { + const text = yield* textOf(command.text) + const creates = todos.filter((todo) => command.now - todo.createdAt < CREATES_WINDOW_MS).length + yield* rateLimitOf(creates) + const todo: Todo = { + id: command.id, + text, + done: false, + position: nextPosition(todos), + version: 1, + createdAt: command.now, + } + return new TodoAdded({ todo }) + }) + +export const addTodo = Workflow.make({ + command: AddTodo, + decision: TodoAdded, + error: AddTodoRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodosRead', (read) => addedOf(command, read.todos)), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/complete-todo.cell.ts b/apps/site/src/features/todo/complete-todo.cell.ts new file mode 100644 index 000000000..a0da80fa3 --- /dev/null +++ b/apps/site/src/features/todo/complete-todo.cell.ts @@ -0,0 +1,36 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { completeTodo } from './complete-todo.workflow' +import { personOf } from './todo-credential' +import { readTodo } from './todo-probe' +import { TodoStore } from './todo-store.service' +import { CompleteTodoRequest, TodoNotFound, TodoStoreUnavailable, TodoVersionConflict } from './todo.schema' + +export const completeTodoCell = Sandwich.named('todo.complete')( + (request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const probe = yield* readTodo({ person, id: request.id }) + return { + person, + id: request.id, + version: request.version, + done: request.done, + probe, + } + }), +) + .decide(completeTodo) + .write({ + TodoCompleted: (decision, command) => + Effect.flatMap(TodoStore, (store) => store.update(command.person, decision.todo, command.version)).pipe( + Effect.map((todo) => ({ todo })), + ), + TodoNotFound: (missing) => Effect.fail(new TodoNotFound({ id: missing.id })), + TodoVersionConflict: (conflict) => + Effect.fail(new TodoVersionConflict({ id: conflict.id, expected: conflict.expected, actual: conflict.actual })), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/complete-todo.workflow.ts b/apps/site/src/features/todo/complete-todo.workflow.ts new file mode 100644 index 000000000..cb32e4589 --- /dev/null +++ b/apps/site/src/features/todo/complete-todo.workflow.ts @@ -0,0 +1,73 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + CompleteTodoRefusal, + PersonId, + Todo, + TodoFound, + TodoMissing, + TodoNotFound, + TodoStoreFailed, + TodoStoreUnavailable, + TodoVersionConflict, + Uuid, +} from './todo.schema.ts' + +const CompleteTodoTypeId: unique symbol = Symbol.for('site/CompleteTodo') + +export class CompleteTodo extends S.Class('CompleteTodo')({ + person: PersonId, + id: Uuid, + version: S.Int, + done: S.Boolean, + probe: S.Union([TodoFound, TodoMissing, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoCompleted extends S.TaggedClass()('TodoCompleted', { + todo: Todo, +}) { + readonly [CompleteTodoTypeId] = CompleteTodoTypeId +} + +const completedOf = (command: CompleteTodo, todo: Todo): Result.Result => + Match.value(todo.version === command.version).pipe( + Match.when( + true, + () => + Result.succeed( + new TodoCompleted({ + todo: { + id: todo.id, + text: todo.text, + done: command.done, + position: todo.position, + version: todo.version + 1, + createdAt: todo.createdAt, + }, + }), + ), + ), + Match.when( + false, + () => Result.fail(new TodoVersionConflict({ id: todo.id, expected: command.version, actual: todo.version })), + ), + Match.exhaustive, + ) + +export const completeTodo = Workflow.make({ + command: CompleteTodo, + decision: TodoCompleted, + error: CompleteTodoRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodoFound', (found) => completedOf(command, found.todo)), + Match.tag('TodoMissing', (missing) => Result.fail(new TodoNotFound({ id: missing.id }))), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/d1-todo-store.ts b/apps/site/src/features/todo/d1-todo-store.ts new file mode 100644 index 000000000..2de70eaaa --- /dev/null +++ b/apps/site/src/features/todo/d1-todo-store.ts @@ -0,0 +1,217 @@ +import * as Effect from 'effect/Effect' +import * as Layer from 'effect/Layer' +import * as S from 'effect/Schema' + +import { TodoStore } from './todo-store.service' +import { + type PersonId, + Todo, + TodoMove, + TodoNotFound, + TodoRow, + Todos, + TodoStoreUnavailable, + TodoVersionConflict, + type Uuid, +} from './todo.schema' + +const COLUMNS = 'id, text, done, position, version, created_at AS createdAt' + +type TodoRow = S.Schema.Type + +const query = (run: () => Promise): Effect.Effect => + Effect.tryPromise({ + try: run, + catch: (cause) => + new TodoStoreUnavailable({ detail: cause instanceof Error ? cause.message : 'the query was rejected' }), + }) + +const rowInvalid = (error: S.SchemaError): TodoStoreUnavailable => + new TodoStoreUnavailable({ detail: `a todo row did not decode: ${error.message.split('\n')[0] ?? 'unknown'}` }) + +const todoOf = (row: TodoRow): Todo => ({ + id: row.id, + text: row.text, + done: row.done, + position: row.position, + version: row.version, + createdAt: row.createdAt, +}) + +const selectTodos = (database: D1Database, person: PersonId): Effect.Effect => + query(() => + database + .prepare(`SELECT ${COLUMNS} FROM todos WHERE person = ?1 ORDER BY position ASC, created_at ASC`) + .bind(person) + .all() + ).pipe( + Effect.flatMap(({ results }) => + S.decodeUnknownEffect(S.Array(TodoRow))(results).pipe( + Effect.mapError(rowInvalid), + Effect.map((rows) => rows.map(todoOf)), + ) + ), + ) + +const selectTodo = ( + database: D1Database, + person: PersonId, + id: Uuid, +): Effect.Effect => + query(() => database.prepare(`SELECT ${COLUMNS} FROM todos WHERE person = ?1 AND id = ?2`).bind(person, id).first()) + .pipe( + Effect.flatMap((row) => Effect.mapError(Effect.fromNullishOr(row), () => new TodoNotFound({ id }))), + Effect.flatMap((row) => S.decodeUnknownEffect(TodoRow)(row).pipe(Effect.mapError(rowInvalid))), + Effect.map(todoOf), + ) + +const insertTodo = ( + database: D1Database, + person: PersonId, + todo: Todo, +): Effect.Effect => + query(() => + database + .prepare( + 'INSERT INTO todos (id, person, text, done, position, version, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) RETURNING ' + + COLUMNS, + ) + .bind(todo.id, person, todo.text, todo.done ? 1 : 0, todo.position, todo.version, todo.createdAt) + .first() + ).pipe( + Effect.flatMap((row) => S.decodeUnknownEffect(TodoRow)(row).pipe(Effect.mapError(rowInvalid))), + Effect.map(todoOf), + ) + +const conflictOf = ( + database: D1Database, + person: PersonId, + id: Uuid, + expectedVersion: number, +): Effect.Effect => + selectTodo(database, person, id).pipe( + Effect.flatMap((current) => + Effect.fail(new TodoVersionConflict({ id, expected: expectedVersion, actual: current.version })) + ), + ) + +const updateTodo = ( + database: D1Database, + person: PersonId, + todo: Todo, + expectedVersion: number, +): Effect.Effect => + query(() => + database + .prepare( + 'UPDATE todos SET text = ?2, done = ?3, position = ?4, version = ?5 WHERE person = ?1 AND id = ?6 AND version = ?7', + ) + .bind(person, todo.text, todo.done ? 1 : 0, todo.position, todo.version, todo.id, expectedVersion) + .run() + ).pipe( + Effect.flatMap(({ meta }) => + Effect.suspend(() => + meta.changes === 1 + ? Effect.succeed(todo) + : conflictOf(database, person, todo.id, expectedVersion) + ) + ), + ) + +const deleteTodo = ( + database: D1Database, + person: PersonId, + id: Uuid, + expectedVersion: number, +): Effect.Effect => + query(() => + database + .prepare('DELETE FROM todos WHERE person = ?1 AND id = ?2 AND version = ?3') + .bind(person, id, expectedVersion) + .run() + ).pipe( + Effect.flatMap(({ meta }) => + Effect.suspend(() => + meta.changes === 1 + ? Effect.succeed(id) + : conflictOf(database, person, id, expectedVersion).pipe(Effect.map((current) => current.id)) + ) + ), + ) + +const reorderFailure = ( + database: D1Database, + person: PersonId, + first: TodoMove, + second: TodoMove, +): Effect.Effect => + selectTodo(database, person, first.id).pipe( + Effect.flatMap((current) => + current.version === first.expectedVersion + ? selectTodo(database, person, second.id).pipe( + Effect.flatMap((other) => + Effect.fail( + new TodoVersionConflict({ + id: other.id, + expected: second.expectedVersion, + actual: other.version, + }), + ) + ), + ) + : Effect.fail( + new TodoVersionConflict({ + id: current.id, + expected: first.expectedVersion, + actual: current.version, + }), + ) + ), + ) + +const reorderTodos = ( + database: D1Database, + person: PersonId, + first: TodoMove, + second: TodoMove, +): Effect.Effect => + query(() => + database + .prepare( + 'UPDATE todos SET position = CASE id WHEN ?2 THEN ?3 ELSE ?4 END, version = CASE id WHEN ?2 THEN ?5 ELSE ?6 END ' + + 'WHERE person = ?1 AND id IN (?2, ?7) AND (SELECT COUNT(*) FROM todos WHERE person = ?1 ' + + 'AND ((id = ?2 AND version = ?8) OR (id = ?7 AND version = ?9))) = 2', + ) + .bind( + person, + first.id, + first.position, + second.position, + first.version, + second.version, + second.id, + first.expectedVersion, + second.expectedVersion, + ) + .run() + ).pipe( + Effect.flatMap(({ meta }) => + Effect.suspend(() => + meta.changes === 2 + ? selectTodos(database, person) + : reorderFailure(database, person, first, second).pipe( + Effect.flatMap((failure) => Effect.fail(failure)), + ) + ) + ), + ) + +export const layer = (database: D1Database): Layer.Layer => + Layer.succeed(TodoStore, { + list: (person) => selectTodos(database, person), + todo: (person, id) => selectTodo(database, person, id), + add: (person, todo) => insertTodo(database, person, todo), + update: (person, todo, expectedVersion) => updateTodo(database, person, todo, expectedVersion), + remove: (person, id, expectedVersion) => deleteTodo(database, person, id, expectedVersion), + reorder: (person, first, second) => reorderTodos(database, person, first, second), + }) diff --git a/apps/site/src/features/todo/index.ts b/apps/site/src/features/todo/index.ts new file mode 100644 index 000000000..ef95c59b4 --- /dev/null +++ b/apps/site/src/features/todo/index.ts @@ -0,0 +1,18 @@ +export * from './add-todo.cell.ts' +export * from './add-todo.workflow.ts' +export * from './complete-todo.cell.ts' +export * from './complete-todo.workflow.ts' +export * from './list-todos.cell.ts' +export * from './list-todos.workflow.ts' +export * from './remove-todo.cell.ts' +export * from './remove-todo.workflow.ts' +export * from './rename-todo.cell.ts' +export * from './rename-todo.workflow.ts' +export * from './reorder-todo.cell.ts' +export * from './reorder-todo.workflow.ts' +export * from './todo-cells.ts' +export * from './todo-credential.ts' +export * from './todo-handlers.ts' +export * from './todo-store.service.ts' +export * from './todo.contract.ts' +export * from './todo.schema.ts' diff --git a/apps/site/src/features/todo/list-todos.cell.ts b/apps/site/src/features/todo/list-todos.cell.ts new file mode 100644 index 000000000..3a8d995b8 --- /dev/null +++ b/apps/site/src/features/todo/list-todos.cell.ts @@ -0,0 +1,22 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { listTodos } from './list-todos.workflow' +import { personOf } from './todo-credential' +import { readTodos } from './todo-probe' +import { ListTodosRequest, TodoStoreUnavailable } from './todo.schema' + +export const listTodosCell = Sandwich.named('todo.list')((request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const probe = yield* readTodos(person) + return { person, probe } + }) +) + .decide(listTodos) + .write({ + TodoListed: (decision) => Effect.succeed(decision.todos), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/list-todos.workflow.ts b/apps/site/src/features/todo/list-todos.workflow.ts new file mode 100644 index 000000000..707568f72 --- /dev/null +++ b/apps/site/src/features/todo/list-todos.workflow.ts @@ -0,0 +1,40 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + ListTodosRefusal, + ListTodosResponse, + PersonId, + TodosRead, + TodoStoreFailed, + TodoStoreUnavailable, +} from './todo.schema.ts' + +const ListTodosTypeId: unique symbol = Symbol.for('site/ListTodos') + +export class ListTodos extends S.Class('ListTodos')({ + person: PersonId, + probe: S.Union([TodosRead, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoListed extends S.TaggedClass()('TodoListed', { + todos: ListTodosResponse, +}) { + readonly [ListTodosTypeId] = ListTodosTypeId +} + +export const listTodos = Workflow.make({ + command: ListTodos, + decision: TodoListed, + error: ListTodosRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodosRead', (read) => Result.succeed(new TodoListed({ todos: read.todos }))), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/migrations/0001_create_todos.sql b/apps/site/src/features/todo/migrations/0001_create_todos.sql new file mode 100644 index 000000000..bfc18b961 --- /dev/null +++ b/apps/site/src/features/todo/migrations/0001_create_todos.sql @@ -0,0 +1,11 @@ +CREATE TABLE todos ( + id TEXT PRIMARY KEY, + person TEXT NOT NULL, + text TEXT NOT NULL, + done INTEGER NOT NULL DEFAULT 0, + position INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL +); + +CREATE INDEX todos_by_person ON todos (person, position); diff --git a/apps/site/src/features/todo/remove-todo.cell.ts b/apps/site/src/features/todo/remove-todo.cell.ts new file mode 100644 index 000000000..5e2ee43e1 --- /dev/null +++ b/apps/site/src/features/todo/remove-todo.cell.ts @@ -0,0 +1,35 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { removeTodo } from './remove-todo.workflow' +import { personOf } from './todo-credential' +import { readTodo } from './todo-probe' +import { TodoStore } from './todo-store.service' +import { RemoveTodoRequest, TodoNotFound, TodoStoreUnavailable, TodoVersionConflict } from './todo.schema' + +export const removeTodoCell = Sandwich.named('todo.remove')( + (request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const probe = yield* readTodo({ person, id: request.id }) + return { + person, + id: request.id, + version: request.version, + probe, + } + }), +) + .decide(removeTodo) + .write({ + TodoRemoved: (decision, command) => + Effect.flatMap(TodoStore, (store) => store.remove(command.person, command.id, command.version)).pipe( + Effect.as({ todo: decision.todo }), + ), + TodoNotFound: (missing) => Effect.fail(new TodoNotFound({ id: missing.id })), + TodoVersionConflict: (conflict) => + Effect.fail(new TodoVersionConflict({ id: conflict.id, expected: conflict.expected, actual: conflict.actual })), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/remove-todo.workflow.ts b/apps/site/src/features/todo/remove-todo.workflow.ts new file mode 100644 index 000000000..9cb46bb70 --- /dev/null +++ b/apps/site/src/features/todo/remove-todo.workflow.ts @@ -0,0 +1,57 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + PersonId, + RemoveTodoRefusal, + Todo, + TodoFound, + TodoMissing, + TodoNotFound, + TodoStoreFailed, + TodoStoreUnavailable, + TodoVersionConflict, + Uuid, +} from './todo.schema.ts' + +const RemoveTodoTypeId: unique symbol = Symbol.for('site/RemoveTodo') + +export class RemoveTodo extends S.Class('RemoveTodo')({ + person: PersonId, + id: Uuid, + version: S.Int, + probe: S.Union([TodoFound, TodoMissing, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoRemoved extends S.TaggedClass()('TodoRemoved', { + todo: Todo, +}) { + readonly [RemoveTodoTypeId] = RemoveTodoTypeId +} + +const removedOf = (command: RemoveTodo, todo: Todo): Result.Result => + Match.value(todo.version === command.version).pipe( + Match.when(true, () => Result.succeed(new TodoRemoved({ todo }))), + Match.when( + false, + () => Result.fail(new TodoVersionConflict({ id: todo.id, expected: command.version, actual: todo.version })), + ), + Match.exhaustive, + ) + +export const removeTodo = Workflow.make({ + command: RemoveTodo, + decision: TodoRemoved, + error: RemoveTodoRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodoFound', (found) => removedOf(command, found.todo)), + Match.tag('TodoMissing', (missing) => Result.fail(new TodoNotFound({ id: missing.id }))), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/rename-todo.cell.ts b/apps/site/src/features/todo/rename-todo.cell.ts new file mode 100644 index 000000000..cad17ad77 --- /dev/null +++ b/apps/site/src/features/todo/rename-todo.cell.ts @@ -0,0 +1,45 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { renameTodo } from './rename-todo.workflow' +import { personOf } from './todo-credential' +import { readTodo } from './todo-probe' +import { TodoStore } from './todo-store.service' +import { + RenameTodoRequest, + TodoNotFound, + TodoStoreUnavailable, + TodoTextMissing, + TodoTextTooLong, + TodoVersionConflict, +} from './todo.schema' + +export const renameTodoCell = Sandwich.named('todo.rename')( + (request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const probe = yield* readTodo({ person, id: request.id }) + return { + person, + id: request.id, + version: request.version, + text: request.text, + probe, + } + }), +) + .decide(renameTodo) + .write({ + TodoRenamed: (decision, command) => + Effect.flatMap(TodoStore, (store) => store.update(command.person, decision.todo, command.version)).pipe( + Effect.map((todo) => ({ todo })), + ), + TodoTextMissing: () => Effect.fail(new TodoTextMissing({})), + TodoTextTooLong: () => Effect.fail(new TodoTextTooLong({})), + TodoNotFound: (missing) => Effect.fail(new TodoNotFound({ id: missing.id })), + TodoVersionConflict: (conflict) => + Effect.fail(new TodoVersionConflict({ id: conflict.id, expected: conflict.expected, actual: conflict.actual })), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/rename-todo.workflow.ts b/apps/site/src/features/todo/rename-todo.workflow.ts new file mode 100644 index 000000000..ea15a3228 --- /dev/null +++ b/apps/site/src/features/todo/rename-todo.workflow.ts @@ -0,0 +1,87 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' +import * as Str from 'effect/String' + +import { + PersonId, + RenameTodoRefusal, + Todo, + TodoFound, + TodoMissing, + TodoNotFound, + TodoStoreFailed, + TodoStoreUnavailable, + TodoText, + TodoTextMissing, + TodoTextTooLong, + TodoVersionConflict, + Uuid, +} from './todo.schema.ts' + +const RenameTodoTypeId: unique symbol = Symbol.for('site/RenameTodo') + +export class RenameTodo extends S.Class('RenameTodo')({ + person: PersonId, + id: Uuid, + version: S.Int, + text: S.String, + probe: S.Union([TodoFound, TodoMissing, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoRenamed extends S.TaggedClass()('TodoRenamed', { + todo: Todo, +}) { + readonly [RenameTodoTypeId] = RenameTodoTypeId +} + +const textOf = (raw: string): Result.Result => { + const text = Str.trim(raw) + return Match.value(Str.isEmpty(text)).pipe( + Match.when(true, () => Result.fail(new TodoTextMissing({}))), + Match.when(false, () => Result.mapError(S.decodeResult(TodoText)(text), () => new TodoTextTooLong({}))), + Match.exhaustive, + ) +} + +const renamedOf = ( + command: RenameTodo, + todo: Todo, +): Result.Result => + Result.gen(function*() { + const version = yield* Match.value(todo.version === command.version).pipe( + Match.when(true, () => Result.succeed(todo.version)), + Match.when( + false, + () => Result.fail(new TodoVersionConflict({ id: todo.id, expected: command.version, actual: todo.version })), + ), + Match.exhaustive, + ) + const text = yield* textOf(command.text) + return new TodoRenamed({ + todo: { + id: todo.id, + text, + done: todo.done, + position: todo.position, + version: version + 1, + createdAt: todo.createdAt, + }, + }) + }) + +export const renameTodo = Workflow.make({ + command: RenameTodo, + decision: TodoRenamed, + error: RenameTodoRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodoFound', (found) => renamedOf(command, found.todo)), + Match.tag('TodoMissing', (missing) => Result.fail(new TodoNotFound({ id: missing.id }))), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/reorder-todo.cell.ts b/apps/site/src/features/todo/reorder-todo.cell.ts new file mode 100644 index 000000000..38322193f --- /dev/null +++ b/apps/site/src/features/todo/reorder-todo.cell.ts @@ -0,0 +1,43 @@ +import { Sandwich } from '@systemfsoftware/effect-cell-types' +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { reorderTodo } from './reorder-todo.workflow' +import { personOf } from './todo-credential' +import { readTodos } from './todo-probe' +import { TodoStore } from './todo-store.service' +import { + ReorderTodoRequest, + TodoNotFound, + TodoNotMovable, + TodoStoreUnavailable, + TodoVersionConflict, +} from './todo.schema' + +export const reorderTodoCell = Sandwich.named('todo.reorder')( + (request: S.Schema.Type) => + Effect.gen(function*() { + const person = yield* personOf(request.credential) + const probe = yield* readTodos(person) + return { + person, + id: request.id, + version: request.version, + direction: request.direction, + probe, + } + }), +) + .decide(reorderTodo) + .write({ + TodoReordered: (decision, command) => + Effect.flatMap(TodoStore, (store) => store.reorder(command.person, decision.first, decision.second)).pipe( + Effect.map((todos) => ({ todos })), + ), + TodoNotFound: (failure) => Effect.fail(new TodoNotFound({ id: failure.id })), + TodoNotMovable: (failure) => Effect.fail(new TodoNotMovable({ id: failure.id, edge: failure.edge })), + TodoVersionConflict: (failure) => + Effect.fail(new TodoVersionConflict({ id: failure.id, expected: failure.expected, actual: failure.actual })), + TodoStoreUnavailable: (failure) => Effect.fail(new TodoStoreUnavailable({ detail: failure.detail })), + CommandRejected: ({ issue }) => Effect.die(new Error(issue)), + }) diff --git a/apps/site/src/features/todo/reorder-todo.workflow.ts b/apps/site/src/features/todo/reorder-todo.workflow.ts new file mode 100644 index 000000000..9e5005349 --- /dev/null +++ b/apps/site/src/features/todo/reorder-todo.workflow.ts @@ -0,0 +1,121 @@ +import { Workflow } from '@systemfsoftware/effect-cell-types' +import * as Match from 'effect/Match' +import * as Option from 'effect/Option' +import * as Result from 'effect/Result' +import * as S from 'effect/Schema' + +import { + PersonId, + ReorderTodoRefusal, + Todo, + TodoDirection, + TodoMove, + TodoNotFound, + TodoNotMovable, + Todos, + TodosRead, + TodoStoreFailed, + TodoStoreUnavailable, + TodoVersionConflict, + Uuid, +} from './todo.schema.ts' + +const ReorderTodoTypeId: unique symbol = Symbol.for('site/ReorderTodo') + +export class ReorderTodo extends S.Class('ReorderTodo')({ + person: PersonId, + id: Uuid, + version: S.Int, + direction: TodoDirection, + probe: S.Union([TodosRead, TodoStoreFailed]), +}) { + static readonly [Workflow.InstrumentationBrand]: Record = {} +} + +export class TodoReordered extends S.TaggedClass()('TodoReordered', { + first: TodoMove, + second: TodoMove, +}) { + readonly [ReorderTodoTypeId] = ReorderTodoTypeId +} + +const neighbourIndex = (index: number, direction: TodoDirection): number => + Match.value(direction).pipe( + Match.when('up', () => index - 1), + Match.when('down', () => index + 1), + Match.exhaustive, + ) + +const edgeOf = (direction: TodoDirection): 'top' | 'bottom' => + Match.value(direction).pipe( + Match.when('up', (): 'top' => 'top'), + Match.when('down', (): 'bottom' => 'bottom'), + Match.exhaustive, + ) + +const movesOf = (todo: Todo, neighbour: Todo): { readonly first: TodoMove; readonly second: TodoMove } => ({ + first: { + id: todo.id, + position: neighbour.position, + version: todo.version + 1, + expectedVersion: todo.version, + }, + second: { + id: neighbour.id, + position: todo.position, + version: neighbour.version + 1, + expectedVersion: neighbour.version, + }, +}) + +const swappedOf = ( + command: ReorderTodo, + todo: Todo, + index: number, + todos: Todos, +): Result.Result => + Match.value(Option.fromNullishOr(todos[neighbourIndex(index, command.direction)])).pipe( + Match.tag('None', () => Result.fail(new TodoNotMovable({ id: todo.id, edge: edgeOf(command.direction) }))), + Match.tag('Some', (some) => Result.succeed(new TodoReordered(movesOf(todo, some.value)))), + Match.exhaustive, + ) + +const reorderedOf = ( + command: ReorderTodo, + todos: Todos, +): Result.Result => + Match.value(Option.fromNullishOr(todos.find((candidate) => candidate.id === command.id))).pipe( + Match.tag('None', () => Result.fail(new TodoNotFound({ id: command.id }))), + Match.tag('Some', (some) => { + const todo = some.value + const index = todos.findIndex((candidate) => candidate.id === todo.id) + return Match.value(todo.version === command.version).pipe( + Match.when( + false, + () => + Result.fail( + new TodoVersionConflict({ + id: todo.id, + expected: command.version, + actual: todo.version, + }), + ), + ), + Match.when(true, () => swappedOf(command, todo, index, todos)), + Match.exhaustive, + ) + }), + Match.exhaustive, + ) + +export const reorderTodo = Workflow.make({ + command: ReorderTodo, + decision: TodoReordered, + error: ReorderTodoRefusal, + decide: (command) => + Match.value(command.probe).pipe( + Match.tag('TodosRead', (read) => reorderedOf(command, read.todos)), + Match.tag('TodoStoreFailed', (failure) => Result.fail(new TodoStoreUnavailable({ detail: failure.detail }))), + Match.exhaustive, + ), +}) diff --git a/apps/site/src/features/todo/todo-cells.ts b/apps/site/src/features/todo/todo-cells.ts new file mode 100644 index 000000000..1b0dd4e9a --- /dev/null +++ b/apps/site/src/features/todo/todo-cells.ts @@ -0,0 +1,20 @@ +import { Cell } from '@systemfsoftware/effect-cell-types' +import type * as Context from 'effect/Context' + +import { addTodoCell } from './add-todo.cell.ts' +import { completeTodoCell } from './complete-todo.cell.ts' +import { listTodosCell } from './list-todos.cell.ts' +import { removeTodoCell } from './remove-todo.cell.ts' +import { renameTodoCell } from './rename-todo.cell.ts' +import { reorderTodoCell } from './reorder-todo.cell.ts' +import { type TodoCells } from './todo-handlers.ts' +import { TodoStore } from './todo-store.service.ts' + +export const todoCellsOf = (context: Context.Context): TodoCells => ({ + todo_list: Cell.provideContext(listTodosCell, context), + todo_add: Cell.provideContext(addTodoCell, context), + todo_complete: Cell.provideContext(completeTodoCell, context), + todo_rename: Cell.provideContext(renameTodoCell, context), + todo_reorder: Cell.provideContext(reorderTodoCell, context), + todo_remove: Cell.provideContext(removeTodoCell, context), +}) diff --git a/apps/site/src/features/todo/todo-client.ts b/apps/site/src/features/todo/todo-client.ts new file mode 100644 index 000000000..e6c769ef4 --- /dev/null +++ b/apps/site/src/features/todo/todo-client.ts @@ -0,0 +1,129 @@ +import * as Effect from 'effect/Effect' +import * as Option from 'effect/Option' +import type { RpcClientError } from 'effect/rpc' +import * as S from 'effect/Schema' + +import { siteClient, SiteClientProtocol } from '../../api/site-rpc-client' +import { newCredential } from './todo-ids' +import { TodoOperations } from './todo.contract' +import type { + TodoNotFound, + TodoNotMovable, + TodoRateLimited, + TodoStoreUnavailable, + TodoTextMissing, + TodoTextTooLong, + TodoVersionConflict, +} from './todo.schema' +import { TodoCredential } from './todo.schema' + +export type TodoOperation = keyof typeof TodoOperations + +export type TodoRequest = S.Schema.Type<(typeof TodoOperations)[Name]['request']> + +export type TodoInput = Omit, 'credential'> + +export type TodoResponse = S.Schema.Type<(typeof TodoOperations)[Name]['response']> + +export type TodoView = TodoResponse<'todo_add'>['todo'] + +export type TodoRefusal = + | TodoTextMissing + | TodoTextTooLong + | TodoRateLimited + | TodoNotFound + | TodoNotMovable + | TodoVersionConflict + | TodoStoreUnavailable + +export type TodoFailure = TodoRefusal | RpcClientError.RpcClientError + +const CREDENTIAL_KEY = 'todo.credential' + +const call = (use: (client: Effect.Success) => Effect.Effect): Effect.Effect => + Effect.scoped(Effect.flatMap(siteClient, use)).pipe(Effect.provide(SiteClientProtocol)) + +const refuse = (failure: TodoRefusal): Effect.Effect => Effect.fail(failure) + +const storedCredential = (): Option.Option => + Option.fromNullishOr(globalThis.localStorage.getItem(CREDENTIAL_KEY)).pipe( + Option.flatMap((raw) => S.decodeOption(TodoCredential)(raw)), + ) + +export const credential: Effect.Effect = Effect.suspend(() => + Option.match(storedCredential(), { + onNone: () => + Effect.sync(() => { + const minted = newCredential() + globalThis.localStorage.setItem(CREDENTIAL_KEY, minted) + return minted + }), + onSome: (value) => Effect.succeed(value), + }) +) + +export const listTodos: Effect.Effect, TodoFailure> = Effect.flatMap( + credential, + (value) => call((client) => client.todo_list({ credential: value })), +) + +export const addTodo = (input: TodoInput<'todo_add'>): Effect.Effect => + Effect.flatMap(credential, (value) => + call((client) => client.todo_add({ ...input, credential: value })).pipe( + Effect.map((response) => response.todo), + Effect.catchTags({ + TodoTextMissing: refuse, + TodoTextTooLong: refuse, + TodoRateLimited: refuse, + TodoStoreUnavailable: refuse, + }), + )) + +export const completeTodo = (input: TodoInput<'todo_complete'>): Effect.Effect => + Effect.flatMap(credential, (value) => + call((client) => client.todo_complete({ ...input, credential: value })).pipe( + Effect.map((response) => response.todo), + Effect.catchTags({ + TodoNotFound: refuse, + TodoVersionConflict: refuse, + TodoStoreUnavailable: refuse, + }), + )) + +export const renameTodo = (input: TodoInput<'todo_rename'>): Effect.Effect => + Effect.flatMap(credential, (value) => + call((client) => client.todo_rename({ ...input, credential: value })).pipe( + Effect.map((response) => response.todo), + Effect.catchTags({ + TodoTextMissing: refuse, + TodoTextTooLong: refuse, + TodoNotFound: refuse, + TodoVersionConflict: refuse, + TodoStoreUnavailable: refuse, + }), + )) + +export const reorderTodo = ( + input: TodoInput<'todo_reorder'>, +): Effect.Effect['todos'], TodoFailure> => + Effect.flatMap(credential, (value) => + call((client) => client.todo_reorder({ ...input, credential: value })).pipe( + Effect.map((response) => response.todos), + Effect.catchTags({ + TodoNotFound: refuse['todos']>, + TodoNotMovable: refuse['todos']>, + TodoVersionConflict: refuse['todos']>, + TodoStoreUnavailable: refuse['todos']>, + }), + )) + +export const removeTodo = (input: TodoInput<'todo_remove'>): Effect.Effect => + Effect.flatMap(credential, (value) => + call((client) => client.todo_remove({ ...input, credential: value })).pipe( + Effect.map((response) => response.todo), + Effect.catchTags({ + TodoNotFound: refuse, + TodoVersionConflict: refuse, + TodoStoreUnavailable: refuse, + }), + )) diff --git a/apps/site/src/features/todo/todo-credential.ts b/apps/site/src/features/todo/todo-credential.ts new file mode 100644 index 000000000..7ce99d8ff --- /dev/null +++ b/apps/site/src/features/todo/todo-credential.ts @@ -0,0 +1,12 @@ +import * as Effect from 'effect/Effect' +import * as S from 'effect/Schema' + +import { PersonId, TodoCredential } from './todo.schema' + +const hexOf = (bytes: Uint8Array): string => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('') + +export const personOf = (credential: TodoCredential): Effect.Effect => + Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(credential))).pipe( + Effect.map((digest) => hexOf(new Uint8Array(digest))), + Effect.flatMap((hex) => Effect.orDie(S.decodeEffect(PersonId)(hex))), + ) diff --git a/apps/site/src/features/todo/todo-handlers.ts b/apps/site/src/features/todo/todo-handlers.ts new file mode 100644 index 000000000..de32d2609 --- /dev/null +++ b/apps/site/src/features/todo/todo-handlers.ts @@ -0,0 +1,65 @@ +import { Cell } from '@systemfsoftware/effect-cell-types' +import * as S from 'effect/Schema' + +import { + AddTodoRefusal, + AddTodoRequest, + AddTodoResponse, + CompleteTodoRefusal, + CompleteTodoRequest, + CompleteTodoResponse, + ListTodosRefusal, + ListTodosRequest, + ListTodosResponse, + RemoveTodoRefusal, + RemoveTodoRequest, + RemoveTodoResponse, + RenameTodoRefusal, + RenameTodoRequest, + RenameTodoResponse, + ReorderTodoRefusal, + ReorderTodoRequest, + ReorderTodoResponse, +} from './todo.schema' + +export interface TodoCells { + readonly todo_list: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > + readonly todo_add: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > + readonly todo_complete: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > + readonly todo_rename: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > + readonly todo_reorder: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > + readonly todo_remove: Cell.Cell< + S.Schema.Type, + S.Schema.Type, + S.Schema.Type + > +} + +export const TodoHandlers = (cells: TodoCells) => ({ + todo_list: (request: S.Schema.Type) => cells.todo_list.run(request), + todo_add: (request: S.Schema.Type) => cells.todo_add.run(request), + todo_complete: (request: S.Schema.Type) => cells.todo_complete.run(request), + todo_rename: (request: S.Schema.Type) => cells.todo_rename.run(request), + todo_reorder: (request: S.Schema.Type) => cells.todo_reorder.run(request), + todo_remove: (request: S.Schema.Type) => cells.todo_remove.run(request), +}) diff --git a/apps/site/src/features/todo/todo-ids.ts b/apps/site/src/features/todo/todo-ids.ts new file mode 100644 index 000000000..888121ac2 --- /dev/null +++ b/apps/site/src/features/todo/todo-ids.ts @@ -0,0 +1,6 @@ +const base64Url = (bytes: Uint8Array): string => + btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '') + +export const newId = (): string => crypto.randomUUID() + +export const newCredential = (): string => base64Url(crypto.getRandomValues(new Uint8Array(32))) diff --git a/apps/site/src/features/todo/todo-page.tsx b/apps/site/src/features/todo/todo-page.tsx new file mode 100644 index 000000000..27bcfcc64 --- /dev/null +++ b/apps/site/src/features/todo/todo-page.tsx @@ -0,0 +1,403 @@ +import * as Effect from 'effect/Effect' +import * as Match from 'effect/Match' +import * as Result from 'effect/Result' +import { type KeyboardEvent, type SubmitEvent, useEffect, useRef, useState } from 'react' + +import { + addTodo, + completeTodo, + listTodos, + removeTodo, + renameTodo, + reorderTodo, + type TodoFailure, + type TodoView, +} from './todo-client' +import { newId } from './todo-ids' + +const EMPTY_NOTICE = 'Nothing on the list yet. Add the first thing.' +const TEXT_NOTICE = 'Write what the todo is.' + +const noticeOf = (failure: TodoFailure): string => + Match.value(failure).pipe( + Match.tag('TodoTextMissing', (refusal) => refusal.message), + Match.tag('TodoTextTooLong', (refusal) => refusal.message), + Match.tag('TodoRateLimited', (refusal) => refusal.message), + Match.tag('TodoNotFound', (refusal) => refusal.message), + Match.tag('TodoNotMovable', (refusal) => refusal.message), + Match.tag('TodoVersionConflict', (refusal) => refusal.message), + Match.tag('TodoStoreUnavailable', (refusal) => refusal.message), + Match.tag('RpcClientError', () => 'The server did not answer.'), + Match.exhaustive, + ) + +const replaceTodo = (todos: ReadonlyArray, updated: TodoView): ReadonlyArray => + todos.map((todo) => (todo.id === updated.id ? updated : todo)) + +const applyAdded = ( + todos: ReadonlyArray, + optimisticId: string, + added: TodoView, +): ReadonlyArray => { + const index = todos.findIndex((todo) => todo.id === optimisticId) + return index === -1 ? [...todos, added] : [...todos.slice(0, index), added, ...todos.slice(index + 1)] +} + +const neighbourIndex = (index: number, direction: 'up' | 'down'): number => direction === 'up' ? index - 1 : index + 1 + +const moved = (todos: ReadonlyArray, todo: TodoView, direction: 'up' | 'down'): ReadonlyArray => { + const index = todos.findIndex((candidate) => candidate.id === todo.id) + const target = neighbourIndex(index, direction) + const withinList = target >= 0 && target < todos.length + const without = todos.filter((candidate) => candidate.id !== todo.id) + return Match.value(withinList).pipe( + Match.when(true, () => [...without.slice(0, target), todo, ...without.slice(target)]), + Match.orElse(() => todos), + ) +} + +const doneMark = (todo: TodoView): string => (todo.done ? '✓' : '') + +const doneLabel = (todo: TodoView): string => (todo.done ? `Mark ${todo.text} not done` : `Mark ${todo.text} done`) + +const isEmpty = (todos: ReadonlyArray, ready: boolean): boolean => todos.length === 0 && ready + +const FIELD_TAGS: ReadonlyArray = ['INPUT', 'TEXTAREA'] + +const inField = (target: EventTarget | null): boolean => + target instanceof HTMLElement && FIELD_TAGS.includes(target.tagName) + +const isComposerShortcut = (event: globalThis.KeyboardEvent): boolean => event.key === 'n' && !inField(event.target) + +const focusComposer = (input: HTMLInputElement | null): void => { + if (input !== null) input.focus() +} + +interface TodoDisplayProps { + readonly todo: TodoView + readonly index: number + readonly total: number + readonly onComplete: () => void + readonly onMoveUp: () => void + readonly onMoveDown: () => void + readonly onRename: () => void + readonly onRemove: () => void +} + +function TodoDisplay(props: TodoDisplayProps) { + return ( + <> + + {props.todo.text} + + + + + + + + ) +} + +interface TodoEditorProps { + readonly todo: TodoView + readonly text: string + readonly onText: (text: string) => void + readonly onKeyDown: (event: KeyboardEvent) => void + readonly onBlur: () => void +} + +function TodoEditor(props: TodoEditorProps) { + return ( + props.onText(event.target.value)} + onKeyDown={props.onKeyDown} + onBlur={props.onBlur} + /> + ) +} + +interface TodoItemProps { + readonly todo: TodoView + readonly index: number + readonly total: number + readonly editing: boolean + readonly editText: string + readonly onEditText: (text: string) => void + readonly onEditKeyDown: (event: KeyboardEvent) => void + readonly onEditBlur: () => void + readonly onComplete: () => void + readonly onMoveUp: () => void + readonly onMoveDown: () => void + readonly onRename: () => void + readonly onRemove: () => void +} + +function TodoItem(props: TodoItemProps) { + return ( +
  • + {props.editing + ? ( + + ) + : ( + + )} +
  • + ) +} + +export function TodoPage() { + const [todos, setTodos] = useState>([]) + const [notice, setNotice] = useState('') + const [draft, setDraft] = useState('') + const [editing, setEditing] = useState(null) + const [editText, setEditText] = useState('') + const [ready, setReady] = useState(false) + const inputRef = useRef(null) + + useEffect(() => { + const program = listTodos.pipe(Effect.catchCause(() => Effect.succeed>([]))) + void Effect.runPromise(program).then((loaded) => { + setTodos(loaded) + setReady(true) + }) + }, []) + + useEffect(() => { + const onKeyDown = (event: globalThis.KeyboardEvent) => { + if (isComposerShortcut(event)) { + event.preventDefault() + focusComposer(inputRef.current) + } + } + globalThis.addEventListener('keydown', onKeyDown) + return () => globalThis.removeEventListener('keydown', onKeyDown) + }, []) + + const attempt = ( + effect: Effect.Effect, + onSuccess: (value: A) => void, + onFailure: (failure: TodoFailure) => void, + ): void => { + const settled = Effect.result(effect) + void Effect.runPromise(settled).then((outcome) => + Result.match(outcome, { + onSuccess: (value) => { + setNotice('') + onSuccess(value) + }, + onFailure: (failure) => { + setNotice(noticeOf(failure)) + onFailure(failure) + }, + }) + ) + } + + const submit = (event: SubmitEvent) => { + event.preventDefault() + const text = draft.trim() + if (text === '') { + setNotice(TEXT_NOTICE) + return + } + const optimistic: TodoView = { + id: newId(), + text, + done: false, + position: todos.length, + version: 1, + createdAt: 0, + } + setTodos((current) => [...current, optimistic]) + setDraft('') + attempt( + addTodo({ text }), + (added) => setTodos((current) => applyAdded(current, optimistic.id, added)), + () => setTodos((current) => current.filter((todo) => todo.id !== optimistic.id)), + ) + } + + const complete = (todo: TodoView) => { + const done = !todo.done + setTodos((current) => replaceTodo(current, { ...todo, done })) + attempt( + completeTodo({ id: todo.id, version: todo.version, done }), + (completed) => setTodos((current) => replaceTodo(current, completed)), + () => setTodos((current) => replaceTodo(current, todo)), + ) + } + + const rename = (todo: TodoView) => { + const text = editText.trim() + if (text === '') { + setNotice(TEXT_NOTICE) + return + } + setEditing(null) + setTodos((current) => replaceTodo(current, { ...todo, text })) + attempt( + renameTodo({ id: todo.id, version: todo.version, text }), + (renamed) => setTodos((current) => replaceTodo(current, renamed)), + () => setTodos((current) => replaceTodo(current, todo)), + ) + } + + const reorder = (todo: TodoView, direction: 'up' | 'down') => { + const previous = todos + setTodos((current) => moved(current, todo, direction)) + attempt( + reorderTodo({ id: todo.id, version: todo.version, direction }), + (reordered) => setTodos(reordered), + () => setTodos(previous), + ) + } + + const remove = (todo: TodoView) => { + const previous = todos + setTodos((current) => current.filter((candidate) => candidate.id !== todo.id)) + attempt( + removeTodo({ id: todo.id, version: todo.version }), + () => {}, + () => setTodos(previous), + ) + } + + const startRename = (todo: TodoView) => { + setEditing(todo.id) + setEditText(todo.text) + } + + const cancelRename = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + event.preventDefault() + setEditing(null) + } + } + + const onRenameKey = (event: KeyboardEvent, todo: TodoView) => { + if (event.key === 'Enter') { + event.preventDefault() + rename(todo) + } + cancelRename(event) + } + + return ( +
    +
    +

    Todos

    +

    + Press n to add a todo. +

    +
    + +
    + + setDraft(event.target.value)} + /> + +
    + +

    + {notice} +

    + +
      + {todos.map((todo, index) => ( + onRenameKey(event, todo)} + onEditBlur={() => rename(todo)} + onComplete={() => complete(todo)} + onMoveUp={() => reorder(todo, 'up')} + onMoveDown={() => reorder(todo, 'down')} + onRename={() => startRename(todo)} + onRemove={() => remove(todo)} + /> + ))} +
    + + +
    + ) +} diff --git a/apps/site/src/features/todo/todo-probe.ts b/apps/site/src/features/todo/todo-probe.ts new file mode 100644 index 000000000..d9898d791 --- /dev/null +++ b/apps/site/src/features/todo/todo-probe.ts @@ -0,0 +1,35 @@ +import * as Effect from 'effect/Effect' +import * as Match from 'effect/Match' + +import { TodoStore } from './todo-store.service' +import { type PersonId, TodoFound, TodoMissing, TodosRead, TodoStoreFailed, type Uuid } from './todo.schema' + +export const readTodos = (person: PersonId): Effect.Effect => + Effect.flatMap(TodoStore, (store) => + store.list(person).pipe( + Effect.match({ + onSuccess: (todos) => new TodosRead({ todos }), + onFailure: (failure) => new TodoStoreFailed({ detail: failure.detail }), + }), + )) + +export interface TodoLookup { + readonly person: PersonId + readonly id: Uuid +} + +export const readTodo = ( + lookup: TodoLookup, +): Effect.Effect => + Effect.flatMap(TodoStore, (store) => + store.todo(lookup.person, lookup.id).pipe( + Effect.match({ + onSuccess: (todo) => new TodoFound({ todo }), + onFailure: (failure) => + Match.value(failure).pipe( + Match.tag('TodoNotFound', (missing) => new TodoMissing({ id: missing.id })), + Match.tag('TodoStoreUnavailable', (unavailable) => new TodoStoreFailed({ detail: unavailable.detail })), + Match.exhaustive, + ), + }), + )) diff --git a/apps/site/src/features/todo/todo-store.service.ts b/apps/site/src/features/todo/todo-store.service.ts new file mode 100644 index 000000000..5076414db --- /dev/null +++ b/apps/site/src/features/todo/todo-store.service.ts @@ -0,0 +1,34 @@ +import * as Context from 'effect/Context' +import type * as Effect from 'effect/Effect' + +import type { + PersonId, + Todo, + TodoMove, + TodoNotFound, + Todos, + TodoStoreUnavailable, + TodoVersionConflict, + Uuid, +} from './todo.schema' + +export class TodoStore extends Context.Service Effect.Effect + readonly todo: (person: PersonId, id: Uuid) => Effect.Effect + readonly add: (person: PersonId, todo: Todo) => Effect.Effect + readonly update: ( + person: PersonId, + todo: Todo, + expectedVersion: number, + ) => Effect.Effect + readonly remove: ( + person: PersonId, + id: Uuid, + expectedVersion: number, + ) => Effect.Effect + readonly reorder: ( + person: PersonId, + first: TodoMove, + second: TodoMove, + ) => Effect.Effect +}>()('site/TodoStore') {} diff --git a/apps/site/src/features/todo/todo.contract.ts b/apps/site/src/features/todo/todo.contract.ts new file mode 100644 index 000000000..69a039014 --- /dev/null +++ b/apps/site/src/features/todo/todo.contract.ts @@ -0,0 +1,78 @@ +import { Tool, Toolkit } from 'effect/ai' +import { Rpc, RpcGroup } from 'effect/rpc' +import * as S from 'effect/Schema' + +import { + AddTodoRefusal, + AddTodoRequest, + AddTodoResponse, + CompleteTodoRefusal, + CompleteTodoRequest, + CompleteTodoResponse, + ListTodosRefusal, + ListTodosRequest, + ListTodosResponse, + RemoveTodoRefusal, + RemoveTodoRequest, + RemoveTodoResponse, + RenameTodoRefusal, + RenameTodoRequest, + RenameTodoResponse, + ReorderTodoRefusal, + ReorderTodoRequest, + ReorderTodoResponse, +} from './todo.schema' + +const operation = < + const Name extends string, + Request extends S.Top, + Response extends S.Top, + Refusal extends S.Top, +>( + name: Name, + schemas: { readonly request: Request; readonly response: Response; readonly refusal: Refusal }, +) => ({ + name, + request: schemas.request, + response: schemas.response, + refusal: schemas.refusal, + rpc: Rpc.make(name, { payload: schemas.request, success: schemas.response, error: schemas.refusal }), + tool: Tool.make(name, { parameters: schemas.request, success: schemas.response, failure: schemas.refusal }), +}) + +export const TodoOperations = { + todo_list: operation('todo_list', { + request: ListTodosRequest, + response: ListTodosResponse, + refusal: ListTodosRefusal, + }), + todo_add: operation('todo_add', { + request: AddTodoRequest, + response: AddTodoResponse, + refusal: AddTodoRefusal, + }), + todo_complete: operation('todo_complete', { + request: CompleteTodoRequest, + response: CompleteTodoResponse, + refusal: CompleteTodoRefusal, + }), + todo_rename: operation('todo_rename', { + request: RenameTodoRequest, + response: RenameTodoResponse, + refusal: RenameTodoRefusal, + }), + todo_reorder: operation('todo_reorder', { + request: ReorderTodoRequest, + response: ReorderTodoResponse, + refusal: ReorderTodoRefusal, + }), + todo_remove: operation('todo_remove', { + request: RemoveTodoRequest, + response: RemoveTodoResponse, + refusal: RemoveTodoRefusal, + }), +} + +export const TodoRpcs = RpcGroup.make(...Object.values(TodoOperations).map((declared) => declared.rpc)) + +export const TodoTools = Toolkit.make(...Object.values(TodoOperations).map((declared) => declared.tool)) diff --git a/apps/site/src/features/todo/todo.css b/apps/site/src/features/todo/todo.css new file mode 100644 index 000000000..e0a56cb04 --- /dev/null +++ b/apps/site/src/features/todo/todo.css @@ -0,0 +1,265 @@ +:root { + --todo-bg: #f6f7f9; + --todo-surface: #ffffff; + --todo-ink: #16181d; + --todo-ink-soft: #5b6270; + --todo-line: #e3e6ec; + --todo-accent: #2f6feb; + --todo-danger: #c0392b; + --todo-radius: 12px; +} + +@media (prefers-color-scheme: dark) { + :root { + --todo-bg: #101216; + --todo-surface: #191c22; + --todo-ink: #f2f4f8; + --todo-ink-soft: #9aa2b1; + --todo-line: #2a2f38; + --todo-accent: #6c9bff; + --todo-danger: #ef7a6d; + } +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; + background: var(--todo-bg); + color: var(--todo-ink); + font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; + font-size: 16px; + line-height: 1.5; + -webkit-text-size-adjust: 100%; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.todo { + width: min(38rem, 100% - 2rem); + margin: 0 auto; + padding: 2.5rem 0 4rem; +} + +.todo__header { + margin-bottom: 1.5rem; +} + +.todo__title { + margin: 0; + font-size: 1.75rem; + line-height: 1.2; + letter-spacing: -0.02em; +} + +.todo__hint { + margin: 0.35rem 0 0; + color: var(--todo-ink-soft); + font-size: 0.9rem; +} + +.todo__hint kbd { + padding: 0.1rem 0.35rem; + border: 1px solid var(--todo-line); + border-bottom-width: 2px; + border-radius: 6px; + background: var(--todo-surface); + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 0.8rem; +} + +.todo__composer { + display: flex; + gap: 0.5rem; + align-items: stretch; +} + +.todo__input { + flex: 1 1 auto; + min-width: 0; + min-height: 2.75rem; + padding: 0.6rem 0.85rem; + border: 1px solid var(--todo-line); + border-radius: var(--todo-radius); + background: var(--todo-surface); + color: inherit; + font: inherit; +} + +.todo__input::placeholder { + color: var(--todo-ink-soft); +} + +.todo__add { + flex: 0 0 auto; + min-height: 2.75rem; + padding: 0 1.1rem; + border: 1px solid transparent; + border-radius: var(--todo-radius); + background: var(--todo-accent); + color: #ffffff; + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.todo__add[disabled] { + opacity: 0.5; + cursor: not-allowed; +} + +.todo__notice { + min-height: 1.5rem; + margin: 0.6rem 0 0; + color: var(--todo-danger); + font-size: 0.9rem; +} + +.todo__list { + margin: 1rem 0 0; + padding: 0; + list-style: none; +} + +.todo__item { + display: flex; + gap: 0.6rem; + align-items: center; + min-height: 3.25rem; + margin-bottom: 0.5rem; + padding: 0.5rem 0.6rem; + border: 1px solid var(--todo-line); + border-radius: var(--todo-radius); + background: var(--todo-surface); +} + +.todo__item[data-done='true'] .todo__text { + color: var(--todo-ink-soft); + text-decoration: line-through; +} + +.todo__check { + flex: 0 0 auto; + width: 1.75rem; + height: 1.75rem; + padding: 0; + border: 1.5px solid var(--todo-line); + border-radius: 50%; + background: transparent; + color: var(--todo-accent); + font: inherit; + line-height: 1; + cursor: pointer; +} + +.todo__check[disabled] { + border-color: var(--todo-accent); + cursor: default; +} + +.todo__text { + flex: 1 1 auto; + min-width: 0; + overflow-wrap: anywhere; +} + +.todo__actions { + display: flex; + flex: 0 0 auto; + gap: 0.15rem; +} + +.todo__action { + width: 2rem; + height: 2rem; + padding: 0; + border: 1px solid transparent; + border-radius: 8px; + background: transparent; + color: var(--todo-ink-soft); + font: inherit; + line-height: 1; + cursor: pointer; +} + +.todo__action:hover:not([disabled]) { + background: var(--todo-bg); + color: var(--todo-ink); +} + +.todo__action[disabled] { + opacity: 0.35; + cursor: not-allowed; +} + +.todo__action--danger:hover:not([disabled]) { + color: var(--todo-danger); +} + +.todo__edit { + flex: 1 1 auto; + min-width: 0; + min-height: 2rem; + padding: 0.35rem 0.5rem; + border: 1px solid var(--todo-accent); + border-radius: 8px; + background: var(--todo-surface); + color: inherit; + font: inherit; +} + +.todo__empty { + margin: 1.5rem 0 0; + color: var(--todo-ink-soft); + text-align: center; +} + +:focus-visible { + outline: 2px solid var(--todo-accent); + outline-offset: 2px; +} + +@media (max-width: 30rem) { + .todo { + padding-top: 1.5rem; + } + + .todo__composer { + flex-wrap: wrap; + } + + .todo__input { + flex: 1 1 100%; + } + + .todo__add { + flex: 1 1 100%; + } + + .todo__item { + flex-wrap: wrap; + } + + .todo__text { + flex: 1 1 calc(100% - 3rem); + } + + .todo__actions { + flex: 1 1 100%; + justify-content: flex-end; + } +} diff --git a/apps/site/src/features/todo/todo.schema.ts b/apps/site/src/features/todo/todo.schema.ts new file mode 100644 index 000000000..6f2422b70 --- /dev/null +++ b/apps/site/src/features/todo/todo.schema.ts @@ -0,0 +1,180 @@ +import * as S from 'effect/Schema' +import * as SchemaGetter from 'effect/SchemaGetter' + +export const Uuid = S.String.pipe(S.check(S.isUUID(4))) +export type Uuid = S.Schema.Type + +export const TodoCredential = S.String.pipe(S.check(S.isMinLength(43), S.isMaxLength(43))) +export type TodoCredential = S.Schema.Type + +export const PersonId = S.String.pipe(S.check(S.isMinLength(64), S.isMaxLength(64)), S.brand('PersonId')) +export type PersonId = S.Schema.Type + +export const TodoText = S.Trimmed.pipe(S.check(S.isMinLength(1), S.isMaxLength(280)), S.brand('TodoText')) +export type TodoText = S.Schema.Type + +export const TodoTextValue = S.Trimmed.pipe(S.check(S.isMinLength(1), S.isMaxLength(280))) +export type TodoTextValue = S.Schema.Type + +export const Todo = S.Struct({ + id: Uuid, + text: TodoTextValue, + done: S.Boolean, + position: S.Int, + version: S.Int, + createdAt: S.Int, +}) +export type Todo = S.Schema.Type + +export const Todos = S.Array(Todo) +export type Todos = S.Schema.Type + +export const TodoMove = S.Struct({ + id: Uuid, + position: S.Int, + version: S.Int, + expectedVersion: S.Int, +}) +export type TodoMove = S.Schema.Type + +export const Done = S.Literals([0, 1]).pipe( + S.decodeTo(S.Boolean, { + decode: SchemaGetter.transform((value) => value === 1), + encode: SchemaGetter.transform<0 | 1, boolean>((value) => (value ? 1 : 0)), + }), +) + +export const TodoRow = S.Struct({ + id: Uuid, + text: S.String, + done: Done, + position: S.Int, + version: S.Int, + createdAt: S.Int, +}) + +export const TodoDirection = S.Literals(['up', 'down']) +export type TodoDirection = S.Schema.Type + +export class TodoNotFound extends S.TaggedError()('TodoNotFound', { + id: S.String, +}) { + override get message(): string { + return `There is no todo ${this.id}.` + } +} + +export class TodoVersionConflict + extends S.TaggedError()('TodoVersionConflict', { + id: S.String, + expected: S.Int, + actual: S.Int, + }) +{ + override get message(): string { + return `Todo ${this.id} changed after you read it (you saw version ${this.expected}, it is now ${this.actual}); reload and try again.` + } +} + +export class TodoNotMovable + extends S.TaggedError()('TodoNotMovable', { + id: S.String, + edge: S.Literals(['top', 'bottom']), + }) +{ + override get message(): string { + return `Todo ${this.id} is already at the ${this.edge} of the list.` + } +} + +export class TodoTextMissing + extends S.TaggedError()('TodoTextMissing', {}) +{ + override get message(): string { + return 'Write what the todo is.' + } +} + +export class TodoTextTooLong + extends S.TaggedError()('TodoTextTooLong', {}) +{ + override get message(): string { + return 'That todo is too long.' + } +} + +export class TodoRateLimited + extends S.TaggedError()('TodoRateLimited', { + limit: S.Int, + }) +{ + override get message(): string { + return `You can add ${this.limit} todos a minute; wait a moment and try again.` + } +} + +export class TodoStoreUnavailable extends S.TaggedError()( + 'TodoStoreUnavailable', + { detail: S.String }, +) { + override get message(): string { + return `The todo store is unavailable: ${this.detail}` + } +} + +export class TodosRead + extends S.TaggedClass()('TodosRead', { todos: Todos }) +{} + +export class TodoFound + extends S.TaggedClass()('TodoFound', { todo: Todo }) +{} + +export class TodoMissing + extends S.TaggedClass()('TodoMissing', { id: S.String }) +{} + +export class TodoStoreFailed + extends S.TaggedClass()('TodoStoreFailed', { detail: S.String }) +{} + +export const ListTodosRequest = S.Struct({ credential: TodoCredential }) +export const ListTodosResponse = S.Array(Todo) +export const ListTodosRefusal = TodoStoreUnavailable +export type ListTodosRefusal = S.Schema.Type + +export const AddTodoRequest = S.Struct({ credential: TodoCredential, text: S.String }) +export const AddTodoResponse = S.Struct({ todo: Todo }) +export const AddTodoRefusal = S.Union([TodoTextMissing, TodoTextTooLong, TodoRateLimited, TodoStoreUnavailable]) +export type AddTodoRefusal = S.Schema.Type + +export const CompleteTodoRequest = S.Struct({ credential: TodoCredential, id: Uuid, version: S.Int, done: S.Boolean }) +export const CompleteTodoResponse = S.Struct({ todo: Todo }) +export const CompleteTodoRefusal = S.Union([TodoNotFound, TodoVersionConflict, TodoStoreUnavailable]) +export type CompleteTodoRefusal = S.Schema.Type + +export const RenameTodoRequest = S.Struct({ credential: TodoCredential, id: Uuid, version: S.Int, text: S.String }) +export const RenameTodoResponse = S.Struct({ todo: Todo }) +export const RenameTodoRefusal = S.Union([ + TodoTextMissing, + TodoTextTooLong, + TodoNotFound, + TodoVersionConflict, + TodoStoreUnavailable, +]) +export type RenameTodoRefusal = S.Schema.Type + +export const ReorderTodoRequest = S.Struct({ + credential: TodoCredential, + id: Uuid, + version: S.Int, + direction: TodoDirection, +}) +export const ReorderTodoResponse = S.Struct({ todos: Todos }) +export const ReorderTodoRefusal = S.Union([TodoNotFound, TodoVersionConflict, TodoNotMovable, TodoStoreUnavailable]) +export type ReorderTodoRefusal = S.Schema.Type + +export const RemoveTodoRequest = S.Struct({ credential: TodoCredential, id: Uuid, version: S.Int }) +export const RemoveTodoResponse = S.Struct({ todo: Todo }) +export const RemoveTodoRefusal = S.Union([TodoNotFound, TodoVersionConflict, TodoStoreUnavailable]) +export type RemoveTodoRefusal = S.Schema.Type diff --git a/apps/site/src/routes/todo.tsx b/apps/site/src/routes/todo.tsx new file mode 100644 index 000000000..492bd8190 --- /dev/null +++ b/apps/site/src/routes/todo.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +import { TodoPage } from '../features/todo/todo-page' + +export const Route = createFileRoute('/todo')({ + component: TodoPage, + head: () => ({ + links: [{ rel: 'stylesheet', href: '/todo.css' }], + meta: [{ title: 'Todos' }], + }), +}) diff --git a/apps/site/src/worker.ts b/apps/site/src/worker.ts index 4c970f21f..d393fa002 100644 --- a/apps/site/src/worker.ts +++ b/apps/site/src/worker.ts @@ -2,15 +2,21 @@ import startHandler from '@tanstack/react-start/server-entry' import { env } from 'cloudflare:workers' import * as Effect from 'effect/Effect' import { HttpRouter } from 'effect/http' +import * as Match from 'effect/Match' import * as S from 'effect/Schema' +import { SITE_MCP_PATH, SiteMcpLive } from './api/site-mcp-server' import { SiteRpcLive } from './api/site-rpc-server' import { SITE_RPC_PATH } from './api/site-rpcs' import { contentSecurityPolicyOf, CspNonce } from './csp/content-security-policy.schema' +import todoCss from './features/todo/todo.css?raw' const siteRpc = HttpRouter.toWebHandler(SiteRpcLive) +const siteMcp = HttpRouter.toWebHandler(SiteMcpLive) const isRpcRequest = (pathname: string): boolean => pathname === SITE_RPC_PATH +const isMcpRequest = (pathname: string): boolean => pathname === SITE_MCP_PATH +const isStyleRequest = (pathname: string): boolean => pathname === '/todo.css' const isAppRequest = (pathname: string): boolean => pathname === '/app' || pathname.startsWith('/app/') const drawNonce = (random: Crypto) => @@ -36,8 +42,16 @@ const appResponse = (request: Request): Promise => { return env.ASSETS.fetch(new Request(url, request)) } +const styleResponse = (): Promise => + Promise.resolve(new Response(todoCss, { headers: { 'content-type': 'text/css; charset=utf-8' } })) + const siteResponse = (request: Request, pathname: string): Promise => - isRpcRequest(pathname) ? siteRpc.handler(request) : Effect.runPromise(serve(request, globalThis.crypto)) + Match.value(pathname).pipe( + Match.when(isRpcRequest, () => siteRpc.handler(request)), + Match.when(isMcpRequest, () => siteMcp.handler(request)), + Match.when(isStyleRequest, () => styleResponse()), + Match.orElse(() => Effect.runPromise(serve(request, globalThis.crypto))), + ) export default { fetch: (request: Request): Promise => { diff --git a/apps/site/tsconfig.json b/apps/site/tsconfig.json index d3a2ec71e..48d07aae4 100644 --- a/apps/site/tsconfig.json +++ b/apps/site/tsconfig.json @@ -15,6 +15,7 @@ }, "include": [ "src", + "fakes", "alchemy.run.ts" ] } diff --git a/tsconfig.base.json b/tsconfig.base.json index a098b44d4..666eca14c 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -6,6 +6,10 @@ // alternative. Drop this when @systemfsoftware/tsconfig carries the same opt-in. "extends": "@systemfsoftware/tsconfig/bundler/dom", "compilerOptions": { - "plugins": [{ "name": "@effect/language-service", "allowedUnstableApis": ["effect/http", "effect/rpc"] }] + "plugins": [{ + "name": "@effect/language-service", + "allowedUnstableApis": ["effect/http", "effect/rpc"], + "allowedExperimentalApis": ["effect/ai"] + }] } }