diff --git a/config/ci/contract-baseline.json b/config/ci/contract-baseline.json index 03dba892..66397689 100644 --- a/config/ci/contract-baseline.json +++ b/config/ci/contract-baseline.json @@ -1,11 +1,11 @@ { "schemaVersion": 1, "owner": "frontend-platform", - "reason": "1101/13-01: FE-GATE-019 checks the promoted archive with --release-root instead of rebuilding, and the deployment slot job sits between promotion and production_gate", + "reason": "U7: FE-GATE-020 runs test:feature-scaffold, which creates a feature with create:feature in a copy and runs the merge gates on it", "gates": 27, - "commands": 98, - "commandReferences": 102, - "artifacts": 109, + "commands": 99, + "commandReferences": 103, + "artifacts": 110, "stages": 5, - "gateShapeSha256": "0a47c3b11f4cb03cc9b3fbb5595ea16b3c45ae042aabe0ab27bf0a62141c6699" + "gateShapeSha256": "02e87e35b87fbc5114af7e1b1ce1ec030062c60ae8bd03c151f1ec9538f2db3b" } diff --git a/config/ci/gates.json b/config/ci/gates.json index 8ebd79e6..4dfb4a39 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -517,6 +517,11 @@ "script": "test:sample-removal", "expect": "pass" }, + { + "id": "test-feature-scaffold", + "script": "test:feature-scaffold", + "expect": "pass" + }, { "id": "test-optional-recipe-removal", "script": "test:optional-recipe-removal", @@ -1604,6 +1609,15 @@ "test-sample-removal" ] }, + { + "id": "artifact-artifacts-tests-feature-scaffold-xml", + "path": "artifacts/tests/feature-scaffold.xml", + "schemaId": "junit", + "production": "command-generated", + "producerCommandIds": [ + "test-feature-scaffold" + ] + }, { "id": "artifact-artifacts-tests-optional-recipe-removal-xml", "path": "artifacts/tests/optional-recipe-removal.xml", @@ -2094,6 +2108,7 @@ "name": "removability", "commandIds": [ "test-sample-removal", + "test-feature-scaffold", "test-optional-recipe-removal", "test-browser-file-storage-removal", "test-realtime-removal" @@ -2101,6 +2116,7 @@ "logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-020-txt", "evidenceArtifactIds": [ "artifact-artifacts-tests-sample-removal-xml", + "artifact-artifacts-tests-feature-scaffold-xml", "artifact-artifacts-tests-optional-recipe-removal-xml", "artifact-artifacts-tests-browser-file-storage-runtime-removal-xml", "artifact-artifacts-tests-realtime-runtime-removal-xml" diff --git a/package.json b/package.json index 4ee15624..f0cf9a37 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "test:a11y": "node scripts/generate-product-feature-index.ts && playwright test --grep @a11y && node scripts/write-a11y-report.ts", "review:a11y-manual": "node scripts/generate-product-feature-index.ts && node scripts/verify-a11y-manual.ts", "test:sample-removal": "node scripts/generate-product-feature-index.ts && node scripts/test-sample-removal.ts", + "test:feature-scaffold": "node scripts/generate-product-feature-index.ts && node scripts/test-feature-scaffold.ts", "test:optional-recipe-removal": "node scripts/test-optional-recipe-removal.ts", "test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts", "test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts", @@ -130,6 +131,7 @@ "check:types:fixture:feature-capability-selection": "tsc -p tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", "check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json", "generate:feature-index": "node scripts/generate-product-feature-index.ts", + "create:feature": "node scripts/generate-product-feature-index.ts && node scripts/create-feature.ts", "check:feature-index": "node scripts/generate-product-feature-index.ts --check", "check:topology": "node scripts/run-vitest.ts run tests/architecture/topology-cardinality.test.ts tests/architecture/context-lazy-loading.test.ts tests/platform/cardinality tests/platform/routing --reporter=default", "check:traffic": "node scripts/run-vitest.ts run tests/platform/execution tests/platform/traffic tests/platform/resilience --reporter=default", diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts new file mode 100644 index 00000000..f31a91b4 --- /dev/null +++ b/scripts/create-feature.ts @@ -0,0 +1,1408 @@ +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { access, mkdir, readdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +import { + composeContractContributions, + ContractContributionError, +} from "../src/contracts/external-contract-runtime.ts"; +import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; + +/** + * U7. `pnpm create:feature ` writes the smallest feature that passes every + * merge gate: one list route without params, one GET (SAFE, EXTERNAL_BEARER), + * one query, one invalidation topic, one CollectionPage with ko-KR and en-US + * copy, and a router page test plus an input test. The templates live in this + * file and import nothing from a sample feature, so the command keeps working + * after a product deletes the sample (test:sample-removal runs it there). + * + * Every global id carries the feature prefix (review 16, 8.3): a copied id + * collides in a registry that is global. The invalidation topic is random. + * Outside the feature folder it writes only the context declaration (for a + * new context) and the route's pending accessibility record; it never + * overwrites a file, and a failed run leaves nothing behind. + */ + +export type InstalledFacts = Readonly<{ + appIds: readonly string[]; + /** Declared feature ids and every src/features directory name. */ + featureIds: readonly string[]; + contexts: readonly Readonly<{ id: string; routePath: string }>[]; + contextDirectories: readonly string[]; + routes: readonly Readonly<{ + routeId: string; + path: string; + chunkId: string; + navigationOrder: number | null; + }>[]; + topics: readonly string[]; + messageKeys: readonly string[]; +}>; + +export type ContractPackageIdentity = Readonly<{ + packageId: string; + version: string; + digest: string; + sourceRevision: string; +}>; + +export type FeatureRequest = Readonly<{ + id: string; + context?: string | undefined; + contractPackage?: ContractPackageIdentity | undefined; +}>; + +export type FeaturePlan = Readonly<{ + id: string; + contextId: string; + newContext: boolean; + routeId: string; + routePath: string; + topic: string; + /** No package was given; the placeholder identity is pinned. */ + placeholder: boolean; + /** Repository-relative path -> content. */ + files: ReadonlyMap; +}>; + +export class CreateFeatureError extends Error {} + +const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u; +/** Telemetry kinds allow 40 characters per segment; the base is one. */ +const MAX_ID_LENGTH = 40; +const TOPIC_SUFFIX = /^[0-9a-z]{26}$/u; +/** Crockford base32, lower case: 32 symbols, so `byte & 31` has no bias. */ +const TOPIC_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"; +const NEW_CONTEXT_MAX_FEATURES = 20; +const NAVIGATION_STEP = 10; + +export function randomTopicSuffix(): string { + return [...randomBytes(26)] + .map((byte) => TOPIC_ALPHABET[byte & 31]) + .join(""); +} + +function baseOf(id: string): string { + return id.endsWith("-feature") && id !== "feature" + ? id.slice(0, -"-feature".length) + : id; +} + +function namesOf(id: string) { + const base = baseOf(id); + const pascal = base + .split("-") + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(""); + return Object.freeze({ + id, + base, + upper: base.toUpperCase().replaceAll("-", "_"), + pascal, + camel: pascal.charAt(0).toLowerCase() + pascal.slice(1), + title: base.charAt(0).toUpperCase() + base.slice(1).replaceAll("-", " "), + }); +} + +type Names = ReturnType; + +function fail(message: string): never { + throw new CreateFeatureError(message); +} + +function assertKebab(value: string, label: string, maxLength: number): void { + if (!KEBAB.test(value) || value.length > maxLength) { + fail( + `${label} "${value}" must be kebab-case (lower-case words joined by single hyphens), at most ${maxLength} characters`, + ); + } +} + +function assertPackageIdentity( + featureId: string, + identity: ContractPackageIdentity, +): void { + try { + composeContractContributions([ + { + contributionId: "create-feature-check", + featureId, + source: { + kind: "EXTERNAL_PACKAGE", + package: { + ...identity, + digest: identity.digest as `sha256:${string}`, + runtimeProtocolVersion: 1, + }, + }, + http: [], + events: [], + }, + ]); + } catch (error) { + fail( + `contract package ${identity.packageId}@${identity.version} is not a pinned identity: ${ + error instanceof ContractContributionError ? error.reason : String(error) + }`, + ); + } +} + +/** The routes, files and ids of one feature. Pure apart from the topic. */ +export function planFeature( + request: FeatureRequest, + installed: InstalledFacts, + topicSuffix: () => string = randomTopicSuffix, +): FeaturePlan { + const { id } = request; + assertKebab(id, "feature id", MAX_ID_LENGTH); + const names = namesOf(id); + const contextIds = new Set([ + ...installed.contexts.map((context) => context.id), + ...installed.contextDirectories, + ]); + if (installed.featureIds.includes(id) || contextIds.has(id)) { + fail(`feature id ${id} is already a feature or context`); + } + const sameBase = installed.featureIds.find( + (featureId) => baseOf(featureId) === names.base, + ); + if (sameBase !== undefined) { + fail( + `feature id ${id} would prefix its ids with "${names.base}", which ${sameBase} already uses`, + ); + } + + const contextId = request.context ?? `${names.base}-context`; + assertKebab(contextId, "context id", 64); + if (installed.featureIds.includes(contextId)) { + fail(`context id ${contextId} is a feature id`); + } + const existing = installed.contexts.find((context) => context.id === contextId); + if (request.context === undefined && contextIds.has(contextId)) { + fail( + `context ${contextId} already exists; pass --context ${contextId} to add the feature to it`, + ); + } + if (existing === undefined && contextIds.has(contextId)) { + fail(`src/contexts has a ${contextId} directory without a context declaration`); + } + const contextRoot = existing + ? existing.routePath.replace(/\/?\*$/u, "") + : contextId.replace(/-context$/u, ""); + if ( + existing === undefined && + installed.contexts.some((context) => context.routePath === `${contextRoot}/*`) + ) { + fail(`another context already owns the route root ${contextRoot}/*`); + } + if (existing === undefined && installed.appIds.length !== 1) { + fail( + `a new context needs exactly one deployable app (declared: ${installed.appIds.join(", ") || "none"}); pass --context `, + ); + } + // A new context gives the feature its root; in an existing one the feature + // takes a segment below the root. + const routePath = existing ? `/${contextRoot}/${names.base}` : `/${contextRoot}`; + const routeId = `${names.upper}_LIST`; + const chunkId = `route-${names.base}-list`; + for (const route of installed.routes) { + if (route.routeId === routeId || route.path === routePath || route.chunkId === chunkId) { + fail( + `route ${routeId} (${routePath}, ${chunkId}) collides with installed route ${route.routeId} (${route.path}, ${route.chunkId})`, + ); + } + } + const messageKeys = [ + `route.${routeId}.navigation`, + `route.${routeId}.title`, + `${names.camel}.list.title`, + `${names.camel}.list.description`, + `${names.camel}.list.resultCount`, + `${names.camel}.list.items`, + ]; + const takenKeys = messageKeys.filter((key) => installed.messageKeys.includes(key)); + if (takenKeys.length > 0) { + fail(`message keys already exist: ${takenKeys.join(", ")}`); + } + + const suffix = topicSuffix(); + const topic = `qinv.${suffix}`; + if (!TOPIC_SUFFIX.test(suffix)) fail(`invalid generated topic ${topic}`); + if (installed.topics.includes(topic)) { + fail(`generated topic ${topic} is already installed; run the command again`); + } + if (request.contractPackage) assertPackageIdentity(id, request.contractPackage); + + const navigationOrder = + Math.max( + 0, + ...installed.routes.flatMap((route) => + route.navigationOrder === null ? [] : [route.navigationOrder], + ), + ) + NAVIGATION_STEP; + const appId = installed.appIds[0] ?? ""; + const shape: Shape = Object.freeze({ + names, + contextId, + routeId, + routePath, + chunkId, + navigationOrder, + topic, + operationId: `${names.upper}_LIST_ITEMS`, + apiPath: `/api/${names.base}-items`, + owner: `feature-frontend-${id}`, + contractPackage: request.contractPackage ?? null, + }); + + const feature = `src/features/${id}`; + const { base } = names; + const files = new Map([ + ...(existing + ? [] + : ([ + [ + `src/contexts/${contextId}/context-module.ts`, + renderContextModule(contextId, appId, contextRoot), + ], + ] as const)), + [`${feature}/feature-module.ts`, renderFeatureModule(shape)], + [`${feature}/feature-runtime.ts`, renderFeatureRuntime(shape)], + [`${feature}/context-routes.ts`, renderContextRoutes(shape)], + [`${feature}/contracts/${base}-feature-contract.ts`, renderFeatureContract(shape)], + [`${feature}/contracts/${base}-schemas.ts`, renderSchemas(shape)], + [`${feature}/contracts/${base}-mapper.ts`, renderMapper(shape)], + [`${feature}/contracts/${base}-api-contract.ts`, renderApiContract(shape)], + [ + `${feature}/contracts/${base}-contract-contribution.ts`, + renderContractContribution(shape), + ], + [`${feature}/contracts/${base}-message-catalog.ts`, renderMessageCatalog(shape)], + [`${feature}/application/${base}-feature-api.ts`, renderFeatureApi(shape)], + [`${feature}/adapters/${base}-http-gateway.ts`, renderHttpGateway(shape)], + [`${feature}/adapters/create-${base}-feature-input.ts`, renderCreateInput(shape)], + [`${feature}/presentation/${base}-feature-runtime.ts`, renderRouteRuntime(shape)], + [`${feature}/presentation/${base}-routes.ts`, renderRoutes(shape)], + [`${feature}/presentation/use-${base}-items.ts`, renderUseItems(shape)], + [`${feature}/presentation/${base}-list-page.tsx`, renderListPage(shape)], + [`tests/features/${id}/${base}-feature-input.test.ts`, renderInputTest(shape)], + [`tests/features/${id}/${base}-list-page.test.tsx`, renderPageTest(shape)], + [`artifacts/tests/a11y-manual/${routeId}.md`, renderA11yRecord(routeId)], + ]); + return Object.freeze({ + id, + contextId, + newContext: existing === undefined, + routeId, + routePath, + topic, + placeholder: request.contractPackage === undefined, + files, + }); +} + +type Shape = Readonly<{ + names: Names; + contextId: string; + routeId: string; + routePath: string; + chunkId: string; + navigationOrder: number; + topic: string; + operationId: string; + apiPath: string; + owner: string; + contractPackage: ContractPackageIdentity | null; +}>; + +const GENERATED = "Generated by `pnpm create:feature`."; + +function renderContextModule(contextId: string, appId: string, root: string): string { + return `/** + * Ownership declaration of the ${contextId} bounded context + * (docs/architecture/starter-experience.md, "Ownership declarations"): the + * app that owns it, its route root and its direct-feature budget. + * ${GENERATED} + */ +export const CONTEXT_MODULE_ID = "${contextId}"; +export const CONTEXT_APP_ID = "${appId}"; +export const CONTEXT_ROUTE_PATH = "${root}/*"; +export const CONTEXT_MAX_FEATURES = ${NEW_CONTEXT_MAX_FEATURES}; +`; +} + +function renderFeatureModule({ names, contextId }: Shape): string { + const { base, upper } = names; + return `import { defineFeatureModule } from "../feature-module.ts"; +import { + ${upper}_FEATURE_CONTRACT, + ${upper}_FEATURE_ID, +} from "./contracts/${base}-feature-contract.ts"; +import { ${upper}_MESSAGE_CATALOGS } from "./contracts/${base}-message-catalog.ts"; + +export const FEATURE_MODULE_ID = "${names.id}" satisfies typeof ${upper}_FEATURE_ID; +/** Owning bounded context (route root and budget live in its declaration). */ +export const FEATURE_CONTEXT_ID = "${contextId}"; + +/** + * Declaration only: this file and what it imports statically are in the + * initial chunk. The executable half, \`feature-runtime.ts\`, is imported + * dynamically when a route of this feature is entered. ${GENERATED} + */ +export const FEATURE_MODULE = defineFeatureModule({ + id: FEATURE_MODULE_ID, + contracts: ${upper}_FEATURE_CONTRACT, + routes: ${upper}_FEATURE_CONTRACT.routes, + messages: ${upper}_MESSAGE_CATALOGS, + loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, +} as const); +`; +} + +function renderFeatureRuntime({ names }: Shape): string { + const { base, upper } = names; + return `import { defineFeatureRuntime } from "../feature-module.ts"; +import { ${upper}_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-${base}-feature-input.ts"; +import { ${upper}_API_CONTRACT } from "./contracts/${base}-api-contract.ts"; +import { ${upper}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts"; +import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts"; + +/** + * The executable half. \`feature-module.ts\` imports this file dynamically, so + * none of it is in the initial chunk. + */ +export const FEATURE_RUNTIME = defineFeatureRuntime({ + featureId: ${upper}_FEATURE_ID, + apiContract: ${upper}_API_CONTRACT, + adapters: [${upper}_FEATURE_ADAPTER_CONTRIBUTION], + contractContributions: [${upper}_CONTRACT_CONTRIBUTION], +} as const); +`; +} + +function renderContextRoutes({ names }: Shape): string { + const { base, upper } = names; + return `import type { RouteObject } from "react-router-dom"; + +import { ${upper}_FEATURE_CONTRACT } from "./contracts/${base}-feature-contract.ts"; +import { ${upper}_ROUTE_RUNTIME } from "./presentation/${base}-feature-runtime.ts"; + +/** + * The routes the owning context loads when its root is visited. A route with + * params or search also puts its codecs on the handle (\`codecs\`). + */ +export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( + Object.values(${upper}_FEATURE_CONTRACT.routes).map((definition) => + Object.freeze({ + id: definition.routeId, + path: definition.path, + handle: Object.freeze({ + routeId: definition.routeId, + runtime: ${upper}_ROUTE_RUNTIME[definition.routeId], + }), + }), + ), +); +`; +} + +function renderContractPackage({ names, contractPackage }: Shape): Readonly<{ + imports: string; + doc: string; + fields: string; +}> { + if (contractPackage === null) { + return { + imports: `import { + PLACEHOLDER_CONTRACT_PACKAGE_DIGEST, + PLACEHOLDER_CONTRACT_PACKAGE_REVISION, + PLACEHOLDER_CONTRACT_PACKAGE_VERSION, +} from "../../../contracts/deployment-admission.ts"; +`, + doc: ` * PLACEHOLDER: no package was given to create:feature. Local and development + * builds work; release admission refuses this identity for staging and + * production. Pin the published package's id, exact version, sha256 digest + * and source revision here.`, + fields: ` packageId: "@org-contracts/${names.base}", + version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION, + digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST, + runtimeProtocolVersion: 1 as const, + sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,`, + }; + } + return { + imports: "", + doc: ` * Pinned when the feature was created; change all four fields together.`, + fields: ` packageId: "${contractPackage.packageId}", + version: "${contractPackage.version}", + digest: "${contractPackage.digest}", + runtimeProtocolVersion: 1 as const, + sourceRevision: "${contractPackage.sourceRevision}",`, + }; +} + +function renderFeatureContract(shape: Shape): string { + const { names, routeId } = shape; + const { base, upper } = names; + const contractPackage = renderContractPackage(shape); + return `${contractPackage.imports}import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts"; +import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts"; + +export const ${upper}_FEATURE_ID = "${names.id}"; +export const ${upper}_ITEM_QUERY_NAMESPACE = defineQueryNamespaceIdentity( + "${base}-item", + 1, +); +/** Random, not copied: a topic id is global and a copy collides. */ +export const ${upper}_ITEM_INVALIDATION_TOPIC = + defineQueryInvalidationTopic("${shape.topic}"); + +/** + * The contract package this feature's API comes from. The release manifest is + * checked against it at boot. +${contractPackage.doc} + */ +export const ${upper}_CONTRACT_PACKAGE = Object.freeze({ +${contractPackage.fields} +}); + +/** + * The declaration half: what the shell reads before a route of this feature + * is entered. It is in the initial chunk, so it holds data only. Route, chunk, + * schema, operation and topic ids are global; keep the feature prefix. + */ +export const ${upper}_FEATURE_CONTRACT = Object.freeze({ + featureId: ${upper}_FEATURE_ID, + routes: Object.freeze({ + ${routeId}: Object.freeze({ + routeId: "${routeId}", + path: "${shape.routePath}", + paramsSchema: null, + searchSchema: null, + access: "session-required", + loadingSurface: "${base}-list", + errorSurface: "feature-boundary", + chunkId: "${shape.chunkId}", + title: "${names.title}", + navigationLabel: "${names.title}", + navigationOrder: ${shape.navigationOrder}, + }), + }), + routeRuntimeContracts: Object.freeze({ + ${routeId}: Object.freeze({ + routeId: "${routeId}", + moduleId: "${base}-list-page", + paramsCodec: "none", + searchCodec: "none", + }), + }), + invalidation: Object.freeze({ + topics: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]), + namespaces: Object.freeze([${upper}_ITEM_QUERY_NAMESPACE]), + edges: Object.freeze([ + Object.freeze({ + topicId: ${upper}_ITEM_INVALIDATION_TOPIC, + namespace: ${upper}_ITEM_QUERY_NAMESPACE, + }), + ]), + }), + topicVersions: Object.freeze([ + Object.freeze({ topicId: ${upper}_ITEM_INVALIDATION_TOPIC, topicVersion: 1 }), + ]), + contractPackages: Object.freeze([${upper}_CONTRACT_PACKAGE]), +} as const); +`; +} + +function renderSchemas({ names }: Shape): string { + const { camel, pascal, upper } = names; + return `import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; +import { z } from "../../../contracts/zod.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; + +/** The GET takes no input. Schema ids are global, so this one is prefixed too. */ +export const ${camel}NoRequestSchema = z.object({}).strict(); + +export const ${camel}ItemDtoSchema = z + .object({ + id: z.string().min(1).max(120), + name: z.string().min(1).max(240), + }) + .strip(); + +export type ${pascal}ItemDto = z.output; + +export const ${camel}ItemListPayloadSchema = z.array(${camel}ItemDtoSchema).max(100); + +/** Problem details; a backend message is never kept. */ +export const ${camel}ProblemSchema = z + .object({ + type: z.string().min(1).max(512), + title: z.string().min(1).max(240), + status: z.int().min(100).max(599), + code: z.string().min(1).max(120).optional(), + }) + .strip(); + +export type ${pascal}Problem = z.output; + +export const ${upper}_VALIDATORS = Object.freeze({ + ${pascal}NoRequest: zodValidator("${pascal}NoRequest", ${camel}NoRequestSchema), + ${pascal}ItemListPayload: zodValidator( + "${pascal}ItemListPayload", + ${camel}ItemListPayloadSchema, + ), + ${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema), +}); + +export const ${upper}_RUNTIME_SCHEMA_CODECS = Object.freeze({ + ${pascal}NoRequest: runtimeSchemaCodecFromValidator(${upper}_VALIDATORS.${pascal}NoRequest), + ${pascal}ItemListPayload: runtimeSchemaCodecFromValidator( + ${upper}_VALIDATORS.${pascal}ItemListPayload, + ), +}); +`; +} + +function renderMapper({ names, owner }: Shape): string { + const { base, camel, pascal, upper } = names; + return `import { + mappingFailure, + mappingSuccess, + type BoundaryMappingResult, + type InstalledBoundaryMapper, +} from "../../../contracts/boundary-mapper.ts"; +import { + ${camel}ItemListPayloadSchema, + type ${pascal}ItemDto, +} from "./${base}-schemas.ts"; + +/** What the page shows. A wire field never reaches presentation by its wire name. */ +export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>; + +/** + * The HTTP contract has already validated the wire shape (\`outputValidator\`), + * so this owns only wire -> view. Put business rules in a \`domain/\` model + * when the feature has some. + */ +export function map${pascal}ItemList( + payload: readonly ${pascal}ItemDto[], +): BoundaryMappingResult { + return mappingSuccess( + Object.freeze( + payload.map((dto) => Object.freeze({ itemId: dto.id, name: dto.name })), + ), + ); +} + +/** The registry row (FE-REG-API). The registry is untyped, so it checks the shape. */ +export const ${upper}_BOUNDARY_MAPPERS = Object.freeze({ + ${pascal}ItemListMapper: Object.freeze({ + mapperId: "${pascal}ItemListMapper", + mapperVersion: 1, + inputSchemaId: "${pascal}ItemListPayload", + outputContractId: "${pascal}ItemList", + owner: "${owner}", + maxOutputItems: 100, + map(value: unknown) { + const parsed = ${camel}ItemListPayloadSchema.safeParse(value); + return parsed.success + ? map${pascal}ItemList(parsed.data) + : mappingFailure("MAPPING_INVARIANT_REJECTED"); + }, + }), +} satisfies Readonly>); +`; +} + +function renderApiContract({ names, operationId, apiPath, owner }: Shape): string { + const { base, pascal, upper } = names; + return `import { defineRestOperation } from "../../../contracts/api-operations.ts"; +import { ${upper}_BOUNDARY_MAPPERS } from "./${base}-mapper.ts"; +import { ${upper}_RUNTIME_SCHEMA_CODECS } from "./${base}-schemas.ts"; + +const OWNER = "${owner}"; + +/** + * The V2 API contract \`check:registries\` governs (FE-REG-API). The executable + * descriptor of the same operation is in \`${base}-contract-contribution.ts\`; + * tests/unit/http-operation-v2-v3-parity.test.ts fails when they disagree. + * Runtime half only: \`feature-runtime.ts\` loads it. + */ +export const ${upper}_API_CONTRACT = Object.freeze({ + runtimeSchemas: ${upper}_RUNTIME_SCHEMA_CODECS, + mappers: ${upper}_BOUNDARY_MAPPERS, + schemas: Object.freeze({ + ${pascal}NoRequest: Object.freeze({ + schemaId: "${pascal}NoRequest", + boundary: "api-request", + owner: OWNER, + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + ${pascal}ItemListPayload: Object.freeze({ + schemaId: "${pascal}ItemListPayload", + boundary: "api-response", + owner: OWNER, + runtime: "zod", + schemaVersion: 1, + direction: "RESPONSE", + unknownFieldPolicy: "STRIP_UNKNOWN", + }), + }), + apiOperations: Object.freeze({ + ${operationId}: defineRestOperation({ + method: "GET", + path: "${apiPath}", + operationId: "${operationId}", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "none", + requestSchema: "${pascal}NoRequest", + responseSchema: "${pascal}ItemListPayload", + owner: OWNER, + contractVersion: 2, + protocol: "REST", + semantics: "QUERY", + replayPolicy: "SAFE", + idempotencyKeyPolicy: "NONE", + mapperId: "${pascal}ItemListMapper", + successStatuses: [200], + responseMediaTypes: ["application/json"], + maxResponseBytes: 262_144, + providerId: "PRIMARY_API", + authProfileId: "EXTERNAL_BEARER", + csrfProfileId: "NO_CSRF_BEARER", + pathSchema: "${pascal}NoRequest", + pathParameterNames: [], + maxEncodedSearchBytes: 0, + }), + }), +} as const); +`; +} + +function renderContractContribution({ names, operationId, apiPath }: Shape): string { + const { base, pascal, upper } = names; + return `import type { + InstalledContractContribution, + InstalledHttpContract, +} from "../../../contracts/external-contract-runtime.ts"; +import { + ${upper}_CONTRACT_PACKAGE, + ${upper}_FEATURE_ID, +} from "./${base}-feature-contract.ts"; +import { + ${upper}_VALIDATORS, + type ${pascal}ItemDto, + type ${pascal}Problem, +} from "./${base}-schemas.ts"; + +/** + * The executable (V3) descriptor of ${operationId}. It belongs to the contract + * package pinned in \`${base}-feature-contract.ts\`: import \`@org-contracts/*\` + * only in this file (external-contract-package-single-import-path) and take + * the package's descriptor instead of this local one. + */ +export const ${operationId}_CONTRACT = Object.freeze({ + contract: Object.freeze({ + operationId: "${operationId}", + method: "GET" as const, + pathTemplate: "${apiPath}", + inputValidator: ${upper}_VALIDATORS.${pascal}NoRequest, + outputValidator: ${upper}_VALIDATORS.${pascal}ItemListPayload, + 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, + commandRecovery: null, + commandEffect: null, + projectRequest() { + return Object.freeze({ + pathValues: Object.freeze({}), + queryEntries: Object.freeze([]), + body: null, + }); + }, + }), + frontend: Object.freeze({ + policyId: "${upper}_LIST_V1", + requestByteLimit: 0, + responseByteLimit: 262_144, + totalDeadlineMs: 10_000, + retryBudget: 2 as const, + authProfileId: "EXTERNAL_BEARER", + diagnosticsOperation: "${base}.list", + }), +}) satisfies InstalledHttpContract< + Readonly>, + readonly ${pascal}ItemDto[], + ${pascal}Problem +>; + +export const ${upper}_CONTRACT_CONTRIBUTION: InstalledContractContribution = + Object.freeze({ + contributionId: "${names.id}-http-v1", + featureId: ${upper}_FEATURE_ID, + source: Object.freeze({ + kind: "EXTERNAL_PACKAGE" as const, + package: ${upper}_CONTRACT_PACKAGE, + }), + http: Object.freeze([ + ${operationId}_CONTRACT, + ]) as readonly InstalledHttpContract[], + events: Object.freeze([]), + }); +`; +} + +function renderMessageCatalog({ names, routeId }: Shape): string { + const { camel, title, upper } = names; + return `/** ko-KR is the source catalog; every locale has the same keys and placeholders. */ +export const ${upper}_MESSAGE_CATALOGS = Object.freeze({ + "ko-KR": Object.freeze({ + "route.${routeId}.navigation": "${title}", + "route.${routeId}.title": "${title}", + "${camel}.list.title": "${title}", + "${camel}.list.description": "create:feature가 만든 목록입니다. 제품 문구로 바꾸세요.", + "${camel}.list.resultCount": "총 {count}개 항목", + "${camel}.list.items": "${title} 목록", + }), + "en-US": Object.freeze({ + "route.${routeId}.navigation": "${title}", + "route.${routeId}.title": "${title}", + "${camel}.list.title": "${title}", + "${camel}.list.description": "A list create:feature generated. Replace this copy with the product's.", + "${camel}.list.resultCount": "Total items: {count}", + "${camel}.list.items": "${title} items", + }), +} as const); +`; +} + +function renderFeatureApi({ names }: Shape): string { + const { base, pascal, upper } = names; + return `import type {} from "../../../application/ports/in/application-api.ts"; +import type { Result } from "../../../contracts/result.ts"; +import { + failOpenTelemetryPort, + NO_OP_TELEMETRY_PORT, + type TelemetryPort, +} from "../../../platform/telemetry/telemetry-port.ts"; +import { ${upper}_FEATURE_ID } from "../contracts/${base}-feature-contract.ts"; +import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; + +export type ${pascal}CallContext = Readonly<{ signal?: AbortSignal }>; + +/** What the feature's pages call. Name methods after what the user does. */ +export type ${pascal}FeatureInput = Readonly<{ + listItems(context?: ${pascal}CallContext): Promise>; +}>; + +declare module "../../../application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "${names.id}": ${pascal}FeatureInput; + } +} + +/** The port the feature's HTTP adapter implements. */ +export type ${pascal}Gateway = Readonly<{ + list(context?: ${pascal}CallContext): Promise>; +}>; + +export function create${pascal}FeatureInput( + gateway: ${pascal}Gateway, + { telemetry = NO_OP_TELEMETRY_PORT }: Readonly<{ telemetry?: TelemetryPort }> = {}, +): ${pascal}FeatureInput { + // Spec §24, §26: telemetry is best-effort and never changes the result. + const events = failOpenTelemetryPort(telemetry); + return Object.freeze({ + async listItems(context) { + const result = await gateway.list(context); + if (!result.ok && result.error.kind !== "REQUEST_ABORTED") { + void events.emit({ + kind: "${base}.list.failed", + severity: "warning", + featureId: ${upper}_FEATURE_ID, + payload: Object.freeze({ reason: result.error.kind }), + }); + } + return result; + }, + }); +} +`; +} + +function renderHttpGateway({ names, operationId, routeId }: Shape): string { + const { base, pascal, upper } = names; + return `import { + defineFeatureHttpOperationForRoutes, + type FeatureHttpBinding, +} from "../../../adapters/http/index.ts"; +import type { ${pascal}Gateway } from "../application/${base}-feature-api.ts"; +import { ${operationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts"; +import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts"; +import { map${pascal}ItemList } from "../contracts/${base}-mapper.ts"; + +const define${pascal}HttpOperation = defineFeatureHttpOperationForRoutes< + keyof typeof ${upper}_FEATURE_CONTRACT.routes +>(); + +export const ${upper}_HTTP_OPERATIONS = Object.freeze({ + ${operationId}: define${pascal}HttpOperation({ + contract: ${operationId}_CONTRACT, + routeId: "${routeId}", + mapSuccess: map${pascal}ItemList, + }), +} as const); + +export function create${pascal}HttpGateway( + http: FeatureHttpBinding, +): ${pascal}Gateway { + return Object.freeze({ + list(context) { + return http.execute("${operationId}", Object.freeze({}), context); + }, + }); +} +`; +} + +function renderCreateInput({ names }: Shape): string { + const { base, pascal, upper } = names; + return `import { createFeatureHttpBinding } from "../../../adapters/http/index.ts"; +import { defineFeatureAdapterContribution } from "../../feature-adapter-contribution.ts"; +import { create${pascal}FeatureInput } from "../application/${base}-feature-api.ts"; +import { ${upper}_FEATURE_ID } from "../contracts/${base}-feature-contract.ts"; +import { + create${pascal}HttpGateway, + ${upper}_HTTP_OPERATIONS, +} from "./${base}-http-gateway.ts"; + +/** The feature receives only the capabilities it names in \`needs\`. */ +export const ${upper}_FEATURE_ADAPTER_CONTRIBUTION = defineFeatureAdapterContribution({ + featureId: ${upper}_FEATURE_ID, + needs: ["http", "telemetry"] as const, + createInput: ({ http, telemetry }) => + Object.freeze({ + featureId: ${upper}_FEATURE_ID, + input: create${pascal}FeatureInput( + create${pascal}HttpGateway(createFeatureHttpBinding(http, ${upper}_HTTP_OPERATIONS)), + { telemetry }, + ), + }), +}); +`; +} + +function renderRouteRuntime({ names, routeId }: Shape): string { + const { base, upper } = names; + return `import { lazy } from "react"; + +/** The lazy page of each route; \`moduleId\` equals the route runtime contract's. */ +export const ${upper}_ROUTE_RUNTIME = { + ${routeId}: Object.freeze({ + moduleId: "${base}-list-page", + Component: lazy(() => import("./${base}-list-page.tsx")), + }), +} as const; +`; +} + +function renderRoutes({ names }: Shape): string { + const { base, camel, upper } = names; + return `import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts"; +import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts"; + +/** + * 16-04. A link names its route ID and the router's builder fills in the + * contract's \`path\`, so the contract stays the one place a path is written. + * Once a route has params or search, pass its codecs as the third argument. + */ +export function ${camel}RouteUrl( + routeId: keyof typeof ${upper}_FEATURE_CONTRACT.routes, + input?: Parameters[1], +): string { + return buildRouteUrl(routeId, input); +} +`; +} + +function renderUseItems({ names, operationId }: Shape): 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(); +const NO_INPUT = Object.freeze({}); + +/** + * §10.4. Bounded estimate of the mapped value: string bytes plus a fixed + * per-item overhead, never \`JSON.stringify\`. + */ +function measureItems(items: readonly ${pascal}ItemView[]): QueryResultMeasure { + let estimatedBytes = 16; + for (const item of items) { + estimatedBytes += + UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16; + } + return { itemCount: items.length, estimatedBytes }; +} + +export function use${pascal}Items() { + const input = useApplicationFeature(${upper}_FEATURE_ID); + const scope = useServerStateScope(); + return useApplicationQuery( + bindQuery( + { + definitionId: "${base}-item-list-v1", + definitionVersion: 1, + owner: ${upper}_FEATURE_ID, + namespace: ${upper}_ITEM_QUERY_NAMESPACE, + operationId: "${operationId}", + profileId: "LIST_STANDARD", + measureResult: measureItems, + execute: (_input: typeof NO_INPUT, { signal }) => input.listItems({ signal }), + }, + NO_INPUT, + scope, + ), + ); +} +`; +} + +function renderListPage({ names }: Shape): string { + const { base, camel, pascal } = names; + return `import { + AsyncSurface, + CollectionPage, +} from "../../../presentation/design-system/index.ts"; +import { useLocale } from "../../../presentation/i18n/index.ts"; +import { use${pascal}Items } from "./use-${base}-items.ts"; + +/** An empty list renders the shared empty state under the page heading. */ +export default function ${pascal}ListPage() { + const { message } = useLocale(); + const query = use${pascal}Items(); + return ( + + +
    + {(query.data ?? []).map((item) => ( +
  • {item.name}
  • + ))} +
+
+
+ ); +} +`; +} + +function renderInputTest({ names, operationId }: Shape): string { + const { base, pascal, upper } = names; + return `import { describe, expect, it, vi } from "vitest"; + +import { createFailure } from "../../../src/contracts/errors.ts"; +import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts"; +import { ${upper}_BOUNDARY_MAPPERS } from "../../../src/features/${names.id}/contracts/${base}-mapper.ts"; +import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts"; + +const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]); + +describe("${names.id} application input", () => { + it("returns the gateway's items without telemetry", async () => { + const emit = vi.fn(); + const input = create${pascal}FeatureInput( + { list: async () => ({ ok: true, value: ITEMS }) }, + { telemetry: { emit } }, + ); + + await expect(input.listItems()).resolves.toEqual({ ok: true, value: ITEMS }); + expect(emit).not.toHaveBeenCalled(); + }); + + it("returns a failed load and reports its kind", async () => { + const failure = createFailure("REQUEST_TIMEOUT", "${operationId}", 0); + const emit = vi.fn(); + const input = create${pascal}FeatureInput( + { list: async () => ({ ok: false, error: failure }) }, + { telemetry: { emit } }, + ); + + await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure }); + expect(emit).toHaveBeenCalledWith({ + kind: "${base}.list.failed", + severity: "warning", + featureId: "${names.id}", + payload: { reason: "REQUEST_TIMEOUT" }, + }); + }); + + it("does not report a load its caller aborted", async () => { + const failure = createFailure("REQUEST_ABORTED", "${operationId}", 0); + const input = create${pascal}FeatureInput({ + list: async () => ({ ok: false, error: failure }), + }); + + await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure }); + }); +}); + +describe("${names.id} registry mapper", () => { + it("maps a list payload and rejects any other shape", () => { + const { map } = ${upper}_BOUNDARY_MAPPERS.${pascal}ItemListMapper; + + expect(map([{ id: "item-1", name: "First item" }])).toEqual({ ok: true, value: ITEMS }); + expect(map({ items: [] })).toEqual({ ok: false, code: "MAPPING_INVARIANT_REJECTED" }); + }); +}); +`; +} + +function renderPageTest({ names, operationId, routeId }: Shape): string { + const { base, camel, upper } = names; + return `// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts"; +import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx"; +import { ${operationId}_CONTRACT } from "../../../src/features/${names.id}/contracts/${base}-contract-contribution.ts"; +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 { createHttpScenarioHandler } from "../../mocks/handlers/http-scenarios.ts"; + +const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"]; +const RUNTIME_CONFIG = { + APP_ENV: "local", + API_BASE_URL: "https://api.test", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "local-build", + RELEASE_ID: "local-release", +}; +const RELEASE_MANIFEST = { + schemaVersion: 1, + appVersion: "0.0.0", + buildId: "local-build", + commitSha: "local", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + releaseId: "local-release", + builtAt: "2026-01-01T00:00:00.000Z", + routeChunks: { "route-home": "assets/home.js" }, +}; + +/** The boot documents come from here; every API call goes to MSW. */ +const fetcher: typeof fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), "http://app.test"); + if (url.pathname === "/config.json") return Promise.resolve(Response.json(RUNTIME_CONFIG)); + if (url.pathname === "/release-manifest.json") { + return Promise.resolve(Response.json(RELEASE_MANIFEST)); + } + return fetch(input instanceof Request ? input : url, init); +}; + +const api = setupServer(); +beforeAll(() => api.listen({ onUnhandledRequest: "error" })); +afterEach(() => api.resetHandlers()); +afterAll(() => api.close()); + +/** Enters the list through the router, as a signed-in user. */ +async function openList() { + const user = userEvent.setup(); + window.history.pushState({}, "", ${camel}RouteUrl("${routeId}")); + render( + , + ); + await user.click(await screen.findByRole("button", { name: KO_MESSAGES["action.signIn"] })); + expect( + await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }), + ).toBeVisible(); + return user; +} + +describe("${names.id} list page through the router", () => { + it("lists the items the API returns", async () => { + api.use( + createHttpScenarioHandler(${operationId}_CONTRACT, { + payload: [{ id: "item-1", name: "First item" }], + }), + ); + await openList(); + + expect(await screen.findByText("First item")).toBeVisible(); + }); + + // tests/e2e/accessibility.spec.ts answers every API with []. + it("renders an empty list as the empty state", async () => { + api.use(createHttpScenarioHandler(${operationId}_CONTRACT, { scenario: "empty", payload: [] })); + await openList(); + + expect(await screen.findByRole("heading", { name: KO_MESSAGES["async.empty"] })).toBeVisible(); + }); + + it("shows a failed load and loads again on retry", async () => { + api.use( + createHttpScenarioHandler(${operationId}_CONTRACT, { + scenario: "server-terminal-503", + payload: [], + }), + ); + const user = await openList(); + const retry = await screen.findByRole("button", { name: KO_MESSAGES["action.retry"] }); + api.use( + createHttpScenarioHandler(${operationId}_CONTRACT, { + payload: [{ id: "item-2", name: "Second item" }], + }), + ); + await user.click(retry); + + expect(await screen.findByText("Second item")).toBeVisible(); + }); +}); +`; +} + +function renderA11yRecord(routeId: string): string { + return `# ${routeId} accessibility review + +Status: pending-manual-review +Route ID: ${routeId} +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: pending +M5 Error association: pending +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. ${GENERATED} +`; +} + +async function exists(target: string): Promise { + return access(target).then( + () => true, + () => false, + ); +} + +/** + * Writes every file or none. An existing file or feature directory is never + * overwritten; a write that fails removes what this call created. + */ +export async function writeFeatureFiles( + root: string, + files: ReadonlyMap, + ownedDirectories: readonly string[] = [], +): Promise { + const taken: string[] = []; + for (const relative of [...ownedDirectories, ...files.keys()]) { + if (await exists(path.join(root, relative))) taken.push(relative); + } + if (taken.length > 0) { + throw new CreateFeatureError(`refusing to overwrite: ${taken.join(", ")}`); + } + const created: string[] = []; + try { + for (const [relative, content] of files) { + const target = path.join(root, relative); + const firstDirectory = await mkdir(path.dirname(target), { recursive: true }); + if (firstDirectory !== undefined) created.push(firstDirectory); + await writeFile(target, content, { flag: "wx" }); + created.push(target); + } + } catch (error) { + await rollBack(created); + throw error; + } + return Object.freeze(created); +} + +async function rollBack(created: readonly string[]): Promise { + for (const target of [...created].reverse()) { + await rm(target, { recursive: true, force: true }); + } +} + +async function directoryNames(directory: string): Promise { + const entries = await readdir(directory, { withFileTypes: true }).catch(() => []); + return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name); +} + +async function readInstalledFacts(root: string): Promise { + const source = await createFileSystemDeclarationSource(root); + const contexts = source.appIds().flatMap((appId) => source.contextsOf(appId)); + // The script's generator run (package.json) made these current. + const { ROUTE_REGISTRY, INVALIDATION_REGISTRY } = await import( + "../src/features/installed-feature-contracts.ts" + ); + const { KO_MESSAGES } = await import("../src/presentation/i18n/catalog.ts"); + return Object.freeze({ + appIds: source.appIds(), + featureIds: [ + ...new Set([ + ...contexts.flatMap((context) => + source.featuresOf(context.id).map((feature) => feature.id), + ), + ...(await directoryNames(path.join(root, "src/features"))), + ]), + ], + contexts: contexts.map(({ id, routePath }) => ({ id, routePath })), + contextDirectories: await directoryNames(path.join(root, "src/contexts")), + routes: Object.values(ROUTE_REGISTRY).map((route) => ({ + routeId: route.routeId, + path: route.path, + chunkId: route.chunkId, + navigationOrder: route.navigationOrder, + })), + topics: [...INVALIDATION_REGISTRY.topics], + messageKeys: Object.keys(KO_MESSAGES), + }); +} + +const USAGE = + "Usage: pnpm create:feature [--context ] " + + "[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ]"; + +function parseRequest(argv: readonly string[]): FeatureRequest { + const args = argv[0] === "--" ? argv.slice(1) : [...argv]; + const { values, positionals } = parseArgs({ + args, + allowPositionals: true, + options: { + context: { type: "string" }, + package: { type: "string" }, + digest: { type: "string" }, + revision: { type: "string" }, + }, + }); + const [id, ...extra] = positionals; + if (id === undefined || extra.length > 0) fail(USAGE); + const given = [values.package, values.digest, values.revision].filter( + (value) => value !== undefined, + ); + if (given.length !== 0 && given.length !== 3) { + fail(`--package, --digest and --revision go together. ${USAGE}`); + } + let contractPackage: ContractPackageIdentity | undefined; + if (values.package !== undefined) { + const at = values.package.lastIndexOf("@"); + if (at <= 0) fail(`--package must be @scope/name@. ${USAGE}`); + contractPackage = Object.freeze({ + packageId: values.package.slice(0, at), + version: values.package.slice(at + 1), + digest: values.digest ?? "", + sourceRevision: values.revision ?? "", + }); + } + return Object.freeze({ id, context: values.context, contractPackage }); +} + +function report(plan: FeaturePlan): string { + const lines = [ + `create:feature: ${plan.id} in ${plan.contextId}${plan.newContext ? " (new context)" : ""}, route ${plan.routeId} at ${plan.routePath}`, + ...[...plan.files.keys()].map((file) => ` created ${file}`), + "", + "Next:", + ` 1. Before a release, have a person review and sign artifacts/tests/a11y-manual/${plan.routeId}.md (FE-GATE-028). The merge gates check only its format.`, + " 2. Run the merge gates: corepack pnpm check:types, lint, check:architecture, check:registries, check:i18n, check:design-system, check:diagnostics, verify:documentation, test:unit, test:component, test:integration, test:coverage, check:ci, build.", + ` The feature's own tests: node scripts/run-vitest.ts run tests/features/${plan.id} (test:coverage runs them in CI)`, + " The registry baseline does not change: new routes, operations, schemas and invalidation topics are additive.", + ]; + return `${lines.join("\n")}\n`; +} + +async function main(): Promise { + const scriptDirectory = path.dirname(fileURLToPath(import.meta.url)); + const root = path.resolve(scriptDirectory, ".."); + let request: FeatureRequest; + try { + request = parseRequest(process.argv.slice(2)); + } catch (error) { + process.stderr.write(`create:feature: ${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 2; + return; + } + try { + const plan = planFeature(request, await readInstalledFacts(root)); + const created = await writeFeatureFiles(root, plan.files, [ + `src/features/${plan.id}`, + `tests/features/${plan.id}`, + ]); + // The generator reads the new declarations; it fails on any it rejects. + const generated = spawnSync( + process.execPath, + [path.join(scriptDirectory, "generate-product-feature-index.ts")], + { cwd: root, encoding: "utf8" }, + ); + if (generated.status !== 0) { + await rollBack(created); + fail(`the feature index generator rejected the feature, nothing was kept:\n${generated.stderr}`); + } + process.stdout.write(report(plan)); + if (plan.placeholder) { + process.stderr.write( + `create:feature warning: no --package was given, so src/features/${plan.id}/contracts/${namesOf(plan.id).base}-feature-contract.ts pins the placeholder contract identity. ` + + "Local and development builds work; release admission refuses it for staging and production. " + + "Pin the published package's id, version, digest and revision there, and take the package's descriptor in the contract contribution.\n", + ); + } + } catch (error) { + process.stderr.write(`create:feature: ${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + await main(); +} diff --git a/scripts/test-feature-scaffold.ts b/scripts/test-feature-scaffold.ts new file mode 100644 index 00000000..61654558 --- /dev/null +++ b/scripts/test-feature-scaffold.ts @@ -0,0 +1,78 @@ +import { mkdir, rm, writeFile } from "node:fs/promises"; + +import { + createRemovalFixtureRoot, + prepareRemovalFixture, + REMOVAL_FIXTURE_COPY_TARGETS, + renderRemovalJunit, + requireRemovalFixtureEnvironment, + runRemovalFixtureCheck, + sealRemovalFixtureRepository, + type RemovalCheck, +} from "./lib/removal-fixture.ts"; + +/** + * U7. A feature from `create:feature` passes the merge gates without an edit + * and breaks no other test. A copy of the repository, sample feature + * included, gets one generated feature and then runs the gates. + * test:sample-removal repeats the generation after deleting the sample + * (decision 4), which proves the command needs nothing from it. + */ +const FEATURE_ID = "scaffold-feature"; +const REPORT = "artifacts/tests/feature-scaffold.xml"; + +const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); +const fixtureRoot = await createRemovalFixtureRoot("feature-scaffold"); + +function check(name: string, script: string, extra: readonly string[] = []): RemovalCheck { + return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script, extra); +} + +try { + // verify:documentation and the documentation tests read these. + await prepareRemovalFixture(fixtureRoot, [ + ...REMOVAL_FIXTURE_COPY_TARGETS, + "README.md", + "CHANGELOG.md", + "docs", + ]); + const created = check("create-feature", "create:feature", [FEATURE_ID]); + const checks: RemovalCheck[] = [created]; + if (created.passed) { + // Commits the copy with the feature, as a project would: git-based + // checks (git grep, git ls-files) then see the feature's files. + sealRemovalFixtureRepository(fixtureRoot); + checks.push( + check("typecheck", "check:types"), + check("lint", "lint"), + check("architecture", "check:architecture"), + check("registries", "check:registries"), + check("i18n", "check:i18n"), + check("design-system", "check:design-system"), + check("diagnostics", "check:diagnostics"), + check("documentation", "verify:documentation"), + check("unit", "test:unit"), + check("component", "test:component"), + check("integration", "test:integration"), + check("features", "exec", ["node", "scripts/run-vitest.ts", "run", "tests/features"]), + check("coverage", "test:coverage"), + check("ci-contract", "check:ci"), + check("build", "build"), + ); + } + const failed = checks.filter((entry) => !entry.passed); + await mkdir("artifacts/tests", { recursive: true }); + await writeFile(REPORT, renderRemovalJunit("feature-scaffold", checks)); + if (failed.length > 0) { + process.stderr.write( + `feature scaffold failed:\n${failed + .map((entry) => ` ${entry.name}: ${entry.failure ?? "failed"}`) + .join("\n")}\n`, + ); + process.exitCode = 1; + } else { + process.stdout.write(`feature scaffold: PASS (${checks.length} checks)\n`); + } +} finally { + await rm(fixtureRoot, { recursive: true, force: true }); +} diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 4f59907e..81bec4c0 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -22,6 +22,7 @@ import { requireRemovalFixtureEnvironment, runRemovalFixtureCheck, runRemovalFixturePnpm, + sealRemovalFixtureRepository, type RemovalCheck, } from "./lib/removal-fixture.ts"; @@ -396,22 +397,25 @@ try { missingCommonTests.push(testPath); }); } - const checks: RemovalCheck[] = [ - outcome("common-test-evidence", missingCommonTests, "platform tests missing"), - check("typecheck", "check:types"), - check("architecture", "check:architecture"), - check("registries", "check:registries"), - check("unit-integration", "test:all"), - check("coverage", "test:coverage"), - check("test-evidence-source", "check:test-evidence:source"), - check("ci-contract", "check:ci"), - check("home-smoke", "exec", [ + const gateChecks = (prefix: string): RemovalCheck[] => [ + check(`${prefix}typecheck`, "check:types"), + check(`${prefix}architecture`, "check:architecture"), + check(`${prefix}registries`, "check:registries"), + check(`${prefix}unit-integration`, "test:all"), + check(`${prefix}coverage`, "test:coverage"), + check(`${prefix}test-evidence-source`, "check:test-evidence:source"), + check(`${prefix}ci-contract`, "check:ci"), + check(`${prefix}home-smoke`, "exec", [ "vitest", "run", "tests/component/router.test.tsx", "--reporter=default", ]), - check("build", "build"), + check(`${prefix}build`, "build"), + ]; + const checks: RemovalCheck[] = [ + outcome("common-test-evidence", missingCommonTests, "platform tests missing"), + ...gateChecks(""), ]; const builtResidue: string[] = []; const buildSucceeded = @@ -442,6 +446,20 @@ try { outcome("built-fixture-id-residue", builtResidue, "built residue"), ); + // U7 (decision 4). The same copy, now without the sample, gets one feature + // from create:feature and runs the same gates again: the command and the + // feature it writes need nothing from the sample. + if (isSample) { + const created = check("scaffold-create-feature", "create:feature", [ + "scaffold-feature", + ]); + checks.push(created); + if (created.passed) { + sealRemovalFixtureRepository(fixtureRoot); + checks.push(...gateChecks("scaffold-")); + } + } + const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( diff --git a/tests/release/fixtures/R10/release-manifest.json b/tests/release/fixtures/R10/release-manifest.json index d7721d99..0ecb4aa4 100644 --- a/tests/release/fixtures/R10/release-manifest.json +++ b/tests/release/fixtures/R10/release-manifest.json @@ -10,7 +10,7 @@ "routeChunks": { "route-home": "assets/app.aaaa.js" }, "contractSet": { "setAlgorithm": "CA_CONTRACT_SET_V1", - "setDigest": "__EMPTY_SET_DIGEST__", - "packages": [] + "setDigest": "__INSTALLED_SET_DIGEST__", + "packages": "__INSTALLED_PACKAGES__" } } diff --git a/tests/release/fixtures/R11/release-manifest.json b/tests/release/fixtures/R11/release-manifest.json index aa80d307..bb6d1309 100644 --- a/tests/release/fixtures/R11/release-manifest.json +++ b/tests/release/fixtures/R11/release-manifest.json @@ -10,7 +10,7 @@ "routeChunks": { "route-home": "assets/app.bbbb.js" }, "contractSet": { "setAlgorithm": "CA_CONTRACT_SET_V1", - "setDigest": "__EMPTY_SET_DIGEST__", - "packages": [] + "setDigest": "__INSTALLED_SET_DIGEST__", + "packages": "__INSTALLED_PACKAGES__" } } diff --git a/tests/release/release-fixture.ts b/tests/release/release-fixture.ts index ad97d0d6..5d5f6c26 100644 --- a/tests/release/release-fixture.ts +++ b/tests/release/release-fixture.ts @@ -5,6 +5,7 @@ import { loadReleaseManifest } from "../../src/bootstrap/load-release-manifest.t import { loadRuntimeConfig } from "../../src/bootstrap/load-runtime-config.ts"; import { releaseMismatchKey } from "../../src/bootstrap/boot-release-recovery.ts"; import { computeContractSetDigest } from "../../src/contracts/contract-set-canonical.ts"; +import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../src/features/installed-contract-contributions.ts"; import type { ReleaseMismatchRecovery } from "../../src/platform/release/release-mismatch-recovery.ts"; /** @@ -17,7 +18,14 @@ export type ReleaseName = "R10" | "R11"; export type Surface = "html" | "config" | "manifest"; const FIXTURE_ROOT = path.resolve("tests/release/fixtures"); -const EMPTY_SET_DIGEST = await computeContractSetDigest([]); +// U7, as 16-02 did for tests/runtime-schema: the build compiles the installed +// features' contract packages, so a coherent manifest carries exactly that +// set. A fixed empty set broke these tests with the first feature that pins +// an EXTERNAL_PACKAGE (every feature create:feature writes). +const INSTALLED_PACKAGES = JSON.stringify(EXPECTED_CONTRACT_SET_PACKAGES); +const INSTALLED_SET_DIGEST = await computeContractSetDigest( + EXPECTED_CONTRACT_SET_PACKAGES, +); type CachePolicy = Readonly<{ surfaces: Readonly<{ @@ -52,10 +60,9 @@ export function readRelease(release: ReleaseName): ReleaseArtifacts { return Object.freeze({ html: readFileSync(path.join(root, "index.html"), "utf8"), config: readFileSync(path.join(root, "config.json"), "utf8"), - manifest: readFileSync(path.join(root, "release-manifest.json"), "utf8").replace( - "__EMPTY_SET_DIGEST__", - EMPTY_SET_DIGEST, - ), + manifest: readFileSync(path.join(root, "release-manifest.json"), "utf8") + .replace('"__INSTALLED_PACKAGES__"', INSTALLED_PACKAGES) + .replace("__INSTALLED_SET_DIGEST__", INSTALLED_SET_DIGEST), assets, }); } diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index dccbc6f8..1fa8fb94 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -195,11 +195,11 @@ describe("CI gate contract", () => { ).filter((gateId) => gateId !== "FE-GATE-016"), ); expect(contract.jobs).toHaveLength(10); - expect(contract.commands).toHaveLength(98); - expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(102); + expect(contract.commands).toHaveLength(99); + expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(103); expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30); - expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(87); - expect(contract.artifacts).toHaveLength(109); + expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(88); + expect(contract.artifacts).toHaveLength(110); expect(contract.stages).toHaveLength(5); expect(contract.retention.classes).toHaveLength(5); expect(index.gates.get("FE-GATE-015")?.commandIds).toHaveLength(2); diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts new file mode 100644 index 00000000..fbadffc9 --- /dev/null +++ b/tests/unit/create-feature.test.ts @@ -0,0 +1,238 @@ +import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + CreateFeatureError, + planFeature, + randomTopicSuffix, + writeFeatureFiles, + type FeatureRequest, + type InstalledFacts, +} from "../../scripts/create-feature.ts"; +import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts"; + +/** + * U7. What `pnpm create:feature` renders, checked without touching the + * repository. test:feature-scaffold writes a feature into a copy and runs the + * gates on it; this file covers the ids, the topic, the order and the refusals. + */ +const INSTALLED: InstalledFacts = Object.freeze({ + appIds: ["template-app"], + featureIds: ["orders-feature", "drafts-feature"], + contexts: [ + { id: "orders-context", routePath: "orders/*" }, + { id: "billing-context", routePath: "billing/*" }, + ], + contextDirectories: ["orders-context", "billing-context"], + routes: [ + { routeId: "APP_HOME", path: "/", chunkId: "route-home", navigationOrder: 10 }, + { routeId: "ORDERS_LIST", path: "/orders", chunkId: "route-orders-list", navigationOrder: 50 }, + { routeId: "NOT_FOUND", path: "*", chunkId: "route-not-found", navigationOrder: null }, + ], + topics: ["qinv.0000000000000000000000000a"], + messageKeys: ["route.APP_HOME.title", "home.list.title"], +}); +const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123"; + +function plan(request: FeatureRequest, installed: InstalledFacts = INSTALLED) { + return planFeature(request, installed, () => TOPIC_SUFFIX); +} + +function rendered(request: FeatureRequest): string { + return [...plan(request).files.values()].join("\n"); +} + +describe("create:feature rendering", () => { + it("prefixes every global id with the feature and carries no sample token", () => { + const text = rendered({ id: "invoice-feature" }); + + expect(text).not.toMatch(/reference/iu); + const ids = [ + ...text.matchAll( + /\b(?:schemaId|inputSchemaId|operationId|mapperId|outputContractId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId|owner)\s*:\s*"([^"]+)"/gu, + ), + ...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu), + ...text.matchAll(/defineQueryNamespaceIdentity\(\s*"([^"]+)"/gu), + ...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu), + ...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu), + ].map((match) => match[1] ?? ""); + expect(ids.length).toBeGreaterThan(30); + for (const id of ids) { + expect(id).toMatch( + /^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_LIST\.|route-invoice-|feature-frontend-invoice-feature$)/u, + ); + } + expect(text).not.toMatch(/"NoRequest"/u); + }); + + it("names the route, context and topic it creates", () => { + const created = plan({ id: "invoice-feature" }); + + expect(created).toMatchObject({ + contextId: "invoice-context", + newContext: true, + routeId: "INVOICE_LIST", + routePath: "/invoice", + topic: `qinv.${TOPIC_SUFFIX}`, + placeholder: true, + }); + expect([...created.files.keys()]).toEqual( + expect.arrayContaining([ + "src/contexts/invoice-context/context-module.ts", + "src/features/invoice-feature/feature-module.ts", + "tests/features/invoice-feature/invoice-feature-input.test.ts", + "tests/features/invoice-feature/invoice-list-page.test.tsx", + "artifacts/tests/a11y-manual/INVOICE_LIST.md", + ]), + ); + expect([...created.files.keys()].some((file) => file.includes("/domain/"))).toBe(false); + expect(created.files.get("src/contexts/invoice-context/context-module.ts")).toContain( + 'CONTEXT_ROUTE_PATH = "invoice/*"', + ); + expect(created.files.get("artifacts/tests/a11y-manual/INVOICE_LIST.md")).toMatch( + /^Status: pending-manual-review$/mu, + ); + }); + + it("generates a fresh lower-case 26-character topic and refuses an installed one", () => { + const first = randomTopicSuffix(); + expect(first).toMatch(/^[0-9a-hjkmnp-tv-z]{26}$/u); + expect(randomTopicSuffix()).not.toBe(first); + expect(() => + planFeature({ id: "invoice-feature" }, INSTALLED, () => "0000000000000000000000000a"), + ).toThrow(/qinv\.0000000000000000000000000a is already installed/u); + }); + + it("places the route after the last navigation entry", () => { + expect(rendered({ id: "invoice-feature" })).toContain("navigationOrder: 60,"); + }); + + it("adds the route under an existing context's root", () => { + const created = plan({ id: "invoice-feature", context: "billing-context" }); + + expect(created).toMatchObject({ newContext: false, routePath: "/billing/invoice" }); + expect([...created.files.keys()].some((file) => file.startsWith("src/contexts/"))).toBe(false); + }); + + it("pins the placeholder through its exported constant, or the given package", () => { + expect(rendered({ id: "invoice-feature" })).toContain( + "digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,", + ); + const digest = `sha256:${"ab".repeat(32)}`; + const pinned = plan({ + id: "invoice-feature", + contractPackage: { + packageId: "@org-contracts/invoice", + version: "1.4.2", + digest, + sourceRevision: "0a1b2c3d", + }, + }); + const contract = pinned.files.get( + "src/features/invoice-feature/contracts/invoice-feature-contract.ts", + ); + expect(pinned.placeholder).toBe(false); + expect(contract).toContain(`digest: "${digest}",`); + expect(contract).not.toContain("PLACEHOLDER"); + expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST); + }); +}); + +describe("create:feature refusals", () => { + it.each(["Invoice", "invoice_feature", "-invoice", "invoice--x", "invoice-", "", "a".repeat(41)])( + "refuses the id %j", + (id) => { + expect(() => plan({ id })).toThrow(/kebab-case/u); + }, + ); + + it.each([ + [{ id: "orders-feature" }, /already a feature or context/u], + [{ id: "orders-context" }, /already a feature or context/u], + [{ id: "orders" }, /prefix its ids with "orders", which orders-feature already uses/u], + [{ id: "billing-feature" }, /pass --context billing-context/u], + [{ id: "invoice-feature", context: "orders" }, /already owns the route root orders\/\*/u], + [{ id: "invoice-feature", context: "drafts-feature" }, /is a feature id/u], + [{ id: "home-feature" }, /message keys already exist: home\.list\.title/u], + [ + { + id: "invoice-feature", + contractPackage: { + packageId: "@org-contracts/invoice", + version: "1.4.2", + digest: "sha256:abc", + sourceRevision: "0a1b2c3d", + }, + }, + /not a pinned identity: invoice-feature: package digest/u, + ], + ] as const)("refuses %j", (request, reason) => { + expect(() => plan(request)).toThrow(reason); + }); + + it("refuses a route that collides with an installed one", () => { + expect(() => + plan( + { id: "invoice-feature" }, + { + ...INSTALLED, + routes: [ + ...INSTALLED.routes, + { routeId: "LEGACY", path: "/invoice", chunkId: "route-legacy", navigationOrder: null }, + ], + }, + ), + ).toThrow(/collides with installed route LEGACY/u); + }); +}); + +describe("create:feature writing", () => { + const roots: string[] = []; + afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); + }); + + async function emptyRoot(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "create-feature-")); + roots.push(root); + return root; + } + + it("refuses to overwrite and writes nothing when one target exists", async () => { + const root = await emptyRoot(); + const files = plan({ id: "invoice-feature" }).files; + await mkdir(path.join(root, "artifacts/tests/a11y-manual"), { recursive: true }); + await writeFile(path.join(root, "artifacts/tests/a11y-manual/INVOICE_LIST.md"), "kept\n"); + + await expect(writeFeatureFiles(root, files)).rejects.toThrow( + /refusing to overwrite: artifacts\/tests\/a11y-manual\/INVOICE_LIST\.md/u, + ); + expect(await readdir(root)).toEqual(["artifacts"]); + }); + + it("refuses an existing feature directory", async () => { + const root = await emptyRoot(); + await mkdir(path.join(root, "src/features/invoice-feature"), { recursive: true }); + + await expect( + writeFeatureFiles(root, plan({ id: "invoice-feature" }).files, [ + "src/features/invoice-feature", + ]), + ).rejects.toThrow(CreateFeatureError); + }); + + it("removes what it wrote when a later write fails", async () => { + const root = await emptyRoot(); + const files = new Map([ + ["src/features/broken/first.ts", "export {};\n"], + // A file cannot be a directory, so this write fails after the first. + ["src/features/broken/first.ts/second.ts", "export {};\n"], + ]); + + await expect(writeFeatureFiles(root, files)).rejects.toThrow(); + await expect(access(path.join(root, "src"))).rejects.toThrow(); + }); +});