diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index a19036d4..6de373e2 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -193,8 +193,8 @@ ], "consumerIdentityField": "operationId", "consumerDirectories": [ - "src/features/reference-feature/adapters", - "src/features/reference-feature/application" + "src/features/*/adapters", + "src/features/*/application" ], "breakingFields": [ "method", @@ -234,8 +234,8 @@ "consumerIdentityField": "schemaId", "consumerDirectories": [ "src/presentation/routes", - "src/features/reference-feature/presentation", - "src/features/reference-feature/contracts" + "src/features/*/presentation", + "src/features/*/contracts" ], "breakingFields": ["schemaId", "boundary", "runtime"] }, diff --git a/docs/architecture/capability-consumer-experience.md b/docs/architecture/capability-consumer-experience.md index f9f2e822..a214da6d 100644 --- a/docs/architecture/capability-consumer-experience.md +++ b/docs/architecture/capability-consumer-experience.md @@ -48,20 +48,19 @@ its business requirement. ## Scenario B — IndexedDB local draft -The original executable consumer probe remains at: +The executable consumer probe is: `tests/contract/consumer-experience/indexeddb-local-draft.test.ts` -with its isolated fixture: +It runs and reads the one Local Draft implementation under +`src/features/local-draft-feature`; the isolated fixture copy it used to probe +had drifted from `src` and was removed (09-12). -`tests/contract/consumer-experience/fixtures/local-draft-feature.ts` - -The architecture is now also exercised by a real vertical slice under: - -`src/features/local-draft-feature` - -It owns the Local Draft domain/application API and binds an -`IndexedDbRepositoryPort` in its feature adapter. The +The feature owns the Local Draft domain/application API and declares the slice +of the repository it calls (`LocalDraftRepository` in +`src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts`). The +host hands in an `IndexedDbRepositoryPort` through the +`indexedDb` capability; the port satisfies that slice structurally. The cross-capability composition contract lives at: `tests/contract/reusable-capability/feature-adapter-composition.test.ts` @@ -80,25 +79,24 @@ It runs against native browser IndexedDB. The test creates the platform save/find/remove through the feature API. The Local Draft feature still does not import the IndexedDB runtime or native browser API. -Measured probe result: +Measured on `src/features/local-draft-feature` (09-12): | Metric | Result | | --- | ---: | -| feature-owned fixture LOC | 97 | -| platform import statements | 1 | +| feature LOC (all `.ts` files) | 295 | +| import statements leaving the feature (`contracts/errors`, `contracts/result`, `application-api`, `feature-adapter-contribution`) | 7 | | native IndexedDB API references | 0 | | `src/adapters/storage/indexeddb/**` imports | 0 | -| runtime-internal IndexedDB types imported by feature | 0 | +| `src/application/ports/browser-file-storage/**` imports | 0 | -The feature depends only on the public application boundary: - -`src/application/ports/browser-file-storage/index.ts` - -and specifically `IndexedDbRepositoryPort`. +The feature does not import the storage runtime or its port, so removing the +browser file/storage runtime (`test:browser-file-storage-removal`) leaves it +compiling. The contract test rejects feature source that reaches for `globalThis.indexedDB`, `IDBFactory`, `IDBDatabase`, `IDBTransaction`, -`IDBObjectStore` or the concrete IndexedDB adapter directory. +`IDBObjectStore`, the concrete IndexedDB adapter directory or the +browser-file-storage port. ## What this does and does not prove diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index 6cb3ca28..d820018e 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -138,6 +138,17 @@ browser-capability test composes the feature over the real `createIndexedDbRuntime` and native IndexedDB, proving that this seam is not limited to an in-memory contract fixture. +The bootstrap does not build `indexedDb`: IndexedDB is an opt-in reference +runtime (`productionComposition: false` in +`config/recipes/frontend-capability-recipes.json`). The composition example is +`recipes/frontend-capabilities/indexeddb-feature-capability.ts` +(`createLocalDraftIndexedDbCapability`, exercised by +`tests/recipes/indexeddb-feature-capability.test.ts`). A product that installs a +feature with `needs: ["indexedDb"]` copies it and adds `indexedDb` to the feature +capabilities in `src/bootstrap/runtime-adapters.ts`. Until it does, that object +fails the app typecheck, and `composeFeatureAdapterInputs()` rejects the +composition with `feature needs indexedDb, which the host did not provide`. + ## Presentation consumer surface `ApplicationProvider` remains the composition root for presentation, but new diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index ab757891..020c17ec 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -26,14 +26,10 @@ remain stable in the shell. ## Registered routes -| ID | Path | Access | Surface | -| --- | --- | --- | --- | -| `APP_HOME` | `/` | public | readiness dashboard | -| `EXAMPLES_UI` | `/examples/ui` | public | interactive primitives and tokens | -| `EXAMPLES_STATES` | `/examples/states` | public | async and access state matrix | -| `EXAMPLES_AUTH` | `/examples/auth` | public | session integration controls | -| `REFERENCE_RESOURCE_LIST` | `/examples/reference-resources` | session-required | removable vertical slice | -| `NOT_FOUND` | `*` | public | safe navigation recovery | +The route list is `ROUTE_REGISTRY` (`src/features/installed-feature-contracts.ts`): +the platform routes of `src/contracts/routes.ts` plus the routes of every +installed feature. The platform overview page (`/examples/platform`) shows the +composed list at runtime, so this document does not keep a copy of it. Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not maintain a second route list. The client access decision never claims to be @@ -69,25 +65,81 @@ safe default. The `demo` adapter reports one fixed demo user as its subject. ## Extending the starter -The steps below describe the current extension path. New platform work should follow +New platform work should follow [routing, page templates, and reusable patterns](./routing-pages-and-patterns.md) and the [TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md) rather than adding another independent route or data-loading convention. -1. Add a serializable contribution under the feature ownership boundary and - install it through `src/features/installed-feature-contracts.ts`. -2. Add the lazy component and route codecs through - `src/features/installed-feature-runtimes.tsx`. -3. Compose feature application inputs and outbound gateways only through - `src/features/installed-feature-adapters.ts`. -4. Use the semantic tokens, UI primitives, and state surfaces before adding a - project-specific variant. -5. Add component behavior, all-engine E2E, automated axe, and signed manual - route evidence. -6. Run `test:sample-removal` to prove the generic starter typechecks, passes - architecture/registry/tests/coverage/source-evidence/home smoke, and builds - without the complete reference feature. +### Ownership declarations + +Features, contexts and apps are discovered by +`scripts/generate-product-feature-index.ts`. Each boundary declares only its +parent, as exported string or integer literals the generator reads: + +| File | Exports | +| --- | --- | +| `src/apps//app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` | +| `src/contexts//context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` | +| `src/features//feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` | +| `src/features//context-routes.ts` | `FEATURE_CONTEXT_ROUTES` | + +The generator writes `src/.generated/` (git-ignored): the feature index the +installed catalogs import, the context index the router loads lazily, and the +selected app. Every build and check script runs it first; run it yourself with +`corepack pnpm generate:feature-index`. It fails, naming the file, when: + +- a directory under `src/features/` has no `feature-module.ts` and no + `NOT_INSTALLED` marker file (`src/features/local-draft-feature/NOT_INSTALLED` + is the one intentional example); +- a feature names an undeclared context, or a context an undeclared app; +- a context or app exceeds its declared budget; +- `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The + variable narrows the installed set here, before anything is compiled. + +### Adding a feature + +1. Create `src/features//feature-module.ts`. Build `FEATURE_MODULE` + with `defineFeatureModule` (`src/features/feature-module.ts`): the feature's + contract (routes, route runtime contracts, API operations, invalidation, + schemas, runtime schemas, mappers), its adapter contributions + (`defineFeatureAdapterContribution`, with `needs` naming the platform + capabilities it receives), its runtime descriptor (route codecs), its message + catalogs and its contract contributions. + `src/features/reference-feature/feature-module.ts` is the complete example. +2. Create `src/features//context-routes.ts` exporting + `FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here; the + owning context loads this file only when its route root is visited + (`src/features/reference-feature/context-routes.ts`). +3. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or + add `src/contexts//context-module.ts` owned by the app. +4. If the feature has application input, augment `ApplicationFeatureInputs` + from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`). +5. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, + `corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts` + keeps the installed catalogs compiling with more than one feature. +6. Run `corepack pnpm test:sample-removal -- --feature=` to prove + the product still builds and passes its gates without the feature. + +Files outside the feature directory: + +| File | Change | +| --- | --- | +| `src/.generated/*` | regenerated automatically | +| `src/contexts//context-module.ts` | only when the feature needs a new context | +| `config/runtime/.json` | optional `FEATURE_OVERRIDES` entry to switch the feature off | +| `src/bootstrap/runtime-adapters.ts` | only when `needs` includes `indexedDb`: add the capability, built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | + +The central catalogs (`src/features/installed-*.ts`) and the registry +governance file do not change: consumer directories there are globs over every +feature (`src/features/*/adapters`, `config/contracts/registry-governance.json`). + +### Before shipping + +- Use the semantic tokens, UI primitives, and state surfaces before adding a + project-specific variant. +- Add component behavior, all-engine E2E, automated axe, and signed manual + route evidence. Theme preference is the public `COLOR_SCHEME` storage contract. Authentication tokens and other secrets remain forbidden storage keys. diff --git a/eslint.config.ts b/eslint.config.ts index 2505f4b5..bb445e91 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -865,4 +865,50 @@ export default [ ], }, }, + { + // 13-06. Vite inlines every loaded VITE_* value into the bundle wherever + // code references the whole `import.meta.env` object, including values no + // code reads. Keyed reads are replaced one by one. + files: [`src/**/*.${sourceExtensions}`], + plugins: { + "build-env": { + rules: { + "no-whole-import-meta-env": { + meta: { + type: "problem", + schema: [], + messages: { + whole: + "Read build variables by key (import.meta.env.VITE_NAME). Referencing import.meta or import.meta.env as a whole bundles every VITE_* value (13-06).", + }, + }, + create(context: any) { + const isMember = (node: any) => + node?.type === "MemberExpression" || + node?.type === "OptionalMemberExpression"; + return { + MetaProperty(node: any) { + if (node.meta?.name !== "import") return; + const member = node.parent; + if (!isMember(member) || member.object !== node || member.computed) { + context.report({ node, messageId: "whole" }); + return; + } + if (member.property?.name !== "env") return; + const read = member.parent; + if (isMember(read) && read.object === member && !read.computed) { + return; + } + context.report({ node: member, messageId: "whole" }); + }, + }; + }, + }, + }, + }, + }, + rules: { + "build-env/no-whole-import-meta-env": "error", + }, + }, ]; diff --git a/package.json b/package.json index 08384a87..505cd341 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "check:i18n:fixture": "node scripts/generate-product-feature-index.ts && node scripts/check-i18n.ts --fixture", "check:adapter-inventory": "node scripts/check-adapter-inventory.ts", "check:remediation-ledger": "node scripts/check-remediation-ledger.ts", - "check:release-admission": "node scripts/check-release-admission.ts", + "check:release-admission": "node scripts/generate-product-feature-index.ts && node scripts/check-release-admission.ts", "check:diagnostics": "node scripts/generate-product-feature-index.ts && node scripts/check-diagnostics.ts", "check:diagnostics:fixture": "node scripts/generate-product-feature-index.ts && node scripts/check-diagnostics.ts --fixture", "check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test && corepack pnpm check:types:recipes && corepack pnpm check:types:web-worker && corepack pnpm check:types:service-worker", @@ -72,7 +72,7 @@ "check:test-evidence:fixture": "node scripts/check-test-evidence.ts --source-root tests/fixtures/test-evidence/forbidden --artifact artifacts/quality/test-evidence-fixture.json", "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/test-sample-removal.ts", + "test:sample-removal": "node scripts/generate-product-feature-index.ts && node scripts/test-sample-removal.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", diff --git a/recipes/frontend-capabilities/indexeddb-feature-capability.ts b/recipes/frontend-capabilities/indexeddb-feature-capability.ts new file mode 100644 index 00000000..c5b7aeb7 --- /dev/null +++ b/recipes/frontend-capabilities/indexeddb-feature-capability.ts @@ -0,0 +1,137 @@ +import { + createIndexedDbRuntime, + type IndexedDbRuntimeDependencies, +} from "../../src/adapters/storage/indexeddb/index.ts"; +import type { IndexedDbDatasetScope } from "../../src/application/ports/browser-file-storage/index.ts"; +import { + createIndexedDbRepositoryProvider, + type IndexedDbRepositoryProvider, +} from "../../src/features/feature-adapter-contribution.ts"; +import type {} from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; +import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts"; + +type LocalDraftRuntimeDependencies = IndexedDbRuntimeDependencies< + LocalDraft, + LocalDraft, + never +>; +type LocalDraftRuntime = ReturnType< + typeof createIndexedDbRuntime +>; + +/** + * 09-05. How a host builds the `indexedDb` feature capability, shown for the + * local-draft sample. IndexedDB is an opt-in reference runtime + * (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json, + * `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does + * not build it. A product that installs a feature with `needs: ["indexedDb"]` + * copies this into its composition, replaces the codec, migrations and storage + * policy with its own decisions, and adds `indexedDb` to the feature + * capabilities there; until it does, that object fails the app typecheck and + * `composeFeatureAdapterInputs` names the missing capability. + * + * The scope tokens come from the product's storage registry and the lifecycle + * authority from its composition root; neither is invented here. + */ +export function createLocalDraftIndexedDbCapability( + options: Readonly<{ + // The sample keeps drafts across sign-out, so its dataset is origin-shared. + scope: IndexedDbDatasetScope & Readonly<{ accountScope: "ORIGIN_SHARED" }>; + authorizeLifecycle: LocalDraftRuntimeDependencies["authorizeLifecycle"]; + /** Defaults to the browser's `indexedDB`; tests pass an in-memory one. */ + factory?: IDBFactory; + }>, +): Readonly<{ + indexedDb: IndexedDbRepositoryProvider; + /** Opens (and migrates) the database; repository calls fail until it has. */ + open(signal?: AbortSignal): ReturnType; + close(): void; +}> { + const runtime = createIndexedDbRuntime({ + ...(options.factory === undefined ? {} : { factory: options.factory }), + scope: options.scope, + storagePolicy: Object.freeze({ + owner: "local-draft-feature", + namespace: "local-draft", + classification: "INTERNAL", + authority: "LOCAL_FIRST", + accountScope: "ORIGIN_SHARED", + retention: Object.freeze({ kind: "EXPLICIT_DELETE" }), + softBudgetBytes: 1_000_000, + hardBudgetBytes: 2_000_000, + evictionPriority: "USER_AUTHORED", + logoutAction: "KEEP_ORIGIN_SHARED", + accountDeletionAction: "KEEP_ORIGIN_SHARED", + pressureAction: "RETAIN", + unavailableFallback: "READ_ONLY", + }), + schemaVersion: 1, + recordStore: "records", + governanceStore: "governance", + retentionStore: "retention", + retentionEligibilityIndex: "by-eligibility", + lifecycleMetadataStores: [], + idempotencyStore: "receipts", + idempotencyExpiryIndex: "by-expiry", + receiptRetentionMs: 60_000, + maxIdempotencyReceipts: 100, + migrations: [ + { + id: "local-draft-schema-v1", + fromVersion: 0, + toVersion: 1, + operations: [ + { kind: "CREATE_STORE", name: "governance", keyPath: "bindingKey" }, + { + kind: "CREATE_STORE", + name: "retention", + keyPath: "recordKey", + indexes: [{ name: "by-eligibility", keyPath: "eligibleAtEpochMs" }], + }, + { kind: "CREATE_STORE", name: "records", keyPath: "key" }, + { + kind: "CREATE_STORE", + name: "receipts", + keyPath: "idempotencyKey", + indexes: [{ name: "by-expiry", keyPath: "expiresAtEpochMs" }], + }, + ], + }, + ], + codec: { + currentVersion: 1, + encode: (value) => ({ ok: true, value }), + measureStoredBytes: (value) => + new TextEncoder().encode(JSON.stringify(value)).byteLength, + decode: (version, value) => { + if (version !== 1 || value === null || typeof value !== "object") { + return { ok: false }; + } + const candidate = value as Partial; + return typeof candidate.draftId === "string" && + typeof candidate.title === "string" && + typeof candidate.body === "string" + ? { ok: true, value: candidate as LocalDraft } + : { ok: false }; + }, + fingerprint: async (value) => { + const bytes = new TextEncoder().encode( + JSON.stringify([value.draftId, value.title, value.body]), + ); + const digest = await crypto.subtle.digest("SHA-256", bytes); + return Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + }, + }, + queryPolicy: { plan: () => ({ limit: 1 }) }, + authorizeLifecycle: options.authorizeLifecycle, + }); + return Object.freeze({ + indexedDb: createIndexedDbRepositoryProvider( + Object.freeze({ "local-draft": runtime }), + ), + open: (signal?: AbortSignal) => runtime.open(signal), + close: () => runtime.close(), + }); +} diff --git a/scripts/check-diagnostics.ts b/scripts/check-diagnostics.ts index 7823f6b5..62a1ac29 100644 --- a/scripts/check-diagnostics.ts +++ b/scripts/check-diagnostics.ts @@ -47,6 +47,7 @@ const diagnosticProducerFiles: Readonly> = { "ui.render.failed": "src/application/create-application.ts", "release.mismatch.detected": "src/application/create-application.ts", "telemetry.delivery.dropped": "src/bootstrap/runtime-adapters.ts", + "feature.override.unknown": "src/bootstrap/runtime-adapters.ts", }; for (const key of DIAGNOSTIC_CONTEXT_ALLOWLIST) { diff --git a/scripts/check-registries.ts b/scripts/check-registries.ts index 9c458640..3bec84f5 100644 --- a/scripts/check-registries.ts +++ b/scripts/check-registries.ts @@ -330,6 +330,27 @@ function projectSnapshotRows( }); } +/** + * 09-07. `src/features/*\/adapters` names that directory in every feature, so + * adding a feature does not mean adding it to this governance file. + */ +async function expandDirectoryPattern(pattern: string): Promise { + const star = pattern.split("/").indexOf("*"); + if (star === -1) return [pattern]; + const segments = pattern.split("/"); + const parent = segments.slice(0, star).join("/"); + const rest = segments.slice(star + 1).join("/"); + const entries = await readdir(parent, { withFileTypes: true }).catch(() => []); + const expanded = await Promise.all( + entries + .filter((entry) => entry.isDirectory()) + .map((entry) => + expandDirectoryPattern(path.join(parent, entry.name, rest)), + ), + ); + return expanded.flat(); +} + async function filesBelow(directory: string): Promise { try { const entries = await readdir(directory, { withFileTypes: true }); @@ -548,7 +569,11 @@ for (const specification of governance.registries) { if (specification.consumerIdentityField) { const consumerFiles = ( await Promise.all( - (specification.consumerDirectories ?? []).map(filesBelow), + (await Promise.all( + (specification.consumerDirectories ?? []).map(expandDirectoryPattern), + )) + .flat() + .map(filesBelow), ) ).flat(); const sourcePath = sourcesByRegistry.get(specification.registryId); diff --git a/scripts/check-release-admission.ts b/scripts/check-release-admission.ts index be06a6d6..15e0299b 100644 --- a/scripts/check-release-admission.ts +++ b/scripts/check-release-admission.ts @@ -7,7 +7,9 @@ import { isDeploymentTarget, type AdmissionInput, } from "../src/contracts/deployment-admission.ts"; +import { unknownProductFeatureOverrides } from "../src/contracts/product-features.ts"; import { parseRuntimeConfigArtifact } from "../src/contracts/release-artifacts.ts"; +import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-manifest.ts"; /** * §6.4 / FE-GATE-027. Refuses to admit an artifact to an environment it was not @@ -79,6 +81,18 @@ async function main(): Promise { } const violations = findAdmissionViolations(declared, config); + // 09-09. Inert by design (a shared document may name another build's + // features), so this warns instead of refusing. + const warnings = unknownProductFeatureOverrides( + COMPILED_PRODUCT_FEATURE_IDS, + "FEATURE_OVERRIDES" in config ? config.FEATURE_OVERRIDES : undefined, + ).map((featureId) => ({ + field: `FEATURE_OVERRIDES.${featureId}`, + reason: `names no feature this build declares (${COMPILED_PRODUCT_FEATURE_IDS.join(", ") || "none"}); the override does nothing`, + })); + for (const warning of warnings) { + process.stderr.write(`release admission warning: ${warning.field} ${warning.reason}\n`); + } await mkdir("artifacts/release", { recursive: true }); await writeFile( RECORD_PATH, @@ -93,6 +107,7 @@ async function main(): Promise { releaseId: config.RELEASE_ID ?? null, status: violations.length === 0 ? "ADMITTED" : "REFUSED", violations, + warnings, }, null, 2, diff --git a/scripts/contracts/release-artifacts.ts b/scripts/contracts/release-artifacts.ts index f459f995..1f1b2270 100644 --- a/scripts/contracts/release-artifacts.ts +++ b/scripts/contracts/release-artifacts.ts @@ -688,6 +688,11 @@ export const deploymentAdmissionArtifactSchema = z violations: z.array( z.object({ field: nonEmptyString, reason: nonEmptyString }).strict(), ), + // 09-09. Findings that do not refuse the artifact, e.g. an override key + // naming a feature this build does not declare. + warnings: z.array( + z.object({ field: nonEmptyString, reason: nonEmptyString }).strict(), + ), }) .strict(); diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 7f96301d..e5ebdac9 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -2,6 +2,8 @@ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts"; + export type FeatureImportEntry = Readonly<{ id: string; importPath: string; @@ -14,8 +16,19 @@ export type FeatureIndexEntry = FeatureImportEntry & Readonly<{ contextMaxFeatures: number; }>; -export function renderFeatureIndex(entries: readonly FeatureImportEntry[]): string { +/** + * `declaredIds` is every feature the app declares, selected or not, so a build + * that left one out still reports it as `NOT_INSTALLED` without importing it. + */ +export function renderFeatureIndex( + entries: readonly FeatureImportEntry[], + declaredIds: readonly string[] = entries.map((entry) => entry.id), +): string { const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id)); + const declared = [...declaredIds] + .sort((left, right) => left.localeCompare(right)) + .map((id) => JSON.stringify(id)) + .join(", "); const imports = sorted .map( (entry, index) => @@ -24,7 +37,7 @@ export function renderFeatureIndex(entries: readonly FeatureImportEntry[]): stri .join("\n"); const modules = sorted.map((_, index) => ` featureModule${index},`).join("\n"); const featureImports = imports.length > 0 ? `${imports}\n` : ""; - return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`; + return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([${declared}]);\n\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`; } export function renderContextIndex(entries: readonly FeatureIndexEntry[]): string { @@ -92,7 +105,8 @@ export function renderContextIndex(entries: readonly FeatureIndexEntry[]): strin } /** - * Spec §3.2 / §5. Ownership declarations the generator reads. Each boundary + * Ownership declarations the generator reads, documented in + * docs/architecture/starter-experience.md ("Ownership declarations"). Each boundary * declares only its parent: * * src/apps//app-module.ts APP_MODULE_ID, APP_MAX_CONTEXTS @@ -164,10 +178,16 @@ export function resolveSelectedApp( return ids[0] as string; } -/** The production selection: one app -> its direct contexts -> their features. */ +/** + * The production selection: one app -> its direct contexts -> their features, + * narrowed by `VITE_PRODUCT_FEATURES` (09-02, D-9). The narrowing happens here + * so the bundle, the Node build scripts and the context router all import the + * same set, and a misspelt id fails the first build step. + */ export function selectAppIndexes( source: TopologyDeclarationSource, appId: string, + productFeatures?: string, ): SelectedAppIndexes { const app = source.app(appId); if (!app) throw new Error(`Unknown deployable app: ${appId}`); @@ -205,11 +225,15 @@ export function selectAppIndexes( if (new Set(ids).size !== ids.length) { throw new Error(`Duplicate generated feature ids: ${ids.join(", ")}`); } + const selected = selectCompiledProductFeatures( + entries.map((entry) => Object.freeze({ featureId: entry.id, entry })), + productFeatures, + ).map(({ entry }) => entry); return Object.freeze({ app, - entries: Object.freeze(entries), - featureIndex: renderFeatureIndex(entries), - contextIndex: renderContextIndex(entries), + entries: Object.freeze(selected), + featureIndex: renderFeatureIndex(selected, ids), + contextIndex: renderContextIndex(selected), appIndex: renderAppIndex(app), }); } @@ -235,9 +259,17 @@ function requiredInteger(source: string, name: string, file: string): number { return parsed; } +/** + * 09-07 (D-10). A feature directory must declare itself or say it is not + * installed. A missing or misspelt `feature-module.ts` used to drop the + * feature from the product without a word. + */ +export const NOT_INSTALLED_MARKER = "NOT_INSTALLED"; + async function readDeclarations( directory: string, fileName: string, + requiredUnless?: string, ): Promise[]> { const found: { directory: string; file: string; source: string }[] = []; let items; @@ -252,7 +284,13 @@ async function readDeclarations( try { found.push({ directory: item.name, file, source: await readFile(file, "utf8") }); } catch { - continue; + if (requiredUnless === undefined) continue; + const marker = await readFile(resolve(directory, item.name, requiredUnless)) + .then(() => true, () => false); + if (marker) continue; + throw new Error( + `src/features/${item.name} has no ${fileName}; add one or mark the directory with ${requiredUnless}`, + ); } } return found; @@ -295,7 +333,11 @@ export async function createFileSystemDeclarationSource( } const featuresByContext = new Map(); const featureIds = new Set(); - for (const declaration of await readDeclarations(resolve(root, "src/features"), "feature-module.ts")) { + for (const declaration of await readDeclarations( + resolve(root, "src/features"), + "feature-module.ts", + NOT_INSTALLED_MARKER, + )) { const feature: FeatureDeclaration = { id: requiredLiteral(declaration.source, "FEATURE_MODULE_ID", declaration.file), contextId: requiredLiteral(declaration.source, "FEATURE_CONTEXT_ID", declaration.file), @@ -321,9 +363,14 @@ export async function createFileSystemDeclarationSource( export async function generateAppIndexes( root: string, requestedApp: string | undefined, + productFeatures?: string, ): Promise { const source = await createFileSystemDeclarationSource(root); - return selectAppIndexes(source, resolveSelectedApp(source, requestedApp)); + return selectAppIndexes( + source, + resolveSelectedApp(source, requestedApp), + productFeatures, + ); } async function main(): Promise { @@ -344,7 +391,11 @@ async function main(): Promise { process.argv.find((argument) => argument.startsWith("--app="))?.slice("--app=".length) || process.env["PRODUCT_APP_ID"] || undefined; - const selected = await generateAppIndexes(root, requestedApp); + const selected = await generateAppIndexes( + root, + requestedApp, + process.env["VITE_PRODUCT_FEATURES"], + ); const rendered = { feature: selected.featureIndex, context: selected.contextIndex, diff --git a/scripts/generate-runtime-config.ts b/scripts/generate-runtime-config.ts index 9ca4ed2b..5e7e8b84 100644 --- a/scripts/generate-runtime-config.ts +++ b/scripts/generate-runtime-config.ts @@ -53,6 +53,17 @@ export async function generateRuntimeConfig( const supplied = environment[variable]; if (supplied !== undefined && supplied !== "") draft[field] = supplied; } + // 13-07. dist, and the release manifest in it, is served under the router + // base path; a root-relative profile URL is rebased onto it. + const basePath = environment["VITE_ROUTER_BASE_PATH"] || "/"; + const manifestUrl = draft["RELEASE_MANIFEST_URL"]; + if ( + typeof manifestUrl === "string" && + manifestUrl.startsWith("/") && + !manifestUrl.startsWith(basePath) + ) { + draft["RELEASE_MANIFEST_URL"] = `${basePath}${manifestUrl.slice(1)}`; + } const buildId = environment["VITE_BUILD_ID"] ?? "local-build"; const releaseId = environment["RELEASE_ID"] ?? "local-release"; draft["BUILD_ID"] = buildId; diff --git a/scripts/lib/classify-vite-bundle.ts b/scripts/lib/classify-vite-bundle.ts index 4521b2e9..2e0660db 100644 --- a/scripts/lib/classify-vite-bundle.ts +++ b/scripts/lib/classify-vite-bundle.ts @@ -2,12 +2,15 @@ type ViteManifestEntry = Readonly<{ file: string; isEntry?: boolean; imports?: readonly string[]; + dynamicImports?: readonly string[]; }>; /** - * Static imports of an entry are part of initial JavaScript. Every remaining - * JavaScript output is governed by the lazy-chunk budget. - * + * Static imports of an entry are part of initial JavaScript, and so are the + * chunks the entry itself imports dynamically: main.tsx only imports the + * application graph that way so it can report a graph that fails to evaluate + * (09-03). Every remaining JavaScript output is governed by the lazy-chunk + * budget. */ export function classifyViteJavascript( manifest: Readonly>, @@ -31,6 +34,7 @@ export function classifyViteJavascript( } if (entry.file.endsWith(".js")) initialFiles.add(entry.file); pendingKeys.push(...(entry.imports ?? [])); + if (entry.isEntry) pendingKeys.push(...(entry.dynamicImports ?? [])); } const allJavaScript = new Set( diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index 9dbd796a..884becff 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process"; import { cp, mkdir, + mkdtemp, readFile, readdir, rm, @@ -160,6 +161,78 @@ function runFixtureGit(root: string, argv: readonly string[]): void { } } +/** + * 14-08. A fresh fixture directory per run: two runs, or a run after one that + * crashed, no longer share (and overwrite) one fixed path. Callers remove it + * in `finally`. + */ +export async function createRemovalFixtureRoot(name: string): Promise { + const parent = path.resolve(".tmp"); + await mkdir(parent, { recursive: true }); + return mkdtemp(path.join(parent, `${name}-`)); +} + +export type RemovalCheck = Readonly<{ + name: string; + passed: boolean; + /** Why this check failed; each check names its own cause. */ + failure?: string; +}>; + +export function runRemovalFixtureCheck( + name: string, + root: string, + pnpmCli: string, + script: string, + extra: readonly string[] = [], +): RemovalCheck { + const status = spawnSync(process.execPath, [pnpmCli, script, ...extra], { + cwd: root, + stdio: "inherit", + env: process.env, + }).status; + return status === 0 + ? { name, passed: true } + : { + name, + passed: false, + failure: `corepack pnpm ${[script, ...extra].join(" ")} exited ${status ?? "on a signal"}`, + }; +} + +function escapeXml(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +/** + * 14-08. The report used to say `failures="1"` whatever failed, and put the + * residue list into every failed testcase, so a type error read as residue. + */ +export function renderRemovalJunit( + suite: string, + checks: readonly RemovalCheck[], +): string { + const failures = checks.filter((check) => !check.passed).length; + const cases = checks + .map((check) => + `${ + check.passed + ? "" + : `` + }`, + ) + .join(""); + return ( + `\n` + + `` + + `${cases}\n` + ); +} + export function runRemovalFixturePnpm( root: string, pnpmCli: string, diff --git a/scripts/test-browser-file-storage-runtime-removal.ts b/scripts/test-browser-file-storage-runtime-removal.ts index d042b892..a1e98de2 100644 --- a/scripts/test-browser-file-storage-runtime-removal.ts +++ b/scripts/test-browser-file-storage-runtime-removal.ts @@ -8,18 +8,19 @@ import path from "node:path"; import { assertNoRuntimeImports, + createRemovalFixtureRoot, prepareRemovalFixture, pruneRemovalFixtureCiContract, regenerateRemovalFixtureWorkflow, removeRuntimeDependentTests, + renderRemovalJunit, requireRemovalFixtureEnvironment, - runRemovalFixturePnpm, + runRemovalFixtureCheck, + type RemovalCheck, } from "./lib/removal-fixture.ts"; -const fixtureRoot = path.resolve( - ".tmp/browser-file-storage-runtime-removal", -); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); +const fixtureRoot = await createRemovalFixtureRoot("browser-file-storage-runtime-removal"); const runtimePaths = [ "src/application/ports/browser-file-storage", "src/application/ports/browser-transfer", @@ -31,6 +32,8 @@ const runtimePaths = [ "src/adapters/storage/opfs", "tests/browser-capabilities", "tests/fixtures/browser-file-storage-boundaries", + // The composition example of this runtime goes with it. + "recipes/frontend-capabilities/indexeddb-feature-capability.ts", ] as const; const runtimeSourceRoots = runtimePaths.filter((entry) => entry.startsWith("src/"), @@ -45,124 +48,117 @@ const removedEvidencePathFragments = [ "browser-capabilities", "browser-file-storage-runtime-removal", ] as const; -function runPnpm(script: string): boolean { - return runRemovalFixturePnpm(fixtureRoot, pnpmCli, script); +function check(name: string, script: string): RemovalCheck { + return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script); } -await prepareRemovalFixture(fixtureRoot); +let checks: RemovalCheck[]; +let removedRuntimeTests: number; +try { + await prepareRemovalFixture(fixtureRoot); -const removedRuntimeTests = - await removeRuntimeDependentTests(fixtureRoot, runtimeSourceRoots); -for (const runtimePath of runtimePaths) { - await rm(path.join(fixtureRoot, runtimePath), { - recursive: true, + removedRuntimeTests = + await removeRuntimeDependentTests(fixtureRoot, runtimeSourceRoots); + for (const runtimePath of runtimePaths) { + await rm(path.join(fixtureRoot, runtimePath), { + recursive: true, + force: true, + }); + } + + const catalogPath = path.join( + fixtureRoot, + "config/recipes/frontend-capability-recipes.json", + ); + const catalog = JSON.parse(await readFile(catalogPath, "utf8")) as { + recipes: Array>; + }; + const browserFileRuntimeRecipeIds = new Set([ + "offline-indexeddb", + "service-worker-pwa", + "file-transfer", + ]); + let removedRuntimeEntries = 0; + for (const recipe of catalog.recipes) { + if ( + typeof recipe.id !== "string" || + !browserFileRuntimeRecipeIds.has(recipe.id) || + !Object.hasOwn(recipe, "referenceRuntime") + ) { + continue; + } + delete recipe.referenceRuntime; + removedRuntimeEntries += 1; + } + if (removedRuntimeEntries !== 3) { + throw new Error( + `Expected three reference runtime catalog entries, removed ${removedRuntimeEntries}`, + ); + } + await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`); + + await rm(path.join(fixtureRoot, "playwright.capabilities.config.ts"), { force: true, }); -} - -const catalogPath = path.join( - fixtureRoot, - "config/recipes/frontend-capability-recipes.json", -); -const catalog = JSON.parse(await readFile(catalogPath, "utf8")) as { - recipes: Array>; -}; -const browserFileRuntimeRecipeIds = new Set([ - "offline-indexeddb", - "service-worker-pwa", - "file-transfer", -]); -let removedRuntimeEntries = 0; -for (const recipe of catalog.recipes) { - if ( - typeof recipe.id !== "string" || - !browserFileRuntimeRecipeIds.has(recipe.id) || - !Object.hasOwn(recipe, "referenceRuntime") - ) { - continue; - } - delete recipe.referenceRuntime; - removedRuntimeEntries += 1; -} -if (removedRuntimeEntries !== 3) { - throw new Error( - `Expected three reference runtime catalog entries, removed ${removedRuntimeEntries}`, + await rm( + path.join(fixtureRoot, "scripts/check-browser-file-storage-boundaries.ts"), + { force: true }, + ); + await rm( + path.join(fixtureRoot, "scripts/verify-browser-capability-evidence.ts"), + { force: true }, + ); + await rm( + path.join(fixtureRoot, "scripts/test-browser-file-storage-runtime-removal.ts"), + { force: true }, + ); + // The root snapshot locks the full repository inventory. This removal fixture + // validates its smaller registry through check:ci and its regenerated workflow. + await rm( + path.join(fixtureRoot, "tests/unit/ci-workflow-generation.test.ts"), + { force: true }, + ); + await rm( + path.join( + fixtureRoot, + "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", + ), + { force: true }, ); -} -await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`); -await rm(path.join(fixtureRoot, "playwright.capabilities.config.ts"), { - force: true, -}); -await rm( - path.join(fixtureRoot, "scripts/check-browser-file-storage-boundaries.ts"), - { force: true }, -); -await rm( - path.join(fixtureRoot, "scripts/verify-browser-capability-evidence.ts"), - { force: true }, -); -await rm( - path.join(fixtureRoot, "scripts/test-browser-file-storage-runtime-removal.ts"), - { force: true }, -); -// The root snapshot locks the full repository inventory. This removal fixture -// validates its smaller registry through check:ci and its regenerated workflow. -await rm( - path.join(fixtureRoot, "tests/unit/ci-workflow-generation.test.ts"), - { force: true }, -); -await rm( - path.join( + await pruneRemovalFixtureCiContract({ + root: fixtureRoot, + removedScripts, + removedEvidencePathFragments, + }); + await regenerateRemovalFixtureWorkflow(fixtureRoot); + await assertNoRuntimeImports( fixtureRoot, - "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", - ), - { force: true }, -); + runtimeSourceRoots, + "browser file/storage", + ); -await pruneRemovalFixtureCiContract({ - root: fixtureRoot, - removedScripts, - removedEvidencePathFragments, -}); -await regenerateRemovalFixtureWorkflow(fixtureRoot); -await assertNoRuntimeImports( - fixtureRoot, - runtimeSourceRoots, - "browser file/storage", -); - -const checks: Array = [ - ["typecheck", runPnpm("check:types")], - ["lint", runPnpm("lint")], - ["architecture", runPnpm("check:architecture")], - ["test", runPnpm("test:all")], - ["build", runPnpm("build")], - ["optional-catalog", runPnpm("check:optional-recipes:source")], - ["ci-contract", runPnpm("check:ci")], -]; -const passed = checks.every(([, result]) => result); + checks = [ + check("typecheck", "check:types"), + check("lint", "lint"), + check("architecture", "check:architecture"), + check("test", "test:all"), + check("build", "build"), + check("optional-catalog", "check:optional-recipes:source"), + check("ci-contract", "check:ci"), + ]; +} finally { + await rm(fixtureRoot, { recursive: true, force: true }); +} +const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( "artifacts/tests/browser-file-storage-runtime-removal.xml", - `\n` + - `` + - checks - .map( - ([name, result]) => - `${result ? "" : ""}`, - ) - .join("") + - `\n`, + renderRemovalJunit("browser-file-storage-runtime-removal", checks), ); -await rm(fixtureRoot, { recursive: true, force: true }); - -if (!passed) { +if (failed.length > 0) { process.stderr.write( - `Browser file/storage runtime removal failed: ${checks - .filter(([, result]) => !result) - .map(([name]) => name) - .join(", ")}\n`, + `Browser file/storage runtime removal failed: ${failed.map((entry) => entry.name).join(", ")}\n`, ); process.exit(1); } diff --git a/scripts/test-optional-recipe-removal.ts b/scripts/test-optional-recipe-removal.ts index a64021bb..e7bca250 100644 --- a/scripts/test-optional-recipe-removal.ts +++ b/scripts/test-optional-recipe-removal.ts @@ -7,98 +7,98 @@ import { import path from "node:path"; import { + createRemovalFixtureRoot, filesBelow, prepareRemovalFixture, pruneRemovalFixtureCiContract, pruneScriptOrchestration, regenerateRemovalFixtureWorkflow, + renderRemovalJunit, requireRemovalFixtureEnvironment, - runRemovalFixturePnpm, + runRemovalFixtureCheck, + type RemovalCheck, } from "./lib/removal-fixture.ts"; -const fixtureRoot = path.resolve(".tmp/optional-recipe-removal"); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); +const fixtureRoot = await createRemovalFixtureRoot("optional-recipe-removal"); -function runPnpm(script: string): boolean { - return runRemovalFixturePnpm(fixtureRoot, pnpmCli, script); +function check(name: string, script: string): RemovalCheck { + return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script); } -await prepareRemovalFixture(fixtureRoot); -for (const rootOnlyTest of [ - "tests/unit/ci-workflow-generation.test.ts", - "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", -]) { - await rm(path.join(fixtureRoot, rootOnlyTest), { force: true }); -} -await rm(path.join(fixtureRoot, "recipes"), { recursive: true, force: true }); -await rm(path.join(fixtureRoot, "tests/recipes"), { - recursive: true, - force: true, -}); - -const removedCiScripts = new Set([ - "check:types:recipes", - "test:recipes", - "check:optional-recipes", - "check:optional-recipes:source", - "check:optional-recipe-fixtures", - "test:optional-recipe-removal", -]); -const fixturePackagePath = path.join(fixtureRoot, "package.json"); -const fixturePackage = JSON.parse(await readFile(fixturePackagePath, "utf8")) as { - scripts: Record; -}; -pruneScriptOrchestration(fixturePackage.scripts, "check:types", removedCiScripts); -pruneScriptOrchestration(fixturePackage.scripts, "test:all", removedCiScripts); -await writeFile(fixturePackagePath, `${JSON.stringify(fixturePackage, null, 2)}\n`); -await pruneRemovalFixtureCiContract({ - root: fixtureRoot, - removedScripts: removedCiScripts, - removedEvidencePathFragments: [ - "optional-recipes", - "optional-recipe-fixtures", - "optional-recipe-removal", - ], -}); -await regenerateRemovalFixtureWorkflow(fixtureRoot); - -const checks: Array<[string, boolean]> = [ - ["typecheck", runPnpm("check:types")], - ["architecture", runPnpm("check:architecture")], - ["test", runPnpm("test:all")], - ["build", runPnpm("build")], - ["ci-contract", runPnpm("check:ci")], -]; -const residue: string[] = []; -for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { - if (!/\.(?:js|css|html|json)$/.test(file)) continue; - const content = await readFile(file, "utf8"); - if (content.includes("frontend-optional-recipe-must-not-reach-production")) { - residue.push(path.relative(fixtureRoot, file)); +let checks: RemovalCheck[]; +try { + await prepareRemovalFixture(fixtureRoot); + for (const rootOnlyTest of [ + "tests/unit/ci-workflow-generation.test.ts", + "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", + ]) { + await rm(path.join(fixtureRoot, rootOnlyTest), { force: true }); } + await rm(path.join(fixtureRoot, "recipes"), { recursive: true, force: true }); + await rm(path.join(fixtureRoot, "tests/recipes"), { + recursive: true, + force: true, + }); + + const removedCiScripts = new Set([ + "check:types:recipes", + "test:recipes", + "check:optional-recipes", + "check:optional-recipes:source", + "check:optional-recipe-fixtures", + "test:optional-recipe-removal", + ]); + const fixturePackagePath = path.join(fixtureRoot, "package.json"); + const fixturePackage = JSON.parse(await readFile(fixturePackagePath, "utf8")) as { + scripts: Record; + }; + pruneScriptOrchestration(fixturePackage.scripts, "check:types", removedCiScripts); + pruneScriptOrchestration(fixturePackage.scripts, "test:all", removedCiScripts); + await writeFile(fixturePackagePath, `${JSON.stringify(fixturePackage, null, 2)}\n`); + await pruneRemovalFixtureCiContract({ + root: fixtureRoot, + removedScripts: removedCiScripts, + removedEvidencePathFragments: [ + "optional-recipes", + "optional-recipe-fixtures", + "optional-recipe-removal", + ], + }); + await regenerateRemovalFixtureWorkflow(fixtureRoot); + + checks = [ + check("typecheck", "check:types"), + check("architecture", "check:architecture"), + check("test", "test:all"), + check("build", "build"), + check("ci-contract", "check:ci"), + ]; + const residue: string[] = []; + for (const file of await filesBelow(path.join(fixtureRoot, "dist")).catch(() => [])) { + if (!/\.(?:js|css|html|json)$/.test(file)) continue; + const content = await readFile(file, "utf8"); + if (content.includes("frontend-optional-recipe-must-not-reach-production")) { + residue.push(path.relative(fixtureRoot, file)); + } + } + checks.push( + residue.length === 0 + ? { name: "bundle-residue", passed: true } + : { name: "bundle-residue", passed: false, failure: `residue: ${residue.join(", ")}` }, + ); +} finally { + await rm(fixtureRoot, { recursive: true, force: true }); } -checks.push(["bundle-residue", residue.length === 0]); -const passed = checks.every(([, result]) => result); +const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( "artifacts/tests/optional-recipe-removal.xml", - `\n` + - `` + - checks - .map( - ([name, result]) => - `${result ? "" : `${residue.join(", ")}`}`, - ) - .join("") + - `\n`, + renderRemovalJunit("optional-recipe-removal", checks), ); -await rm(fixtureRoot, { recursive: true, force: true }); -if (!passed) { +if (failed.length > 0) { process.stderr.write( - `Optional recipe removal failed: ${checks - .filter(([, result]) => !result) - .map(([name]) => name) - .join(", ")}\n`, + `Optional recipe removal failed: ${failed.map((entry) => entry.name).join(", ")}\n`, ); process.exit(1); } diff --git a/scripts/test-realtime-runtime-removal.ts b/scripts/test-realtime-runtime-removal.ts index 309d2190..e8e25405 100644 --- a/scripts/test-realtime-runtime-removal.ts +++ b/scripts/test-realtime-runtime-removal.ts @@ -8,16 +8,19 @@ import path from "node:path"; import { assertNoRuntimeImports, + createRemovalFixtureRoot, prepareRemovalFixture, pruneRemovalFixtureCiContract, regenerateRemovalFixtureWorkflow, removeRuntimeDependentTests, + renderRemovalJunit, requireRemovalFixtureEnvironment, - runRemovalFixturePnpm, + runRemovalFixtureCheck, + type RemovalCheck, } from "./lib/removal-fixture.ts"; -const fixtureRoot = path.resolve(".tmp/realtime-runtime-removal"); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); +const fixtureRoot = await createRemovalFixtureRoot("realtime-runtime-removal"); const runtimePaths = [ "src/application/ports/realtime", "src/application/ports/out/web-push-control.ts", @@ -41,111 +44,104 @@ const removedEvidencePathFragments = [ "realtime-boundaries", "realtime-runtime-removal", ] as const; -function runPnpm(script: string): boolean { - return runRemovalFixturePnpm(fixtureRoot, pnpmCli, script); +function check(name: string, script: string): RemovalCheck { + return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script); } -await prepareRemovalFixture(fixtureRoot); +let checks: RemovalCheck[]; +let removedRuntimeTests: number; +try { + await prepareRemovalFixture(fixtureRoot); -const removedRuntimeTests = - await removeRuntimeDependentTests(fixtureRoot, runtimeSourceRoots); -for (const runtimePath of runtimePaths) { - await rm(path.join(fixtureRoot, runtimePath), { - recursive: true, - force: true, - }); -} + removedRuntimeTests = + await removeRuntimeDependentTests(fixtureRoot, runtimeSourceRoots); + for (const runtimePath of runtimePaths) { + await rm(path.join(fixtureRoot, runtimePath), { + recursive: true, + force: true, + }); + } -const outputPortsIndexPath = path.join( - fixtureRoot, - "src/application/ports/out/index.ts", -); -const outputPortsIndex = await readFile(outputPortsIndexPath, "utf8"); -await writeFile( - outputPortsIndexPath, - outputPortsIndex.replace( - 'export type { WebPushControlPort } from "./web-push-control.ts";\n', - "", - ), -); - -const catalogPath = path.join( - fixtureRoot, - "config/recipes/frontend-capability-recipes.json", -); -const catalog = JSON.parse(await readFile(catalogPath, "utf8")) as { - recipes: Array>; -}; -const realtimeRecipe = catalog.recipes.find( - (recipe) => recipe.id === "realtime", -); -if (!realtimeRecipe || !Object.hasOwn(realtimeRecipe, "referenceRuntime")) { - throw new Error("Expected realtime reference runtime catalog entry"); -} -delete realtimeRecipe.referenceRuntime; -await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`); - -for (const scriptPath of [ - "scripts/check-realtime-boundaries.ts", - "scripts/check-realtime-boundary-fixtures.ts", - "scripts/lib/realtime-boundaries.ts", - "scripts/test-realtime-runtime-removal.ts", -]) { - await rm(path.join(fixtureRoot, scriptPath), { force: true }); -} -// The root snapshot locks the full repository inventory. This removal fixture -// validates its smaller registry through check:ci and its regenerated workflow. -await rm( - path.join(fixtureRoot, "tests/unit/ci-workflow-generation.test.ts"), - { force: true }, -); -await rm( - path.join( + const outputPortsIndexPath = path.join( fixtureRoot, - "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", - ), - { force: true }, -); + "src/application/ports/out/index.ts", + ); + const outputPortsIndex = await readFile(outputPortsIndexPath, "utf8"); + await writeFile( + outputPortsIndexPath, + outputPortsIndex.replace( + 'export type { WebPushControlPort } from "./web-push-control.ts";\n', + "", + ), + ); -await pruneRemovalFixtureCiContract({ - root: fixtureRoot, - removedScripts: new Set(runtimeScripts), - removedEvidencePathFragments, -}); -await regenerateRemovalFixtureWorkflow(fixtureRoot); -await assertNoRuntimeImports(fixtureRoot, runtimeSourceRoots, "realtime"); + const catalogPath = path.join( + fixtureRoot, + "config/recipes/frontend-capability-recipes.json", + ); + const catalog = JSON.parse(await readFile(catalogPath, "utf8")) as { + recipes: Array>; + }; + const realtimeRecipe = catalog.recipes.find( + (recipe) => recipe.id === "realtime", + ); + if (!realtimeRecipe || !Object.hasOwn(realtimeRecipe, "referenceRuntime")) { + throw new Error("Expected realtime reference runtime catalog entry"); + } + delete realtimeRecipe.referenceRuntime; + await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`); -const checks: Array = [ - ["typecheck", runPnpm("check:types")], - ["lint", runPnpm("lint")], - ["architecture", runPnpm("check:architecture")], - ["test", runPnpm("test:all")], - ["build", runPnpm("build")], - ["optional-catalog", runPnpm("check:optional-recipes:source")], - ["ci-contract", runPnpm("check:ci")], -]; -const passed = checks.every(([, result]) => result); + for (const scriptPath of [ + "scripts/check-realtime-boundaries.ts", + "scripts/check-realtime-boundary-fixtures.ts", + "scripts/lib/realtime-boundaries.ts", + "scripts/test-realtime-runtime-removal.ts", + ]) { + await rm(path.join(fixtureRoot, scriptPath), { force: true }); + } + // The root snapshot locks the full repository inventory. This removal fixture + // validates its smaller registry through check:ci and its regenerated workflow. + await rm( + path.join(fixtureRoot, "tests/unit/ci-workflow-generation.test.ts"), + { force: true }, + ); + await rm( + path.join( + fixtureRoot, + "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", + ), + { force: true }, + ); + + await pruneRemovalFixtureCiContract({ + root: fixtureRoot, + removedScripts: new Set(runtimeScripts), + removedEvidencePathFragments, + }); + await regenerateRemovalFixtureWorkflow(fixtureRoot); + await assertNoRuntimeImports(fixtureRoot, runtimeSourceRoots, "realtime"); + + checks = [ + check("typecheck", "check:types"), + check("lint", "lint"), + check("architecture", "check:architecture"), + check("test", "test:all"), + check("build", "build"), + check("optional-catalog", "check:optional-recipes:source"), + check("ci-contract", "check:ci"), + ]; +} finally { + await rm(fixtureRoot, { recursive: true, force: true }); +} +const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( "artifacts/tests/realtime-runtime-removal.xml", - `\n` + - `` + - checks - .map( - ([name, result]) => - `${result ? "" : ""}`, - ) - .join("") + - `\n`, + renderRemovalJunit("realtime-runtime-removal", checks), ); -await rm(fixtureRoot, { recursive: true, force: true }); - -if (!passed) { +if (failed.length > 0) { process.stderr.write( - `Realtime runtime removal failed: ${checks - .filter(([, result]) => !result) - .map(([name]) => name) - .join(", ")}\n`, + `Realtime runtime removal failed: ${failed.map((entry) => entry.name).join(", ")}\n`, ); process.exit(1); } diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 732601ae..8113f6c1 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -1,32 +1,150 @@ import { access, mkdir, - mkdtemp, + readdir, readFile, rm, writeFile, } from "node:fs/promises"; import path from "node:path"; +import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts"; +import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; import { isProductionModulePath } from "./lib/risk-coverage.ts"; import { + createRemovalFixtureRoot, filesBelow, prepareRemovalFixture, pruneRemovalFixtureCiContract, pruneScriptOrchestration, regenerateRemovalFixtureWorkflow, + renderRemovalJunit, requireRemovalFixtureEnvironment, + runRemovalFixtureCheck, runRemovalFixturePnpm, + type RemovalCheck, } from "./lib/removal-fixture.ts"; -const fixtureParent = path.resolve(".tmp"); -await mkdir(fixtureParent, { recursive: true }); -const fixtureRoot = await mkdtemp( - path.join(fixtureParent, "reference-feature-removal-"), -); +/** + * 09-07 (D-10). Removes one installed feature, `--feature=` (default: the + * reference sample), from a copy of the repository and proves the rest still + * typechecks, tests, covers and builds. Every feature loses its directory, its + * tests/features directory, its context when no other feature is left in it, + * its runtime-profile override and its central policy rows. The sample also + * owns the extra paths and scripts listed in SAMPLE_EXTRAS. + */ +const featureId = + process.argv.find((argument) => argument.startsWith("--feature=")) + ?.slice("--feature=".length) ?? "reference-feature"; + +type FeatureExtras = Readonly<{ + paths: readonly string[]; + ciScripts: readonly string[]; + evidencePathFragments: readonly string[]; + residue: RegExp; +}>; + +const SAMPLE_EXTRAS: Readonly> = Object.freeze({ + "reference-feature": Object.freeze({ + paths: [ + "tests/integration/http-scenario-catalog.test.ts", + "tests/component/product-feature-switch.test.tsx", + "tests/e2e/reference-form.spec.ts", + "tests/e2e/reference-route.spec.ts", + "tests/mocks", + "tests/fixtures/typecheck/invalid-feature-input.ts", + "tests/fixtures/typecheck/invalid-reference-operation.ts", + "tests/fixtures/typecheck/invalid-http-operation-input.ts", + "tests/fixtures/typecheck/invalid-http-wire-mapper.ts", + "tests/fixtures/typecheck/invalid-http-operation-id.ts", + "tests/fixtures/typecheck/invalid-http-route-id.ts", + "tests/fixtures/typecheck/invalid-feature-contribution-input.ts", + "tests/fixtures/typecheck/invalid-feature-capability-selection.ts", + "tests/fixtures/typecheck/tsconfig.feature-input.json", + "tests/fixtures/typecheck/tsconfig.reference-operation.json", + "tests/fixtures/typecheck/tsconfig.http-operation-input.json", + "tests/fixtures/typecheck/tsconfig.http-wire-mapper.json", + "tests/fixtures/typecheck/tsconfig.http-operation-id.json", + "tests/fixtures/typecheck/tsconfig.http-route-id.json", + "tests/fixtures/typecheck/tsconfig.feature-contribution-input.json", + "tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", + ], + ciScripts: [ + "check:types:fixture:feature-input", + "check:types:fixture:reference-operation", + "check:types:fixture:http-operation-input", + "check:types:fixture:http-wire-mapper", + "check:types:fixture:http-operation-id", + "check:types:fixture:http-route-id", + "check:types:fixture:feature-contribution-input", + "check:types:fixture:feature-capability-selection", + "test:http-scenario-evidence", + "test:reference-feature", + ], + evidencePathFragments: [ + "reference-feature.xml", + "http-scenario-executions", + "http-scenario-evidence", + ], + residue: /REFERENCE_RESOURCE|reference-feature|reference-resource/i, + }), +}); + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +} + +async function locateFeature(id: string) { + const source = await createFileSystemDeclarationSource(process.cwd()); + for (const appId of source.appIds()) { + for (const context of source.contextsOf(appId)) { + const features = source.featuresOf(context.id); + const feature = features.find((candidate) => candidate.id === id); + if (!feature) continue; + let contextDirectory: string | null = null; + for (const entry of await readdir("src/contexts", { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const declaration = await readFile( + path.join("src/contexts", entry.name, "context-module.ts"), + "utf8", + ).catch(() => ""); + if ( + new RegExp(`CONTEXT_MODULE_ID\\s*=\\s*["']${escapeRegExp(context.id)}["']`, "u") + .test(declaration) + ) { + contextDirectory = `src/contexts/${entry.name}`; + } + } + return Object.freeze({ + directory: feature.directory, + // The context goes with its last feature. + contextDirectory: features.length === 1 ? contextDirectory : null, + }); + } + } + throw new Error(`No installed feature declares FEATURE_MODULE_ID "${id}"`); +} + +const located = await locateFeature(featureId); +const extras: FeatureExtras = SAMPLE_EXTRAS[featureId] ?? Object.freeze({ + paths: [], + ciScripts: [], + evidencePathFragments: [], + residue: new RegExp( + `${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`, + "i", + ), +}); +// Captured from this repository before the copy loses them. +const featureRouteIds = Object.entries(ROUTE_FEATURE_OWNER) + .filter(([, owner]) => owner === featureId) + .map(([routeId]) => routeId); + +const fixtureRoot = await createRemovalFixtureRoot(`${featureId}-removal`); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); -const featureSource = "src/features/reference-feature"; -const featureTests = "tests/features/reference-feature"; +const featureSource = `src/features/${located.directory}`; +const featureTests = `tests/features/${located.directory}`; +const isSample = featureId in SAMPLE_EXTRAS; /** * Platform tests that must survive the sample feature's removal. Asserting they * are still present is what stops the removal fixture from "passing" by having @@ -41,29 +159,10 @@ const commonTestPaths = [ const featureOwnedPaths = [ featureSource, featureTests, - // The sample's bounded-context declaration; the template app stays. - "src/contexts/reference-context", - "tests/integration/http-scenario-catalog.test.ts", - "tests/component/product-feature-switch.test.tsx", - "tests/e2e/reference-form.spec.ts", - "tests/e2e/reference-route.spec.ts", - "tests/mocks", - "tests/fixtures/typecheck/invalid-feature-input.ts", - "tests/fixtures/typecheck/invalid-reference-operation.ts", - "tests/fixtures/typecheck/invalid-http-operation-input.ts", - "tests/fixtures/typecheck/invalid-http-wire-mapper.ts", - "tests/fixtures/typecheck/invalid-http-operation-id.ts", - "tests/fixtures/typecheck/invalid-http-route-id.ts", - "tests/fixtures/typecheck/invalid-feature-contribution-input.ts", - "tests/fixtures/typecheck/invalid-feature-capability-selection.ts", - "tests/fixtures/typecheck/tsconfig.feature-input.json", - "tests/fixtures/typecheck/tsconfig.reference-operation.json", - "tests/fixtures/typecheck/tsconfig.http-operation-input.json", - "tests/fixtures/typecheck/tsconfig.http-wire-mapper.json", - "tests/fixtures/typecheck/tsconfig.http-operation-id.json", - "tests/fixtures/typecheck/tsconfig.http-route-id.json", - "tests/fixtures/typecheck/tsconfig.feature-contribution-input.json", - "tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", + // The feature's bounded-context declaration when it was the last feature in + // it; the template app stays. + ...(located.contextDirectory === null ? [] : [located.contextDirectory]), + ...extras.paths, ]; type CoveragePolicy = { @@ -93,6 +192,17 @@ function runPnpm(script: string, extra: string[] = []): boolean { return runRemovalFixturePnpm(fixtureRoot, pnpmCli, script, extra); } +function check(name: string, script: string, extra: string[] = []): RemovalCheck { + return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script, extra); +} + +/** 14-08. A non-command check fails with its own findings, nothing else's. */ +function outcome(name: string, findings: readonly string[], label: string): RemovalCheck { + return findings.length === 0 + ? { name, passed: true } + : { name, passed: false, failure: `${label}: ${findings.join(", ")}` }; +} + try { await prepareRemovalFixture(fixtureRoot); for (const excludedFixtureTest of [ @@ -152,7 +262,7 @@ try { FEATURE_OVERRIDES?: Record; }; if (runtimeConfig.FEATURE_OVERRIDES) { - delete runtimeConfig.FEATURE_OVERRIDES["reference-feature"]; + delete runtimeConfig.FEATURE_OVERRIDES[featureId]; } await writeFile( profilePath, @@ -164,6 +274,7 @@ try { (modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`), ); if ( + isSample && retainedCriticalModules.length === coveragePolicy.criticalModules.length ) { throw new Error("Reference feature coverage policy is not registered"); @@ -202,12 +313,12 @@ try { } evidencePolicy[policyKey] = contributions.filter((candidate: unknown) => { const contribution = candidate as EvidenceContribution; - const retained = contribution.owner !== "reference-feature"; + const retained = contribution.owner !== featureId; if (!retained) removedEvidenceContributions += 1; return retained; }); } - if (removedEvidenceContributions === 0) { + if (isSample && removedEvidenceContributions === 0) { throw new Error("Reference feature test evidence policy is not registered"); } await writeFile( @@ -230,7 +341,7 @@ try { consumers: registry.consumers.filter( (candidate: unknown) => { const consumer = candidate as GovernanceConsumer; - return !consumer.path?.includes("features/reference-feature"); + return !consumer.path?.includes(featureSource); }, ), } @@ -240,7 +351,7 @@ try { consumerDirectories: registry.consumerDirectories.filter( (directory: unknown) => typeof directory !== "string" || - !directory.includes("features/reference-feature"), + !directory.includes(featureSource), ), } : {}), @@ -251,41 +362,28 @@ try { `${JSON.stringify(removalGovernance, null, 2)}\n`, ); - const removedCiScripts = new Set([ - "check:types:fixture:feature-input", - "check:types:fixture:reference-operation", - "check:types:fixture:http-operation-input", - "check:types:fixture:http-wire-mapper", - "check:types:fixture:http-operation-id", - "check:types:fixture:http-route-id", - "check:types:fixture:feature-contribution-input", - "check:types:fixture:feature-capability-selection", - "test:http-scenario-evidence", - "test:reference-feature", - ]); + const removedCiScripts = new Set(extras.ciScripts); const fixturePackagePath = path.join(fixtureRoot, "package.json"); const fixturePackage = JSON.parse(await readFile(fixturePackagePath, "utf8")) as { scripts: Record; }; pruneScriptOrchestration(fixturePackage.scripts, "test:all", removedCiScripts); - delete fixturePackage.scripts["check:http-scenario-evidence"]; - delete fixturePackage.scripts["check:http-scenario-evidence:fixture"]; + if (isSample) { + delete fixturePackage.scripts["check:http-scenario-evidence"]; + delete fixturePackage.scripts["check:http-scenario-evidence:fixture"]; + } await writeFile(fixturePackagePath, `${JSON.stringify(fixturePackage, null, 2)}\n`); await pruneRemovalFixtureCiContract({ root: fixtureRoot, removedScripts: removedCiScripts, - removedEvidencePathFragments: [ - "reference-feature.xml", - "http-scenario-executions", - "http-scenario-evidence", - ], + removedEvidencePathFragments: extras.evidencePathFragments, }); // D-13: removing the sample is a breaking registry change. The fixture // records the new registry baseline the way a downstream project does, and // the canonical check:registries then runs against it. if (!runRemovalFixturePnpm(fixtureRoot, pnpmCli, "update:registry-baseline", [], { REGISTRY_BASELINE_OWNER: "removal-fixture", - REGISTRY_BASELINE_REASON: "reference feature removed", + REGISTRY_BASELINE_REASON: `${featureId} removed`, })) { throw new Error("Registry baseline failed to update after sample removal"); } @@ -296,60 +394,43 @@ try { for (const file of await filesBelow(path.join(fixtureRoot, root))) { const relative = path.relative(fixtureRoot, file); const content = await readFile(file, "utf8"); - if ( - /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test( - `${relative}\n${content}`, - ) - ) { + if (extras.residue.test(`${relative}\n${content}`)) { residue.push(relative); } } } - const checks: Array<[string, boolean]> = [ - [ - "common-test-evidence", - ( - await Promise.all( - commonTestPaths.map(async (testPath) => { - try { - await access(path.join(fixtureRoot, testPath)); - return true; - } catch { - return false; - } - }), - ) - ).every(Boolean), - ], - ["typecheck", runPnpm("check:types")], - ["architecture", runPnpm("check:architecture")], - ["registries", runPnpm("check:registries")], - ["unit-integration", runPnpm("test:all")], - ["coverage", runPnpm("test:coverage")], - ["test-evidence-source", runPnpm("check:test-evidence:source")], - ["ci-contract", runPnpm("check:ci")], - [ - "home-smoke", - runPnpm("exec", [ - "vitest", - "run", - "tests/component/router.test.tsx", - "--reporter=default", - ]), - ], - ["build", runPnpm("build")], + const missingCommonTests: string[] = []; + for (const testPath of commonTestPaths) { + await access(path.join(fixtureRoot, testPath)).catch(() => { + 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", [ + "vitest", + "run", + "tests/component/router.test.tsx", + "--reporter=default", + ]), + check("build", "build"), ]; const builtResidue: string[] = []; const buildSucceeded = - checks.find(([name]) => name === "build")?.[1] === true; + checks.find(({ name }) => name === "build")?.passed === true; if (buildSucceeded) { for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { if (!/\.(?:js|css|html|json)$/.test(file)) continue; const content = await readFile(file, "utf8"); - if ( - /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content) - ) { + if (extras.residue.test(content)) { builtResidue.push(path.relative(fixtureRoot, file)); } } @@ -360,37 +441,35 @@ try { `file://${fixtureRoot}/scripts/`, ).href}?removed=${Date.now()}` ) as { ROUTE_REGISTRY: Readonly> }; - const routeIds = Object.keys(routeCatalog.ROUTE_REGISTRY); - const routeAbsent = routeIds.every((routeId) => !routeId.startsWith("REFERENCE_")); - checks.push(["route-absent", routeAbsent]); - checks.push(["fixture-id-residue", residue.length === 0]); - checks.push(["built-fixture-id-residue", builtResidue.length === 0]); + const routeIds = new Set(Object.keys(routeCatalog.ROUTE_REGISTRY)); + checks.push( + outcome( + "route-absent", + featureRouteIds.filter((routeId) => routeIds.has(routeId)), + "routes still registered", + ), + outcome("fixture-id-residue", residue, "residue"), + outcome("built-fixture-id-residue", builtResidue, "built residue"), + ); - const passed = checks.every(([, result]) => result); + const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( - "artifacts/tests/sample-removal.xml", - `\n` + - `` + - checks - .map( - ([name, result]) => - `${result ? "" : `${[...residue, ...builtResidue].join(", ")}`}`, - ) - .join("") + - `\n`, + isSample + ? "artifacts/tests/sample-removal.xml" + : `artifacts/tests/feature-removal-${featureId}.xml`, + renderRemovalJunit(`${featureId}-removal`, checks), ); - if (!passed) { - const failures = checks - .filter(([, result]) => !result) - .map(([name]) => name); + if (failed.length > 0) { process.stderr.write( - `Reference feature removal failed: ${failures.join(", ")}; residue: ${[...residue, ...builtResidue].join(", ")}\n`, + `${featureId} removal failed:\n${failed + .map((entry) => ` ${entry.name}: ${entry.failure ?? "failed"}`) + .join("\n")}\n`, ); process.exitCode = 1; } else { process.stdout.write( - `Reference feature removal: PASS (${checks.length} checks, no fixture IDs)\n`, + `${featureId} removal: PASS (${checks.length} checks, no fixture IDs)\n`, ); } } finally { diff --git a/src/apps/template-app/app-module.ts b/src/apps/template-app/app-module.ts index 0b10e621..c26eb78d 100644 --- a/src/apps/template-app/app-module.ts +++ b/src/apps/template-app/app-module.ts @@ -1,5 +1,6 @@ /** - * Spec §5.3. Ownership declaration of the template deployable app. The + * Ownership declaration of the template deployable app + * (docs/architecture/starter-experience.md, "Ownership declarations"). The * generator reads these literals; contexts name this id as their owner. */ export const APP_MODULE_ID = "template-app"; diff --git a/src/bootstrap/boot.tsx b/src/bootstrap/boot.tsx new file mode 100644 index 00000000..5d4526ee --- /dev/null +++ b/src/bootstrap/boot.tsx @@ -0,0 +1,62 @@ +import { createRoot } from "react-dom/client"; + +import { recordBootFailure } from "../adapters/diagnostics/index.ts"; +import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; +import { + createBootReleaseRecovery, + decideBootFailure, +} from "./boot-release-recovery.ts"; +import { createRuntimeComposition } from "./create-runtime-composition.ts"; +import { initializeColorScheme } from "./initialize-color-scheme.ts"; +import { ReleaseManifestError } from "./load-release-manifest.ts"; +import { BootConfigError } from "./load-runtime-config.ts"; +import { unexpectedBootFailure } from "./render-boot-failure.tsx"; +import { RuntimeApplication } from "./runtime-application.tsx"; + +/** + * The application boot. main.tsx imports this module dynamically, so a module + * in this static graph that throws while it evaluates rejects that import and + * main.tsx shows the failure (09-03). Failures after evaluation are handled + * here. + */ +const rootElement = document.getElementById("root"); + +if (!rootElement) { + throw new Error("Missing #root mount element"); +} + +const root = createRoot(rootElement); + +async function boot(): Promise { + const releaseRecovery = createBootReleaseRecovery(); + try { + const composition = await createRuntimeComposition(); + // A coherent boot clears any reload-once marker from a previous mismatch. + releaseRecovery.markCoherentBoot(); + document.documentElement.dataset.buildId = composition.release.buildId; + document.documentElement.dataset.releaseId = composition.release.releaseId; + initializeColorScheme(composition.application.preferences); + root.render(); + import.meta.hot?.dispose(() => { + void composition.dispose(); + }); + } catch (error: unknown) { + const safe = + error instanceof BootConfigError || error instanceof ReleaseManifestError + ? error.safe + : unexpectedBootFailure(error); + + recordBootFailure(error, safe); + // Spec §45. A rolling-release mismatch gets exactly one fresh navigation + // (HTML is revalidated); a repeat of the same mismatch fails closed. + if (decideBootFailure(error, releaseRecovery) === "reload-once") { + window.location.reload(); + return; + } + root.render( + window.location.reload()} />, + ); + } +} + +void boot(); diff --git a/src/bootstrap/load-runtime-config.ts b/src/bootstrap/load-runtime-config.ts index 9cfc3a36..ac12061e 100644 --- a/src/bootstrap/load-runtime-config.ts +++ b/src/bootstrap/load-runtime-config.ts @@ -21,6 +21,8 @@ export type BootConfigSafe = Readonly<{ buildId: string; configSchemaVersion?: string; releaseId?: string; + /** 09-04. Names of rejected keys (never their values), bounded. */ + invalidKeys?: readonly string[]; supportReference: string; }>; @@ -28,8 +30,12 @@ type BootConfigSafeInput = Readonly<{ buildId: string; configSchemaVersion?: string; releaseId?: string; + invalidKeys?: readonly string[]; }>; +const SAFE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u; +const MAX_INVALID_KEYS = 5; + export class BootConfigError extends Error { readonly kind = "BOOT_CONFIG_FAILURE" as const; readonly code: string; @@ -45,6 +51,9 @@ export class BootConfigError extends Error { buildId: safe.buildId, configSchemaVersion: safe.configSchemaVersion, releaseId: safe.releaseId, + ...(safe.invalidKeys === undefined + ? {} + : { invalidKeys: safe.invalidKeys }), supportReference: `${safe.buildId}:${code}`, }); } @@ -122,12 +131,21 @@ export async function loadRuntimeConfig( const versionAccepted = !validated.issues.some( (issue) => issue.path === "CONFIG_SCHEMA_VERSION", ); + // 09-04. Key names tell an operator what to fix without echoing a value; + // they still come from the rejected document, so they are bounded. + const invalidKeys = [ + ...new Set(validated.issues.map((issue) => issue.path)), + ] + .filter((path) => SAFE_KEY_PATTERN.test(path)) + .sort() + .slice(0, MAX_INVALID_KEYS); throw new BootConfigError("CONFIG_SCHEMA_INVALID", { buildId: buildConfig.buildId, configSchemaVersion: versionAccepted && typeof rawConfig.CONFIG_SCHEMA_VERSION === "string" ? rawConfig.CONFIG_SCHEMA_VERSION : undefined, + invalidKeys, }); } diff --git a/src/bootstrap/main.tsx b/src/bootstrap/main.tsx index 49ff1f73..381d6ee6 100644 --- a/src/bootstrap/main.tsx +++ b/src/bootstrap/main.tsx @@ -1,54 +1,17 @@ -import { createRoot } from "react-dom/client"; - -import { recordBootFailure } from "../adapters/diagnostics/index.ts"; -import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; import "../presentation/styles/theme.css"; -import { - createBootReleaseRecovery, - decideBootFailure, -} from "./boot-release-recovery.ts"; -import { createRuntimeComposition } from "./create-runtime-composition.ts"; -import { initializeColorScheme } from "./initialize-color-scheme.ts"; -import { ReleaseManifestError } from "./load-release-manifest.ts"; -import { BootConfigError } from "./load-runtime-config.ts"; -import { RuntimeApplication } from "./runtime-application.tsx"; -const rootElement = document.getElementById("root"); - -if (!rootElement) { - throw new Error("Missing #root mount element"); -} - -const root = createRoot(rootElement); - -async function boot(): Promise { - const releaseRecovery = createBootReleaseRecovery(); - try { - const composition = await createRuntimeComposition(); - // A coherent boot clears any reload-once marker from a previous mismatch. - releaseRecovery.markCoherentBoot(); - document.documentElement.dataset.buildId = composition.release.buildId; - document.documentElement.dataset.releaseId = composition.release.releaseId; - initializeColorScheme(composition.application.preferences); - root.render(); - import.meta.hot?.dispose(() => { - void composition.dispose(); - }); - } catch (error: unknown) { - const safe = - error instanceof BootConfigError || error instanceof ReleaseManifestError - ? error.safe - : { supportReference: "boot:unknown" }; - - recordBootFailure(error, safe); - // Spec §45. A rolling-release mismatch gets exactly one fresh navigation - // (HTML is revalidated); a repeat of the same mismatch fails closed. - if (decideBootFailure(error, releaseRecovery) === "reload-once") { - window.location.reload(); - return; - } - root.render(); - } -} - -void boot(); +/** + * 09-03. The entry imports the application graph dynamically. A module in it + * that throws while it evaluates (a duplicate message key, a route or + * operation conflict) used to stop the entry before any handler ran, leaving + * the static loading shell up. Now it rejects this import and the failure is + * shown. + * + * The entry stays free of anything the application graph also imports (no + * JSX, no React): whatever it hosted, every chunk would import from it, and + * the entry's hash changes with every build id. + */ +void import("./boot.tsx").catch(async (error: unknown) => { + const { renderBootFailure } = await import("./render-boot-failure.tsx"); + renderBootFailure(error); +}); diff --git a/src/bootstrap/render-boot-failure.tsx b/src/bootstrap/render-boot-failure.tsx new file mode 100644 index 00000000..b25fe0ee --- /dev/null +++ b/src/bootstrap/render-boot-failure.tsx @@ -0,0 +1,43 @@ +import { createRoot } from "react-dom/client"; + +import { recordBootFailure } from "../adapters/diagnostics/index.ts"; +import { getBuildConfig } from "../contracts/env.ts"; +import { + BootErrorShell, + type BootErrorShellProps, +} from "../presentation/boundaries/boot-error-shell.tsx"; + +const ERROR_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9]{0,39}$/u; + +/** + * 09-04. A boot failure no loader classified: an assembly defect, a module + * that threw while evaluating. It is shown as such, with the build and the + * error's class name, never its message; a development build also reports + * the original error to the console (`reportError`; direct console calls are + * refused by check:diagnostics), where it was otherwise lost. + */ +export function unexpectedBootFailure(error: unknown): BootErrorShellProps { + if (import.meta.env.DEV) globalThis.reportError?.(error); + const { buildId } = getBuildConfig(); + const name = error instanceof Error ? error.name : ""; + const code = ERROR_NAME_PATTERN.test(name) ? name : "UNKNOWN_ERROR"; + return Object.freeze({ + kind: "BOOT_UNEXPECTED_FAILURE", + code, + buildId, + supportReference: `${buildId}:BOOT_UNEXPECTED_FAILURE`, + }); +} + +/** + * 09-03. Renders the boot failure when the application graph (boot.tsx) could + * not even be evaluated. Nothing here reaches the installed feature graph, so + * it still loads when that graph throws. + */ +export function renderBootFailure(error: unknown): void { + const safe = unexpectedBootFailure(error); + recordBootFailure(error, safe); + const rootElement = document.getElementById("root"); + if (!rootElement) throw error; + createRoot(rootElement).render(); +} diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 87bdfbdf..bee3614a 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -56,6 +56,7 @@ import { import { activeProductFeatureIds, resolveProductFeatures, + unknownProductFeatureOverrides, } from "../contracts/product-features.ts"; import { describeRuntimeCapabilities } from "../contracts/runtime-capabilities.ts"; import { @@ -457,6 +458,16 @@ export async function createRuntimeAdapters( const activeFeatureIds = new Set( activeProductFeatureIds(productFeatureStatuses), ); + for (const key of unknownProductFeatureOverrides( + COMPILED_PRODUCT_FEATURE_IDS, + config.FEATURE_OVERRIDES, + )) { + diagnostics.record({ + level: "warn", + eventId: "feature.override.unknown", + context: { feature_override_key: key }, + }); + } const productFeatures = Object.freeze({ getSnapshot() { return productFeatureStatuses; @@ -572,6 +583,11 @@ export async function createRuntimeAdapters( ...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }), }); // Each installed contribution receives only the capabilities it declares. + // 09-05. `indexedDb` is not built here: IndexedDB is an opt-in reference + // runtime (`productionComposition: false`). Installing a feature that needs + // it makes this object fail the app typecheck until the product adds + // `indexedDb`, built as in recipes/frontend-capabilities/ + // indexeddb-feature-capability.ts. const featureCapabilities = Object.freeze({ http: contractOperations, telemetry: featureTelemetry, diff --git a/src/bootstrap/runtime-config-schema.ts b/src/bootstrap/runtime-config-schema.ts index 7e87bfe6..6eae5b04 100644 --- a/src/bootstrap/runtime-config-schema.ts +++ b/src/bootstrap/runtime-config-schema.ts @@ -101,8 +101,15 @@ export function validateRuntimeConfig(value: unknown): RuntimeConfigValidation { return Object.freeze({ success: false as const, issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ path: issue.path.join("."), code: issue.code }), + result.error.issues.flatMap((issue) => + // 09-04. A misspelt top-level key is one `unrecognized_keys` issue + // at the root; name each key so the boot error can say which. + (issue.code === "unrecognized_keys" + ? issue.keys.map((key) => [...issue.path, key]) + : [issue.path] + ).map((path) => + Object.freeze({ path: path.join("."), code: issue.code }), + ), ), ), }); diff --git a/src/contexts/reference-context/context-module.ts b/src/contexts/reference-context/context-module.ts index bba3c41d..11c6996b 100644 --- a/src/contexts/reference-context/context-module.ts +++ b/src/contexts/reference-context/context-module.ts @@ -1,5 +1,6 @@ /** - * Spec §5.2. Ownership declaration of the reference bounded context: the app + * Ownership declaration of the reference bounded context (the rules are in + * docs/architecture/starter-experience.md, "Ownership declarations"): the app * that owns it, its route root, and its direct-feature budget. Features name * this id as their owner. */ diff --git a/src/contracts/diagnostics.ts b/src/contracts/diagnostics.ts index 9d348645..8bd9a9af 100644 --- a/src/contracts/diagnostics.ts +++ b/src/contracts/diagnostics.ts @@ -18,6 +18,7 @@ export const DIAGNOSTIC_EVENT_REGISTRY = Object.freeze({ "ui.render.failed": Object.freeze({ level: "error" }), "release.mismatch.detected": Object.freeze({ level: "warn" }), "telemetry.delivery.dropped": Object.freeze({ level: "warn" }), + "feature.override.unknown": Object.freeze({ level: "warn" }), }); export type DiagnosticEventId = keyof typeof DIAGNOSTIC_EVENT_REGISTRY; @@ -41,6 +42,7 @@ export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([ "operation", "reason", "queue_size_bucket", + "feature_override_key", ] as const); export type DiagnosticContextKey = (typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number]; @@ -82,6 +84,9 @@ export const DIAGNOSTIC_CONTEXT_CARDINALITY = Object.freeze({ operation: "topology", reason: "taxonomy", queue_size_bucket: "bounded", + // 09-09. A key from the deployed runtime document; it changes with a config + // deployment, not with traffic. + feature_override_key: "deployment", } satisfies Readonly>); export type DiagnosticContext = Readonly< diff --git a/src/contracts/env.ts b/src/contracts/env.ts index c5b20beb..b9905a3b 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -57,8 +57,9 @@ export const ENV_REGISTRY = Object.freeze({ CAPABILITY_OVERRIDES: runtime("public", false, null), // §3.5: likewise for features — subtractive, keyed by installed feature id. FEATURE_OVERRIDES: runtime("public", false, null), - // §3.5: build-time narrowing of the product manifest. A feature left out - // here is not imported by any registry and never reaches the bundle. + // §3.5: build-time narrowing of the product manifest, applied by + // scripts/generate-product-feature-index.ts (09-02). A feature left out here + // is not imported by any registry and never reaches the bundle. VITE_PRODUCT_FEATURES: build("compile-time", false, null), }); @@ -119,13 +120,25 @@ export type BuildEnvironment = Readonly<{ VITE_RUNTIME_CONFIG_URL?: string; }>; +/** + * 13-06. Each variable is read by key so Vite replaces it on its own. Passing + * `import.meta.env` whole made Vite inline every loaded VITE_* value, read or + * not, into this module's chunk. + */ export function getBuildConfig( - environment: BuildEnvironment = import.meta.env as BuildEnvironment, + environment: BuildEnvironment = { + VITE_BUILD_ID: import.meta.env.VITE_BUILD_ID, + VITE_COMMIT_SHA: import.meta.env.VITE_COMMIT_SHA, + VITE_ROUTER_BASE_PATH: import.meta.env.VITE_ROUTER_BASE_PATH, + VITE_RUNTIME_CONFIG_URL: import.meta.env.VITE_RUNTIME_CONFIG_URL, + }, ) { const buildId = environment.VITE_BUILD_ID || "local-build"; const commitSha = environment.VITE_COMMIT_SHA || "local"; const routerBasePath = environment.VITE_ROUTER_BASE_PATH || "/"; - const runtimeConfigUrl = environment.VITE_RUNTIME_CONFIG_URL || "/config.json"; + // 13-07. dist is served under the base path, so the default follows it. + const runtimeConfigUrl = + environment.VITE_RUNTIME_CONFIG_URL || `${routerBasePath}config.json`; return Object.freeze({ buildId, commitSha, routerBasePath, runtimeConfigUrl }); } diff --git a/src/contracts/product-features.ts b/src/contracts/product-features.ts index a6e5cd26..78a762dd 100644 --- a/src/contracts/product-features.ts +++ b/src/contracts/product-features.ts @@ -5,12 +5,12 @@ * Two different questions, deliberately answered by two different inputs: * * - **Installed** is a build-time decision. `VITE_PRODUCT_FEATURES` selects - * from the features this source tree declares; a feature left out contributes - * no route, no operation, no schema, no codec and no adapter, so nothing can - * reach it. It does *not* shrink the bundle: a static import cannot be undone - * by a value, and building the import graph from a configuration string is - * exactly what §3.5 forbids. Physical removal is FE-GATE-020's job — delete - * the feature directory and rebuild, which that gate proves still works. + * from the features this source tree declares. The index generator + * (`scripts/generate-product-feature-index.ts`) applies it before anything is + * compiled (09-02, D-9), so a feature left out is not imported by the bundle, + * the Node build scripts or the context router, and a misspelt id fails the + * first build step. Deleting the feature directory is still the way to take + * its source out of the repository; FE-GATE-020 proves that works. * - **Active** is a runtime decision. `FEATURE_OVERRIDES` in the runtime config * may take an installed feature out of service without a rebuild. * @@ -128,6 +128,21 @@ export function resolveProductFeatures( ); } +/** + * 09-09. Override keys naming no feature this build declares. They stay inert, + * since one runtime document may serve builds with different features, but a + * misspelt kill switch has to be reported rather than silently ignored. + */ +export function unknownProductFeatureOverrides( + compiledIds: readonly string[], + overrides: ProductFeatureOverrideMap = {}, +): readonly string[] { + const declared = new Set(compiledIds); + return Object.freeze( + Object.keys(overrides).filter((featureId) => !declared.has(featureId)).sort(), + ); +} + /** The feature ids serving traffic right now. */ export function activeProductFeatureIds( statuses: readonly ProductFeatureStatus[], diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts index d58eee8e..087a482a 100644 --- a/src/features/feature-adapter-contribution.ts +++ b/src/features/feature-adapter-contribution.ts @@ -174,6 +174,20 @@ export function composeFeatureAdapterInputs< } seen.add(contribution.featureId); if (!enabled.has(contribution.featureId)) continue; + // 09-05. The context type already asks for every declared need, but a + // host that widens it (or JavaScript) used to reach the feature's factory + // and fail there as an anonymous TypeError. + const provided = context as Readonly< + Partial> + >; + const missing = contribution.needs.find( + (need) => provided[need] === undefined, + ); + if (missing !== undefined) { + throw new TypeError( + `feature ${contribution.featureId} needs ${missing}, which the host did not provide`, + ); + } const installed = invokeContribution( contribution as unknown as FeatureAdapterContribution< diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts index fbea274b..7d78588e 100644 --- a/src/features/installed-feature-adapters.ts +++ b/src/features/installed-feature-adapters.ts @@ -5,9 +5,18 @@ import { } from "./feature-adapter-contribution.ts"; import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; -const INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze( - INSTALLED_PRODUCT_FEATURE_MODULES.flatMap((module) => module.adapters), -); +// 09-01. Indexed access distributes over the installed-module union, so this is +// every installed contribution. `flatMap` alone infers its element type from +// the first union member and rejected the second installed feature. +type InstalledFeatureAdapterContribution = + (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number]["adapters"][number]; + +const INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS: readonly InstalledFeatureAdapterContribution[] = + Object.freeze( + INSTALLED_PRODUCT_FEATURE_MODULES.flatMap( + (module): readonly InstalledFeatureAdapterContribution[] => module.adapters, + ), + ); type InstalledFeatureCapabilityContext = ContributionsCapabilityContext< typeof INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS @@ -15,7 +24,8 @@ type InstalledFeatureCapabilityContext = ContributionsCapabilityContext< /** * Adapter installation is a projection of feature-owned descriptors. Adding a - * feature changes its descriptor and the generated index, not this composer. + * feature changes its descriptor and the generated index, not this composer + * (tests/unit/two-feature-install-typecheck.test.ts installs a second one). * * Q-6.9-5. The runtime composer passes `activeFeatureIds` (installed minus * `FEATURE_OVERRIDES`). A feature switched off there gets no input, so diff --git a/src/features/installed-feature-contracts.ts b/src/features/installed-feature-contracts.ts index 2ec8c8a0..dd736089 100644 --- a/src/features/installed-feature-contracts.ts +++ b/src/features/installed-feature-contracts.ts @@ -16,15 +16,17 @@ import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts"; export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES; -type InstalledFeatureContract = (typeof INSTALLED_FEATURE_CONTRACTS)[number]; - +// 09-01. The registries keep composeUniqueRecord's own type, the intersection +// of every record. The former cast to `PLATFORM & InstalledFeatureContract[...]` +// was an intersection with a union once two features were installed, which +// kept only the route keys common to both. export const ROUTE_REGISTRY = composeUniqueRecord( [ PLATFORM_ROUTE_REGISTRY, ...INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.routes), ], () => "route registry", -) as typeof PLATFORM_ROUTE_REGISTRY & InstalledFeatureContract["routes"]; +); export const ROUTE_RUNTIME_CONTRACT = composeUniqueRecord( [ @@ -34,8 +36,7 @@ export const ROUTE_RUNTIME_CONTRACT = composeUniqueRecord( ), ], () => "route runtime contract", -) as typeof PLATFORM_ROUTE_RUNTIME_CONTRACT & - InstalledFeatureContract["routeRuntimeContracts"]; +); export const API_OPERATIONS = composeApiOperations( INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.apiOperations), @@ -44,25 +45,38 @@ export const REST_PROFILE_BINDINGS_VALID = validateRestProfileBindings( API_OPERATIONS, Object.freeze({ PRIMARY_API: Object.freeze(["omit"] as const) }), ); +// 09-01. Element types are spelled out for the same reason as in +// installed-feature-adapters.ts: flatMap over the installed-contract union +// otherwise returns the member arrays unflattened. +type InstalledInvalidation = + (typeof INSTALLED_FEATURE_CONTRACTS)[number]["invalidation"]; +type InstalledTopicVersion = + (typeof INSTALLED_FEATURE_CONTRACTS)[number]["topicVersions"][number]; + export const INVALIDATION_REGISTRY = Object.freeze({ topics: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.topics, + (contract): readonly InstalledInvalidation["topics"][number][] => + contract.invalidation.topics, ), ), namespaces: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.namespaces, + (contract): readonly InstalledInvalidation["namespaces"][number][] => + contract.invalidation.namespaces, ), ), edges: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.edges, + (contract): readonly InstalledInvalidation["edges"][number][] => + contract.invalidation.edges, ), ), }); export const INVALIDATION_TOPIC_VERSIONS = Object.freeze( - INSTALLED_FEATURE_CONTRACTS.flatMap((contract) => contract.topicVersions), + INSTALLED_FEATURE_CONTRACTS.flatMap( + (contract): readonly InstalledTopicVersion[] => contract.topicVersions, + ), ); export const SCHEMA_REGISTRY = composeSchemaRegistry([ PLATFORM_SCHEMA_REGISTRY, diff --git a/src/features/installed-feature-messages.ts b/src/features/installed-feature-messages.ts index ecd72782..c52d134c 100644 --- a/src/features/installed-feature-messages.ts +++ b/src/features/installed-feature-messages.ts @@ -7,16 +7,21 @@ type UnionToIntersection = ( ) extends (value: infer Intersection) => void ? Intersection : never; -type LocaleCatalog = UnionToIntersection< - InstalledModule extends unknown - ? InstalledModule["messages"] extends Readonly> - ? Catalog - : Readonly> - : never ->; -type InstalledLocale = InstalledModule extends unknown - ? Extract +// 09-01. These conditionals take the module as a type parameter so they +// distribute over the installed-module union. Applied to the union alias +// itself they saw only the locales every feature shares, and a second feature +// without catalogs erased the whole message table. +type ModuleCatalog = + Module extends Readonly<{ messages: Readonly> }> + ? Catalog + : Readonly>; +type ModuleLocale = Module extends Readonly<{ messages: infer Messages }> + ? Extract : never; +type LocaleCatalog = UnionToIntersection< + ModuleCatalog +>; +type InstalledLocale = ModuleLocale; /** * Q-6.9-12. One catalog per locale that any installed feature declares. The diff --git a/src/features/installed-feature-runtimes.tsx b/src/features/installed-feature-runtimes.tsx index 5195e6c4..f7f456a6 100644 --- a/src/features/installed-feature-runtimes.tsx +++ b/src/features/installed-feature-runtimes.tsx @@ -3,9 +3,17 @@ import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-cod import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx"; import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; -const INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS = Object.freeze( - INSTALLED_PRODUCT_FEATURE_MODULES.flatMap((module) => module.runtimes), -); +// 09-01. See installed-feature-adapters.ts: the element type is spelled out so +// a second installed feature widens it instead of failing inference. +type InstalledFeatureRuntimeContribution = + (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number]["runtimes"][number]; + +const INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS: readonly InstalledFeatureRuntimeContribution[] = + Object.freeze( + INSTALLED_PRODUCT_FEATURE_MODULES.flatMap( + (module): readonly InstalledFeatureRuntimeContribution[] => module.runtimes, + ), + ); export const ROUTE_CODECS = composeUniqueRecord( [ diff --git a/src/features/installed-product-manifest.ts b/src/features/installed-product-manifest.ts index 22f79029..58e4c371 100644 --- a/src/features/installed-product-manifest.ts +++ b/src/features/installed-product-manifest.ts @@ -1,55 +1,26 @@ import { + DECLARED_PRODUCT_FEATURE_IDS, PRODUCT_FEATURE_MODULES, type ProductFeatureModule, } from "../.generated/product-feature-index.ts"; -import { - selectCompiledProductFeatures, - type SelectableProductFeature, -} from "../contracts/product-features.ts"; /** - * Product installation has one generated static source of truth. Feature-owned - * descriptors are discovered at build time; runtime configuration can only - * subtract from that compiled set. + * Product installation has one generated static source of truth. The + * generator discovers feature-owned descriptors and applies the build-time + * `VITE_PRODUCT_FEATURES` selection (09-02, D-9), so a feature left out is not + * imported by the bundle, the Node build scripts or the context router alike. + * Runtime configuration can only subtract from that installed set. */ -export const COMPILED_PRODUCT_FEATURE_MODULES: readonly ProductFeatureModule[] = + +/** Every feature the source tree declares, installed or not. */ +export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = + DECLARED_PRODUCT_FEATURE_IDS; + +export const INSTALLED_PRODUCT_FEATURE_MODULES: readonly ProductFeatureModule[] = PRODUCT_FEATURE_MODULES; -export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze( - COMPILED_PRODUCT_FEATURE_MODULES.map((feature) => feature.id), -); - -function declaredFeatureSelection(): string | undefined { - const environment = ( - import.meta as unknown as { - env?: Readonly>; - } - ).env; - return environment?.["VITE_PRODUCT_FEATURES"]; -} - -type CompiledFeatureModule = ProductFeatureModule; -type CompiledFeatureContract = CompiledFeatureModule["contracts"]; -type SelectableFeatureModule = SelectableProductFeature & - Readonly<{ module: CompiledFeatureModule }>; - -const SELECTABLE_PRODUCT_FEATURE_MODULES: readonly SelectableFeatureModule[] = - Object.freeze( - COMPILED_PRODUCT_FEATURE_MODULES.map((module) => - Object.freeze({ featureId: module.id, module }), - ), - ); - -const INSTALLED_SELECTION = selectCompiledProductFeatures( - SELECTABLE_PRODUCT_FEATURE_MODULES, - declaredFeatureSelection(), -); - -export const INSTALLED_PRODUCT_FEATURE_MODULES: readonly CompiledFeatureModule[] = - Object.freeze(INSTALLED_SELECTION.map((entry) => entry.module)); - /** Backward-compatible projection consumed by the existing contract composer. */ -export const INSTALLED_PRODUCT_FEATURES: readonly CompiledFeatureContract[] = +export const INSTALLED_PRODUCT_FEATURES: readonly ProductFeatureModule["contracts"][] = Object.freeze( INSTALLED_PRODUCT_FEATURE_MODULES.map((module) => module.contracts), ); diff --git a/src/features/local-draft-feature/NOT_INSTALLED b/src/features/local-draft-feature/NOT_INSTALLED new file mode 100644 index 00000000..1c481d10 --- /dev/null +++ b/src/features/local-draft-feature/NOT_INSTALLED @@ -0,0 +1,6 @@ +local-draft is an architecture sample for the indexedDb feature capability, not +a product feature. It has no feature-module.ts on purpose, so the index +generator (scripts/generate-product-feature-index.ts) leaves it out; its +composition is exercised by tests/contract/reusable-capability and +recipes/frontend-capabilities/indexeddb-feature-capability.ts. To install it, +add feature-module.ts and context-routes.ts and delete this file. diff --git a/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts b/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts index 93b62d1e..9b7461cc 100644 --- a/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts +++ b/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts @@ -1,6 +1,3 @@ -import type { - IndexedDbRepositoryPort, -} from "../../../application/ports/browser-file-storage/index.ts"; import { defineFeatureAdapterContribution, } from "../../feature-adapter-contribution.ts"; @@ -8,22 +5,24 @@ import type {} from "../../feature-adapter-contribution.ts"; import { createLocalDraftFeatureInput, } from "../application/local-draft-api.ts"; -import type { LocalDraft } from "../domain/local-draft.ts"; import { LOCAL_DRAFT_FEATURE_ID, LOCAL_DRAFT_REPOSITORY_ID, } from "../contracts/local-draft-contract.ts"; -import { createLocalDraftStore } from "./local-draft-indexeddb-store.ts"; +import { + createLocalDraftStore, + type LocalDraftRepository, +} from "./local-draft-indexeddb-store.ts"; declare module "../../feature-adapter-contribution.ts" { interface FeatureIndexedDbRepositories { - "local-draft": IndexedDbRepositoryPort; + "local-draft": LocalDraftRepository; } } export function createLocalDraftFeatureInstalledInput(context: Readonly<{ indexedDb: Readonly<{ - get(repositoryId: "local-draft"): IndexedDbRepositoryPort; + get(repositoryId: "local-draft"): LocalDraftRepository; }>; }>) { const repository = context.indexedDb.get(LOCAL_DRAFT_REPOSITORY_ID); diff --git a/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts b/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts index bc777beb..9f0fd0a9 100644 --- a/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts +++ b/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts @@ -1,7 +1,3 @@ -import type { - BrowserDataFailure, - IndexedDbRepositoryPort, -} from "../../../application/ports/browser-file-storage/index.ts"; import { createFailure, type AppFailure, @@ -16,7 +12,43 @@ import type { } from "../application/local-draft-api.ts"; import type { LocalDraft } from "../domain/local-draft.ts"; -function failureKind(failure: BrowserDataFailure): FailureKind { +type RepositoryFailure = Readonly<{ code: string }>; +type RepositoryResult = Result; + +/** + * 00-02. The part of the `indexedDb` capability this feature calls. The host + * hands in the reusable runtime (`IndexedDbRepositoryPort`), + * which satisfies this shape structurally (the recipe and the browser spec + * compile that assignment). Importing the port instead tied the feature to the + * browser storage runtime, which a product may remove. + */ +export type LocalDraftRepository = Readonly<{ + read( + key: string, + signal?: AbortSignal, + ): Promise< + RepositoryResult | null> + >; + compareAndSwap( + input: Readonly<{ + key: string; + value: LocalDraft; + expectedRevision: number | null; + idempotencyKey: string; + signal?: AbortSignal; + }>, + ): Promise>>; + remove( + input: Readonly<{ + key: string; + expectedRevision: number; + idempotencyKey: string; + signal?: AbortSignal; + }>, + ): Promise>; +}>; + +function failureKind(failure: RepositoryFailure): FailureKind { if (failure.code === "QUOTA_EXCEEDED") return "STORAGE_QUOTA_EXCEEDED"; if (failure.code === "CONFLICT") return "CONFLICT"; if (failure.code === "ABORTED") return "REQUEST_ABORTED"; @@ -24,7 +56,7 @@ function failureKind(failure: BrowserDataFailure): FailureKind { } function mapFailure( - failure: BrowserDataFailure, + failure: RepositoryFailure, operationId: string, ): AppFailure { return createFailure(failureKind(failure), operationId, 0, { @@ -33,7 +65,7 @@ function mapFailure( } function failed( - failure: BrowserDataFailure, + failure: RepositoryFailure, operationId: string, ): Result { return Object.freeze({ @@ -48,7 +80,7 @@ function failed( * cross this file. */ export function createLocalDraftStore( - repository: IndexedDbRepositoryPort, + repository: LocalDraftRepository, ): LocalDraftStore { return Object.freeze({ async save(command: SaveLocalDraftCommand, signal?: AbortSignal) { diff --git a/src/features/local-draft-feature/application/local-draft-api.ts b/src/features/local-draft-feature/application/local-draft-api.ts index bed3224b..3b384b63 100644 --- a/src/features/local-draft-feature/application/local-draft-api.ts +++ b/src/features/local-draft-feature/application/local-draft-api.ts @@ -1,6 +1,7 @@ +import { createFailure } from "../../../contracts/errors.ts"; import type { Result } from "../../../contracts/result.ts"; import type {} from "../../../application/ports/in/application-api.ts"; -import type { LocalDraft } from "../domain/local-draft.ts"; +import { createLocalDraft, type LocalDraft } from "../domain/local-draft.ts"; export type LocalDraftRecord = Readonly<{ draft: LocalDraft; @@ -9,6 +10,7 @@ export type LocalDraftRecord = Readonly<{ export type SaveLocalDraftCommand = Readonly<{ draft: LocalDraft; + /** Only unambiguous while draft ids are never reused (see LocalDraft.draftId). */ expectedRevision: number | null; idempotencyKey: string; }>; @@ -59,8 +61,19 @@ export function createLocalDraftFeatureInput( store: LocalDraftStore, ): LocalDraftFeatureInput { return Object.freeze({ - saveDraft(command, context) { - return store.save(command, context?.signal); + // 09-06. The domain rules (trimmed non-blank id and title, bounded + // lengths) are applied here; the store never sees an unchecked draft. + async saveDraft(command, context) { + let draft: LocalDraft; + try { + draft = createLocalDraft(command.draft); + } catch { + return Object.freeze({ + ok: false as const, + error: createFailure("VALIDATION_REJECTED", "LOCAL_DRAFT_SAVE", 0), + }); + } + return store.save(Object.freeze({ ...command, draft }), context?.signal); }, findDraft(draftId, context) { return store.find(draftId, context?.signal); diff --git a/src/features/local-draft-feature/domain/local-draft.ts b/src/features/local-draft-feature/domain/local-draft.ts index 877fe12b..8e023ee2 100644 --- a/src/features/local-draft-feature/domain/local-draft.ts +++ b/src/features/local-draft-feature/domain/local-draft.ts @@ -1,4 +1,14 @@ export type LocalDraft = Readonly<{ + /** + * 09-08. One id per draft, never reused after the draft is removed. The + * repository deletes without a tombstone and a recreated record starts again + * at revision 1, so a tab still holding revision N of the removed draft + * could compare-and-swap over a new draft that reused its id (the capability + * port's revision contract says so: IndexedDbWriteReceipt.revision in + * src/application/ports/browser-file-storage/indexeddb-port.ts). A fresh id + * per draft (for example crypto.randomUUID()) makes that stale save a + * CONFLICT; a product that must reuse ids needs tombstones instead. + */ draftId: string; title: string; body: string; diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md index cc34c8d6..8c07b364 100644 --- a/src/features/reference-feature/README.md +++ b/src/features/reference-feature/README.md @@ -45,7 +45,8 @@ route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route t feature가 실제 contribution을 소유한다. - contract: `reference-feature-contract.ts` -- component/codec: `REFERENCE_FEATURE_RUNTIME_CONTRIBUTION` +- route codec: `REFERENCE_FEATURE_RUNTIME_DESCRIPTOR` (`feature-module.ts`가 설치) +- page component: `REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 lazy로 적재) - bootstrap input: `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION` 중앙 파일인 `installed-feature-contracts.ts`, diff --git a/src/presentation/boundaries/boot-error-shell.tsx b/src/presentation/boundaries/boot-error-shell.tsx index d3fe5ecd..97e90da5 100644 --- a/src/presentation/boundaries/boot-error-shell.tsx +++ b/src/presentation/boundaries/boot-error-shell.tsx @@ -1,4 +1,17 @@ -import { formatMessage } from "../i18n/index.ts"; +import { BOOT_MESSAGES } from "../i18n/boot-messages.ts"; + +// 09-03. Read from the boot messages alone, not the i18n catalog: the shell +// has to render when the installed feature graph failed to evaluate. +const MESSAGES = BOOT_MESSAGES["ko-KR"]; + +// 09-10. Failures a fresh load can fix: the config or manifest request did +// not complete. Retrying stays a user action; nothing reloads on its own. +const RETRYABLE_CODES: ReadonlySet = new Set([ + "CONFIG_FETCH_FAILED", + "CONFIG_TIMEOUT", + "MANIFEST_FETCH_FAILED", + "MANIFEST_TIMEOUT", +]); export type BootErrorShellProps = Readonly<{ kind?: string; @@ -6,48 +19,69 @@ export type BootErrorShellProps = Readonly<{ buildId?: string; configSchemaVersion?: string; releaseId?: string; + invalidKeys?: readonly string[]; supportReference: string; + onRetry?: () => void; }>; export function BootErrorShell({ - kind = "BOOT_CONFIG_FAILURE", + // 09-04. A failure nobody classified is not a configuration failure. + kind = "BOOT_UNEXPECTED_FAILURE", code = "BOOT_FAILED", buildId, configSchemaVersion, releaseId, + invalidKeys, supportReference, + onRetry, }: BootErrorShellProps) { + const retry = onRetry !== undefined && RETRYABLE_CODES.has(code); return (
-

