Files
clean-architecture-frontend…/recipes/frontend-capabilities/indexeddb-feature-capability.ts
DongHyeonka b72cd7d4a7 test(fixtures): local-draft 샘플을 IndexedDB 소비자 fixture로 옮긴다
src/features/local-draft-feature는 기능이 아니라 IndexedDB recipe의
소비자다. 시험 5개와 recipe가 쓰고, 그래서 생성기에 NOT_A_FEATURE
예외가 있었다(S4 3.1절 S-3).

코드를 tests/fixtures/indexeddb-consumer/로 옮기고 import만 고쳤다.
NOT_A_FEATURE 표식은 이 폴더만 썼고 다운스트림 둘에도 없어 생성기에서
지웠다. 선언 없는 폴더는 밖으로 옮기라는 메시지로 실패한다. 매뉴얼
오류표, README, starter-experience, capability-consumer-experience,
patterns를 고쳤다.

위험: fixture는 기능 폴더 밖이라 기능 계층 규칙(dependency-cruiser)이
걸리지 않는다. recipe가 tests/ 아래 파일을 type import한다.

검증(desktop): test:contract, test:recipes, test:browser-capabilities,
test:unit 통과.
2026-11-08 13:51:55 +09:00

139 lines
5.3 KiB
TypeScript

import {
createIndexedDbRuntime,
type IndexedDbRuntimeDependencies,
} from "../../src/adapters/storage/indexeddb/index.ts";
import type { IndexedDbDatasetScope } from "../../src/application/ports/browser-file-storage/index.ts";
import {
createIndexedDbRepositoryProvider,
type IndexedDbRepositoryProvider,
} from "../../src/features/feature-adapter-contribution.ts";
import type {} from "../../tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts";
import type { LocalDraft } from "../../tests/fixtures/indexeddb-consumer/domain/local-draft.ts";
type LocalDraftRuntimeDependencies = IndexedDbRuntimeDependencies<
LocalDraft,
LocalDraft,
never
>;
type LocalDraftRuntime = ReturnType<
typeof createIndexedDbRuntime<LocalDraft, LocalDraft, never>
>;
/**
* 09-05. How a host builds the `indexedDb` feature capability, shown for the
* local-draft consumer the tests compose (tests/fixtures/indexeddb-consumer).
* IndexedDB is an opt-in reference runtime
* (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json,
* `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does
* not build it. A product that installs a feature with `needs: ["indexedDb"]`
* copies this into `src/bootstrap/product-composition.ts`, replaces the codec,
* migrations and storage policy with its own decisions, and returns `indexedDb`
* there; until it does, the feature capabilities fail the app typecheck and
* `composeFeatureAdapterInputs` names the missing capability.
*
* The scope tokens come from the product's storage registry and the lifecycle
* authority from its composition root; neither is invented here.
*/
export function createLocalDraftIndexedDbCapability(
options: Readonly<{
// The sample keeps drafts across sign-out, so its dataset is origin-shared.
scope: IndexedDbDatasetScope & Readonly<{ accountScope: "ORIGIN_SHARED" }>;
authorizeLifecycle: LocalDraftRuntimeDependencies["authorizeLifecycle"];
/** Defaults to the browser's `indexedDB`; tests pass an in-memory one. */
factory?: IDBFactory;
}>,
): Readonly<{
indexedDb: IndexedDbRepositoryProvider;
/** Opens (and migrates) the database; repository calls fail until it has. */
open(signal?: AbortSignal): ReturnType<LocalDraftRuntime["open"]>;
close(): void;
}> {
const runtime = createIndexedDbRuntime<LocalDraft, LocalDraft, never>({
...(options.factory === undefined ? {} : { factory: options.factory }),
scope: options.scope,
storagePolicy: Object.freeze({
owner: "local-draft-feature",
namespace: "local-draft",
classification: "INTERNAL",
authority: "LOCAL_FIRST",
accountScope: "ORIGIN_SHARED",
retention: Object.freeze({ kind: "EXPLICIT_DELETE" }),
softBudgetBytes: 1_000_000,
hardBudgetBytes: 2_000_000,
evictionPriority: "USER_AUTHORED",
logoutAction: "KEEP_ORIGIN_SHARED",
accountDeletionAction: "KEEP_ORIGIN_SHARED",
pressureAction: "RETAIN",
unavailableFallback: "READ_ONLY",
}),
schemaVersion: 1,
recordStore: "records",
governanceStore: "governance",
retentionStore: "retention",
retentionEligibilityIndex: "by-eligibility",
lifecycleMetadataStores: [],
idempotencyStore: "receipts",
idempotencyExpiryIndex: "by-expiry",
receiptRetentionMs: 60_000,
maxIdempotencyReceipts: 100,
migrations: [
{
id: "local-draft-schema-v1",
fromVersion: 0,
toVersion: 1,
operations: [
{ kind: "CREATE_STORE", name: "governance", keyPath: "bindingKey" },
{
kind: "CREATE_STORE",
name: "retention",
keyPath: "recordKey",
indexes: [{ name: "by-eligibility", keyPath: "eligibleAtEpochMs" }],
},
{ kind: "CREATE_STORE", name: "records", keyPath: "key" },
{
kind: "CREATE_STORE",
name: "receipts",
keyPath: "idempotencyKey",
indexes: [{ name: "by-expiry", keyPath: "expiresAtEpochMs" }],
},
],
},
],
codec: {
currentVersion: 1,
encode: (value) => ({ ok: true, value }),
measureStoredBytes: (value) =>
new TextEncoder().encode(JSON.stringify(value)).byteLength,
decode: (version, value) => {
if (version !== 1 || value === null || typeof value !== "object") {
return { ok: false };
}
const candidate = value as Partial<LocalDraft>;
return typeof candidate.draftId === "string" &&
typeof candidate.title === "string" &&
typeof candidate.body === "string"
? { ok: true, value: candidate as LocalDraft }
: { ok: false };
},
fingerprint: async (value) => {
const bytes = new TextEncoder().encode(
JSON.stringify([value.draftId, value.title, value.body]),
);
const digest = await crypto.subtle.digest("SHA-256", bytes);
return Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, "0"),
).join("");
},
},
queryPolicy: { plan: () => ({ limit: 1 }) },
authorizeLifecycle: options.authorizeLifecycle,
});
return Object.freeze({
indexedDb: createIndexedDbRepositoryProvider(
Object.freeze({ "local-draft": runtime }),
),
open: (signal?: AbortSignal) => runtime.open(signal),
close: () => runtime.close(),
});
}