/** * 1103/09-06, 03-07. The `--with-create` slice of `pnpm create:feature`: the * paired backend scaffold's other two endpoints * (clean-architecture-backend-template scripts/new-feature.sh, * `__Feature__Controller.java.tmpl`): `POST /` answers 201 with the * new item in the Envelope, `GET //{id}` reads one. With them come a * detail page, a create form with the unknown-result handling, and tests that * answer with the backend's own bodies. The base templates in * `create-feature.ts` call into this file where the slice adds to one of * their files; the files only the slice has are rendered here whole. * * The backend generates a NOT_IDEMPOTENT create, which reads no * Idempotency-Key, so the default command is NEVER: no key, no resend. * `--keyed` is for a backend create made KEYED with its IdempotencyExecutor * (its docs/manual/05-idempotency.md). Like the rest of the command, nothing * here imports a sample feature. * * 1105/16-02. The backend scaffold facts copied here (name limit, error * codes, 201 and the endpoints, the check order behind refusedBeforeWrite) * and the path rule in create-feature.ts are listed with their backend * files in config/contracts/backend-contract-pin.json `scaffoldSources`; * `check:backend-contract-drift` says when one of those files changes. */ export type WriteSemantics = "NEVER" | "KEYED"; export type SliceRoute = Readonly<{ routeId: string; path: string; chunkId: string; moduleId: string; loadingSurface: string; }>; export type WriteSlice = Readonly<{ semantics: WriteSemantics; /** The detail route's path parameter. */ idParam: string; detail: SliceRoute; create: SliceRoute; getOperationId: string; createOperationId: string; /** The backend scaffold's `__FEATURE___INVALID` (400) and `_NOT_FOUND` (404). */ invalidCode: string; notFoundCode: string; }>; type SliceNames = Readonly<{ id: string; base: string; upper: string; pascal: string; camel: string; title: string; }>; type SliceShape = Readonly<{ names: SliceNames; routeId: string; apiPath: string; write: WriteSlice; }>; /** The backend aggregate's `NAME_MAX_LENGTH`; its create refuses a longer name. */ const BACKEND_NAME_MAX_LENGTH = 100; export function planWriteSlice( names: SliceNames, listPath: string, semantics: WriteSemantics, ): WriteSlice { const { base, camel, upper } = names; const route = (suffix: string, path: string): SliceRoute => Object.freeze({ routeId: `${upper}_${suffix.toUpperCase()}`, path, chunkId: `route-${base}-${suffix}`, moduleId: `${base}-${suffix}-page`, loadingSurface: `${base}-${suffix}`, }); return Object.freeze({ semantics, idParam: `${camel}Id`, // `items/` keeps the detail apart from the static `new` (01 6단계). detail: route("detail", `${listPath}/items/:${camel}Id`), create: route("create", `${listPath}/new`), getOperationId: `${upper}_GET_ITEM`, createOperationId: `${upper}_CREATE_ITEM`, invalidCode: `${upper}_INVALID`, notFoundCode: `${upper}_NOT_FOUND`, }); } export function writeSliceMessageKeys(names: SliceNames, slice: WriteSlice): string[] { const { camel } = names; return [ ...[slice.detail.routeId, slice.create.routeId].flatMap((routeId) => [ `route.${routeId}.navigation`, `route.${routeId}.title`, ]), `${camel}.list.create`, `${camel}.detail.titlePending`, `${camel}.detail.itemId`, `${camel}.form.title`, `${camel}.form.name`, `${camel}.form.save`, `${camel}.form.saving`, ]; } /** Route titles, ko-KR then en-US. The contract's `title` repeats ko-KR. */ export function writeSliceRouteTitles(names: SliceNames) { const { title } = names; return Object.freeze({ detail: Object.freeze({ ko: `${title} 상세`, en: `${title} detail` }), create: Object.freeze({ ko: `${title} 만들기`, en: `New ${title}` }), }); } // --------------------------------------------------------------------------- // Fragments the base templates insert. export function renderWriteRoutes({ names, write }: SliceShape): string { const titles = writeSliceRouteTitles(names); const entry = (route: SliceRoute, paramsSchema: string, title: string) => ` ${route.routeId}: Object.freeze({ routeId: "${route.routeId}", path: "${route.path}", paramsSchema: ${paramsSchema}, searchSchema: null, access: "session-required", loadingSurface: "${route.loadingSurface}", errorSurface: "feature-boundary", chunkId: "${route.chunkId}", title: "${title}", navigationLabel: null, navigationOrder: null, }), `; return ( entry(write.detail, `"${names.pascal}Params"`, titles.detail.ko) + entry(write.create, "null", titles.create.ko) ); } export function renderWriteRouteRuntimeContracts({ names, write }: SliceShape): string { const entry = (route: SliceRoute, paramsCodec: string) => ` ${route.routeId}: Object.freeze({ routeId: "${route.routeId}", moduleId: "${route.moduleId}", paramsCodec: "${paramsCodec}", searchCodec: "none", }), `; return entry(write.detail, `${names.pascal}Params`) + entry(write.create, "none"); } export function renderWriteSchemas({ names, write }: SliceShape): string { const { camel, pascal, upper } = names; return ` /** The backend aggregate's \`NAME_MAX_LENGTH\`. The request and the form share it. */ export const ${upper}_NAME_MAX_LENGTH = ${BACKEND_NAME_MAX_LENGTH}; /** * The detail route's params and the GET's input. The backend reads the id as * a canonical UUID and answers another text with 400 BAD_PARAMETER. */ export const ${camel}ParamsSchema = z .object({ ${write.idParam}: z.string().trim().min(1).max(120), }) .strict(); export type ${pascal}Params = z.output; /** * The backend's \`Create__Feature__HttpRequest\`. It has no bean validation: * the aggregate refuses a blank or longer name with 400 ${write.invalidCode}. */ export const ${camel}CreateCommandSchema = z .object({ name: z.string().min(1).max(${upper}_NAME_MAX_LENGTH), }) .strict(); export type ${pascal}CreateRequest = z.output; `; } export function renderWriteValidators({ names }: SliceShape): string { const { camel, pascal } = names; return ` ${pascal}Params: zodValidator("${pascal}Params", ${camel}ParamsSchema), ${pascal}ItemPayload: zodValidator("${pascal}ItemPayload", ${camel}ItemDtoSchema), ${pascal}CreateCommand: zodValidator("${pascal}CreateCommand", ${camel}CreateCommandSchema), `; } export function renderWriteMapper({ names }: SliceShape): string { const { pascal } = names; return ` export function map${pascal}Item( dto: ${pascal}ItemDto, ): BoundaryMappingResult<${pascal}ItemView> { return mappingSuccess(toView(dto)); } `; } export function renderWriteSchemaRows({ names }: SliceShape): string { const { pascal } = names; const row = ( schemaId: string, boundary: string, direction: string, unknownFieldPolicy: string, ) => ` ${schemaId}: Object.freeze({ schemaId: "${schemaId}", boundary: "${boundary}", owner: OWNER, runtime: "zod", schemaVersion: 1, direction: "${direction}", unknownFieldPolicy: "${unknownFieldPolicy}", }), `; return ( row(`${pascal}Params`, "route-params", "REQUEST", "REJECT_UNKNOWN") + row(`${pascal}ItemPayload`, "api-response", "RESPONSE", "STRIP_UNKNOWN") + row(`${pascal}CreateCommand`, "api-request", "REQUEST", "REJECT_UNKNOWN") ); } export function renderWriteDescriptors({ names, write }: SliceShape): string { const { base, pascal, upper } = names; const keyed = write.semantics === "KEYED"; const semantics = keyed ? ` // The backend create runs behind its IdempotencyExecutor // (http-contract.md §2): the same key replays, never applies twice. retrySemantics: "KEYED" as const,` : ` // new-feature.sh generates a NOT_IDEMPOTENT create: the backend reads no // Idempotency-Key and a second request creates a second item. Make the // backend create KEYED (its docs/manual/05-idempotency.md) before this. retrySemantics: "NEVER" as const,`; const recovery = keyed ? ` // The intent's key, which the executor sends as Idempotency-Key. Recorded // in FE-REG-API; the executor does not read it. commandRecovery: Object.freeze({ mode: "IDEMPOTENCY_REPLAY" as const, operationIdentityField: "idempotencyKey", }),` : ` commandRecovery: null,`; const budget = keyed ? ` // One automatic resend, with the same key, after 503 // IDEMPOTENCY_UNAVAILABLE (refused before the work ran). The app's // MAX_RETRY_ATTEMPTS caps it too. A lost response is never resent on its // own: the form offers the same-key resend. retryBudget: 1 as const,` : ` retryBudget: 0 as const,`; return ` /** * The paired backend's \`GET //{id}\`: the item in the Envelope, or * 404 ${write.notFoundCode}. */ export const ${write.getOperationId}_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "${write.getOperationId}", method: "GET" as const, pathTemplate: \`\${API_PATH}/{id}\`, inputValidator: ${upper}_VALIDATORS.${pascal}Params, outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload, problemValidator: ${upper}_VALIDATORS.${pascal}Problem, acceptedStatuses: Object.freeze([200]), emptyBodyStatuses: Object.freeze([]), retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, responseEnvelope: "ENVELOPE_V1" as const, commandRecovery: null, commandEffect: null, projectRequest(input: ${pascal}Params) { return Object.freeze({ pathValues: Object.freeze({ id: input.${write.idParam} }), queryEntries: Object.freeze([]), body: null, }); }, }), frontend: Object.freeze({ policyId: "${upper}_GET_V1", requestByteLimit: 0, responseByteLimit: 32_768, totalDeadlineMs: 10_000, retryBudget: 2 as const, authProfileId: "EXTERNAL_BEARER", diagnosticsOperation: "${base}.detail", }), }) satisfies InstalledHttpContract<${pascal}Params, ${pascal}ItemDto, ${pascal}Problem>; /** * 1103/03-01. Whether a failed create applied. The executor's backend table * decides 400, 409, 422 and the backend's own 5xx answers; \`classifyProblem\` * gets every other status. */ const ${upper}_CREATE_EFFECT: CommandEffectDescriptor<${pascal}Problem> = Object.freeze({ successEffect: "APPLIED_CONFIRMED" as const, classifyProblem: () => "MAYBE_APPLIED" as const, // The backend refuses these before the use case runs: 401 in the security // filter chain, 403 at the use case's @RequiresPermission proxy, 429 in the // rate-limit interceptor. Recheck if the use case asks AuthorizationPort // after it writes. classifyStatus: () => "NOT_APPLIED" as const, // CreateUseCase checks the name before its transaction. List a // code here only when the endpoint raises it before any write. refusedBeforeWrite: Object.freeze(["${write.invalidCode}"]), }); /** The paired backend's \`POST /\`: 201 with the new item in the Envelope. */ export const ${write.createOperationId}_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "${write.createOperationId}", method: "POST" as const, pathTemplate: API_PATH, inputValidator: ${upper}_VALIDATORS.${pascal}CreateCommand, outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload, problemValidator: ${upper}_VALIDATORS.${pascal}Problem, acceptedStatuses: Object.freeze([201]), emptyBodyStatuses: Object.freeze([]), ${semantics} requestBody: "JSON" as const, responseBody: "REQUIRED_JSON" as const, responseEnvelope: "ENVELOPE_V1" as const, ${recovery} commandEffect: ${upper}_CREATE_EFFECT, projectRequest(input: ${pascal}CreateRequest) { return Object.freeze({ pathValues: Object.freeze({}), queryEntries: Object.freeze([]), body: Object.freeze({ name: input.name }), }); }, }), frontend: Object.freeze({ policyId: "${upper}_CREATE_V1", requestByteLimit: 4_096, responseByteLimit: 32_768, totalDeadlineMs: 10_000, ${budget} authProfileId: "EXTERNAL_BEARER", diagnosticsOperation: "${base}.create", }), }) satisfies InstalledHttpContract<${pascal}CreateRequest, ${pascal}ItemDto, ${pascal}Problem>; `; } export function renderWriteMessages({ names, write }: SliceShape, locale: "ko" | "en"): string { const { camel } = names; const titles = writeSliceRouteTitles(names); const copy = locale === "ko" ? { create: "새 항목 만들기", titlePending: `${names.title} 항목`, itemId: "ID", formTitle: titles.create.ko, name: "이름", save: "저장", saving: "저장 중…", } : { create: "Create item", titlePending: `${names.title} item`, itemId: "ID", formTitle: titles.create.en, name: "Name", save: "Save", saving: "Saving…", }; return ` "route.${write.detail.routeId}.navigation": "${titles.detail[locale]}", "route.${write.detail.routeId}.title": "${titles.detail[locale]}", "route.${write.create.routeId}.navigation": "${titles.create[locale]}", "route.${write.create.routeId}.title": "${titles.create[locale]}", "${camel}.list.create": "${copy.create}", "${camel}.detail.titlePending": "${copy.titlePending}", "${camel}.detail.itemId": "${copy.itemId}", "${camel}.form.title": "${copy.formTitle}", "${camel}.form.name": "${copy.name}", "${camel}.form.save": "${copy.save}", "${camel}.form.saving": "${copy.saving}", `; } export function renderWriteGatewayOperations({ names, write }: SliceShape): string { const { pascal } = names; return ` ${write.getOperationId}: define${pascal}HttpOperation({ contract: ${write.getOperationId}_CONTRACT, routeId: "${write.detail.routeId}", mapSuccess: map${pascal}Item, }), ${write.createOperationId}: define${pascal}HttpOperation({ contract: ${write.createOperationId}_CONTRACT, routeId: "${write.create.routeId}", mapSuccess: map${pascal}Item, // The scaffold aggregate has one rule, on the name: show the backend's // refusal on that field. Map each field the aggregate grows. mapProblem: (problem) => problem.code === "${write.invalidCode}" ? Object.freeze({ kind: "VALIDATION_REJECTED" as const, code: problem.code, validationIssues: Object.freeze([Object.freeze({ path: "name", code: "INVALID" })]), }) : undefined, }), `; } export function renderWriteGatewayMethods({ write }: SliceShape): string { return ` get(${write.idParam}, context) { return http.execute("${write.getOperationId}", Object.freeze({ ${write.idParam} }), context); }, create(command, context) { return http.execute("${write.createOperationId}", command, context); }, `; } // --------------------------------------------------------------------------- // Files only the slice has. export function renderRouteCodecs({ names }: SliceShape): string { const { base, camel, pascal, upper } = names; return `import { ${camel}ParamsSchema } from "../contracts/${base}-schemas.ts"; /** * The route codecs, keyed by the codec ids \`routeRuntimeContracts\` names. * They load with the context routes (\`context-routes.ts\` puts them on each * handle), not with the declaration in the initial chunk. */ export const ${upper}_ROUTE_CODECS = { ${pascal}Params: ${camel}ParamsSchema, } as const; `; } export function renderUseItem({ names }: SliceShape): string { const { base, pascal, upper } = names; return `import { bindQuery, type QueryResultMeasure } from "../../../contracts/server-state.ts"; import { useApplicationQuery } from "../../../presentation/adapters/query/application-query.ts"; import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx"; import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx"; import { ${upper}_FEATURE_ID, ${upper}_ITEM_QUERY_NAMESPACE, } from "../contracts/${base}-feature-contract.ts"; import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; const UTF8 = new TextEncoder(); function measureItem(item: ${pascal}ItemView): QueryResultMeasure { return { itemCount: 1, estimatedBytes: UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16, }; } /** One item. A save of this feature invalidates its namespace, so a new item shows. */ export function use${pascal}Item(itemId: string) { const input = useApplicationFeature(${upper}_FEATURE_ID); const scope = useServerStateScope(); return useApplicationQuery( bindQuery( { definitionId: "${base}-item-detail-v1", definitionVersion: 1, namespace: ${upper}_ITEM_QUERY_NAMESPACE, profileId: "DETAIL_STANDARD", measureResult: measureItem, execute: (selected: string, { signal }) => input.getItem(selected, { signal }), }, itemId, scope, ), ); } `; } export function renderUseCreate({ names, write }: SliceShape): string { const { base, pascal, upper } = names; return `import { commandMutationIdentity, type BoundMutation, } from "../../../contracts/server-state.ts"; import { useApplicationMutation } from "../../../presentation/adapters/query/application-query.ts"; import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx"; import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx"; import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; import { ${write.createOperationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts"; import { ${upper}_FEATURE_ID, ${upper}_ITEM_INVALIDATION_TOPIC, } from "../contracts/${base}-feature-contract.ts"; import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; /** * 1103/16-05. The operation id and whether the intent carries an * idempotency key are the descriptor's. A second save while one runs is * refused, and a saved item invalidates the list and the detail. */ const ${upper}_CREATE_MUTATION_POLICY = Object.freeze({ definitionId: "${base}-create-v1", definitionVersion: 1, ...commandMutationIdentity(${write.createOperationId}_CONTRACT), duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, invalidate: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]), }); export function use${pascal}Create() { const input = useApplicationFeature(${upper}_FEATURE_ID); const scope = useServerStateScope(); const mutation: BoundMutation<${pascal}CreateCommand, ${pascal}ItemView> = Object.freeze({ ...${upper}_CREATE_MUTATION_POLICY, scope, execute: input.createItem, }); return useApplicationMutation(mutation); } `; } export function renderForm({ names }: SliceShape): string { const { base, camel, pascal, upper } = names; return `import { z } from "../../../contracts/zod.ts"; import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; import { ${upper}_NAME_MAX_LENGTH } from "../contracts/${base}-schemas.ts"; /** What the user types. The length comes from the request schema's constant. */ export const ${camel}FormSchema = z .object({ name: z.string().trim().min(1).max(${upper}_NAME_MAX_LENGTH), }) .strict(); export type ${pascal}FormValues = z.infer; export const ${upper}_FORM_DEFAULTS: ${pascal}FormValues = Object.freeze({ name: "" }); export function to${pascal}CreateCommand(values: ${pascal}FormValues): ${pascal}CreateCommand { return Object.freeze({ name: values.name }); } `; } export function renderDetailPage({ names, routeId }: SliceShape): string { const { base, camel, pascal } = names; return `import { Link } from "react-router-dom"; import { AsyncSurface, DetailPage, } from "../../../presentation/design-system/index.ts"; import { useLocale } from "../../../presentation/i18n/index.ts"; import { ${camel}RouteUrl, use${pascal}ItemId } from "./${base}-routes.ts"; import { use${pascal}Item } from "./use-${base}-item.ts"; /** The heading stays while the item loads or fails, so the page always has an h1. */ export default function ${pascal}DetailPage() { const { message } = useLocale(); const itemId = use${pascal}ItemId(); const query = use${pascal}Item(itemId); const item = query.data; return ( {message("${camel}.list.title")}} heading={{ title: item?.name ?? message("${camel}.detail.titlePending") }} metadata={ item ? (
{message("${camel}.detail.itemId")}
{item.itemId}
) : null } feedback={} /> ); } `; } export function renderCreatePage({ names, routeId, write }: SliceShape): string { const { base, camel, pascal, upper } = names; return `import { useCallback } from "react"; import { Link, useNavigate } from "react-router-dom"; import type { Result } from "../../../contracts/result.ts"; import { AsyncSurface, Button, DirtyNavigationDialog, ErrorSummary, Form, FormActions, FormFailureStatus, FormField, FormPage, useAppForm, useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; import { useLocale } from "../../../presentation/i18n/index.ts"; import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; import { ${upper}_FORM_DEFAULTS, ${camel}FormSchema, to${pascal}CreateCommand, type ${pascal}FormValues, } from "./${base}-form.ts"; import { ${camel}RouteUrl } from "./${base}-routes.ts"; import { use${pascal}Create } from "./use-${base}-create.ts"; /** * The create form. A saved item opens its detail page. The backend's refusal * of the name (400 ${write.invalidCode}, refused before the write) shows on * the field and the form saves again. A save whose result is unknown (the * response was lost) keeps the form: the user checks, or, for a KEYED * command, resends the same request with the same key. */ export default function ${pascal}CreatePage() { const navigate = useNavigate(); const { message } = useLocale(); const fieldLabels = { name: message("${camel}.form.name"), } satisfies Record; const mutation = use${pascal}Create(); const openSaved = useCallback( (outcome: Result<${pascal}ItemView> | null) => { if (outcome?.ok) { void navigate( ${camel}RouteUrl("${write.detail.routeId}", { params: { ${write.idParam}: outcome.value.itemId }, }), ); } return outcome; }, [navigate], ); const submit = useCallback( async (command: ${pascal}CreateCommand) => { const outcome = await mutation.submit(command); openSaved(outcome); return outcome; }, [mutation, openSaved], ); const form = useAppForm({ schema: ${camel}FormSchema, defaultValues: ${upper}_FORM_DEFAULTS, allowedServerFields: ["name"], mapToCommand: to${pascal}CreateCommand, submit, }); const effectUnknown = mutation.state.indicator === "mutation-effect-unknown"; const blocked = effectUnknown || mutation.state.indicator === "mutation-pending"; const guard = useDirtyNavigationGuard(form.dirty && !form.pending); return (
{ if (blocked) { event.preventDefault(); return; } void form.submitForm(event); }} > {message("${camel}.list.title")}} heading={{ title: message("${camel}.form.title") }} errorSummary={ } fields={ } formActions={ {/* Busy, not disabled, while saving: a disabled button drops keyboard focus (1103/08-02). */} } feedback={ form.failure ? ( void form.submitForm() : undefined} /> ) : effectUnknown ? ( { void mutation.reconcileUnknownEffect(resolution).then(form.settleApplied); }} // Drawn only for a request with a key (a KEYED command). onResendUnknownEffect={() => { void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect())); }} /> ) : null } guard={} /> ); } `; } export function renderCreatePageTest({ names, apiPath, write }: SliceShape): string { const { base, camel, upper } = names; const keyed = write.semantics === "KEYED"; const unknownTest = keyed ? ` // KEYED: the key is kept, and the resend carries it, so the backend's // IdempotencyExecutor replays the first request instead of applying twice. it("resends a create whose response was lost with the same key", async () => { const posts = answerCreate(() => HttpResponse.error()); const user = await openForm(); await user.type(await nameField(), "First item"); await user.click(saveButton()); expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); expect(saveButton()).toBeDisabled(); answerCreate(() => created(), posts); answerItem(); await user.click(screen.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] })); expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); expect(posts).toHaveLength(2); expect(posts[0]!.headers.get("idempotency-key")).toMatch(/^[\\x21-\\x7e]+$/u); expect(posts[1]!.headers.get("idempotency-key")).toBe(posts[0]!.headers.get("idempotency-key")); });` : ` // NEVER: the backend scaffold's create reads no key, so a resend would be a // second, unprotected create. The form keeps the unknown result and offers // no resend; the user checks the list. it("keeps a create whose response was lost unknown and offers no resend", async () => { const posts = answerCreate(() => HttpResponse.error()); const user = await openForm(); await user.type(await nameField(), "First item"); await user.click(saveButton()); expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); expect( screen.queryByRole("button", { name: KO_MESSAGES["action.resendMutation"] }), ).toBeNull(); expect(saveButton()).toBeDisabled(); expect(posts).toHaveLength(1); expect(posts[0]!.headers.get("idempotency-key")).toBeNull(); });`; return `// @vitest-environment jsdom import { screen } from "@testing-library/react"; import { http, HttpResponse, type JsonBodyType } from "msw"; import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { ${upper}_MESSAGE_CATALOGS } from "../../../src/features/${names.id}/contracts/${base}-message-catalog.ts"; import { ${camel}RouteUrl } from "../../../src/features/${names.id}/presentation/${base}-routes.ts"; import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; import { API, openSignedIn } from "./${base}-test-app.tsx"; const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"]; const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f"; const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" }; const api = setupServer(); beforeAll(() => api.listen({ onUnhandledRequest: "error" })); afterEach(() => api.resetHandlers()); afterAll(() => api.close()); /** * The paired backend's answers, written out (new-feature.sh's controller and * http-contract.md §1), not taken from the shared scenarios: a descriptor * that stops reading this wire fails here. */ function created() { return HttpResponse.json( { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }, { status: 201, headers: { Location: \`\${API}${apiPath}/\${ITEM_ID}\` } }, ); } function refusedName() { return HttpResponse.json( { success: false, error: { code: "${write.invalidCode}", category: "VALIDATION", message: "backend message", retryable: false, }, meta: META, }, { status: 400 }, ); } /** Answers POST ${apiPath} and keeps a copy of each request it receives. */ function answerCreate(respond: () => Response, posts: Request[] = []) { api.use( http.post(\`\${API}${apiPath}\`, ({ request }) => { posts.push(request.clone()); return respond(); }), ); return posts; } function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) { api.use( http.get(\`\${API}${apiPath}/:id\`, () => HttpResponse.json({ success: true, data: body, meta: META }), ), ); } async function openForm() { const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}")); expect( await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.form.title"] }), ).toBeVisible(); return user; } // The label also holds the required mark, so the name is matched, not equal. const nameField = () => screen.findByRole("textbox", { name: new RegExp(MESSAGES["${camel}.form.name"], "u") }); const saveButton = () => screen.getByRole("button", { name: MESSAGES["${camel}.form.save"] }); describe("${names.id} create form on the paired backend", () => { it("saves a new item and opens it", async () => { const posts = answerCreate(created); answerItem(); const user = await openForm(); await user.type(await nameField(), " First item "); await user.click(saveButton()); expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); expect(await posts[0]!.json()).toEqual({ name: "First item" }); }); // 1103/03-01. refusedBeforeWrite makes this NOT_APPLIED, so the form takes // the next save instead of holding an unknown result. it("shows the backend's refusal of the name on the field and saves again", async () => { const posts = answerCreate(refusedName); const user = await openForm(); await user.type(await nameField(), "Refused name"); await user.click(saveButton()); expect(await screen.findAllByText(KO_MESSAGES["form.validation.invalid"])).not.toHaveLength(0); expect(await nameField()).toHaveAttribute("aria-invalid", "true"); expect(saveButton()).toBeEnabled(); answerCreate(created, posts); answerItem(); await user.clear(await nameField()); await user.type(await nameField(), "First item"); await user.click(saveButton()); expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); expect(posts).toHaveLength(2); }); ${unknownTest} }); `; } /** The gateway test cases of the slice, inside the base gateway test's describe. */ export function renderWriteGatewayTests({ names, apiPath, write }: SliceShape): string { const keyed = write.semantics === "KEYED"; const keyCases = keyed ? ` // http-contract.md §2: refused before the work ran, to be resent with the // same key. The only answer the executor resends on its own (retryBudget 1). it("sends the intent's key, and resends once with it after 503 IDEMPOTENCY_UNAVAILABLE", async () => { const keys = answerCreate(201, CREATED_BODY); // Registered last, so it answers first, once. answerCreate(503, failure("IDEMPOTENCY_UNAVAILABLE", undefined, "TRANSIENT_DEPENDENCY"), keys, true); await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({ ok: true, value: { itemId: ITEM_ID, name: "First item" }, }); expect(keys).toEqual(["key-1", "key-1"]); }); // http-contract.md §2: the first request with this key still runs. The // result is unknown; the form resends it later with the same key, the // executor never does on its own. it("leaves 409 IDEMPOTENT_IN_FLIGHT maybe applied and does not resend it", async () => { const keys = answerCreate(409, failure("IDEMPOTENT_IN_FLIGHT", undefined, "CONFLICT")); await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({ ok: false, error: { code: "IDEMPOTENT_IN_FLIGHT", effect: "MAYBE_APPLIED" }, }); expect(keys).toEqual(["key-1"]); }); it("refuses a create without the intent's key before sending", async () => { const keys = answerCreate(201, CREATED_BODY); await expect(gateway().create({ name: "First item" }, {} as never)).resolves.toMatchObject({ ok: false, }); expect(keys).toEqual([]); });` : ` it("sends no idempotency key: the backend scaffold's create reads none", async () => { const keys = answerCreate(201, CREATED_BODY); await gateway().create({ name: "First item" }, { intent: INTENT }); expect(keys).toEqual([null]); });`; return ` it("reads one item, and the backend's not-found code", async () => { api.use( http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () => HttpResponse.json({ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }), ), ); await expect(gateway().get(ITEM_ID)).resolves.toEqual({ ok: true, value: { itemId: ITEM_ID, name: "First item" }, }); api.use( http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () => HttpResponse.json(failure("${write.notFoundCode}", undefined, "NOT_FOUND"), { status: 404 }), ), ); await expect(gateway().get(ITEM_ID)).resolves.toMatchObject({ ok: false, error: { kind: "NOT_FOUND", code: "${write.notFoundCode}", httpStatus: 404 }, }); }); it("reads the 201 Envelope of a create", async () => { answerCreate(201, CREATED_BODY); await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({ ok: true, value: { itemId: ITEM_ID, name: "First item" }, }); }); // 1103/03-01. Declared in refusedBeforeWrite: not applied, shown on the field. it("reads 400 ${write.invalidCode} as not applied, on the name field", async () => { answerCreate(400, failure("${write.invalidCode}")); await expect(gateway().create({ name: "Refused" }, { intent: INTENT })).resolves.toMatchObject({ ok: false, error: { kind: "VALIDATION_REJECTED", code: "${write.invalidCode}", effect: "NOT_APPLIED", validationIssues: [{ path: "name", code: "INVALID" }], }, }); }); it("leaves a create whose response was lost maybe applied, and does not resend it", async () => { const keys: (string | null)[] = []; api.use( http.post(\`\${API}${apiPath}\`, ({ request }) => { keys.push(request.headers.get("idempotency-key")); return HttpResponse.error(); }), ); await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({ ok: false, error: { effect: "MAYBE_APPLIED" }, }); expect(keys).toHaveLength(1); }); ${keyCases} `; } /** The slice's helpers for the gateway test, after its own. */ export function renderWriteGatewayHelpers({ apiPath, write }: SliceShape): string { const key = write.semantics === "KEYED" ? ` idempotencyKey: "key-1",` : ""; return ` const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f"; const CREATED_BODY = { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }; const INTENT = defineMutationIntent({ intentId: "intent-1", operationId: "${write.createOperationId}", canonicalInputIdentity: "create-1",${key} createdAtMonotonicMs: 0, }); /** * Answers POST ${apiPath} and records the Idempotency-Key each request * carried (\`null\` when none). The handler registered last answers first. */ function answerCreate( status: number, body: JsonBodyType, keys: (string | null)[] = [], once = false, ) { api.use( http.post( \`\${API}${apiPath}\`, ({ request }) => { keys.push(request.headers.get("idempotency-key")); return HttpResponse.json(body, { status }); }, { once }, ), ); return keys; } `; }