{formatMessage("ko-KR", "boot.failure.title")}

+

{MESSAGES["boot.failure.title"]}

-
{formatMessage("ko-KR", "boot.field.error")}
+
{MESSAGES["boot.field.error"]}
{kind}
-
{formatMessage("ko-KR", "boot.field.code")}
+
{MESSAGES["boot.field.code"]}
{code}
{buildId && ( <> -
{formatMessage("ko-KR", "boot.field.build")}
+
{MESSAGES["boot.field.build"]}
{buildId}
)} {configSchemaVersion && ( <> -
{formatMessage("ko-KR", "boot.field.configSchema")}
+
{MESSAGES["boot.field.configSchema"]}
{configSchemaVersion}
)} {releaseId && ( <> -
{formatMessage("ko-KR", "boot.field.release")}
+
{MESSAGES["boot.field.release"]}
{releaseId}
)} + {invalidKeys && invalidKeys.length > 0 && ( + <> +
{MESSAGES["boot.field.invalidKeys"]}
+
{invalidKeys.join(", ")}
+ + )}
+ {retry && ( + <> +

{MESSAGES["boot.retry.hint"]}

+ + + )}

- {formatMessage("ko-KR", "boot.supportReference", { - reference: supportReference, - })} + {MESSAGES["boot.supportReference"].replace( + "{reference}", + () => supportReference, + )}

); diff --git a/src/presentation/i18n/boot-messages.ts b/src/presentation/i18n/boot-messages.ts new file mode 100644 index 00000000..b49b75dd --- /dev/null +++ b/src/presentation/i18n/boot-messages.ts @@ -0,0 +1,34 @@ +/** + * 09-03. The boot failure shell's words. They live apart from `catalog.ts` + * because the catalog merges every installed feature's messages: when that + * feature graph throws while it evaluates, the shell reporting it must still + * load. `catalog.ts` spreads these in, so they stay ordinary message keys. + */ +export const BOOT_MESSAGES = Object.freeze({ + "ko-KR": Object.freeze({ + "boot.failure.title": "애플리케이션을 시작할 수 없습니다.", + "boot.field.error": "오류", + "boot.field.code": "코드", + "boot.field.build": "빌드", + "boot.field.configSchema": "설정 스키마", + "boot.field.release": "릴리스", + "boot.field.invalidKeys": "잘못된 설정 키", + "boot.retry.hint": "네트워크 연결을 확인한 뒤 다시 시도해 주세요.", + "boot.retry.action": "다시 시도", + "boot.supportReference": "지원 참조: {reference}", + } as const), + "en-US": Object.freeze({ + "boot.failure.title": "The application could not start.", + "boot.field.error": "Error", + "boot.field.code": "Code", + "boot.field.build": "Build", + "boot.field.configSchema": "Configuration schema", + "boot.field.release": "Release", + "boot.field.invalidKeys": "Invalid configuration keys", + "boot.retry.hint": "Check the network connection and try again.", + "boot.retry.action": "Try again", + "boot.supportReference": "Support reference: {reference}", + } as const), +}); + +export type BootMessageKey = keyof (typeof BOOT_MESSAGES)["ko-KR"]; diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 6ec1a18c..f5276223 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -1,4 +1,5 @@ import { INSTALLED_MESSAGE_CATALOGS } from "../../features/installed-feature-messages.ts"; +import { BOOT_MESSAGES } from "./boot-messages.ts"; const PLATFORM_KO_MESSAGES = { "common.unavailable": "요청한 문구를 표시할 수 없습니다.", @@ -145,13 +146,7 @@ const PLATFORM_KO_MESSAGES = { "error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.", "error.render_failure": "화면을 표시하지 못했습니다.", "error.unknown_failure": "예상하지 못한 문제가 발생했습니다.", - "boot.failure.title": "애플리케이션을 시작할 수 없습니다.", - "boot.field.error": "오류", - "boot.field.code": "코드", - "boot.field.build": "빌드", - "boot.field.configSchema": "설정 스키마", - "boot.field.release": "릴리스", - "boot.supportReference": "지원 참조: {reference}", + ...BOOT_MESSAGES["ko-KR"], } as const; export const KO_MESSAGES = { @@ -305,13 +300,7 @@ const PLATFORM_EN_MESSAGES = { "error.asset_mismatch": "The page assets do not match this release.", "error.render_failure": "The page could not be displayed.", "error.unknown_failure": "An unexpected problem occurred.", - "boot.failure.title": "The application could not start.", - "boot.field.error": "Error", - "boot.field.code": "Code", - "boot.field.build": "Build", - "boot.field.configSchema": "Configuration schema", - "boot.field.release": "Release", - "boot.supportReference": "Support reference: {reference}", + ...BOOT_MESSAGES["en-US"], } as const satisfies Record; export const EN_MESSAGES = { diff --git a/tests/component/boot-module-failure.test.tsx b/tests/component/boot-module-failure.test.tsx new file mode 100644 index 00000000..d715a695 --- /dev/null +++ b/tests/component/boot-module-failure.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment jsdom + +import { screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +// 09-03. A throw while the feature graph evaluates (a duplicate message key, +// a route or operation conflict) used to stop main.tsx before boot() ran, so +// the static "loading" shell stayed up forever. +vi.mock("../../src/.generated/product-feature-index.ts", () => { + throw new TypeError("Duplicate ko-KR message key: probe.title"); +}); + +describe("boot entry (09-03)", () => { + it("shows the boot error shell when the app graph fails to evaluate", async () => { + document.body.innerHTML = + '
불러오는 중
'; + vi.spyOn(console, "error").mockImplementation(() => {}); + + await import("../../src/bootstrap/main.tsx"); + + const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 }); + expect(shell).toHaveTextContent("애플리케이션을 시작할 수 없습니다."); + expect(document.querySelector("[data-boot-shell]")).toBeNull(); + }); +}); diff --git a/tests/component/boot-unexpected-failure.test.tsx b/tests/component/boot-unexpected-failure.test.tsx new file mode 100644 index 00000000..f8c2503b --- /dev/null +++ b/tests/component/boot-unexpected-failure.test.tsx @@ -0,0 +1,52 @@ +// @vitest-environment jsdom + +import { render, screen, within } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx"; + +// 09-04. An assembly defect (here the TypeError a missing feature capability +// used to produce) was shown as BOOT_CONFIG_FAILURE and the error was dropped. +const assemblyDefect = new TypeError( + "Cannot read properties of undefined (reading 'get')", +); +vi.mock("../../src/bootstrap/create-runtime-composition.ts", () => ({ + createRuntimeComposition: async () => { + throw assemblyDefect; + }, +})); + +describe("unexpected boot failure (09-04)", () => { + it("is shown as BOOT_UNEXPECTED_FAILURE and reports the error in development", async () => { + document.body.innerHTML = + '
불러오는 중
'; + // jsdom has no reportError; browsers do. + const reportError = vi.fn<(error: unknown) => void>(); + vi.stubGlobal("reportError", reportError); + + await import("../../src/bootstrap/main.tsx"); + + const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 }); + expect(shell).toHaveTextContent("BOOT_UNEXPECTED_FAILURE"); + expect(shell).not.toHaveTextContent("BOOT_CONFIG_FAILURE"); + expect(shell).toHaveTextContent("local-build"); + expect(shell).toHaveTextContent("TypeError"); + expect(shell).not.toHaveTextContent("reading 'get'"); + expect(reportError).toHaveBeenCalledWith(assemblyDefect); + }); + + it("lists the rejected configuration keys", () => { + const view = render( + , + ); + const shell = within(view.container).getByRole("alert"); + expect(within(shell).getByText("잘못된 설정 키")).toBeInTheDocument(); + expect(shell).toHaveTextContent("TELEMETRY_ENABELD"); + }); +}); diff --git a/tests/component/context-route-gateway.test.tsx b/tests/component/context-route-gateway.test.tsx index 7d3a27a5..ffaaf233 100644 --- a/tests/component/context-route-gateway.test.tsx +++ b/tests/component/context-route-gateway.test.tsx @@ -14,6 +14,7 @@ import { createTestApplication } from "../helpers/create-test-application.ts"; * and the third one's routes module fails to download. */ vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/apps/template-app.ts", async () => { diff --git a/tests/component/render-boundary.test.tsx b/tests/component/render-boundary.test.tsx index 63208a00..812d520f 100644 --- a/tests/component/render-boundary.test.tsx +++ b/tests/component/render-boundary.test.tsx @@ -73,6 +73,39 @@ describe("render recovery boundaries", () => { expect(shell).not.toHaveTextContent("stack"); }); + it.each(["CONFIG_FETCH_FAILED", "CONFIG_TIMEOUT", "MANIFEST_FETCH_FAILED", "MANIFEST_TIMEOUT"])( + "offers a retry for the network failure %s (09-10)", + async (code) => { + const onRetry = vi.fn(); + const user = userEvent.setup(); + render( + , + ); + expect(screen.getByRole("alert")).toHaveTextContent( + "네트워크 연결을 확인한 뒤 다시 시도해 주세요.", + ); + await user.click(screen.getByRole("button", { name: "다시 시도" })); + expect(onRetry).toHaveBeenCalledTimes(1); + }, + ); + + it("offers no retry for a failure a reload cannot fix (09-10)", () => { + render( + {}} + />, + ); + expect(screen.queryByRole("button")).toBeNull(); + }); + it("allows a boundary reset action without reloading the page", async () => { let shouldThrow = true; function Recoverable() { diff --git a/tests/component/route-status-surfaces.test.tsx b/tests/component/route-status-surfaces.test.tsx index 754c7515..2fda7e8b 100644 --- a/tests/component/route-status-surfaces.test.tsx +++ b/tests/component/route-status-surfaces.test.tsx @@ -18,6 +18,7 @@ import { createTestApplication } from "../helpers/create-test-application.ts"; // Feature-route surfaces run against a test-only feature, not the removable // sample (FE-GATE-020 runs the suite after deleting the sample). vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/component/router.test.tsx b/tests/component/router.test.tsx index cd6cbb71..294e527f 100644 --- a/tests/component/router.test.tsx +++ b/tests/component/router.test.tsx @@ -16,6 +16,7 @@ import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub. // Feature-route surfaces run against a test-only feature, not the removable // sample (FE-GATE-020 runs this file after deleting the sample). vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/contract/consumer-experience/fixtures/local-draft-feature.ts b/tests/contract/consumer-experience/fixtures/local-draft-feature.ts deleted file mode 100644 index 5a78fed7..00000000 --- a/tests/contract/consumer-experience/fixtures/local-draft-feature.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type { - BrowserDataResult, - IndexedDbRepositoryPort, -} from "../../../../src/application/ports/browser-file-storage/index.ts"; - -export type LocalDraft = Readonly<{ - draftId: string; - title: string; - body: string; -}>; - -export type SaveLocalDraftCommand = Readonly<{ - draft: LocalDraft; - expectedRevision: number | null; - idempotencyKey: string; -}>; - -export type RemoveLocalDraftCommand = Readonly<{ - draftId: string; - expectedRevision: number; - idempotencyKey: string; -}>; - -export type LocalDraftRecord = Readonly<{ - draft: LocalDraft; - revision: number; -}>; - -export interface LocalDraftStore { - save( - command: SaveLocalDraftCommand, - signal?: AbortSignal, - ): Promise>>; - find( - draftId: string, - signal?: AbortSignal, - ): Promise>; - remove( - command: RemoveLocalDraftCommand, - signal?: AbortSignal, - ): Promise>; -} - -/** - * Feature-owned binding over the technology-neutral IndexedDB application port. - * - * The feature knows its domain type and optimistic concurrency inputs. It does - * not know database names, stores, transactions, native IDB objects, codecs, - * migrations, quota handling or connection lifecycle. - */ -export function createLocalDraftStore( - repository: IndexedDbRepositoryPort, -): LocalDraftStore { - const store: LocalDraftStore = { - async save(command, signal) { - const result = await repository.compareAndSwap({ - key: command.draft.draftId, - value: command.draft, - expectedRevision: command.expectedRevision, - idempotencyKey: command.idempotencyKey, - signal, - }); - if (!result.ok) return result; - return Object.freeze({ - ok: true as const, - value: Object.freeze({ revision: result.value.revision }), - }); - }, - - async find(draftId, signal) { - const result = await repository.read(draftId, signal); - if (!result.ok) return result; - return Object.freeze({ - ok: true as const, - value: - result.value === null - ? null - : Object.freeze({ - draft: result.value.value, - revision: result.value.revision, - }), - }); - }, - - async remove(command, signal) { - const result = await repository.remove({ - key: command.draftId, - expectedRevision: command.expectedRevision, - idempotencyKey: command.idempotencyKey, - signal, - }); - if (!result.ok) return result; - return Object.freeze({ ok: true as const, value: undefined }); - }, - }; - return Object.freeze(store); -} diff --git a/tests/contract/consumer-experience/indexeddb-local-draft.test.ts b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts index f25dfae9..d2dc3975 100644 --- a/tests/contract/consumer-experience/indexeddb-local-draft.test.ts +++ b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts @@ -1,4 +1,5 @@ -import { readFile } from "node:fs/promises"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -6,10 +7,25 @@ import type { BrowserDataResult, IndexedDbRepositoryPort, } from "../../../src/application/ports/browser-file-storage/index.ts"; -import { - createLocalDraftStore, - type LocalDraft, -} from "./fixtures/local-draft-feature.ts"; +import { createLocalDraftStore } from "../../../src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts"; +import type { LocalDraft } from "../../../src/features/local-draft-feature/domain/local-draft.ts"; + +// 09-12. This probe used to exercise a copy of the feature under fixtures/, +// which had drifted from src (it returned raw storage failures). It now reads +// and runs the one implementation. +const FEATURE_ROOT = "src/features/local-draft-feature"; + +async function featureSources(directory: string): Promise { + const entries = await readdir(directory, { withFileTypes: true }); + const nested = await Promise.all( + entries.map((entry) => { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) return featureSources(target); + return /\.tsx?$/u.test(entry.name) ? [target] : []; + }), + ); + return nested.flat(); +} function success(value: Value): BrowserDataResult { return Object.freeze({ ok: true as const, value }); @@ -133,29 +149,26 @@ describe("IndexedDB local-draft consumer experience", () => { }); }); - it("keeps native IndexedDB and runtime internals out of feature-owned code", async () => { - const source = await readFile( - new URL("./fixtures/local-draft-feature.ts", import.meta.url), - "utf8", - ); - - const importLines = source - .split("\n") - .filter((line) => line.startsWith("import ")); - expect(importLines).toHaveLength(1); - expect(source).toContain( - "src/application/ports/browser-file-storage/index.ts", - ); - - for (const forbidden of [ - "src/adapters/storage/indexeddb", - "globalThis.indexedDB", - "IDBFactory", - "IDBDatabase", - "IDBTransaction", - "IDBObjectStore", - ]) { - expect(source).not.toContain(forbidden); + it("keeps native IndexedDB and the storage runtime out of feature-owned code", async () => { + const files = await featureSources(FEATURE_ROOT); + expect(files.length).toBeGreaterThan(0); + for (const file of files) { + const source = await readFile(file, "utf8"); + for (const forbidden of [ + "adapters/storage/indexeddb", + "application/ports/browser-file-storage", + "globalThis.indexedDB", + "IDBFactory", + "IDBDatabase", + "IDBTransaction", + "IDBObjectStore", + ]) { + const importsOrUses = source + .split("\n") + .filter((line) => !/^\s*(?:\*|\/\/)/u.test(line)) + .some((line) => line.includes(forbidden)); + expect(importsOrUses, `${file} uses ${forbidden}`).toBe(false); + } } }); }); diff --git a/tests/contract/reusable-capability/feature-adapter-composition.test.ts b/tests/contract/reusable-capability/feature-adapter-composition.test.ts index 945d8194..8eeaaeb0 100644 --- a/tests/contract/reusable-capability/feature-adapter-composition.test.ts +++ b/tests/contract/reusable-capability/feature-adapter-composition.test.ts @@ -140,6 +140,29 @@ describe("feature adapter composition", () => { ).toThrow(/duplicate.*test-http-feature/u); }); + it("names the feature and the capability the host did not provide (09-05)", () => { + const withoutIndexedDb = Object.freeze({ http }) as unknown as Parameters< + typeof composeFeatureAdapterInputs< + readonly [typeof LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] + > + >[2]; + expect(() => + composeFeatureAdapterInputs( + Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const), + Object.freeze(["local-draft"]), + withoutIndexedDb, + ), + ).toThrow("feature local-draft needs indexedDb, which the host did not provide"); + // A feature switched off gets no input, so its needs are not asked for. + expect( + composeFeatureAdapterInputs( + Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const), + Object.freeze([]), + withoutIndexedDb, + ), + ).toEqual({}); + }); + it("rejects an input installed under another feature's id (Q-6.9-6)", () => { const wrongId = defineFeatureAdapterContribution({ featureId: "test-http-feature", diff --git a/tests/helpers/fixture-feature.tsx b/tests/helpers/fixture-feature.tsx index 3f56a130..3dccdf1c 100644 --- a/tests/helpers/fixture-feature.tsx +++ b/tests/helpers/fixture-feature.tsx @@ -11,6 +11,7 @@ import { defineFeatureModule } from "../../src/features/feature-module.ts"; * indexes, so they do not depend on the removable sample feature (FE-GATE-020): * * vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + * DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], * PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], * })); * vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/recipes/indexeddb-feature-capability.test.ts b/tests/recipes/indexeddb-feature-capability.test.ts new file mode 100644 index 00000000..c386dd6b --- /dev/null +++ b/tests/recipes/indexeddb-feature-capability.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; + +import { composeFeatureAdapterInputs } from "../../src/features/feature-adapter-contribution.ts"; +import { LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION } from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; +import { createLocalDraftIndexedDbCapability } from "../../recipes/frontend-capabilities/indexeddb-feature-capability.ts"; +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; + +describe("IndexedDB feature capability recipe (09-05)", () => { + it("composes local-draft over the recipe's IndexedDB capability", async () => { + const memory = new MemoryIndexedDbFactory(); + const capability = createLocalDraftIndexedDbCapability({ + scope: Object.freeze({ + authorityToken: "a1b2c3d4e5f60718293a4b5c6d7e8f90", + namespaceToken: "n1b2c3d4e5f60718293a4b5c6d7e8f90", + partitionToken: "p1b2c3d4e5f60718293a4b5c6d7e8f90", + accountScope: "ORIGIN_SHARED" as const, + }), + authorizeLifecycle: () => ({ authorized: false }), + factory: memory.factory, + }); + try { + await expect(capability.open()).resolves.toEqual({ + ok: true, + value: undefined, + }); + const inputs = composeFeatureAdapterInputs( + Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const), + Object.freeze(["local-draft"]), + Object.freeze({ indexedDb: capability.indexedDb }), + ); + const localDraft = inputs["local-draft"]; + if (!localDraft) throw new Error("local-draft input was not composed"); + const draft = Object.freeze({ + draftId: "draft-1", + title: "Architecture notes", + body: "Stored through the recipe capability.", + }); + + await expect( + localDraft.saveDraft({ + draft, + expectedRevision: null, + idempotencyKey: "local-draft-create-1", + }), + ).resolves.toEqual({ ok: true, value: { revision: 1 } }); + await expect(localDraft.findDraft("draft-1")).resolves.toEqual({ + ok: true, + value: { draft, revision: 1 }, + }); + } finally { + capability.close(); + } + }); +}); diff --git a/tests/runtime-schema/runtime-config.test.ts b/tests/runtime-schema/runtime-config.test.ts index b7b71af0..39ac1f86 100644 --- a/tests/runtime-schema/runtime-config.test.ts +++ b/tests/runtime-schema/runtime-config.test.ts @@ -268,6 +268,32 @@ describe("runtime configuration boundary", () => { }, ); + it("names the rejected keys, never their values (09-04)", async () => { + const failure = await loadRuntimeConfig({ + buildConfig: { + buildId: "build-a", + commitSha: "local", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + fetcher: async () => + new Response( + JSON.stringify({ + ...validConfig, + REQUEST_TIMEOUT_MS: -1, + TELEMETRY_ENABELD: "value-probe", + ["" + "x".repeat(200)]: true, + }), + { headers: { "content-type": "application/json" } }, + ), + }).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(BootConfigError); + const safe = (failure as BootConfigError).safe; + expect(safe.invalidKeys).toEqual(["REQUEST_TIMEOUT_MS", "TELEMETRY_ENABELD"]); + expect(JSON.stringify(safe)).not.toContain("value-probe"); + }); + it("returns only safe boot fields on failure", async () => { await expect( loadRuntimeConfig({ diff --git a/tests/scripts/generate-product-feature-index.test.ts b/tests/scripts/generate-product-feature-index.test.ts index 60164d9b..1f1bcfd4 100644 --- a/tests/scripts/generate-product-feature-index.test.ts +++ b/tests/scripts/generate-product-feature-index.test.ts @@ -4,6 +4,8 @@ import { generateAppIndexes, renderContextIndex, renderFeatureIndex, + selectAppIndexes, + type TopologyDeclarationSource, } from "../../scripts/generate-product-feature-index.ts"; describe("feature index generator", () => { @@ -132,6 +134,25 @@ describe("app-scoped selection from ownership declarations", () => { await expect(generateAppIndexes(overContexts, "a")).rejects.toThrow(/App a context cardinality 2 exceeds budget 1/); }); + it("refuses a feature directory without a declaration or NOT_INSTALLED marker (09-07)", async () => { + const files = { + "src/apps/a/app-module.ts": app("a"), + "src/contexts/c/context-module.ts": context("c", "a"), + "src/features/f/feature-module.ts": feature("f", "c"), + // A misspelt declaration file used to drop the feature without a word. + "src/features/typo/feature-modul.ts": feature("typo", "c"), + }; + await expect(generateAppIndexes(await repo(files), "a")).rejects.toThrow( + /src\/features\/typo has no feature-module\.ts/u, + ); + const marked = await repo({ + ...files, + "src/features/typo/NOT_INSTALLED": "Composed only by tests.\n", + }); + const selected = await generateAppIndexes(marked, "a"); + expect(selected.entries.map((entry) => entry.id)).toEqual(["f"]); + }); + it("skips contexts without features and never imports another app's features", async () => { const root = await repo({ "src/apps/a/app-module.ts": app("a"), @@ -149,3 +170,66 @@ describe("app-scoped selection from ownership declarations", () => { expect(selected.appIndex).toContain('id: "a"'); }); }); + +describe("build-time product selection (09-02)", () => { + const source: TopologyDeclarationSource = Object.freeze({ + appIds: () => ["a"], + app: (appId: string) => + appId === "a" ? Object.freeze({ id: "a", maxContexts: 20 }) : undefined, + contextsOf: () => [ + Object.freeze({ id: "c", appId: "a", routePath: "c/*", maxFeatures: 200 }), + ], + featuresOf: () => [ + Object.freeze({ id: "f1", contextId: "c", directory: "f1" }), + Object.freeze({ id: "f2", contextId: "c", directory: "f2" }), + ], + }); + const declared = + 'DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze(["f1", "f2"])'; + + it("keeps every declared feature when nothing is selected", () => { + for (const selection of [undefined, "", " "]) { + const selected = selectAppIndexes(source, "a", selection); + expect(selected.entries.map((entry) => entry.id)).toEqual(["f1", "f2"]); + expect(selected.featureIndex).toBe(selectAppIndexes(source, "a").featureIndex); + expect(selected.featureIndex).toContain(declared); + } + }); + + it("imports only the selected features and still declares the rest", () => { + const selected = selectAppIndexes(source, "a", "f2"); + expect(selected.entries.map((entry) => entry.id)).toEqual(["f2"]); + expect(selected.featureIndex).not.toContain("features/f1/"); + expect(selected.contextIndex).not.toContain("features/f1/"); + expect(selected.contextIndex).toContain("features/f2/context-routes.ts"); + expect(selected.featureIndex).toContain(declared); + }); + + it("imports nothing for an explicit none", () => { + const selected = selectAppIndexes(source, "a", "none"); + expect(selected.entries).toEqual([]); + expect(selected.featureIndex).not.toMatch(/features\/f[12]\//u); + expect(selected.contextIndex).toBe(renderContextIndex([])); + expect(selected.featureIndex).toContain(declared); + }); + + it("fails generation on an id the app does not declare", () => { + expect(() => selectAppIndexes(source, "a", "f1,f3")).toThrow( + /VITE_PRODUCT_FEATURES names features this build does not contain: f3/u, + ); + }); + + it("fails the generator command, the first build step, on a misspelt id", async () => { + const { spawnSync } = await import("node:child_process"); + const run = spawnSync( + process.execPath, + ["scripts/generate-product-feature-index.ts", "--check"], + { + encoding: "utf8", + env: { ...process.env, VITE_PRODUCT_FEATURES: "reference-featrue" }, + }, + ); + expect(run.status).not.toBe(0); + expect(run.stderr).toMatch(/does not contain: reference-featrue/u); + }); +}); diff --git a/tests/unit/build-environment-bundle.test.ts b/tests/unit/build-environment-bundle.test.ts new file mode 100644 index 00000000..78490be8 --- /dev/null +++ b/tests/unit/build-environment-bundle.test.ts @@ -0,0 +1,86 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { filesBelow } from "../../scripts/lib/removal-fixture.ts"; + +/** + * 13-06. Which VITE_* values reach the bundle. The declared values the app + * reads must still be there (build id, commit, runtime config URL, base path); + * a declared value nothing reads and an undeclared one must not be, and the + * design-system chunk must not change with the build id. + */ +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +function inheritedEnvironment(): NodeJS.ProcessEnv { + return Object.fromEntries( + Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")), + ); +} + +async function build(variables: Readonly>) { + const outDir = await mkdtemp(path.join(tmpdir(), "build-environment-")); + roots.push(outDir); + const run = spawnSync( + path.resolve("node_modules/.bin/vite"), + ["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"], + { encoding: "utf8", env: { ...inheritedEnvironment(), ...variables } }, + ); + const contents = run.status === 0 + ? await Promise.all( + (await filesBelow(outDir)) + .filter((file) => /\.(?:js|html)$/u.test(file)) + .map(async (file) => ({ file, text: await readFile(file, "utf8") })), + ) + : []; + return { run, outDir, contents }; +} + +const DECLARED = Object.freeze({ + VITE_COMMIT_SHA: "commit-probe-13", + VITE_ROUTER_BASE_PATH: "/base-probe/", + VITE_RUNTIME_CONFIG_URL: "/base-probe/runtime-probe.json", + // Declared, but applied by the index generator; the bundle never reads it. + VITE_PRODUCT_FEATURES: "unreferenced-probe-13", +}); + +describe("build variables in the bundle (13-06)", () => { + it("keeps the values the app reads and nothing else", async () => { + const first = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-1" }); + expect(first.run.stderr).toBe(""); + expect(first.run.status).toBe(0); + const bundled = (value: string) => + first.contents.some(({ text }) => text.includes(value)); + expect(bundled("build-probe-1")).toBe(true); + expect(bundled("commit-probe-13")).toBe(true); + expect(bundled("/base-probe/runtime-probe.json")).toBe(true); + const html = first.contents.find(({ file }) => file.endsWith("index.html")); + expect(html?.text).toContain('src="/base-probe/assets/'); + expect(bundled("unreferenced-probe-13")).toBe(false); + + const second = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-2" }); + expect(second.run.status).toBe(0); + const designSystem = async (outDir: string) => + (await readdir(path.join(outDir, "assets"))).filter((name) => + name.startsWith("design-system-"), + ); + const firstChunks = await designSystem(first.outDir); + expect(firstChunks).toHaveLength(1); + expect(await designSystem(second.outDir)).toEqual(firstChunks); + }, 120_000); + + it("refuses a VITE_* variable the build does not declare", async () => { + const refused = await build({ VITE_PAYMENT_KEY: "sk_live_probe" }); + expect(refused.run.status).not.toBe(0); + expect(refused.run.stderr + refused.run.stdout).toMatch( + /Undeclared VITE_\* build variables: VITE_PAYMENT_KEY/u, + ); + }, 120_000); +}); diff --git a/tests/unit/bundle-classification.test.ts b/tests/unit/bundle-classification.test.ts index c5e2e75c..bb17acf8 100644 --- a/tests/unit/bundle-classification.test.ts +++ b/tests/unit/bundle-classification.test.ts @@ -26,6 +26,31 @@ describe("Vite bundle classification", () => { }); }); + it("counts the entry's own dynamic imports as initial (09-03)", () => { + // main.tsx does nothing but import the application graph dynamically, so + // that graph is loaded on every visit; the routes it lazy-loads are not. + expect( + classifyViteJavascript({ + "index.html": { + file: "assets/entry.js", + isEntry: true, + dynamicImports: ["src/boot.tsx"], + }, + "src/boot.tsx": { + file: "assets/boot.js", + imports: ["_shared.js"], + dynamicImports: ["src/lazy.js"], + }, + "_shared.js": { file: "assets/shared.js" }, + "src/lazy.js": { file: "assets/lazy.js" }, + }), + ).toEqual({ + initialFiles: ["assets/boot.js", "assets/entry.js", "assets/shared.js"], + lazyFiles: ["assets/lazy.js"], + missingImports: [], + }); + }); + it("reports a manifest import that cannot be resolved", () => { expect( classifyViteJavascript({ diff --git a/tests/unit/feature-override-diagnostics.test.ts b/tests/unit/feature-override-diagnostics.test.ts new file mode 100644 index 00000000..91446b0d --- /dev/null +++ b/tests/unit/feature-override-diagnostics.test.ts @@ -0,0 +1,123 @@ +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts"; +import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts"; + +type Runtime = Parameters[0]["runtime"]; + +// 09-09. An override key this build does not declare stays inert (one runtime +// document may serve several builds), but a misspelt kill switch used to leave +// the feature running without a trace. +const MISSPELT = "reference-featrue"; + +function runtimeWith(overrides: Readonly>): Runtime { + return { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + REQUEST_TIMEOUT_MS: 1000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: overrides, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }; +} + +const release = { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: {}, +} as Parameters[0]["release"]; + +describe("unknown feature override keys (09-09)", () => { + it("records one diagnostic per key the build does not declare", async () => { + const declared = COMPILED_PRODUCT_FEATURE_IDS[0]; + const adapters = await createRuntimeAdapters({ + runtime: runtimeWith({ + [MISSPELT]: "DISABLED", + ...(declared === undefined ? {} : { [declared]: "DISABLED" }), + }), + release, + host: {}, + }); + try { + const unknown = adapters.outputPorts.diagnostics + .entries() + .filter((entry) => entry.eventId === "feature.override.unknown"); + expect(unknown).toEqual([ + expect.objectContaining({ + level: "warn", + context: { feature_override_key: MISSPELT }, + }), + ]); + } finally { + adapters.infrastructure.dispose(); + } + }); + + it("warns in the admission record without refusing the artifact", async () => { + const root = await mkdtemp(path.join(tmpdir(), "admission-override-")); + try { + const config = await generateRuntimeConfig("local", {}); + await mkdir(path.join(root, "dist"), { recursive: true }); + await writeFile( + path.join(root, "dist/config.json"), + JSON.stringify({ ...config, FEATURE_OVERRIDES: { [MISSPELT]: "DISABLED" } }), + ); + const result = spawnSync( + process.execPath, + [path.resolve("scripts/check-release-admission.ts")], + { + cwd: root, + encoding: "utf8", + env: { ...process.env, APP_PROFILE: "local", RELEASE_TARGET: "local" }, + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stderr).toContain(MISSPELT); + const record = JSON.parse( + await readFile(path.join(root, "artifacts/release/deployment-admission.json"), "utf8"), + ) as { status: string; warnings: { field: string; reason: string }[] }; + expect(record.status).toBe("ADMITTED"); + expect(record.warnings).toEqual([ + expect.objectContaining({ field: `FEATURE_OVERRIDES.${MISSPELT}` }), + ]); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/unit/feature-removal-argument.test.ts b/tests/unit/feature-removal-argument.test.ts new file mode 100644 index 00000000..b5db92dc --- /dev/null +++ b/tests/unit/feature-removal-argument.test.ts @@ -0,0 +1,20 @@ +import { spawnSync } from "node:child_process"; + +import { describe, expect, it } from "vitest"; + +// 09-07 (D-10). The removal gate takes the feature to remove as an argument +// instead of hard-coding the sample; an id no feature declares stops it before +// any fixture is built. +describe("feature removal argument", () => { + it("refuses a feature id that no installed feature declares", () => { + const run = spawnSync( + process.execPath, + ["scripts/test-sample-removal.ts", "--feature=missing-feature"], + { encoding: "utf8" }, + ); + expect(run.status).not.toBe(0); + expect(run.stderr).toMatch( + /No installed feature declares FEATURE_MODULE_ID "missing-feature"/u, + ); + }); +}); diff --git a/tests/unit/local-draft-api.test.ts b/tests/unit/local-draft-api.test.ts new file mode 100644 index 00000000..337f29db --- /dev/null +++ b/tests/unit/local-draft-api.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createLocalDraftFeatureInput, + type LocalDraftStore, +} from "../../src/features/local-draft-feature/application/local-draft-api.ts"; + +function recordingStore() { + const save = vi.fn(async () => + Object.freeze({ ok: true as const, value: Object.freeze({ revision: 1 }) }), + ); + const store: LocalDraftStore = Object.freeze({ + save, + find: async () => Object.freeze({ ok: true as const, value: null }), + remove: async () => Object.freeze({ ok: true as const, value: undefined }), + }); + return { save, store }; +} + +function command(draft: Readonly<{ draftId: string; title: string; body: string }>) { + return Object.freeze({ draft, expectedRevision: null, idempotencyKey: "save-1" }); +} + +describe("local-draft save applies the domain rules (09-06)", () => { + it.each([ + ["a blank draft id", { draftId: " ", title: "Title", body: "" }], + ["a blank title", { draftId: "draft-1", title: " ", body: "" }], + ["a 161-character title", { draftId: "draft-1", title: "t".repeat(161), body: "" }], + ["a body over 100,000 characters", { draftId: "draft-1", title: "Title", body: "b".repeat(100_001) }], + ])("rejects %s without calling the store", async (_case, draft) => { + const { save, store } = recordingStore(); + const result = await createLocalDraftFeatureInput(store).saveDraft(command(draft)); + expect(result).toMatchObject({ + ok: false, + error: { kind: "VALIDATION_REJECTED", operationId: "LOCAL_DRAFT_SAVE" }, + }); + expect(save).not.toHaveBeenCalled(); + }); + + it("stores the normalized draft at the limits", async () => { + const { save, store } = recordingStore(); + const title = "t".repeat(160); + const body = "b".repeat(100_000); + await expect( + createLocalDraftFeatureInput(store).saveDraft( + command({ draftId: " draft-1 ", title: ` ${title} `, body }), + ), + ).resolves.toEqual({ ok: true, value: { revision: 1 } }); + expect(save).toHaveBeenCalledWith( + expect.objectContaining({ draft: { draftId: "draft-1", title, body } }), + undefined, + ); + }); +}); diff --git a/tests/unit/product-feature-selection-build.test.ts b/tests/unit/product-feature-selection-build.test.ts new file mode 100644 index 00000000..987efb1c --- /dev/null +++ b/tests/unit/product-feature-selection-build.test.ts @@ -0,0 +1,101 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; +import { filesBelow } from "../../scripts/lib/removal-fixture.ts"; +import { ROUTE_FEATURE_OWNER } from "../../src/features/installed-feature-contracts.ts"; +import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts"; + +/** + * 09-02 (D-9). `VITE_PRODUCT_FEATURES=none` has to leave every feature out of + * every consumer, not only the browser bundle: the generated context index + * (router), the installed contract contributions (Node contract-set + * generation) and the built assets. This runs the production generator and a + * Vite build over a copy of the build inputs. Written against whatever + * features the tree declares, so it holds after the sample's removal too. + */ +const BUILD_INPUTS = [ + "src", + "public", + "index.html", + "package.json", + "vite.config.ts", + "tsconfig.base.json", + "tsconfig.app.json", + "scripts/lib/vite-module-inventory.ts", +] as const; +// Feature ids stay: the generated index still declares them so the platform +// overview reports NOT_INSTALLED. Their modules and route ids go. +const FEATURE_ROUTE_IDS = Object.keys(ROUTE_FEATURE_OWNER); +const FEATURE_MODULE = /^src\/(?:features\/[^/]+|contexts\/[^/]+)\//u; + +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("VITE_PRODUCT_FEATURES=none build (09-02)", () => { + it("leaves every feature out of the context index, the contract set and dist", async () => { + const root = await mkdtemp(path.join(tmpdir(), "product-selection-build-")); + roots.push(root); + for (const input of BUILD_INPUTS) { + await mkdir(path.dirname(path.join(root, input)), { recursive: true }); + await cp(path.resolve(input), path.join(root, input), { recursive: true }); + } + await linkFixtureNodeModules(root); + const env = { ...process.env, VITE_PRODUCT_FEATURES: "none" }; + + const generated = spawnSync( + process.execPath, + [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], + { encoding: "utf8", env }, + ); + expect(generated.stderr).toBe(""); + expect(generated.status).toBe(0); + const contextIndex = await readFile( + path.join(root, "src/.generated/product-context-index.ts"), + "utf8", + ); + expect(contextIndex).not.toContain("../features/"); + + const contributions = (await import( + pathToFileURL(path.join(root, "src/features/installed-contract-contributions.ts")).href + )) as typeof import("../../src/features/installed-contract-contributions.ts"); + expect(contributions.INSTALLED_CONTRACT_CONTRIBUTIONS).toEqual([]); + const manifest = (await import( + pathToFileURL(path.join(root, "src/features/installed-product-manifest.ts")).href + )) as typeof import("../../src/features/installed-product-manifest.ts"); + expect(manifest.INSTALLED_PRODUCT_FEATURE_IDS).toEqual([]); + // Still declared, so the platform overview reports them as NOT_INSTALLED. + expect(manifest.COMPILED_PRODUCT_FEATURE_IDS).toEqual(COMPILED_PRODUCT_FEATURE_IDS); + + const built = spawnSync( + path.resolve("node_modules/.bin/vite"), + ["build", "--logLevel", "error"], + { cwd: root, encoding: "utf8", env }, + ); + expect(built.stderr).toBe(""); + expect(built.status).toBe(0); + const residue: string[] = []; + for (const file of await filesBelow(path.join(root, "dist"))) { + if (!/\.(?:js|css|html)$/u.test(file)) continue; + const content = await readFile(file, "utf8"); + for (const routeId of FEATURE_ROUTE_IDS) { + if (content.includes(routeId)) residue.push(`${path.relative(root, file)}: ${routeId}`); + } + } + expect(residue).toEqual([]); + const inventory = JSON.parse( + await readFile(path.join(root, "dist/.vite/module-inventory.json"), "utf8"), + ) as { chunks: { modules: string[] }[] }; + const modules = inventory.chunks.flatMap((chunk) => chunk.modules); + expect(modules).toContain("src/features/installed-product-manifest.ts"); + expect(modules.filter((module) => FEATURE_MODULE.test(module))).toEqual([]); + }, 120_000); +}); diff --git a/tests/unit/removal-fixture.test.ts b/tests/unit/removal-fixture.test.ts index 61bdebd9..001b11e0 100644 --- a/tests/unit/removal-fixture.test.ts +++ b/tests/unit/removal-fixture.test.ts @@ -9,6 +9,7 @@ import { assertNoRuntimeImports, pruneRemovalFixtureCiContract, removeRuntimeDependentTests, + renderRemovalJunit, runtimeImportGraph, } from "../../scripts/lib/removal-fixture.ts"; @@ -155,3 +156,30 @@ describe("release evidence fixture copy", () => { } }); }); + +describe("removal JUnit report (14-08)", () => { + it("counts every failure and gives each check its own cause", () => { + const xml = renderRemovalJunit("reference-feature-removal", [ + { name: "typecheck", passed: false, failure: "corepack pnpm check:types exited 2" }, + { name: "architecture", passed: true }, + { name: "build", passed: false, failure: "corepack pnpm build exited 1" }, + { + name: "fixture-id-residue", + passed: false, + failure: "residue: tests/a.test.ts, tests/&c.ts", + }, + ]); + expect(xml).toContain('tests="4" failures="3"'); + expect(xml).toContain( + '', + ); + expect(xml).toContain(''); + expect(xml).toContain( + '', + ); + expect(xml).toContain( + 'message="residue: tests/a.test.ts, tests/<b>&c.ts"', + ); + expect(xml.match(/residue:/gu)).toHaveLength(1); + }); +}); diff --git a/tests/unit/sub-path-deployment.test.ts b/tests/unit/sub-path-deployment.test.ts new file mode 100644 index 00000000..1d10e0cd --- /dev/null +++ b/tests/unit/sub-path-deployment.test.ts @@ -0,0 +1,66 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts"; +import { getBuildConfig } from "../../src/contracts/env.ts"; + +/** + * 13-07. A build served from a sub-path must fetch its runtime config and + * release manifest from that sub-path; dist is served under the base, so a + * root URL is a 404 at boot. + */ +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("sub-path deployment URLs (13-07)", () => { + it("derives the runtime config URL from the base path", () => { + expect(getBuildConfig({ VITE_ROUTER_BASE_PATH: "/app/" }).runtimeConfigUrl).toBe( + "/app/config.json", + ); + expect(getBuildConfig({}).runtimeConfigUrl).toBe("/config.json"); + expect( + getBuildConfig({ + VITE_ROUTER_BASE_PATH: "/app/", + VITE_RUNTIME_CONFIG_URL: "/app/runtime.json", + }).runtimeConfigUrl, + ).toBe("/app/runtime.json"); + }); + + it("rebases the profile's root release manifest URL onto the base path", async () => { + const rebased = await generateRuntimeConfig("local", { VITE_ROUTER_BASE_PATH: "/app/" }); + expect(rebased["RELEASE_MANIFEST_URL"]).toBe("/app/release-manifest.json"); + const root = await generateRuntimeConfig("local", {}); + expect(root["RELEASE_MANIFEST_URL"]).toBe("/release-manifest.json"); + }); + + it("fails the build when an explicit runtime config URL leaves the base path", async () => { + const outDir = await mkdtemp(path.join(tmpdir(), "sub-path-build-")); + roots.push(outDir); + const environment = Object.fromEntries( + Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")), + ); + const run = spawnSync( + path.resolve("node_modules/.bin/vite"), + ["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"], + { + encoding: "utf8", + env: { + ...environment, + VITE_ROUTER_BASE_PATH: "/app/", + VITE_RUNTIME_CONFIG_URL: "/config.json", + }, + }, + ); + expect(run.status).not.toBe(0); + expect(run.stderr + run.stdout).toMatch( + /VITE_RUNTIME_CONFIG_URL \/config\.json is outside VITE_ROUTER_BASE_PATH \/app\//u, + ); + }, 120_000); +}); diff --git a/tests/unit/two-feature-install-typecheck.test.ts b/tests/unit/two-feature-install-typecheck.test.ts new file mode 100644 index 00000000..756491d0 --- /dev/null +++ b/tests/unit/two-feature-install-typecheck.test.ts @@ -0,0 +1,181 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; + +/** + * 09-01. The central composers (`src/features/installed-*`) are typed from the + * generated feature index, so the repository's own typecheck only ever sees + * the features it ships. This installs two more into a copy of `src`, in a + * context of their own so the check survives the sample's removal: one with a + * route, a runtime and both locales but no adapter, and one shaped differently + * on every composed axis (an adapter that needs telemetry, no routes, no + * runtime, one locale). It regenerates the index + * with the production generator and runs the app typecheck over the copy. + */ +const SECOND_FEATURE_MODULE = `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts"; +import { defineFeatureModule } from "../feature-module.ts"; + +type SecondFeatureInput = Readonly<{ ping(): string }>; + +declare module "../../application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "second-feature": SecondFeatureInput; + } +} + +export const FEATURE_MODULE_ID = "second-feature"; +export const FEATURE_CONTEXT_ID = "two-feature-context"; + +export const FEATURE_MODULE = defineFeatureModule({ + id: FEATURE_MODULE_ID, + contracts: { + featureId: FEATURE_MODULE_ID, + routes: {}, + routeRuntimeContracts: {}, + apiOperations: {}, + // Frozen empty arrays type as \`readonly never[]\`, not \`readonly []\`. + invalidation: { + topics: Object.freeze([]), + namespaces: Object.freeze([]), + edges: Object.freeze([]), + }, + topicVersions: Object.freeze([]), + schemas: {}, + runtimeSchemas: {}, + mappers: {}, + }, + routes: {}, + adapters: [ + defineFeatureAdapterContribution({ + featureId: FEATURE_MODULE_ID, + needs: ["telemetry"] as const, + createInput: () => + Object.freeze({ + featureId: FEATURE_MODULE_ID, + input: Object.freeze({ ping: () => "pong" }), + }), + }), + ], + runtimes: [], + messages: { "en-US": { "secondFeature.title": "Second feature" } }, + contractContributions: [], +} as const); +`; + +const SECOND_FEATURE_ROUTES = `import type { RouteObject } from "react-router-dom"; + +export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze([]); +`; + +const ROUTED_FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts"; + +export const FEATURE_MODULE_ID = "routed-feature"; +export const FEATURE_CONTEXT_ID = "two-feature-context"; + +const ROUTES = { + ROUTED_ITEMS: { + routeId: "ROUTED_ITEMS", + path: "/two-feature/items", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "routed-items", + errorSurface: "feature-boundary", + chunkId: "route-routed-items", + title: "route.ROUTED_ITEMS.title", + navigationLabel: null, + navigationOrder: null, + }, +} as const; + +const MESSAGES = { + "route.ROUTED_ITEMS.title": "Routed items", + "route.ROUTED_ITEMS.navigation": "Routed items", +} as const; + +export const FEATURE_MODULE = defineFeatureModule({ + id: FEATURE_MODULE_ID, + contracts: { + featureId: FEATURE_MODULE_ID, + routes: ROUTES, + routeRuntimeContracts: { + ROUTED_ITEMS: { + routeId: "ROUTED_ITEMS", + moduleId: "routed-items-page", + paramsCodec: "none", + searchCodec: "none", + }, + }, + apiOperations: {}, + invalidation: { topics: [], namespaces: [], edges: [] }, + topicVersions: [], + schemas: {}, + runtimeSchemas: {}, + mappers: {}, + }, + routes: ROUTES, + adapters: [], + runtimes: [{ featureId: FEATURE_MODULE_ID, routeCodecs: {}, routeRuntime: {} }], + messages: { "ko-KR": MESSAGES, "en-US": MESSAGES }, + contractContributions: [], +} as const); +`; + +const CONTEXT_MODULE = `export const CONTEXT_MODULE_ID = "two-feature-context"; +export const CONTEXT_APP_ID = "template-app"; +export const CONTEXT_ROUTE_PATH = "two-feature/*"; +export const CONTEXT_MAX_FEATURES = 2; +`; + +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("installing a second feature (09-01)", () => { + it("keeps the app typecheck green with two differently shaped features", async () => { + const root = await mkdtemp(path.join(tmpdir(), "two-feature-install-")); + roots.push(root); + await cp(path.resolve("src"), path.join(root, "src"), { recursive: true }); + for (const config of ["tsconfig.base.json", "tsconfig.app.json"]) { + await cp(path.resolve(config), path.join(root, config)); + } + await linkFixtureNodeModules(root); + const files: Readonly> = { + "src/contexts/two-feature-context/context-module.ts": CONTEXT_MODULE, + "src/features/routed-feature/feature-module.ts": ROUTED_FEATURE_MODULE, + "src/features/routed-feature/context-routes.ts": SECOND_FEATURE_ROUTES, + "src/features/second-feature/feature-module.ts": SECOND_FEATURE_MODULE, + "src/features/second-feature/context-routes.ts": SECOND_FEATURE_ROUTES, + }; + for (const [file, content] of Object.entries(files)) { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), content); + } + + const generated = spawnSync( + process.execPath, + [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], + { encoding: "utf8" }, + ); + expect(generated.stderr).toBe(""); + expect(generated.status).toBe(0); + const index = await readFile(path.join(root, "src/.generated/product-feature-index.ts"), "utf8"); + expect(index).toContain("../features/second-feature/feature-module.ts"); + expect(index).toContain("../features/routed-feature/feature-module.ts"); + + const typecheck = spawnSync( + path.resolve("node_modules/.bin/tsc"), + ["--project", path.join(root, "tsconfig.app.json")], + { encoding: "utf8" }, + ); + expect(typecheck.stdout + typecheck.stderr).toBe(""); + expect(typecheck.status).toBe(0); + }, 60_000); +}); diff --git a/vite.config.ts b/vite.config.ts index 7fc05d4a..6acd6049 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,8 +1,27 @@ -import { defineConfig } from "vite"; +import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts"; +import { ENV_REGISTRY } from "./src/contracts/env.ts"; + +/** + * 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once + * something bundles it, so a value the build does not declare is refused + * rather than carried along. + */ +function assertDeclaredBuildVariables(mode: string): void { + const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_")) + .filter((name) => !Object.hasOwn(ENV_REGISTRY, name)) + .sort(); + if (undeclared.length > 0) { + throw new Error( + `Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` + + "Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " + + "VITE_ values are published to the browser.", + ); + } +} /** * §6.1. One sub-path, declared once. @@ -24,11 +43,41 @@ function routerBasePath(environment: NodeJS.ProcessEnv): string { return declared; } -export default defineConfig({ - base: routerBasePath(process.env), - plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], - build: { - manifest: true, - sourcemap: false, - }, +/** + * 13-07. The runtime document ships inside dist, which is served under the + * base path. An explicit root-relative URL outside it would 404 at boot. + */ +function assertRuntimeConfigUnderBase( + environment: NodeJS.ProcessEnv, + base: string, +): void { + const declared = environment["VITE_RUNTIME_CONFIG_URL"]; + if (declared?.startsWith("/") && !declared.startsWith(base)) { + throw new Error( + `VITE_RUNTIME_CONFIG_URL ${declared} is outside VITE_ROUTER_BASE_PATH ${base}`, + ); + } +} + +export default defineConfig(({ mode }) => { + assertDeclaredBuildVariables(mode); + const base = routerBasePath(process.env); + assertRuntimeConfigUnderBase(process.env, base); + return { + base, + plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], + build: { + manifest: true, + sourcemap: false, + rollupOptions: { + output: { + // 09-03. The entry now imports the app dynamically, so Vite's preload + // helper would land in the entry chunk and every lazy chunk would + // import the entry, whose hash changes with each build id. + manualChunks: (id: string) => + id.includes("vite/preload-helper") ? "preload-helper" : undefined, + }, + }, + }, + }; });