refactor: 도메인이 100개 1000개씩 늘어나도 유지보수 쉬운 구조로 변경
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
import type {
|
||||
ApplicationFeatureId,
|
||||
ApplicationFeatureInputs,
|
||||
} from "../application/ports/in/application-api.ts";
|
||||
import type {
|
||||
InstalledHttpOperationExecutor,
|
||||
} from "../adapters/http/index.ts";
|
||||
import type { TelemetryPort } from "../platform/telemetry/telemetry-port.ts";
|
||||
|
||||
/**
|
||||
* Features augment this registry with the repository identities they consume.
|
||||
* The provider is a composition capability; feature use cases never import it.
|
||||
*/
|
||||
export interface FeatureIndexedDbRepositories {}
|
||||
|
||||
export type FeatureIndexedDbRepositoryId = Extract<
|
||||
keyof FeatureIndexedDbRepositories,
|
||||
string
|
||||
>;
|
||||
|
||||
export type IndexedDbRepositoryProvider = Readonly<{
|
||||
get<RepositoryId extends FeatureIndexedDbRepositoryId>(
|
||||
repositoryId: RepositoryId,
|
||||
): FeatureIndexedDbRepositories[RepositoryId];
|
||||
}>;
|
||||
|
||||
export function createIndexedDbRepositoryProvider(
|
||||
repositories: Readonly<Partial<FeatureIndexedDbRepositories>>,
|
||||
): IndexedDbRepositoryProvider {
|
||||
const snapshot = Object.freeze({ ...repositories });
|
||||
return Object.freeze({
|
||||
get<RepositoryId extends FeatureIndexedDbRepositoryId>(
|
||||
repositoryId: RepositoryId,
|
||||
): FeatureIndexedDbRepositories[RepositoryId] {
|
||||
const repository = snapshot[repositoryId];
|
||||
if (!repository) {
|
||||
throw new TypeError(
|
||||
`IndexedDB repository is not installed: ${repositoryId}`,
|
||||
);
|
||||
}
|
||||
return repository as FeatureIndexedDbRepositories[RepositoryId];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export type FeaturePlatformCapabilities = Readonly<{
|
||||
http: InstalledHttpOperationExecutor;
|
||||
indexedDb: IndexedDbRepositoryProvider;
|
||||
/** Spec §24. Provider-neutral, bounded, fail-open feature telemetry. */
|
||||
telemetry: TelemetryPort;
|
||||
}>;
|
||||
|
||||
export type FeaturePlatformCapabilityId =
|
||||
keyof FeaturePlatformCapabilities;
|
||||
|
||||
export type FeatureCapabilitySelection<
|
||||
Needs extends readonly FeaturePlatformCapabilityId[],
|
||||
> = Pick<FeaturePlatformCapabilities, Needs[number]>;
|
||||
|
||||
const FEATURE_ADAPTER_CONTRIBUTION = Symbol(
|
||||
"feature-adapter-contribution",
|
||||
);
|
||||
|
||||
type FeatureAdapterContributionDefinition<
|
||||
FeatureId extends ApplicationFeatureId,
|
||||
Needs extends readonly FeaturePlatformCapabilityId[],
|
||||
> = Readonly<{
|
||||
featureId: FeatureId;
|
||||
needs: Needs;
|
||||
createInput(
|
||||
context: FeatureCapabilitySelection<Needs>,
|
||||
): Readonly<{
|
||||
featureId: FeatureId;
|
||||
input: ApplicationFeatureInputs[FeatureId];
|
||||
}>;
|
||||
}>;
|
||||
|
||||
export type FeatureAdapterContribution<
|
||||
FeatureId extends ApplicationFeatureId,
|
||||
Needs extends readonly FeaturePlatformCapabilityId[],
|
||||
> = FeatureAdapterContributionDefinition<FeatureId, Needs> &
|
||||
Readonly<{
|
||||
[FEATURE_ADAPTER_CONTRIBUTION]: true;
|
||||
}>;
|
||||
|
||||
export function defineFeatureAdapterContribution<
|
||||
const FeatureId extends ApplicationFeatureId,
|
||||
const Needs extends readonly FeaturePlatformCapabilityId[],
|
||||
>(
|
||||
contribution: FeatureAdapterContributionDefinition<FeatureId, Needs>,
|
||||
): FeatureAdapterContribution<FeatureId, Needs> {
|
||||
return Object.freeze({
|
||||
...contribution,
|
||||
needs: Object.freeze([...contribution.needs]) as unknown as Needs,
|
||||
[FEATURE_ADAPTER_CONTRIBUTION]: true as const,
|
||||
});
|
||||
}
|
||||
|
||||
type ContributionShape = Readonly<{
|
||||
[FEATURE_ADAPTER_CONTRIBUTION]: true;
|
||||
featureId: ApplicationFeatureId;
|
||||
needs: readonly FeaturePlatformCapabilityId[];
|
||||
createInput: (...args: never[]) => unknown;
|
||||
}>;
|
||||
|
||||
type ContributionNeeds<Contribution> =
|
||||
Contribution extends Readonly<{
|
||||
needs: readonly (infer Capability)[];
|
||||
}>
|
||||
? Extract<Capability, FeaturePlatformCapabilityId>
|
||||
: never;
|
||||
|
||||
export type ContributionsCapabilityContext<
|
||||
Contributions extends readonly ContributionShape[],
|
||||
> = Pick<
|
||||
FeaturePlatformCapabilities,
|
||||
ContributionNeeds<Contributions[number]>
|
||||
>;
|
||||
|
||||
export type InstalledFeatureInputs = Readonly<
|
||||
Partial<ApplicationFeatureInputs>
|
||||
>;
|
||||
|
||||
function setFeatureInput<FeatureId extends ApplicationFeatureId>(
|
||||
target: Partial<ApplicationFeatureInputs>,
|
||||
featureId: FeatureId,
|
||||
input: ApplicationFeatureInputs[FeatureId],
|
||||
): void {
|
||||
const writable = target as Record<
|
||||
ApplicationFeatureId,
|
||||
ApplicationFeatureInputs[ApplicationFeatureId]
|
||||
>;
|
||||
writable[featureId] = input;
|
||||
}
|
||||
|
||||
function invokeContribution<
|
||||
FeatureId extends ApplicationFeatureId,
|
||||
Needs extends readonly FeaturePlatformCapabilityId[],
|
||||
>(
|
||||
contribution: FeatureAdapterContribution<FeatureId, Needs>,
|
||||
context: FeaturePlatformCapabilities,
|
||||
) {
|
||||
return contribution.createInput(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamic catalog assembly stays centralized here. Type authority lives at each
|
||||
* feature contribution; the only dynamic write is isolated in setFeatureInput.
|
||||
*/
|
||||
export function composeFeatureAdapterInputs<
|
||||
const Contributions extends readonly ContributionShape[],
|
||||
>(
|
||||
contributions: Contributions,
|
||||
enabledFeatureIds: readonly string[],
|
||||
context: ContributionsCapabilityContext<Contributions>,
|
||||
): InstalledFeatureInputs {
|
||||
const enabled = new Set<string>(enabledFeatureIds);
|
||||
const result: Partial<ApplicationFeatureInputs> = {};
|
||||
|
||||
for (const contribution of contributions) {
|
||||
if (contribution[FEATURE_ADAPTER_CONTRIBUTION] !== true) {
|
||||
throw new TypeError(
|
||||
"Feature adapter contribution must be defined through defineFeatureAdapterContribution()",
|
||||
);
|
||||
}
|
||||
if (!enabled.has(contribution.featureId)) continue;
|
||||
|
||||
const installed = invokeContribution(
|
||||
contribution as unknown as FeatureAdapterContribution<
|
||||
ApplicationFeatureId,
|
||||
readonly FeaturePlatformCapabilityId[]
|
||||
>,
|
||||
context as FeaturePlatformCapabilities,
|
||||
);
|
||||
setFeatureInput(result, installed.featureId, installed.input);
|
||||
}
|
||||
|
||||
return Object.freeze(result);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
export type FeatureContractIdentity = Readonly<{ featureId: string }>;
|
||||
|
||||
type EmptyRecord = Readonly<Record<never, never>>;
|
||||
|
||||
/**
|
||||
* Zero-feature products are a supported topology. The fallback contract keeps
|
||||
* every composer's property access valid without pretending that any feature
|
||||
* route, operation, schema, mapper, or invalidation edge exists.
|
||||
*/
|
||||
export type EmptyFeatureContract = FeatureContractIdentity &
|
||||
Readonly<{
|
||||
routes: EmptyRecord;
|
||||
routeRuntimeContracts: EmptyRecord;
|
||||
apiOperations: EmptyRecord;
|
||||
invalidation: Readonly<{
|
||||
topics: readonly [];
|
||||
namespaces: readonly [];
|
||||
edges: readonly [];
|
||||
}>;
|
||||
topicVersions: readonly [];
|
||||
schemas: EmptyRecord;
|
||||
runtimeSchemas: EmptyRecord;
|
||||
mappers: EmptyRecord;
|
||||
}>;
|
||||
|
||||
export type FeatureMessageCatalogs = Readonly<
|
||||
Record<string, Readonly<Record<string, string>>>
|
||||
>;
|
||||
|
||||
type EmptyFeatureMessageCatalogs = Readonly<
|
||||
Record<string, Readonly<Record<never, never>>>
|
||||
>;
|
||||
|
||||
type EmptyFeatureRuntimeDescriptor = Readonly<{
|
||||
featureId: string;
|
||||
routeCodecs: EmptyRecord;
|
||||
routeRuntime: EmptyRecord;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* The default parameters deliberately describe the empty-product fallback.
|
||||
* Concrete generated modules retain their literal types; only an empty
|
||||
* generated tuple resolves to this default shape.
|
||||
*/
|
||||
export type FeatureModule<
|
||||
Contract extends FeatureContractIdentity = EmptyFeatureContract,
|
||||
Routes extends Readonly<Record<string, unknown>> = EmptyRecord,
|
||||
Adapter = never,
|
||||
Runtime = EmptyFeatureRuntimeDescriptor,
|
||||
Messages extends FeatureMessageCatalogs = EmptyFeatureMessageCatalogs,
|
||||
ContractContribution = never,
|
||||
> = Readonly<{
|
||||
id: string;
|
||||
contracts: Contract;
|
||||
routes: Routes;
|
||||
adapters: readonly Adapter[];
|
||||
runtimes: readonly Runtime[];
|
||||
messages: Messages;
|
||||
contractContributions: readonly ContractContribution[];
|
||||
}>;
|
||||
|
||||
/** Structural supertype used when accepting any concrete feature descriptor. */
|
||||
export type AnyFeatureModule = FeatureModule<
|
||||
FeatureContractIdentity,
|
||||
Readonly<Record<string, unknown>>,
|
||||
unknown,
|
||||
unknown,
|
||||
FeatureMessageCatalogs,
|
||||
unknown
|
||||
>;
|
||||
|
||||
export function defineFeatureModule<const Module extends AnyFeatureModule>(
|
||||
module: Module,
|
||||
): Readonly<Module> {
|
||||
if (module.id !== module.contracts.featureId) {
|
||||
throw new TypeError(
|
||||
`Feature module id ${module.id} does not match contract featureId ${module.contracts.featureId}`,
|
||||
);
|
||||
}
|
||||
return Object.freeze({
|
||||
...module,
|
||||
adapters: Object.freeze([...module.adapters]),
|
||||
runtimes: Object.freeze([...module.runtimes]),
|
||||
contractContributions: Object.freeze([...module.contractContributions]),
|
||||
}) as unknown as Readonly<Module>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
composeContractContributions,
|
||||
type InstalledContractContribution,
|
||||
type InstalledContractPackageIdentity,
|
||||
} from "../contracts/external-contract-runtime.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts";
|
||||
|
||||
export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
|
||||
Object.freeze(
|
||||
INSTALLED_PRODUCT_FEATURE_MODULES.flatMap(
|
||||
(module) => module.contractContributions,
|
||||
),
|
||||
);
|
||||
|
||||
export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions(
|
||||
INSTALLED_CONTRACT_CONTRIBUTIONS,
|
||||
);
|
||||
|
||||
export const EXPECTED_CONTRACT_SET_PACKAGES: readonly InstalledContractPackageIdentity[] =
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS.externalPackages;
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
composeFeatureAdapterInputs,
|
||||
type ContributionsCapabilityContext,
|
||||
type InstalledFeatureInputs,
|
||||
} 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),
|
||||
);
|
||||
|
||||
type InstalledFeatureCapabilityContext = ContributionsCapabilityContext<
|
||||
typeof INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS
|
||||
>;
|
||||
|
||||
/**
|
||||
* Adapter installation is a projection of feature-owned descriptors. Adding a
|
||||
* feature changes its descriptor and the generated index, not this composer.
|
||||
*/
|
||||
export function createInstalledFeatureInputs(
|
||||
context: InstalledFeatureCapabilityContext,
|
||||
): InstalledFeatureInputs {
|
||||
return composeFeatureAdapterInputs(
|
||||
INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS,
|
||||
INSTALLED_PRODUCT_FEATURE_MODULES.map((module) => module.id),
|
||||
context,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
composeApiOperations,
|
||||
validateApiRuntimeBindings,
|
||||
} from "../contracts/api-operations.ts";
|
||||
import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts";
|
||||
import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.ts";
|
||||
import { validateRestProfileBindings } from "../contracts/rest-profiles.ts";
|
||||
import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.ts";
|
||||
import {
|
||||
composeRuntimeSchemaCodecs,
|
||||
composeSchemaRegistry,
|
||||
PLATFORM_SCHEMA_REGISTRY,
|
||||
} from "../contracts/schema-registry.ts";
|
||||
import { composeUniqueRecord } from "../platform/cardinality/compose-unique-record.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts";
|
||||
|
||||
export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES;
|
||||
|
||||
type InstalledFeatureContract = (typeof INSTALLED_FEATURE_CONTRACTS)[number];
|
||||
|
||||
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(
|
||||
[
|
||||
PLATFORM_ROUTE_RUNTIME_CONTRACT,
|
||||
...INSTALLED_FEATURE_CONTRACTS.map(
|
||||
(contract) => contract.routeRuntimeContracts,
|
||||
),
|
||||
],
|
||||
() => "route runtime contract",
|
||||
) as typeof PLATFORM_ROUTE_RUNTIME_CONTRACT &
|
||||
InstalledFeatureContract["routeRuntimeContracts"];
|
||||
|
||||
export const API_OPERATIONS = composeApiOperations(
|
||||
INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.apiOperations),
|
||||
);
|
||||
export const REST_PROFILE_BINDINGS_VALID = validateRestProfileBindings(
|
||||
API_OPERATIONS,
|
||||
Object.freeze({ PRIMARY_API: Object.freeze(["omit"] as const) }),
|
||||
);
|
||||
export const INVALIDATION_REGISTRY = Object.freeze({
|
||||
topics: Object.freeze(
|
||||
INSTALLED_FEATURE_CONTRACTS.flatMap(
|
||||
(contract) => contract.invalidation.topics,
|
||||
),
|
||||
),
|
||||
namespaces: Object.freeze(
|
||||
INSTALLED_FEATURE_CONTRACTS.flatMap(
|
||||
(contract) => contract.invalidation.namespaces,
|
||||
),
|
||||
),
|
||||
edges: Object.freeze(
|
||||
INSTALLED_FEATURE_CONTRACTS.flatMap(
|
||||
(contract) => contract.invalidation.edges,
|
||||
),
|
||||
),
|
||||
});
|
||||
export const INVALIDATION_TOPIC_VERSIONS = Object.freeze(
|
||||
INSTALLED_FEATURE_CONTRACTS.flatMap((contract) => contract.topicVersions),
|
||||
);
|
||||
export const SCHEMA_REGISTRY = composeSchemaRegistry([
|
||||
PLATFORM_SCHEMA_REGISTRY,
|
||||
...INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.schemas),
|
||||
]);
|
||||
export const RUNTIME_SCHEMA_CODECS = composeRuntimeSchemaCodecs(
|
||||
INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.runtimeSchemas),
|
||||
);
|
||||
export const MAPPER_REGISTRY = composeBoundaryMapperRegistry(
|
||||
INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.mappers),
|
||||
);
|
||||
export const API_RUNTIME_BINDINGS_VALID = validateApiRuntimeBindings(
|
||||
API_OPERATIONS,
|
||||
SCHEMA_REGISTRY,
|
||||
RUNTIME_SCHEMA_CODECS,
|
||||
MAPPER_REGISTRY,
|
||||
);
|
||||
|
||||
export const ROUTE_FEATURE_OWNER: Readonly<Record<string, string>> =
|
||||
Object.freeze(
|
||||
Object.fromEntries(
|
||||
INSTALLED_FEATURE_CONTRACTS.flatMap((contract) =>
|
||||
Object.keys(contract.routes).map(
|
||||
(routeId) => [routeId, contract.featureId] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const NAVIGATION_ROUTES = Object.freeze(
|
||||
Object.values(ROUTE_REGISTRY)
|
||||
.filter(isNavigableRoute)
|
||||
.sort((left, right) => left.navigationOrder - right.navigationOrder),
|
||||
);
|
||||
|
||||
type InstalledRouteDefinition =
|
||||
(typeof ROUTE_REGISTRY)[keyof typeof ROUTE_REGISTRY];
|
||||
type NavigableRoute = InstalledRouteDefinition &
|
||||
Readonly<{ navigationOrder: number }>;
|
||||
|
||||
function isNavigableRoute(
|
||||
definition: InstalledRouteDefinition,
|
||||
): definition is NavigableRoute {
|
||||
return definition.navigationOrder !== null;
|
||||
}
|
||||
|
||||
export function getRoute(routeId: string): InstalledRouteDefinition {
|
||||
const registry: Readonly<Record<string, InstalledRouteDefinition>> =
|
||||
ROUTE_REGISTRY;
|
||||
const selected = registry[routeId];
|
||||
if (!selected) throw new Error(`Unregistered route: ${routeId}`);
|
||||
return selected;
|
||||
}
|
||||
|
||||
export function routePath(routeId: string): string {
|
||||
return getRoute(routeId).path;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts";
|
||||
|
||||
type InstalledModule = (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number];
|
||||
type UnionToIntersection<Union> = (
|
||||
Union extends unknown ? (value: Union) => void : never
|
||||
) extends (value: infer Intersection) => void
|
||||
? Intersection
|
||||
: never;
|
||||
type LocaleCatalog<Locale extends string> = UnionToIntersection<
|
||||
InstalledModule extends unknown
|
||||
? InstalledModule["messages"] extends Readonly<Record<Locale, infer Catalog>>
|
||||
? Catalog
|
||||
: Readonly<Record<string, never>>
|
||||
: never
|
||||
>;
|
||||
|
||||
function composeLocale<Locale extends string>(locale: Locale): LocaleCatalog<Locale> {
|
||||
const result: Record<string, string> = {};
|
||||
for (const module of INSTALLED_PRODUCT_FEATURE_MODULES) {
|
||||
const catalogs = module.messages as Readonly<
|
||||
Record<string, Readonly<Record<string, string>>>
|
||||
>;
|
||||
const catalog = catalogs[locale];
|
||||
if (!catalog) continue;
|
||||
for (const [key, value] of Object.entries(catalog)) {
|
||||
if (Object.hasOwn(result, key)) {
|
||||
throw new TypeError(`Duplicate ${locale} message key: ${key}`);
|
||||
}
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
return Object.freeze(result) as LocaleCatalog<Locale>;
|
||||
}
|
||||
|
||||
export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||
"ko-KR": composeLocale("ko-KR"),
|
||||
"en-US": composeLocale("en-US"),
|
||||
} as const);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { composeUniqueRecord } from "../platform/cardinality/compose-unique-record.ts";
|
||||
import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.ts";
|
||||
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),
|
||||
);
|
||||
|
||||
export const ROUTE_CODECS = composeUniqueRecord(
|
||||
[
|
||||
PLATFORM_ROUTE_CODECS,
|
||||
...INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS.map(
|
||||
(contribution) => contribution.routeCodecs,
|
||||
),
|
||||
],
|
||||
() => "route codec",
|
||||
);
|
||||
|
||||
export const ROUTE_RUNTIME = composeUniqueRecord(
|
||||
[
|
||||
PLATFORM_ROUTE_RUNTIME,
|
||||
...INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS.map(
|
||||
(contribution) => contribution.routeRuntime,
|
||||
),
|
||||
],
|
||||
() => "route runtime",
|
||||
);
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
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.
|
||||
*/
|
||||
export const COMPILED_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<Record<string, string | undefined>>;
|
||||
}
|
||||
).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[] =
|
||||
Object.freeze(
|
||||
INSTALLED_PRODUCT_FEATURE_MODULES.map((module) => module.contracts),
|
||||
);
|
||||
|
||||
export const INSTALLED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze(
|
||||
INSTALLED_PRODUCT_FEATURE_MODULES.map((feature) => feature.id),
|
||||
);
|
||||
|
||||
export const INSTALLED_PRODUCT_FEATURE_ID_SET: ReadonlySet<string> =
|
||||
new Set(INSTALLED_PRODUCT_FEATURE_IDS);
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { InstalledOfflineCommandContribution } from "../contracts/offline-command.ts";
|
||||
import type {
|
||||
InstalledRealtimeContribution,
|
||||
InstalledRuntimeCapabilities,
|
||||
} from "../contracts/runtime-capabilities.ts";
|
||||
import {
|
||||
validateRealtimeContributions,
|
||||
} from "../contracts/runtime-capabilities.ts";
|
||||
import type { InstalledServiceWorkerSelection } from "../contracts/service-worker.ts";
|
||||
import {
|
||||
validateWebWorkerContributions,
|
||||
type InstalledWebWorkerContribution,
|
||||
} from "../contracts/web-worker.ts";
|
||||
|
||||
/**
|
||||
* §3.5. Static optional capability selection SSOT.
|
||||
*
|
||||
* Adding an entry here is what installs a capability. Runtime Config can only
|
||||
* disable what this file already selected, and no dynamic import path is ever
|
||||
* built from a configuration string.
|
||||
*
|
||||
* Current template state, matching the §25 stop conditions:
|
||||
*
|
||||
* - realtime: `NOT_SELECTED`. The RT-01..RT-04 common runtime exists and is
|
||||
* independently verified, but no product contribution supplies an exact
|
||||
* endpoint, event descriptor and recovery mode (§13.6).
|
||||
* - webWorkers: `NOT_SELECTED`. No profiled CPU-bound task with an owner
|
||||
* exists, so no production worker entry is created (§16.2).
|
||||
* - serviceWorker: `null`. Switching to `ACTIVE` also enables the two-pass
|
||||
* build in `scripts/build-frontend.ts`.
|
||||
* - offlineCommands: `NOT_SELECTED`. No external package declares a `KEYED`
|
||||
* operation with a recovery descriptor (§19.3).
|
||||
*/
|
||||
|
||||
const REALTIME: readonly InstalledRealtimeContribution[] = Object.freeze([]);
|
||||
|
||||
const WEB_WORKERS: readonly InstalledWebWorkerContribution[] = Object.freeze([]);
|
||||
|
||||
const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;
|
||||
|
||||
const OFFLINE_COMMANDS: InstalledOfflineCommandContribution | null = null;
|
||||
|
||||
export const INSTALLED_RUNTIME_CAPABILITIES: InstalledRuntimeCapabilities =
|
||||
Object.freeze({
|
||||
realtime: validateRealtimeContributions(REALTIME),
|
||||
webWorkers: validateWebWorkerContributions(WEB_WORKERS),
|
||||
serviceWorker: SERVICE_WORKER,
|
||||
offlineCommands: OFFLINE_COMMANDS,
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import type {
|
||||
IndexedDbRepositoryPort,
|
||||
} from "../../../application/ports/browser-file-storage/index.ts";
|
||||
import {
|
||||
defineFeatureAdapterContribution,
|
||||
} from "../../feature-adapter-contribution.ts";
|
||||
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";
|
||||
|
||||
declare module "../../feature-adapter-contribution.ts" {
|
||||
interface FeatureIndexedDbRepositories {
|
||||
"local-draft": IndexedDbRepositoryPort<LocalDraft, never>;
|
||||
}
|
||||
}
|
||||
|
||||
export function createLocalDraftFeatureInstalledInput(context: Readonly<{
|
||||
indexedDb: Readonly<{
|
||||
get(repositoryId: "local-draft"): IndexedDbRepositoryPort<LocalDraft, never>;
|
||||
}>;
|
||||
}>) {
|
||||
const repository = context.indexedDb.get(LOCAL_DRAFT_REPOSITORY_ID);
|
||||
return Object.freeze({
|
||||
featureId: LOCAL_DRAFT_FEATURE_ID,
|
||||
input: createLocalDraftFeatureInput(createLocalDraftStore(repository)),
|
||||
});
|
||||
}
|
||||
|
||||
export const LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION =
|
||||
defineFeatureAdapterContribution({
|
||||
featureId: LOCAL_DRAFT_FEATURE_ID,
|
||||
needs: ["indexedDb"] as const,
|
||||
createInput: createLocalDraftFeatureInstalledInput,
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import type {
|
||||
BrowserDataFailure,
|
||||
IndexedDbRepositoryPort,
|
||||
} from "../../../application/ports/browser-file-storage/index.ts";
|
||||
import {
|
||||
createFailure,
|
||||
type AppFailure,
|
||||
type FailureKind,
|
||||
} from "../../../contracts/errors.ts";
|
||||
import type { Result } from "../../../contracts/result.ts";
|
||||
import type {
|
||||
LocalDraftStore,
|
||||
LocalDraftRecord,
|
||||
RemoveLocalDraftCommand,
|
||||
SaveLocalDraftCommand,
|
||||
} from "../application/local-draft-api.ts";
|
||||
import type { LocalDraft } from "../domain/local-draft.ts";
|
||||
|
||||
function failureKind(failure: BrowserDataFailure): FailureKind {
|
||||
if (failure.code === "QUOTA_EXCEEDED") return "STORAGE_QUOTA_EXCEEDED";
|
||||
if (failure.code === "CONFLICT") return "CONFLICT";
|
||||
if (failure.code === "ABORTED") return "REQUEST_ABORTED";
|
||||
return "STORAGE_UNAVAILABLE";
|
||||
}
|
||||
|
||||
function mapFailure(
|
||||
failure: BrowserDataFailure,
|
||||
operationId: string,
|
||||
): AppFailure {
|
||||
return createFailure(failureKind(failure), operationId, 0, {
|
||||
code: `INDEXEDDB_${failure.code}`,
|
||||
});
|
||||
}
|
||||
|
||||
function failed<Value>(
|
||||
failure: BrowserDataFailure,
|
||||
operationId: string,
|
||||
): Result<Value> {
|
||||
return Object.freeze({
|
||||
ok: false as const,
|
||||
error: mapFailure(failure, operationId),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature-owned adapter over the reusable IndexedDB repository capability.
|
||||
* Native IDB objects, migrations, connection leases and quota internals do not
|
||||
* cross this file.
|
||||
*/
|
||||
export function createLocalDraftStore(
|
||||
repository: IndexedDbRepositoryPort<LocalDraft, never>,
|
||||
): LocalDraftStore {
|
||||
return Object.freeze({
|
||||
async save(command: SaveLocalDraftCommand, signal?: AbortSignal) {
|
||||
const result = await repository.compareAndSwap({
|
||||
key: command.draft.draftId,
|
||||
value: command.draft,
|
||||
expectedRevision: command.expectedRevision,
|
||||
idempotencyKey: command.idempotencyKey,
|
||||
signal,
|
||||
});
|
||||
return result.ok
|
||||
? Object.freeze({
|
||||
ok: true as const,
|
||||
value: Object.freeze({ revision: result.value.revision }),
|
||||
})
|
||||
: failed<Readonly<{ revision: number }>>(
|
||||
result.error,
|
||||
"LOCAL_DRAFT_SAVE",
|
||||
);
|
||||
},
|
||||
|
||||
async find(draftId: string, signal?: AbortSignal) {
|
||||
const result = await repository.read(draftId, signal);
|
||||
if (!result.ok) {
|
||||
return failed<LocalDraftRecord | null>(
|
||||
result.error,
|
||||
"LOCAL_DRAFT_FIND",
|
||||
);
|
||||
}
|
||||
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: RemoveLocalDraftCommand, signal?: AbortSignal) {
|
||||
const result = await repository.remove({
|
||||
key: command.draftId,
|
||||
expectedRevision: command.expectedRevision,
|
||||
idempotencyKey: command.idempotencyKey,
|
||||
signal,
|
||||
});
|
||||
return result.ok
|
||||
? Object.freeze({ ok: true as const, value: undefined })
|
||||
: failed<void>(result.error, "LOCAL_DRAFT_REMOVE");
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Result } from "../../../contracts/result.ts";
|
||||
import type {} from "../../../application/ports/in/application-api.ts";
|
||||
import type { LocalDraft } from "../domain/local-draft.ts";
|
||||
|
||||
export type LocalDraftRecord = Readonly<{
|
||||
draft: LocalDraft;
|
||||
revision: number;
|
||||
}>;
|
||||
|
||||
export type SaveLocalDraftCommand = Readonly<{
|
||||
draft: LocalDraft;
|
||||
expectedRevision: number | null;
|
||||
idempotencyKey: string;
|
||||
}>;
|
||||
|
||||
export type RemoveLocalDraftCommand = Readonly<{
|
||||
draftId: string;
|
||||
expectedRevision: number;
|
||||
idempotencyKey: string;
|
||||
}>;
|
||||
|
||||
export type LocalDraftStore = Readonly<{
|
||||
save(
|
||||
command: SaveLocalDraftCommand,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<Readonly<{ revision: number }>>>;
|
||||
find(
|
||||
draftId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<LocalDraftRecord | null>>;
|
||||
remove(
|
||||
command: RemoveLocalDraftCommand,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<void>>;
|
||||
}>;
|
||||
|
||||
export type LocalDraftFeatureInput = Readonly<{
|
||||
saveDraft(
|
||||
command: SaveLocalDraftCommand,
|
||||
context?: Readonly<{ signal?: AbortSignal }>,
|
||||
): Promise<Result<Readonly<{ revision: number }>>>;
|
||||
findDraft(
|
||||
draftId: string,
|
||||
context?: Readonly<{ signal?: AbortSignal }>,
|
||||
): Promise<Result<LocalDraftRecord | null>>;
|
||||
removeDraft(
|
||||
command: RemoveLocalDraftCommand,
|
||||
context?: Readonly<{ signal?: AbortSignal }>,
|
||||
): Promise<Result<void>>;
|
||||
}>;
|
||||
|
||||
declare module "../../../application/ports/in/application-api.ts" {
|
||||
interface ApplicationFeatureInputs {
|
||||
"local-draft": LocalDraftFeatureInput;
|
||||
}
|
||||
}
|
||||
|
||||
export function createLocalDraftFeatureInput(
|
||||
store: LocalDraftStore,
|
||||
): LocalDraftFeatureInput {
|
||||
return Object.freeze({
|
||||
saveDraft(command, context) {
|
||||
return store.save(command, context?.signal);
|
||||
},
|
||||
findDraft(draftId, context) {
|
||||
return store.find(draftId, context?.signal);
|
||||
},
|
||||
removeDraft(command, context) {
|
||||
return store.remove(command, context?.signal);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export const LOCAL_DRAFT_FEATURE_ID = "local-draft" as const;
|
||||
export const LOCAL_DRAFT_REPOSITORY_ID = "local-draft" as const;
|
||||
@@ -0,0 +1,21 @@
|
||||
export type LocalDraft = Readonly<{
|
||||
draftId: string;
|
||||
title: string;
|
||||
body: string;
|
||||
}>;
|
||||
|
||||
export function createLocalDraft(values: LocalDraft): LocalDraft {
|
||||
const draftId = values.draftId.trim();
|
||||
const title = values.title.trim();
|
||||
if (!draftId || !title) {
|
||||
throw new TypeError("Local draft requires draftId and title");
|
||||
}
|
||||
if (title.length > 160 || values.body.length > 100_000) {
|
||||
throw new TypeError("Local draft exceeds bounded field limits");
|
||||
}
|
||||
return Object.freeze({
|
||||
draftId,
|
||||
title,
|
||||
body: values.body,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
# Reference feature ownership and removal
|
||||
|
||||
이 모듈은 제품 도메인이 아니라 새 기능의 수직 경계를 검증하는 제거 가능한
|
||||
reference implementation이다.
|
||||
|
||||
## 소유 경계
|
||||
|
||||
- `domain`: 외부 DTO와 React를 모르는 불변 model
|
||||
- `application`: UI가 호출하는 list/get/create input과 gateway 계약
|
||||
- `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter
|
||||
- `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper
|
||||
- `presentation`: route input을 query/form controller로 연결하는 inbound
|
||||
adapter, 독립 form schema/command mapper와 list/detail/form/status page
|
||||
|
||||
generic application은 비어 있는 `ApplicationFeatureInputs`와 typed
|
||||
`features.has/get` registry만 소유한다. 이 feature의 application API가 module
|
||||
augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므로
|
||||
등록되지 않은 ID와 잘못된 input shape는 typecheck에서 거절된다. feature hook은
|
||||
별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로
|
||||
설치되지 않은 ID가 들어오는 경우를 위해 `get`의 runtime guard도 유지한다.
|
||||
|
||||
예측 가능한 실패는 canonical shared contract인
|
||||
`src/contracts/result.ts`의 `Result<Value, Failure = AppFailure>`로 반환한다.
|
||||
`src/application/result.ts`는 기존 호출자를 위한 deprecated migration shim일
|
||||
뿐 새 코드의 import 경로가 아니다. `AppFailure.kind`는
|
||||
`ERROR_REGISTRY` key에서 파생된 닫힌 vocabulary이며, transport 호환 이름인
|
||||
`ApiFailure`는 같은 type의 alias다.
|
||||
|
||||
HTTP adapter는 `src/adapters/http/feature-http-binding.ts`의 capability-specific
|
||||
typed binding을 사용한다. feature는 operation ID, route ID, request type, 성공
|
||||
value type, mapper만 소유한다. timeout/cancellation/auth/transport/contract
|
||||
violation을 `AppFailure`로 정규화하는 책임은 reusable HTTP capability가 소유한다.
|
||||
따라서 gateway 메서드는 transport outcome이나 runtime result guard를 반복 구현하지
|
||||
않고도 정확한 결과 타입을 반환한다.
|
||||
|
||||
route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route type은
|
||||
`route-contract.ts`, React context/provider/hook은 `route-input.tsx`가 각각
|
||||
소유한다. reference page는 `app-router.tsx`를 역참조하지 않고 좁은
|
||||
`useRouteInput` 경계만 사용하므로 lazy route와 router 사이의 순환 의존을 만들지
|
||||
않는다. page는 HTTP client, storage, auth owner, output port나 TanStack API를
|
||||
직접 import하지 않는다.
|
||||
|
||||
## 설치 지점
|
||||
|
||||
feature가 실제 contribution을 소유한다.
|
||||
|
||||
- contract: `reference-feature-contract.ts`
|
||||
- component/codec: `REFERENCE_FEATURE_RUNTIME_CONTRIBUTION`
|
||||
- bootstrap input: `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`
|
||||
|
||||
중앙 파일인 `installed-feature-contracts.ts`,
|
||||
`installed-feature-runtimes.tsx`, `installed-feature-adapters.ts`는 선택된
|
||||
contribution을 합치는 역할만 한다. 새 기능의 내부 조립 규칙을 중앙 catalog에
|
||||
추가하지 않는다.
|
||||
|
||||
## 검증과 제거
|
||||
|
||||
```sh
|
||||
corepack pnpm test:reference-feature
|
||||
corepack pnpm test:sample-removal
|
||||
```
|
||||
|
||||
첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든
|
||||
query/mutation/form 상태와 production composition을 검증한다. 두 번째 명령은 임시
|
||||
복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로
|
||||
재생성한다. feature 소유 coverage include, risk-policy 행과 test-evidence
|
||||
contribution도 제거한 뒤 typecheck, architecture, registry, unit/integration,
|
||||
coverage, source evidence, home smoke, production build와 source/built fixture ID
|
||||
잔여 0개를 검사한다. generic feature registry의 성공 경로는 reference와 무관한
|
||||
unit test가 소유하므로 feature 삭제 후에도 공통 boundary coverage가 유지된다.
|
||||
|
||||
CI의 negative type fixture는 잘못된 feature ID/input shape, registry에 없는
|
||||
failure kind, operation과 route ID의 불일치가 실제로 컴파일 실패하는지도
|
||||
검증한다. Architecture fixture는 허용 edge뿐 아니라 unresolved import, 금지 계층
|
||||
edge와 TypeScript 순환 의존을 각각 거절해야 통과한다.
|
||||
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
createFeatureHttpBinding,
|
||||
type InstalledHttpOperationExecutor,
|
||||
} from "../../../adapters/http/index.ts";
|
||||
import {
|
||||
defineFeatureAdapterContribution,
|
||||
} from "../../feature-adapter-contribution.ts";
|
||||
import { createReferenceFeatureInput } from "../application/reference-feature-api.ts";
|
||||
import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts";
|
||||
import {
|
||||
REFERENCE_FEATURE_ID,
|
||||
} from "../contracts/reference-feature-contract.ts";
|
||||
import {
|
||||
createReferenceHttpGateway,
|
||||
REFERENCE_HTTP_OPERATIONS,
|
||||
} from "./reference-http-gateway.ts";
|
||||
|
||||
export type InstalledContractOperationExecutor =
|
||||
InstalledHttpOperationExecutor;
|
||||
|
||||
/**
|
||||
* Feature-owned composition seam.
|
||||
*
|
||||
* The feature receives only the HTTP capability it declares in `needs`.
|
||||
* HTTP lifecycle/error normalization stays in the reusable capability binding.
|
||||
*/
|
||||
export function createReferenceFeatureInstalledInput(context: Readonly<{
|
||||
http: InstalledHttpOperationExecutor;
|
||||
telemetry?: TelemetryPort;
|
||||
}>) {
|
||||
const http = createFeatureHttpBinding(
|
||||
context.http,
|
||||
REFERENCE_HTTP_OPERATIONS,
|
||||
);
|
||||
|
||||
return Object.freeze({
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
input: createReferenceFeatureInput(
|
||||
createReferenceHttpGateway(http),
|
||||
context.telemetry === undefined ? {} : { telemetry: context.telemetry },
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export const REFERENCE_FEATURE_ADAPTER_CONTRIBUTION =
|
||||
defineFeatureAdapterContribution({
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
needs: ["http", "telemetry"] as const,
|
||||
createInput: createReferenceFeatureInstalledInput,
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
defineFeatureHttpOperationForRoutes,
|
||||
type FeatureHttpBinding,
|
||||
} from "../../../adapters/http/index.ts";
|
||||
import {
|
||||
CREATE_REFERENCE_RESOURCE_CONTRACT,
|
||||
GET_REFERENCE_RESOURCE_CONTRACT,
|
||||
LIST_REFERENCE_RESOURCES_CONTRACT,
|
||||
} from "../contracts/reference-feature-contract-contribution.ts";
|
||||
import {
|
||||
REFERENCE_FEATURE_CONTRACT,
|
||||
} from "../contracts/reference-feature-contract.ts";
|
||||
import {
|
||||
mapReferenceResourceListPayload,
|
||||
mapReferenceResourcePayload,
|
||||
} from "../contracts/reference-mapper.ts";
|
||||
import type {
|
||||
ReferenceGateway,
|
||||
} from "../application/reference-feature-api.ts";
|
||||
|
||||
export type ReferenceFeatureRouteId =
|
||||
keyof typeof REFERENCE_FEATURE_CONTRACT.routes;
|
||||
|
||||
const defineReferenceHttpOperation =
|
||||
defineFeatureHttpOperationForRoutes<ReferenceFeatureRouteId>();
|
||||
|
||||
export const REFERENCE_HTTP_OPERATIONS = Object.freeze({
|
||||
LIST_REFERENCE_RESOURCES: defineReferenceHttpOperation({
|
||||
contract: LIST_REFERENCE_RESOURCES_CONTRACT,
|
||||
routeId: "REFERENCE_RESOURCE_LIST",
|
||||
mapSuccess: mapReferenceResourceListPayload,
|
||||
}),
|
||||
CREATE_REFERENCE_RESOURCE: defineReferenceHttpOperation({
|
||||
contract: CREATE_REFERENCE_RESOURCE_CONTRACT,
|
||||
routeId: "REFERENCE_RESOURCE_LIST",
|
||||
mapSuccess: mapReferenceResourcePayload,
|
||||
mapProblem(problem, metadata) {
|
||||
if (metadata.status === 409) {
|
||||
return Object.freeze({
|
||||
kind: "CONFLICT" as const,
|
||||
code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT",
|
||||
});
|
||||
}
|
||||
if (metadata.status === 422) {
|
||||
return Object.freeze({
|
||||
kind: "VALIDATION_REJECTED" as const,
|
||||
code: problem.code ?? "REFERENCE_RESOURCE_REJECTED",
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
}),
|
||||
GET_REFERENCE_RESOURCE: defineReferenceHttpOperation({
|
||||
contract: GET_REFERENCE_RESOURCE_CONTRACT,
|
||||
routeId: "REFERENCE_RESOURCE_DETAIL",
|
||||
mapSuccess: mapReferenceResourcePayload,
|
||||
}),
|
||||
} as const);
|
||||
|
||||
export type ReferenceHttpBinding = FeatureHttpBinding<
|
||||
typeof REFERENCE_HTTP_OPERATIONS
|
||||
>;
|
||||
|
||||
export function createReferenceHttpGateway(
|
||||
http: ReferenceHttpBinding,
|
||||
): ReferenceGateway {
|
||||
return Object.freeze({
|
||||
list(filters, context) {
|
||||
return http.execute("LIST_REFERENCE_RESOURCES", filters, context);
|
||||
},
|
||||
create(command, context) {
|
||||
return http.execute("CREATE_REFERENCE_RESOURCE", command, context);
|
||||
},
|
||||
get(resourceId, context) {
|
||||
return http.execute(
|
||||
"GET_REFERENCE_RESOURCE",
|
||||
Object.freeze({ resourceId }),
|
||||
context,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
defineAppError,
|
||||
type AppError,
|
||||
} from "../../../platform/errors/app-error.ts";
|
||||
import type { ApiFailure } from "../../../contracts/errors.ts";
|
||||
|
||||
/**
|
||||
* Spec §17–§19. The reference feature's own domain errors.
|
||||
*
|
||||
* This union is local to the feature. It satisfies the platform `AppError`
|
||||
* envelope structurally; nothing central enumerates it, so adding or removing
|
||||
* this feature never edits a shared error type.
|
||||
*/
|
||||
export type ReferenceError =
|
||||
| (AppError & {
|
||||
readonly kind: "reference.not-found";
|
||||
readonly category: "domain";
|
||||
readonly severity: "warning";
|
||||
readonly retryability: "never";
|
||||
})
|
||||
| (AppError & {
|
||||
readonly kind: "reference.conflict";
|
||||
readonly category: "domain";
|
||||
readonly severity: "warning";
|
||||
readonly retryability: "never";
|
||||
})
|
||||
| (AppError & {
|
||||
readonly kind: "reference.rejected";
|
||||
readonly category: "validation";
|
||||
readonly severity: "warning";
|
||||
readonly retryability: "never";
|
||||
});
|
||||
|
||||
export const REFERENCE_ERRORS = Object.freeze({
|
||||
NOT_FOUND: defineAppError({
|
||||
kind: "reference.not-found",
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
}),
|
||||
CONFLICT: defineAppError({
|
||||
kind: "reference.conflict",
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
}),
|
||||
REJECTED: defineAppError({
|
||||
kind: "reference.rejected",
|
||||
category: "validation",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
}),
|
||||
} satisfies Record<string, ReferenceError>);
|
||||
|
||||
/**
|
||||
* Interprets a transport-normalized failure in this feature's own vocabulary.
|
||||
* Anything that is not a reference domain outcome stays `null`: the platform
|
||||
* error mapping, not this feature, owns transport/contract failures.
|
||||
*/
|
||||
export function toReferenceError(failure: ApiFailure): ReferenceError | null {
|
||||
switch (failure.kind) {
|
||||
case "NOT_FOUND":
|
||||
return REFERENCE_ERRORS.NOT_FOUND;
|
||||
case "CONFLICT":
|
||||
return REFERENCE_ERRORS.CONFLICT;
|
||||
case "VALIDATION_REJECTED":
|
||||
return REFERENCE_ERRORS.REJECTED;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { Result } from "../../../contracts/result.ts";
|
||||
import type {} from "../../../application/ports/in/application-api.ts";
|
||||
import {
|
||||
toReferenceView,
|
||||
type ReferenceResourceView,
|
||||
} from "../contracts/reference-mapper.ts";
|
||||
import type { ReferenceResource } from "../domain/reference-resource.ts";
|
||||
import type { MutationIntent } from "../../../contracts/mutation-intent.ts";
|
||||
import type { ExecutionContext } from "../../../platform/execution/execution-context.ts";
|
||||
import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts";
|
||||
import type { ApiFailure } from "../../../contracts/errors.ts";
|
||||
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
|
||||
|
||||
/**
|
||||
* Spec §10. Every call may join a caller-owned interaction so several
|
||||
* operations share one request/retry/concurrency budget and one deadline.
|
||||
*/
|
||||
export type ReferenceCallContext = Readonly<{
|
||||
signal?: AbortSignal;
|
||||
execution?: ExecutionContext;
|
||||
}>;
|
||||
|
||||
export type ReferenceListFilters = Readonly<{
|
||||
cursor?: string;
|
||||
limit: number;
|
||||
tags?: readonly string[];
|
||||
}>;
|
||||
|
||||
export type ReferenceResult<Value> = Result<Value>;
|
||||
|
||||
export type ReferenceCreateCommand = Readonly<{
|
||||
name: string;
|
||||
note?: string;
|
||||
}>;
|
||||
|
||||
export type ReferenceFeatureInput = Readonly<{
|
||||
listResources(
|
||||
filters: ReferenceListFilters,
|
||||
context?: ReferenceCallContext,
|
||||
): Promise<ReferenceResult<readonly ReferenceResourceView[]>>;
|
||||
createResource(
|
||||
command: ReferenceCreateCommand,
|
||||
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
|
||||
): Promise<ReferenceResult<ReferenceResourceView>>;
|
||||
getResource(
|
||||
resourceId: string,
|
||||
context?: ReferenceCallContext,
|
||||
): Promise<ReferenceResult<ReferenceResourceView>>;
|
||||
}>;
|
||||
|
||||
declare module "../../../application/ports/in/application-api.ts" {
|
||||
interface ApplicationFeatureInputs {
|
||||
"reference-feature": ReferenceFeatureInput;
|
||||
}
|
||||
}
|
||||
|
||||
export type ReferenceGateway = Readonly<{
|
||||
list(
|
||||
filters: ReferenceListFilters,
|
||||
context?: ReferenceCallContext,
|
||||
): Promise<ReferenceResult<readonly ReferenceResource[]>>;
|
||||
create(
|
||||
command: ReferenceCreateCommand,
|
||||
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
|
||||
): Promise<ReferenceResult<ReferenceResource>>;
|
||||
get(
|
||||
resourceId: string,
|
||||
context?: ReferenceCallContext,
|
||||
): Promise<ReferenceResult<ReferenceResource>>;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Spec §24. Feature-owned telemetry payload. The platform envelope carries it;
|
||||
* no central union lists it. Only the bounded failure kind leaves the feature.
|
||||
*/
|
||||
export type ReferenceLoadFailedPayload = Readonly<{
|
||||
operation: "list" | "detail";
|
||||
reason: ApiFailure["kind"];
|
||||
}>;
|
||||
|
||||
function reportLoadFailure(
|
||||
telemetry: TelemetryPort | undefined,
|
||||
operation: ReferenceLoadFailedPayload["operation"],
|
||||
failure: ApiFailure,
|
||||
context: ReferenceCallContext | undefined,
|
||||
): void {
|
||||
if (!telemetry || failure.kind === "REQUEST_ABORTED") return;
|
||||
const payload: ReferenceLoadFailedPayload = { operation, reason: failure.kind };
|
||||
try {
|
||||
// Fire-and-forget: telemetry never changes the business result.
|
||||
void Promise.resolve(
|
||||
telemetry.emit({
|
||||
kind: "reference.load.failed",
|
||||
severity: "warning",
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
...(context?.execution === undefined
|
||||
? {}
|
||||
: { interactionId: context.execution.interaction.id }),
|
||||
payload,
|
||||
}),
|
||||
).catch(() => undefined);
|
||||
} catch {
|
||||
// A throwing port is contained at the call site (spec §26).
|
||||
}
|
||||
}
|
||||
|
||||
export function createReferenceFeatureInput(
|
||||
gateway: ReferenceGateway,
|
||||
observability: Readonly<{ telemetry?: TelemetryPort }> = {},
|
||||
): ReferenceFeatureInput {
|
||||
const { telemetry } = observability;
|
||||
return Object.freeze({
|
||||
async listResources(filters, context) {
|
||||
const result = await gateway.list(filters, context);
|
||||
if (!result.ok) reportLoadFailure(telemetry, "list", result.error, context);
|
||||
return result.ok
|
||||
? {
|
||||
ok: true as const,
|
||||
value: result.value.map((resource) => toReferenceView(resource)),
|
||||
}
|
||||
: result;
|
||||
},
|
||||
async createResource(command, context) {
|
||||
const result = await gateway.create(command, context);
|
||||
return result.ok
|
||||
? { ok: true as const, value: toReferenceView(result.value) }
|
||||
: result;
|
||||
},
|
||||
async getResource(resourceId, context) {
|
||||
const result = await gateway.get(resourceId, context);
|
||||
if (!result.ok) reportLoadFailure(telemetry, "detail", result.error, context);
|
||||
return result.ok
|
||||
? { ok: true as const, value: toReferenceView(result.value) }
|
||||
: result;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { RouteObject } from "react-router-dom";
|
||||
|
||||
import { REFERENCE_FEATURE_CONTRACT } from "./contracts/reference-feature-contract.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_RUNTIME } from "./presentation/reference-feature-runtime.ts";
|
||||
|
||||
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze(
|
||||
Object.values(REFERENCE_FEATURE_CONTRACT.routes).map((definition) => {
|
||||
const runtime = REFERENCE_FEATURE_ROUTE_RUNTIME[
|
||||
definition.routeId as keyof typeof REFERENCE_FEATURE_ROUTE_RUNTIME
|
||||
];
|
||||
return Object.freeze({
|
||||
id: definition.routeId,
|
||||
path: definition.path,
|
||||
handle: Object.freeze({
|
||||
routeId: definition.routeId,
|
||||
runtime,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,259 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
CommandEffectDescriptor,
|
||||
InstalledContractContribution,
|
||||
InstalledHttpContract,
|
||||
RuntimeValidator,
|
||||
} from "../../../contracts/external-contract-runtime.ts";
|
||||
import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts";
|
||||
import {
|
||||
createReferenceResourceCommandSchema,
|
||||
referenceProblemSchema,
|
||||
referenceResourceDtoSchema,
|
||||
referenceResourceListQuerySchema,
|
||||
referenceResourceParamsSchema,
|
||||
type ReferenceProblem,
|
||||
} from "./reference-schemas.ts";
|
||||
|
||||
export type { ReferenceProblem } from "./reference-schemas.ts";
|
||||
|
||||
/**
|
||||
* §4.8. The single `TEMPLATE_FIXTURE` contribution. It keeps the reference
|
||||
* HTTP vertical executable as deterministic template data and is excluded from
|
||||
* `contractSet`. A product feature MUST instead pin an external package and
|
||||
* import it from its own `contracts/<service>-contract-contribution.ts`.
|
||||
*/
|
||||
|
||||
function zodValidator<T>(
|
||||
schemaId: string,
|
||||
schema: z.ZodType<T>,
|
||||
): RuntimeValidator<T> {
|
||||
return Object.freeze({
|
||||
schemaId,
|
||||
safeParse(value: unknown) {
|
||||
const result = schema.safeParse(value);
|
||||
if (result.success) {
|
||||
return Object.freeze({
|
||||
success: true as const,
|
||||
data: structuredClone(result.data),
|
||||
});
|
||||
}
|
||||
return Object.freeze({
|
||||
success: false as const,
|
||||
issues: Object.freeze(
|
||||
result.error.issues.map((issue) =>
|
||||
Object.freeze({
|
||||
path: Object.freeze(
|
||||
issue.path.map((segment): string | number =>
|
||||
typeof segment === "number" ? segment : String(segment),
|
||||
),
|
||||
),
|
||||
code: String(issue.code),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const PROBLEM_VALIDATOR = zodValidator(
|
||||
"ReferenceProblem",
|
||||
referenceProblemSchema,
|
||||
);
|
||||
|
||||
/**
|
||||
* Fixture-side classifier standing in for the package-provided pure bounded
|
||||
* classifier. A status the fixture does not describe stays `MAYBE_APPLIED`.
|
||||
*/
|
||||
const CREATE_EFFECT: CommandEffectDescriptor<ReferenceProblem> = Object.freeze({
|
||||
successEffect: "APPLIED_CONFIRMED" as const,
|
||||
classifyProblem({
|
||||
status,
|
||||
}: Readonly<{ status: number; problem: ReferenceProblem }>) {
|
||||
if (status === 400 || status === 409 || status === 422) {
|
||||
return "NOT_APPLIED";
|
||||
}
|
||||
return "MAYBE_APPLIED";
|
||||
},
|
||||
});
|
||||
|
||||
export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId: "LIST_REFERENCE_RESOURCES",
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/api/reference-resources",
|
||||
inputValidator: zodValidator(
|
||||
"ReferenceResourceListQuery",
|
||||
referenceResourceListQuerySchema,
|
||||
),
|
||||
outputValidator: zodValidator(
|
||||
"ReferenceResourceListPayload",
|
||||
z.array(referenceResourceDtoSchema).max(100),
|
||||
),
|
||||
problemValidator: PROBLEM_VALIDATOR,
|
||||
acceptedStatuses: Object.freeze([200]),
|
||||
emptyBodyStatuses: Object.freeze([]),
|
||||
retrySemantics: "SAFE" as const,
|
||||
requestBody: "NONE" as const,
|
||||
responseBody: "REQUIRED_JSON" as const,
|
||||
commandRecovery: null,
|
||||
commandEffect: null,
|
||||
projectRequest(input: z.output<typeof referenceResourceListQuerySchema>) {
|
||||
const entries: (readonly [string, string])[] = [];
|
||||
if (input.cursor !== undefined) entries.push(["cursor", input.cursor]);
|
||||
entries.push(["limit", String(input.limit)]);
|
||||
for (const tag of input.tags ?? []) entries.push(["tags", tag]);
|
||||
return Object.freeze({
|
||||
pathValues: Object.freeze({}),
|
||||
queryEntries: Object.freeze(entries),
|
||||
body: null,
|
||||
});
|
||||
},
|
||||
}),
|
||||
frontend: Object.freeze({
|
||||
policyId: "REFERENCE_LIST_V1",
|
||||
requestByteLimit: 0,
|
||||
responseByteLimit: 262_144,
|
||||
totalDeadlineMs: 10_000,
|
||||
retryBudget: 2 as const,
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
diagnosticsOperation: "reference.list",
|
||||
traffic: Object.freeze({
|
||||
maxPhysicalRequests: 3,
|
||||
maxRetries: 2,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
}),
|
||||
}),
|
||||
}) satisfies InstalledHttpContract<
|
||||
z.output<typeof referenceResourceListQuerySchema>,
|
||||
readonly z.output<typeof referenceResourceDtoSchema>[],
|
||||
ReferenceProblem
|
||||
>;
|
||||
|
||||
export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId: "GET_REFERENCE_RESOURCE",
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/api/reference-resources/{resourceId}",
|
||||
inputValidator: zodValidator(
|
||||
"ReferenceResourceParams",
|
||||
referenceResourceParamsSchema,
|
||||
),
|
||||
outputValidator: zodValidator(
|
||||
"ReferenceResourcePayload",
|
||||
referenceResourceDtoSchema,
|
||||
),
|
||||
problemValidator: PROBLEM_VALIDATOR,
|
||||
acceptedStatuses: Object.freeze([200]),
|
||||
emptyBodyStatuses: Object.freeze([]),
|
||||
retrySemantics: "SAFE" as const,
|
||||
requestBody: "NONE" as const,
|
||||
responseBody: "REQUIRED_JSON" as const,
|
||||
commandRecovery: null,
|
||||
commandEffect: null,
|
||||
projectRequest(input: z.output<typeof referenceResourceParamsSchema>) {
|
||||
return Object.freeze({
|
||||
pathValues: Object.freeze({ resourceId: input.resourceId }),
|
||||
queryEntries: Object.freeze([]),
|
||||
body: null,
|
||||
});
|
||||
},
|
||||
}),
|
||||
frontend: Object.freeze({
|
||||
policyId: "REFERENCE_DETAIL_V1",
|
||||
requestByteLimit: 0,
|
||||
responseByteLimit: 32_768,
|
||||
totalDeadlineMs: 10_000,
|
||||
retryBudget: 2 as const,
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
diagnosticsOperation: "reference.detail",
|
||||
traffic: Object.freeze({
|
||||
maxPhysicalRequests: 3,
|
||||
maxRetries: 2,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
}),
|
||||
}),
|
||||
}) satisfies InstalledHttpContract<
|
||||
z.output<typeof referenceResourceParamsSchema>,
|
||||
z.output<typeof referenceResourceDtoSchema>,
|
||||
ReferenceProblem
|
||||
>;
|
||||
|
||||
export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId: "CREATE_REFERENCE_RESOURCE",
|
||||
method: "POST" as const,
|
||||
pathTemplate: "/api/reference-resources",
|
||||
inputValidator: zodValidator(
|
||||
"CreateReferenceResourceCommand",
|
||||
createReferenceResourceCommandSchema,
|
||||
),
|
||||
outputValidator: zodValidator(
|
||||
"ReferenceResourcePayload",
|
||||
referenceResourceDtoSchema,
|
||||
),
|
||||
problemValidator: PROBLEM_VALIDATOR,
|
||||
acceptedStatuses: Object.freeze([200, 201]),
|
||||
emptyBodyStatuses: Object.freeze([]),
|
||||
retrySemantics: "KEYED" as const,
|
||||
requestBody: "JSON" as const,
|
||||
responseBody: "REQUIRED_JSON" as const,
|
||||
commandRecovery: Object.freeze({
|
||||
mode: "IDEMPOTENCY_REPLAY" as const,
|
||||
operationIdentityField: "idempotencyKey",
|
||||
}),
|
||||
commandEffect: CREATE_EFFECT,
|
||||
projectRequest(input: z.output<typeof createReferenceResourceCommandSchema>) {
|
||||
return Object.freeze({
|
||||
pathValues: Object.freeze({}),
|
||||
queryEntries: Object.freeze([]),
|
||||
body: Object.freeze({ ...input }),
|
||||
});
|
||||
},
|
||||
}),
|
||||
frontend: Object.freeze({
|
||||
policyId: "REFERENCE_CREATE_V1",
|
||||
requestByteLimit: 32_768,
|
||||
responseByteLimit: 32_768,
|
||||
totalDeadlineMs: 10_000,
|
||||
/**
|
||||
* §8.3. A KEYED command has no automatic retry after a dispatched attempt
|
||||
* lost its response; the fixture therefore declares a zero budget rather
|
||||
* than relying on a runtime special case.
|
||||
*/
|
||||
retryBudget: 0 as const,
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
diagnosticsOperation: "reference.create",
|
||||
traffic: Object.freeze({
|
||||
maxPhysicalRequests: 1,
|
||||
maxRetries: 0,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
}),
|
||||
}),
|
||||
}) satisfies InstalledHttpContract<
|
||||
z.output<typeof createReferenceResourceCommandSchema>,
|
||||
z.output<typeof referenceResourceDtoSchema>,
|
||||
ReferenceProblem
|
||||
>;
|
||||
|
||||
export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribution =
|
||||
Object.freeze({
|
||||
contributionId: "reference-feature-http-v1",
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
source: Object.freeze({
|
||||
kind: "TEMPLATE_FIXTURE" as const,
|
||||
fixtureId: "REFERENCE_FEATURE_V1" as const,
|
||||
revision: 1 as const,
|
||||
}),
|
||||
http: Object.freeze([
|
||||
LIST_REFERENCE_RESOURCES_CONTRACT,
|
||||
GET_REFERENCE_RESOURCE_CONTRACT,
|
||||
CREATE_REFERENCE_RESOURCE_CONTRACT,
|
||||
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
|
||||
events: Object.freeze([]),
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
|
||||
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
|
||||
import { defineRestOperation } from "../../../contracts/api-operations.ts";
|
||||
import { REFERENCE_RUNTIME_SCHEMA_CODECS } from "./reference-schemas.ts";
|
||||
import { REFERENCE_BOUNDARY_MAPPERS } from "./reference-mapper.ts";
|
||||
|
||||
export const REFERENCE_FEATURE_ID = "reference-feature";
|
||||
export const REFERENCE_RESOURCE_QUERY_NAMESPACE = defineQueryNamespaceIdentity(
|
||||
"reference-resource",
|
||||
1,
|
||||
);
|
||||
export const REFERENCE_RESOURCE_INVALIDATION_TOPIC =
|
||||
defineQueryInvalidationTopic("qinv.01k10f7m3w9p6r2c8v5n4x");
|
||||
|
||||
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
runtimeSchemas: REFERENCE_RUNTIME_SCHEMA_CODECS,
|
||||
mappers: REFERENCE_BOUNDARY_MAPPERS,
|
||||
schemas: Object.freeze({
|
||||
ReferenceResourceParams: Object.freeze({
|
||||
schemaId: "ReferenceResourceParams",
|
||||
boundary: "route-params",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "REQUEST",
|
||||
unknownFieldPolicy: "REJECT_UNKNOWN",
|
||||
}),
|
||||
ReferenceResourceListQuery: Object.freeze({
|
||||
schemaId: "ReferenceResourceListQuery",
|
||||
boundary: "route-search-api-request",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "REQUEST",
|
||||
unknownFieldPolicy: "REJECT_UNKNOWN",
|
||||
}),
|
||||
CreateReferenceResourceCommand: Object.freeze({
|
||||
schemaId: "CreateReferenceResourceCommand",
|
||||
boundary: "api-request",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "REQUEST",
|
||||
unknownFieldPolicy: "REJECT_UNKNOWN",
|
||||
}),
|
||||
NoRequest: Object.freeze({
|
||||
schemaId: "NoRequest",
|
||||
boundary: "api-request",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "REQUEST",
|
||||
unknownFieldPolicy: "REJECT_UNKNOWN",
|
||||
}),
|
||||
ReferenceResourceListPayload: Object.freeze({
|
||||
schemaId: "ReferenceResourceListPayload",
|
||||
boundary: "api-response",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "RESPONSE",
|
||||
unknownFieldPolicy: "STRIP_UNKNOWN",
|
||||
}),
|
||||
ReferenceResourcePayload: Object.freeze({
|
||||
schemaId: "ReferenceResourcePayload",
|
||||
boundary: "api-response",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
runtime: "zod",
|
||||
schemaVersion: 1,
|
||||
direction: "RESPONSE",
|
||||
unknownFieldPolicy: "STRIP_UNKNOWN",
|
||||
}),
|
||||
}),
|
||||
routes: Object.freeze({
|
||||
REFERENCE_RESOURCE_LIST: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_LIST",
|
||||
path: "/examples/reference-resources",
|
||||
paramsSchema: null,
|
||||
searchSchema: "ReferenceResourceListQuery",
|
||||
access: "session-required",
|
||||
loadingSurface: "reference-resource-list",
|
||||
errorSurface: "feature-boundary",
|
||||
chunkId: "route-reference-resources",
|
||||
title: "Reference feature",
|
||||
navigationLabel: "Reference feature",
|
||||
navigationOrder: 50,
|
||||
}),
|
||||
REFERENCE_RESOURCE_DETAIL: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_DETAIL",
|
||||
path: "/examples/reference-resources/:resourceId",
|
||||
paramsSchema: "ReferenceResourceParams",
|
||||
searchSchema: null,
|
||||
access: "session-required",
|
||||
loadingSurface: "reference-resource-detail",
|
||||
errorSurface: "feature-boundary",
|
||||
chunkId: "route-reference-resource-detail",
|
||||
title: "Reference detail",
|
||||
navigationLabel: null,
|
||||
navigationOrder: null,
|
||||
}),
|
||||
REFERENCE_RESOURCE_FORM: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_FORM",
|
||||
path: "/examples/reference-resources/new",
|
||||
paramsSchema: null,
|
||||
searchSchema: null,
|
||||
access: "session-required",
|
||||
loadingSurface: "reference-resource-form",
|
||||
errorSurface: "feature-boundary",
|
||||
chunkId: "route-reference-resource-form",
|
||||
title: "Reference form",
|
||||
navigationLabel: null,
|
||||
navigationOrder: null,
|
||||
}),
|
||||
REFERENCE_RESOURCE_STATUS: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_STATUS",
|
||||
path: "/examples/reference-resources/status",
|
||||
paramsSchema: null,
|
||||
searchSchema: null,
|
||||
access: "session-required",
|
||||
loadingSurface: "reference-resource-status",
|
||||
errorSurface: "feature-boundary",
|
||||
chunkId: "route-reference-resource-status",
|
||||
title: "Reference status",
|
||||
navigationLabel: null,
|
||||
navigationOrder: null,
|
||||
}),
|
||||
}),
|
||||
routeRuntimeContracts: Object.freeze({
|
||||
REFERENCE_RESOURCE_LIST: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_LIST",
|
||||
moduleId: "reference-resource-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "ReferenceResourceListQuery",
|
||||
}),
|
||||
REFERENCE_RESOURCE_DETAIL: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_DETAIL",
|
||||
moduleId: "reference-resource-detail-page",
|
||||
paramsCodec: "ReferenceResourceParams",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
REFERENCE_RESOURCE_FORM: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_FORM",
|
||||
moduleId: "reference-resource-form-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
REFERENCE_RESOURCE_STATUS: Object.freeze({
|
||||
routeId: "REFERENCE_RESOURCE_STATUS",
|
||||
moduleId: "reference-resource-status-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
}),
|
||||
apiOperations: Object.freeze({
|
||||
LIST_REFERENCE_RESOURCES: defineRestOperation({
|
||||
method: "GET",
|
||||
path: "/api/reference-resources",
|
||||
operationId: "LIST_REFERENCE_RESOURCES",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "search",
|
||||
requestSchema: "ReferenceResourceListQuery",
|
||||
responseSchema: "ReferenceResourceListPayload",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
contractVersion: 2,
|
||||
protocol: "REST",
|
||||
semantics: "QUERY",
|
||||
replayPolicy: "SAFE",
|
||||
idempotencyKeyPolicy: "NONE",
|
||||
mapperId: "ReferenceResourceListMapper",
|
||||
successStatuses: [200],
|
||||
responseMediaTypes: ["application/json"],
|
||||
maxResponseBytes: 262_144,
|
||||
providerId: "PRIMARY_API",
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
csrfProfileId: "NO_CSRF_BEARER",
|
||||
pathSchema: "NoRequest",
|
||||
pathParameterNames: [],
|
||||
maxEncodedSearchBytes: 4_096,
|
||||
}),
|
||||
CREATE_REFERENCE_RESOURCE: defineRestOperation({
|
||||
method: "POST",
|
||||
path: "/api/reference-resources",
|
||||
operationId: "CREATE_REFERENCE_RESOURCE",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "keyed",
|
||||
retry: "runtime",
|
||||
requestSource: "body",
|
||||
requestSchema: "CreateReferenceResourceCommand",
|
||||
responseSchema: "ReferenceResourcePayload",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
contractVersion: 2,
|
||||
protocol: "REST",
|
||||
semantics: "COMMAND",
|
||||
replayPolicy: "KEYED_COMMAND",
|
||||
idempotencyKeyPolicy: "REQUIRED",
|
||||
mapperId: "ReferenceResourceMapper",
|
||||
successStatuses: [200, 201],
|
||||
responseMediaTypes: ["application/json"],
|
||||
maxResponseBytes: 32_768,
|
||||
providerId: "PRIMARY_API",
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
csrfProfileId: "NO_CSRF_BEARER",
|
||||
pathSchema: "NoRequest",
|
||||
pathParameterNames: [],
|
||||
maxEncodedSearchBytes: 0,
|
||||
}),
|
||||
GET_REFERENCE_RESOURCE: defineRestOperation({
|
||||
method: "GET",
|
||||
path: "/api/reference-resources/{resourceId}",
|
||||
operationId: "GET_REFERENCE_RESOURCE",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "none",
|
||||
requestSchema: "NoRequest",
|
||||
responseSchema: "ReferenceResourcePayload",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
contractVersion: 2,
|
||||
protocol: "REST",
|
||||
semantics: "QUERY",
|
||||
replayPolicy: "SAFE",
|
||||
idempotencyKeyPolicy: "NONE",
|
||||
mapperId: "ReferenceResourceMapper",
|
||||
successStatuses: [200],
|
||||
responseMediaTypes: ["application/json"],
|
||||
maxResponseBytes: 32_768,
|
||||
providerId: "PRIMARY_API",
|
||||
authProfileId: "REFERENCE_EXTERNAL_BEARER",
|
||||
csrfProfileId: "NO_CSRF_BEARER",
|
||||
pathSchema: "ReferenceResourceParams",
|
||||
pathParameterNames: ["resourceId"],
|
||||
maxEncodedSearchBytes: 0,
|
||||
}),
|
||||
}),
|
||||
invalidation: Object.freeze({
|
||||
topics: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]),
|
||||
namespaces: Object.freeze([REFERENCE_RESOURCE_QUERY_NAMESPACE]),
|
||||
edges: Object.freeze([
|
||||
Object.freeze({
|
||||
topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
topicVersions: Object.freeze([
|
||||
Object.freeze({
|
||||
topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
topicVersion: 1,
|
||||
}),
|
||||
]),
|
||||
} as const);
|
||||
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
createReferenceResource,
|
||||
type ReferenceResource,
|
||||
} from "../domain/reference-resource.ts";
|
||||
import {
|
||||
mappingFailure,
|
||||
mappingSuccess,
|
||||
type InstalledBoundaryMapper,
|
||||
type MappingResult,
|
||||
} from "../../../contracts/boundary-mapper.ts";
|
||||
import type { ReferenceResourceDto } from "./reference-schemas.ts";
|
||||
|
||||
export type ReferenceResourceView = Readonly<{
|
||||
resourceId: string;
|
||||
title: string;
|
||||
createdAt: string | null;
|
||||
optimistic?: boolean;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Operation-specific mapper. The HTTP contract has already validated the wire
|
||||
* shape, so this mapper owns only wire -> domain construction.
|
||||
*/
|
||||
export function mapReferenceResourcePayload(
|
||||
dto: ReferenceResourceDto,
|
||||
): MappingResult<ReferenceResource> {
|
||||
try {
|
||||
return mappingSuccess(
|
||||
createReferenceResource({
|
||||
id: dto.id,
|
||||
displayName: dto.name,
|
||||
createdAt: dto.createdAt ?? null,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return mappingFailure("MAPPING_INVARIANT_REJECTED");
|
||||
}
|
||||
}
|
||||
|
||||
export function mapReferenceResourceListPayload(
|
||||
payload: readonly ReferenceResourceDto[],
|
||||
): MappingResult<readonly ReferenceResource[]> {
|
||||
const output: ReferenceResource[] = [];
|
||||
for (const item of payload) {
|
||||
const mapped = mapReferenceResourcePayload(item);
|
||||
if (!mapped.ok) return mapped;
|
||||
output.push(mapped.value);
|
||||
}
|
||||
return mappingSuccess(Object.freeze(output));
|
||||
}
|
||||
|
||||
function isReferenceResourceDto(value: unknown): value is ReferenceResourceDto {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const dto = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof dto.id === "string" &&
|
||||
typeof dto.name === "string" &&
|
||||
(dto.createdAt === undefined || typeof dto.createdAt === "string")
|
||||
);
|
||||
}
|
||||
|
||||
function mapUnknownReferenceResourcePayload(
|
||||
value: unknown,
|
||||
): MappingResult<ReferenceResource> {
|
||||
return isReferenceResourceDto(value)
|
||||
? mapReferenceResourcePayload(value)
|
||||
: mappingFailure("MAPPING_INVARIANT_REJECTED");
|
||||
}
|
||||
|
||||
function mapUnknownReferenceResourceListPayload(
|
||||
value: unknown,
|
||||
): MappingResult<readonly ReferenceResource[]> {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
value.length > 100 ||
|
||||
!value.every(isReferenceResourceDto)
|
||||
) {
|
||||
return mappingFailure(
|
||||
Array.isArray(value) && value.length > 100
|
||||
? "OUTPUT_LIMIT_EXCEEDED"
|
||||
: "MAPPING_INVARIANT_REJECTED",
|
||||
);
|
||||
}
|
||||
return mapReferenceResourceListPayload(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry-facing compatibility projection. The registry is intentionally
|
||||
* untyped, so its adapter performs the defensive shape check. Feature HTTP
|
||||
* bindings use the typed operation-specific mappers above.
|
||||
*/
|
||||
export function mapReferenceOperation(
|
||||
operationId: string,
|
||||
payload: unknown,
|
||||
): MappingResult<ReferenceResource | readonly ReferenceResource[]> {
|
||||
if (operationId === "LIST_REFERENCE_RESOURCES") {
|
||||
return mapUnknownReferenceResourceListPayload(payload);
|
||||
}
|
||||
if (
|
||||
operationId === "CREATE_REFERENCE_RESOURCE" ||
|
||||
operationId === "GET_REFERENCE_RESOURCE"
|
||||
) {
|
||||
return mapUnknownReferenceResourcePayload(payload);
|
||||
}
|
||||
return mappingFailure("MAPPING_INVARIANT_REJECTED");
|
||||
}
|
||||
|
||||
export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({
|
||||
ReferenceResourceListMapper: Object.freeze({
|
||||
mapperId: "ReferenceResourceListMapper",
|
||||
mapperVersion: 1,
|
||||
inputSchemaId: "ReferenceResourceListPayload",
|
||||
outputContractId: "ReferenceResourceList",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
maxOutputItems: 100,
|
||||
map: mapUnknownReferenceResourceListPayload,
|
||||
}),
|
||||
ReferenceResourceMapper: Object.freeze({
|
||||
mapperId: "ReferenceResourceMapper",
|
||||
mapperVersion: 1,
|
||||
inputSchemaId: "ReferenceResourcePayload",
|
||||
outputContractId: "ReferenceResource",
|
||||
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||
maxOutputItems: 1,
|
||||
map: mapUnknownReferenceResourcePayload,
|
||||
}),
|
||||
} satisfies Readonly<Record<string, InstalledBoundaryMapper>>);
|
||||
|
||||
export function toReferenceView(
|
||||
resource: ReferenceResource,
|
||||
): ReferenceResourceView {
|
||||
return Object.freeze({
|
||||
resourceId: resource.id,
|
||||
title: resource.displayName,
|
||||
createdAt: resource.createdAt,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({
|
||||
"ko-KR": Object.freeze({
|
||||
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||
}),
|
||||
"en-US": Object.freeze({
|
||||
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||
}),
|
||||
} as const);
|
||||
@@ -0,0 +1,128 @@
|
||||
import { z } from "zod";
|
||||
import type { RuntimeSchemaCodec } from "../../../contracts/schema-registry.ts";
|
||||
|
||||
export const referenceResourceListQuerySchema = z
|
||||
.object({
|
||||
cursor: z.string().min(1).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
tags: z
|
||||
.preprocess(
|
||||
(value) =>
|
||||
value === undefined
|
||||
? undefined
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
: [value],
|
||||
z.array(z.string().trim().min(1)).readonly(),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const referenceResourceParamsSchema = z
|
||||
.object({
|
||||
resourceId: z.string().trim().min(1).max(120),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const referenceResourceDtoSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).max(120),
|
||||
name: z.string().min(1).max(240),
|
||||
createdAt: z.string().datetime().optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export type ReferenceResourceDto = z.output<
|
||||
typeof referenceResourceDtoSchema
|
||||
>;
|
||||
|
||||
export const referenceProblemSchema = z
|
||||
.object({
|
||||
type: z.string().min(1).max(512),
|
||||
title: z.string().min(1).max(240),
|
||||
status: z.int().min(100).max(599),
|
||||
code: z.string().min(1).max(120).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export type ReferenceProblem = z.output<typeof referenceProblemSchema>;
|
||||
|
||||
export const createReferenceResourceCommandSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
note: z.string().trim().max(500).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const payloadSchemas = {
|
||||
ReferenceResourceListPayload: z.array(referenceResourceDtoSchema).max(100),
|
||||
ReferenceResourcePayload: referenceResourceDtoSchema,
|
||||
} satisfies Record<string, z.ZodType>;
|
||||
|
||||
const requestSchemas = {
|
||||
ReferenceResourceParams: referenceResourceParamsSchema,
|
||||
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
||||
NoRequest: z.object({}).strict(),
|
||||
CreateReferenceResourceCommand: createReferenceResourceCommandSchema,
|
||||
} satisfies Record<string, z.ZodType>;
|
||||
|
||||
function project(result: z.ZodSafeParseResult<unknown>) {
|
||||
return result.success
|
||||
? ({ success: true as const, data: structuredClone(result.data) })
|
||||
: ({
|
||||
success: false as const,
|
||||
issues: result.error.issues.map((issue) => ({
|
||||
path: issue.path.join("."),
|
||||
code: issue.code,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
function codec(
|
||||
schemaId: string,
|
||||
schema: z.ZodType,
|
||||
): RuntimeSchemaCodec {
|
||||
return Object.freeze({
|
||||
schemaId,
|
||||
parse: (value: unknown) => project(schema.safeParse(value)),
|
||||
});
|
||||
}
|
||||
|
||||
export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({
|
||||
ReferenceResourceParams: codec(
|
||||
"ReferenceResourceParams",
|
||||
referenceResourceParamsSchema,
|
||||
),
|
||||
ReferenceResourceListQuery: codec(
|
||||
"ReferenceResourceListQuery",
|
||||
referenceResourceListQuerySchema,
|
||||
),
|
||||
NoRequest: codec("NoRequest", requestSchemas.NoRequest),
|
||||
CreateReferenceResourceCommand: codec(
|
||||
"CreateReferenceResourceCommand",
|
||||
requestSchemas.CreateReferenceResourceCommand,
|
||||
),
|
||||
ReferenceResourceListPayload: codec(
|
||||
"ReferenceResourceListPayload",
|
||||
payloadSchemas.ReferenceResourceListPayload,
|
||||
),
|
||||
ReferenceResourcePayload: codec(
|
||||
"ReferenceResourcePayload",
|
||||
payloadSchemas.ReferenceResourcePayload,
|
||||
),
|
||||
});
|
||||
|
||||
export function validateReferencePayload(schemaId: string, value: unknown) {
|
||||
const schema = payloadSchemas[schemaId as keyof typeof payloadSchemas];
|
||||
return schema
|
||||
? project(schema.safeParse(value))
|
||||
: { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] };
|
||||
}
|
||||
|
||||
export function validateReferenceRequest(schemaId: string, value: unknown) {
|
||||
const schema = requestSchemas[schemaId as keyof typeof requestSchemas];
|
||||
return schema
|
||||
? project(schema.safeParse(value))
|
||||
: { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export type ReferenceResource = Readonly<{
|
||||
id: string;
|
||||
displayName: string;
|
||||
createdAt: string | null;
|
||||
}>;
|
||||
|
||||
export function createReferenceResource(
|
||||
values: ReferenceResource,
|
||||
): ReferenceResource {
|
||||
if (!values.id || !values.displayName) {
|
||||
throw new TypeError("Reference resource invariants require id and displayName");
|
||||
}
|
||||
return Object.freeze({ ...values });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { defineFeatureModule } from "../feature-module.ts";
|
||||
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts";
|
||||
import {
|
||||
REFERENCE_FEATURE_CONTRACT,
|
||||
REFERENCE_FEATURE_ID,
|
||||
} from "./contracts/reference-feature-contract.ts";
|
||||
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts";
|
||||
import { REFERENCE_MESSAGE_CATALOGS } from "./contracts/reference-message-catalog.ts";
|
||||
import { REFERENCE_FEATURE_RUNTIME_DESCRIPTOR } from "./presentation/reference-feature-runtime-descriptor.ts";
|
||||
|
||||
export const FEATURE_MODULE_ID =
|
||||
"reference-feature" satisfies typeof REFERENCE_FEATURE_ID;
|
||||
/** Owning bounded context (route root and budget live in its declaration). */
|
||||
export const FEATURE_CONTEXT_ID = "reference-context";
|
||||
|
||||
export const REFERENCE_FEATURE_MODULE = defineFeatureModule({
|
||||
id: FEATURE_MODULE_ID,
|
||||
contracts: REFERENCE_FEATURE_CONTRACT,
|
||||
routes: REFERENCE_FEATURE_CONTRACT.routes,
|
||||
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
|
||||
runtimes: [REFERENCE_FEATURE_RUNTIME_DESCRIPTOR],
|
||||
messages: REFERENCE_MESSAGE_CATALOGS,
|
||||
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
|
||||
} as const);
|
||||
|
||||
export const FEATURE_MODULE = REFERENCE_FEATURE_MODULE;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
|
||||
import {
|
||||
referenceResourceListQuerySchema,
|
||||
referenceResourceParamsSchema,
|
||||
} from "../contracts/reference-schemas.ts";
|
||||
|
||||
export const REFERENCE_FEATURE_ROUTE_CODECS = {
|
||||
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
||||
ReferenceResourceParams: referenceResourceParamsSchema,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Boot-safe feature runtime metadata. Page components are deliberately absent:
|
||||
* executable route chunks are owned and loaded by the bounded context route
|
||||
* module, so Node-side composition and app boot do not pull the page graph in.
|
||||
*/
|
||||
export const REFERENCE_FEATURE_RUNTIME_DESCRIPTOR = Object.freeze({
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
routeCodecs: REFERENCE_FEATURE_ROUTE_CODECS,
|
||||
routeRuntime: Object.freeze({}),
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { lazy } from "react";
|
||||
|
||||
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-feature-runtime-descriptor.ts";
|
||||
|
||||
export { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-feature-runtime-descriptor.ts";
|
||||
|
||||
export const REFERENCE_FEATURE_ROUTE_RUNTIME = {
|
||||
REFERENCE_RESOURCE_LIST: Object.freeze({
|
||||
moduleId: "reference-resource-page",
|
||||
Component: lazy(() => import("./reference-resource-page.tsx")),
|
||||
}),
|
||||
REFERENCE_RESOURCE_DETAIL: Object.freeze({
|
||||
moduleId: "reference-resource-detail-page",
|
||||
Component: lazy(() => import("./reference-resource-detail-page.tsx")),
|
||||
}),
|
||||
REFERENCE_RESOURCE_FORM: Object.freeze({
|
||||
moduleId: "reference-resource-form-page",
|
||||
Component: lazy(() => import("./reference-resource-form-page.tsx")),
|
||||
}),
|
||||
REFERENCE_RESOURCE_STATUS: Object.freeze({
|
||||
moduleId: "reference-resource-status-page",
|
||||
Component: lazy(() => import("./reference-resource-status-page.tsx")),
|
||||
}),
|
||||
} as const;
|
||||
|
||||
/** Context-owned lazy route modules consume this executable contribution. */
|
||||
export const REFERENCE_FEATURE_RUNTIME_CONTRIBUTION = Object.freeze({
|
||||
featureId: REFERENCE_FEATURE_ID,
|
||||
routeCodecs: REFERENCE_FEATURE_ROUTE_CODECS,
|
||||
routeRuntime: REFERENCE_FEATURE_ROUTE_RUNTIME,
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
REFERENCE_FEATURE_ROUTE_CODECS,
|
||||
REFERENCE_FEATURE_ROUTE_RUNTIME,
|
||||
REFERENCE_FEATURE_RUNTIME_CONTRIBUTION,
|
||||
} from "./reference-feature-runtime.ts";
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import {
|
||||
AsyncSurface,
|
||||
DetailPage,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
||||
import { useLocale } from "../../../presentation/i18n/index.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceDetail } from "./use-reference-feature.ts";
|
||||
|
||||
export default function ReferenceResourceDetailPage() {
|
||||
const { date, message } = useLocale();
|
||||
const route = useRouteInput();
|
||||
const resourceId = String(route.params.resourceId);
|
||||
const { query } = useReferenceDetail(resourceId);
|
||||
const resource = query.data;
|
||||
const failureAction = useReferenceFailureAction(query.state.failure);
|
||||
|
||||
return (
|
||||
<DetailPage
|
||||
key={resourceId}
|
||||
breadcrumb={
|
||||
<Link to="/examples/reference-resources">Reference resources</Link>
|
||||
}
|
||||
heading={{
|
||||
eyebrow: "DetailPage",
|
||||
title: resource?.title ?? "Reference detail",
|
||||
description: "route param과 detail query의 reset 경계를 확인합니다.",
|
||||
}}
|
||||
metadata={
|
||||
resource ? (
|
||||
<dl>
|
||||
<dt>Resource ID</dt>
|
||||
<dd>{resource.resourceId}</dd>
|
||||
<dt>Created</dt>
|
||||
<dd>
|
||||
{resource.createdAt
|
||||
? date(new Date(resource.createdAt))
|
||||
: message("common.noDisplayValue")}
|
||||
</dd>
|
||||
</dl>
|
||||
) : (
|
||||
<p>요약 정보를 준비하고 있습니다.</p>
|
||||
)
|
||||
}
|
||||
feedback={
|
||||
<AsyncSurface
|
||||
state={query.state}
|
||||
onAction={failureAction}
|
||||
onRetry={query.retry}
|
||||
>
|
||||
{resource ? (
|
||||
<p>이 영역에는 제품별 상세 section을 조립할 수 있습니다.</p>
|
||||
) : null}
|
||||
</AsyncSurface>
|
||||
}
|
||||
aside={<p>상세 페이지의 관련 정보 slot입니다.</p>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import {
|
||||
Button,
|
||||
AsyncSurface,
|
||||
DirtyNavigationDialog,
|
||||
ErrorSummary,
|
||||
Form,
|
||||
FormActions,
|
||||
FormPage,
|
||||
FormField,
|
||||
useAppForm,
|
||||
useDirtyNavigationGuard,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
REFERENCE_FORM_DEFAULTS,
|
||||
referenceResourceFormSchema,
|
||||
toCreateReferenceCommand,
|
||||
type ReferenceResourceFormValues,
|
||||
} from "./reference-resource-form.ts";
|
||||
import { useReferenceCreate } from "./use-reference-feature.ts";
|
||||
|
||||
const FIELD_LABELS = Object.freeze({
|
||||
name: "새 항목 이름",
|
||||
note: "설명",
|
||||
}) satisfies Record<keyof ReferenceResourceFormValues, string>;
|
||||
|
||||
export default function ReferenceResourceFormPage() {
|
||||
const navigate = useNavigate();
|
||||
const mutation = useReferenceCreate();
|
||||
const submit = useCallback(
|
||||
(command: ReturnType<typeof toCreateReferenceCommand>) =>
|
||||
mutation.submit(command),
|
||||
[mutation],
|
||||
);
|
||||
const form = useAppForm({
|
||||
schema: referenceResourceFormSchema,
|
||||
defaultValues: REFERENCE_FORM_DEFAULTS,
|
||||
allowedServerFields: ["name", "note"],
|
||||
mapToCommand: toCreateReferenceCommand,
|
||||
submit,
|
||||
});
|
||||
const mutationEffectUnknown =
|
||||
mutation.state.indicator === "mutation-effect-unknown";
|
||||
const mutationBlocked =
|
||||
mutationEffectUnknown || mutation.state.indicator === "mutation-pending";
|
||||
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
|
||||
|
||||
return (
|
||||
<Form
|
||||
id={form.formId}
|
||||
pending={form.pending}
|
||||
onSubmit={(event) => {
|
||||
if (mutationBlocked) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
void form.submitForm(event);
|
||||
}}
|
||||
>
|
||||
<FormPage
|
||||
breadcrumb={
|
||||
<button
|
||||
className="ui-button ui-button--ghost"
|
||||
type="button"
|
||||
onClick={() => navigate("/examples/reference-resources")}
|
||||
>
|
||||
목록으로 돌아가기
|
||||
</button>
|
||||
}
|
||||
heading={{
|
||||
eyebrow: "FormPage",
|
||||
title: "Reference resource 만들기",
|
||||
description:
|
||||
"presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.",
|
||||
}}
|
||||
errorSummary={
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldLabels={FIELD_LABELS}
|
||||
fieldId={form.fieldId}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
}
|
||||
fields={
|
||||
<>
|
||||
<FormField
|
||||
{...form.field("name")}
|
||||
label={FIELD_LABELS.name}
|
||||
description="앞뒤 공백은 command mapper 전에 제거됩니다."
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
<FormField
|
||||
{...form.field("note")}
|
||||
label={FIELD_LABELS.note}
|
||||
description="선택 입력이며 비어 있으면 command에 포함되지 않습니다."
|
||||
autoComplete="off"
|
||||
/>
|
||||
</>
|
||||
}
|
||||
formActions={
|
||||
<FormActions sticky>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate("/examples/reference-resources")}
|
||||
disabled={form.pending || mutationBlocked}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.pending || mutationBlocked}
|
||||
>
|
||||
{form.pending ? "저장 중…" : "저장"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => form.reset()}
|
||||
disabled={!form.dirty || form.pending || mutationBlocked}
|
||||
>
|
||||
초기화
|
||||
</Button>
|
||||
</FormActions>
|
||||
}
|
||||
feedback={
|
||||
mutationEffectUnknown ? (
|
||||
<AsyncSurface
|
||||
state={mutation.state}
|
||||
onReconcileUnknownEffect={(resolution) => {
|
||||
void mutation.reconcileUnknownEffect(resolution).then(() => {
|
||||
if (resolution === "APPLIED") {
|
||||
form.settleApplied();
|
||||
} else {
|
||||
form.settleNotApplied();
|
||||
}
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : form.result === "success" ? (
|
||||
<p role="status">저장했습니다.</p>
|
||||
) : form.result === "conflict" ? (
|
||||
<p role="status">충돌을 해결한 뒤 다시 제출할 수 있습니다.</p>
|
||||
) : null
|
||||
}
|
||||
aside={
|
||||
<p>
|
||||
form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만
|
||||
application command로 변환됩니다.
|
||||
</p>
|
||||
}
|
||||
guard={<DirtyNavigationDialog guard={guard} />}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const referenceResourceFormSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2, "이름은 두 글자 이상이어야 합니다.")
|
||||
.max(120),
|
||||
note: z.string().trim().max(500).default(""),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type ReferenceResourceFormValues = z.infer<
|
||||
typeof referenceResourceFormSchema
|
||||
>;
|
||||
|
||||
export const REFERENCE_FORM_DEFAULTS: ReferenceResourceFormValues =
|
||||
Object.freeze({
|
||||
name: "",
|
||||
note: "",
|
||||
});
|
||||
|
||||
export function toCreateReferenceCommand(values: ReferenceResourceFormValues) {
|
||||
return Object.freeze({
|
||||
name: values.name,
|
||||
...(values.note ? { note: values.note } : {}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
|
||||
import {
|
||||
AsyncSurface,
|
||||
Button,
|
||||
CollectionPage,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceFeature } from "./use-reference-feature.ts";
|
||||
|
||||
export default function ReferenceResourcePage() {
|
||||
const navigate = useNavigate();
|
||||
const { filters, query } = useReferenceFeature();
|
||||
const failureAction = useReferenceFailureAction(query.state.failure);
|
||||
|
||||
return (
|
||||
<CollectionPage
|
||||
heading={{
|
||||
eyebrow: "제거 가능한 수직 슬라이스",
|
||||
title: "Reference feature",
|
||||
description:
|
||||
"URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.",
|
||||
}}
|
||||
actions={[
|
||||
{
|
||||
kind: "button",
|
||||
label: "새 항목 만들기",
|
||||
onAction: () => navigate("/examples/reference-resources/new"),
|
||||
},
|
||||
]}
|
||||
activeFilters={
|
||||
<p data-testid="reference-filter">
|
||||
limit {filters.limit}
|
||||
{filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""}
|
||||
</p>
|
||||
}
|
||||
toolbar={<Button onClick={() => void query.retry()}>새로고침</Button>}
|
||||
resultCount={
|
||||
query.data ? `총 ${query.data.length}개 항목` : "결과 확인 중"
|
||||
}
|
||||
>
|
||||
<AsyncSurface
|
||||
state={query.state}
|
||||
onAction={failureAction}
|
||||
onRetry={query.retry}
|
||||
>
|
||||
<ul aria-label="Reference resources">
|
||||
{(query.data ?? []).map((resource) => (
|
||||
<li key={resource.resourceId}>
|
||||
<Link
|
||||
to={`/examples/reference-resources/${encodeURIComponent(resource.resourceId)}`}
|
||||
>
|
||||
{resource.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</AsyncSurface>
|
||||
</CollectionPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { StatusPage } from "../../../presentation/design-system/index.ts";
|
||||
|
||||
export default function ReferenceResourceStatusPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<StatusPage
|
||||
variant="maintenance"
|
||||
heading={{
|
||||
eyebrow: "StatusPage · maintenance",
|
||||
title: "잠시 사용할 수 없습니다.",
|
||||
description:
|
||||
"도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.",
|
||||
}}
|
||||
primaryAction={{
|
||||
kind: "button",
|
||||
label: "목록으로 이동",
|
||||
onAction: () => navigate("/examples/reference-resources"),
|
||||
}}
|
||||
supportReference="REFERENCE-STATUS-DEMO"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback } from "react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
|
||||
import type { AppFailure } from "../../../contracts/errors.ts";
|
||||
import { useSession } from "../../../presentation/providers/session-provider.tsx";
|
||||
|
||||
const REFERENCE_SUPPORT_ROUTE = "/examples/reference-resources/status";
|
||||
|
||||
/**
|
||||
* Reference queries own concrete destinations for generic application failure
|
||||
* actions. Retry remains query-owned; guarded release reloads remain in the
|
||||
* chunk recovery boundary.
|
||||
*/
|
||||
export function useReferenceFailureAction(
|
||||
failure: AppFailure | undefined,
|
||||
): (() => void) | undefined {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { beginSignIn } = useSession();
|
||||
const action = failure?.action;
|
||||
const handleAction = useCallback(() => {
|
||||
if (action === "reauth") {
|
||||
const returnTo = `${location.pathname}${location.search}${location.hash}`;
|
||||
void beginSignIn(returnTo).catch(() => {
|
||||
void navigate("/");
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (action === "navigate") {
|
||||
void navigate("/");
|
||||
return;
|
||||
}
|
||||
if (action === "contact-support") {
|
||||
void navigate(REFERENCE_SUPPORT_ROUTE);
|
||||
}
|
||||
}, [
|
||||
action,
|
||||
beginSignIn,
|
||||
location.hash,
|
||||
location.pathname,
|
||||
location.search,
|
||||
navigate,
|
||||
]);
|
||||
|
||||
return action === "reauth" ||
|
||||
action === "navigate" ||
|
||||
action === "contact-support"
|
||||
? handleAction
|
||||
: undefined;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx";
|
||||
import {
|
||||
useApplicationMutation,
|
||||
useApplicationQuery,
|
||||
} from "../../../presentation/adapters/query/application-query.ts";
|
||||
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
||||
import {
|
||||
REFERENCE_FEATURE_ID,
|
||||
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
REFERENCE_RESOURCE_QUERY_NAMESPACE,
|
||||
} from "../contracts/reference-feature-contract.ts";
|
||||
import type {
|
||||
ReferenceCreateCommand,
|
||||
ReferenceFeatureInput,
|
||||
ReferenceListFilters,
|
||||
} from "../application/reference-feature-api.ts";
|
||||
import type { ReferenceResourceView } from "../contracts/reference-mapper.ts";
|
||||
import {
|
||||
bindQuery,
|
||||
type BoundMutation,
|
||||
type QueryResultMeasure,
|
||||
} from "../../../contracts/server-state.ts";
|
||||
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
|
||||
|
||||
const UTF8 = new TextEncoder();
|
||||
|
||||
/**
|
||||
* §10.4. Feature-owned measurement over the mapped application value. There is
|
||||
* no generic fallback: bounded string bytes plus fixed primitive width plus a
|
||||
* small per-item overhead, never `JSON.stringify` or a recursive walker.
|
||||
*/
|
||||
function measureResourceView(view: ReferenceResourceView): QueryResultMeasure {
|
||||
return {
|
||||
itemCount: 1,
|
||||
estimatedBytes:
|
||||
UTF8.encode(view.resourceId).byteLength +
|
||||
UTF8.encode(view.title).byteLength +
|
||||
UTF8.encode(view.createdAt ?? "").byteLength +
|
||||
32,
|
||||
};
|
||||
}
|
||||
|
||||
function measureResourceList(
|
||||
views: readonly ReferenceResourceView[],
|
||||
): QueryResultMeasure {
|
||||
let estimatedBytes = 16;
|
||||
for (const view of views) {
|
||||
estimatedBytes += measureResourceView(view).estimatedBytes;
|
||||
}
|
||||
return { itemCount: views.length, estimatedBytes };
|
||||
}
|
||||
|
||||
const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({
|
||||
definitionId: "reference-resource-create-v1",
|
||||
definitionVersion: 1,
|
||||
operationId: "CREATE_REFERENCE_RESOURCE",
|
||||
requiresIdempotencyKey: true,
|
||||
owner: REFERENCE_FEATURE_ID,
|
||||
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
|
||||
invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]),
|
||||
});
|
||||
|
||||
type ReferenceCreateMutationBinding = Pick<
|
||||
BoundMutation<ReferenceCreateCommand, ReferenceResourceView>,
|
||||
"scope" | "execute"
|
||||
>;
|
||||
|
||||
function bindReferenceCreateMutation(
|
||||
binding: ReferenceCreateMutationBinding,
|
||||
): BoundMutation<ReferenceCreateCommand, ReferenceResourceView> {
|
||||
return Object.freeze({
|
||||
...REFERENCE_CREATE_MUTATION_POLICY,
|
||||
...binding,
|
||||
});
|
||||
}
|
||||
|
||||
export function useReferenceFeatureInput(): ReferenceFeatureInput {
|
||||
return useApplicationFeature(REFERENCE_FEATURE_ID);
|
||||
}
|
||||
|
||||
export function useReferenceDetail(resourceId: string) {
|
||||
const input = useReferenceFeatureInput();
|
||||
const scope = useServerStateScope();
|
||||
const query = useApplicationQuery(
|
||||
bindQuery(
|
||||
{
|
||||
definitionId: "reference-resource-detail-v1",
|
||||
definitionVersion: 1,
|
||||
owner: REFERENCE_FEATURE_ID,
|
||||
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId,
|
||||
namespaceVersion:
|
||||
REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion,
|
||||
operationId: "GET_REFERENCE_RESOURCE",
|
||||
profileId: "DETAIL_STANDARD",
|
||||
measureResult: measureResourceView,
|
||||
execute: (selectedResourceId: string, { signal }) =>
|
||||
input.getResource(selectedResourceId, { signal }),
|
||||
},
|
||||
resourceId,
|
||||
scope,
|
||||
),
|
||||
);
|
||||
return Object.freeze({ query });
|
||||
}
|
||||
|
||||
export function useReferenceCreate() {
|
||||
const input = useReferenceFeatureInput();
|
||||
const scope = useServerStateScope();
|
||||
const mutation = bindReferenceCreateMutation({
|
||||
scope,
|
||||
execute: input.createResource,
|
||||
});
|
||||
return useApplicationMutation(mutation);
|
||||
}
|
||||
|
||||
export function useReferenceFeature() {
|
||||
const input = useReferenceFeatureInput();
|
||||
const scope = useServerStateScope();
|
||||
const routeInput = useRouteInput();
|
||||
const filters = routeInput.search as ReferenceListFilters;
|
||||
const query = useApplicationQuery(
|
||||
bindQuery(
|
||||
{
|
||||
definitionId: "reference-resource-list-v1",
|
||||
definitionVersion: 1,
|
||||
owner: REFERENCE_FEATURE_ID,
|
||||
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId,
|
||||
namespaceVersion:
|
||||
REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion,
|
||||
operationId: "LIST_REFERENCE_RESOURCES",
|
||||
profileId: "LIST_STANDARD",
|
||||
measureResult: measureResourceList,
|
||||
execute: (selectedFilters: ReferenceListFilters, { signal }) =>
|
||||
input.listResources(selectedFilters, { signal }),
|
||||
},
|
||||
filters,
|
||||
scope,
|
||||
),
|
||||
);
|
||||
const mutation = useApplicationMutation(
|
||||
bindReferenceCreateMutation({
|
||||
scope,
|
||||
execute: input.createResource,
|
||||
}),
|
||||
);
|
||||
return Object.freeze({ filters, query, mutation });
|
||||
}
|
||||
Reference in New Issue
Block a user