import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { createSchemaTransformerV2 } from "../../src/plugin.ts"; import { asObjectSchema, getTypeFromCode, getTypeFromFiles } from "../utils.ts"; describe("Schema: CFC authoring aliases", () => { it("lowers Confidential and OpaqueInput through the canonical Cfc carrier", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; type OpaqueInput = Cfc; type ProjectionPath = Cfc; type ProjectionOf = ProjectionPath; type Ref = { readonly __ct_ref_root__?: Root; readonly __ct_ref_path__?: Path; }; type Projection = SourceRef extends Ref< infer Root, infer Path extends readonly unknown[] > ? ProjectionOf : never; interface SchemaRoot { secret: Confidential; token: OpaqueInput; projectionOf: ProjectionOf<{ title: string }, readonly ["title"]>; projectionPath: ProjectionPath<{ title: string }, "/source", readonly ["nested", "path"]>; projection: Projection>; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const secret = schema.properties?.secret as any; expect(secret.type).toBe("string"); expect(secret.ifc?.confidentiality).toEqual(["secret"]); const token = schema.properties?.token as any; expect(token.type).toBe("string"); expect(token.ifc?.opaque).toBe(true); const projectionOf = schema.properties?.projectionOf as any; expect(projectionOf.type).toBe("object"); expect(projectionOf.properties?.title?.type).toBe("string"); expect(projectionOf.ifc?.projection).toEqual({ from: "/", path: "/title", }); const projectionPath = schema.properties?.projectionPath as any; expect(projectionPath.type).toBe("object"); expect(projectionPath.properties?.title?.type).toBe("string"); expect(projectionPath.ifc?.projection).toEqual({ from: "/source", path: "/nested/path", }); const projection = schema.properties?.projection as any; expect(projection.type).toBe("object"); expect(projection.properties?.title?.type).toBe("string"); expect(projection.ifc?.projection).toEqual({ from: "/", path: "/nested/path", }); }); it("expands nested aliases before lowering canonical Cfc metadata", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; type SecretText = Confidential; interface SchemaRoot { secret: SecretText<{ value: string }>; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const secret = schema.properties?.secret as any; expect(secret.type).toBe("object"); expect(secret.properties?.value?.type).toBe("string"); expect(secret.ifc?.confidentiality).toEqual(["secret"]); }); it("preserves CFC metadata under writable cell wrappers", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; interface SchemaRoot { labelled: Writable>; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const labelled = schema.properties?.labelled as any; expect(labelled.type).toBe("string"); expect(labelled.asCell).toEqual(["cell"]); expect(labelled.ifc?.confidentiality).toEqual(["prompt-influence"]); }); it("lowers the remaining canonical metadata aliases and merges nested Cfc metadata", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; type Integrity = Cfc; type AddIntegrity = Cfc; type RepresentsCurrentUser = Cfc; type AuthoredByCurrentUser = Cfc; type RequiresIntegrity = Cfc; type MaxConfidentiality = Cfc; type ExactCopy = Cfc; type LengthPreservedFrom = Cfc; type FilteredFrom = Cfc; type SubsetOf = Cfc; type PermutationOf = Cfc; type OpaqueInput = Cfc; interface SchemaRoot { confidential: Confidential; integrity: Integrity; addIntegrity: AddIntegrity; representsCurrentUser: RepresentsCurrentUser<{ name: string }>; authoredByCurrentUser: AuthoredByCurrentUser<{ body: string }>; requiresIntegrity: RequiresIntegrity; maxConfidentiality: MaxConfidentiality; exactCopy: ExactCopy; lengthPreserved: LengthPreservedFrom; filteredFrom: FilteredFrom; subsetOf: SubsetOf; permutationOf: PermutationOf; opaque: OpaqueInput; merged: Cfc, { integrity: readonly ["outer"] }>; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); expect((schema.properties?.confidential as any).ifc?.confidentiality) .toEqual([ "confidential", ]); expect((schema.properties?.integrity as any).ifc?.integrity).toEqual([ "integrity", ]); expect((schema.properties?.addIntegrity as any).ifc?.addIntegrity) .toEqual(["add-integrity"]); expect((schema.properties?.representsCurrentUser as any).ifc?.addIntegrity) .toEqual([{ kind: "represents-principal", subject: { __ctCurrentPrincipal: true }, }]); expect((schema.properties?.authoredByCurrentUser as any).ifc?.addIntegrity) .toEqual([{ kind: "authored-by", subject: { __ctCurrentPrincipal: true }, }]); expect((schema.properties?.requiresIntegrity as any).ifc?.requiredIntegrity) .toEqual(["required-integrity"]); expect( (schema.properties?.maxConfidentiality as any).ifc?.maxConfidentiality, ) .toEqual(["max-confidentiality"]); expect((schema.properties?.exactCopy as any).ifc?.exactCopyOf) .toBe("/source"); expect((schema.properties?.lengthPreserved as any).ifc?.collection).toEqual( { sourceCollection: "/collection", lengthPreserved: true, }, ); expect((schema.properties?.filteredFrom as any).ifc?.collection).toEqual({ filteredFrom: "/filtered", }); expect((schema.properties?.subsetOf as any).ifc?.collection).toEqual({ subsetOf: "/subset", }); expect((schema.properties?.permutationOf as any).ifc?.collection).toEqual({ permutationOf: "/permutation", }); expect((schema.properties?.opaque as any).ifc?.opaque).toEqual({ schema: { type: "string" }, allowPassThrough: false, }); expect((schema.properties?.merged as any).ifc?.confidentiality).toEqual([ "nested", ]); expect((schema.properties?.merged as any).ifc?.integrity).toEqual([ "outer", ]); expect((schema.properties?.merged as any).properties?.value?.type).toBe( "string", ); }); it("preserves object-shaped integrity atoms authored through Cfc metadata", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; interface Message { senderId: string; body: string; } interface SchemaRoot { message: Cfc; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); expect((schema.properties?.message as any).ifc?.integrity).toEqual([{ kind: "authored-by", subject: "alice", }]); }); it("preserves object-shaped confidentiality atoms authored through canonical aliases", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; interface SchemaRoot { body: Confidential; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); expect((schema.properties?.body as any).ifc?.confidentiality).toEqual([{ type: "https://commonfabric.org/cfc/atom/Caveat", kind: "prompt-influence", source: "of:message", }]); }); it("preserves object-shaped confidentiality atoms referenced with typeof", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type Confidential = Cfc; const HEALTH_RECORD_CONFIDENTIALITY = { type: "https://commonfabric.org/cfc/atom/Resource", class: "SensitiveHealthRecord", subject: "did:example:patient", } as const; interface SchemaRoot { body: Confidential; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); expect((schema.properties?.body as any).ifc?.confidentiality).toEqual([{ type: "https://commonfabric.org/cfc/atom/Resource", class: "SensitiveHealthRecord", subject: "did:example:patient", }]); }); it("preserves primitive Cfc metadata through generic aliases", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type AuthorshipIntegrity = { readonly kind: "authored-by"; readonly subject: Author; }; type AuthoredMessageBody = Cfc< string, { integrity: readonly [AuthorshipIntegrity] } >; interface SchemaRoot { body: AuthoredMessageBody<"alice">; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const body = schema.properties?.body as any; expect(body.type).toBe("string"); expect(body.ifc?.integrity).toEqual([{ kind: "authored-by", subject: "alice", }]); }); it("preserves tuple metadata through chained generic Cfc aliases", async () => { const code = ` type Cfc = T & { readonly __ct_cfc__?: Meta }; type WriteAuthorizedBy = Cfc; type TrustedActionWriteWithIntegrity< T, Binding, Action extends string, Pattern extends string, Integrity extends readonly [string, ...string[]], > = Cfc< WriteAuthorizedBy, { uiContract: { helper: "UiAction"; action: Action; trustedPattern: Pattern; requiredEventIntegrity: Integrity; }; } >; type TrustedActionWrite< T, Binding, Action extends string, Pattern extends string, > = TrustedActionWriteWithIntegrity; declare function handler(fn: (argument: A, state: B) => void): { readonly __handler: [A, B] }; interface Writable { get(): T; set(value: T): void; } const TRUSTED_SAVE_ACTION = "TrustedSaveTitle"; const TRUSTED_SAVE_SURFACE = "TrustedSaveSurface"; const commitTrustedSaveTitle = handler }>( (_, { title }) => title.set(title.get().trim()), ); interface SchemaRoot { savedTitle: TrustedActionWrite< string, typeof commitTrustedSaveTitle, typeof TRUSTED_SAVE_ACTION, typeof TRUSTED_SAVE_SURFACE >; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const savedTitle = schema.properties?.savedTitle as any; expect(savedTitle.type).toBe("string"); expect(savedTitle.ifc?.uiContract).toEqual({ helper: "UiAction", action: "TrustedSaveTitle", trustedPattern: "TrustedSaveSurface", requiredEventIntegrity: ["TrustedSaveSurface"], }); expect(savedTitle.ifc?.writeAuthorizedBy).toEqual({ __ctWriterIdentityOf: { file: "test.ts", path: ["commitTrustedSaveTitle"], }, }); }); it("preserves imported writeAuthorizedBy binding declaration identity", async () => { const { type, checker } = await getTypeFromFiles( { "/trusted.ts": ` export type Cfc = T & { readonly __ct_cfc__?: Meta }; export type WriteAuthorizedBy = Cfc; export type TrustedActionWriteWithIntegrity< T, Binding, Action extends string, Pattern extends string, Integrity extends readonly [string, ...string[]], > = Cfc< WriteAuthorizedBy, { uiContract: { helper: "UiAction"; action: Action; trustedPattern: Pattern; requiredEventIntegrity: Integrity; }; } >; declare function handler(fn: (argument: A, state: B) => void): { readonly __handler: [A, B] }; interface Writable { get(): T; set(value: T): void; } export const TRUSTED_SEND_ACTION = "TrustedSend"; export const TRUSTED_SEND_SURFACE = "TrustedSendSurface"; export const commitTrustedMessageSend = handler }>( (_, { messages }) => messages.set([...messages.get(), "sent"]), ); export type TrustedSentMessage = TrustedActionWriteWithIntegrity< { origin: "sent"; body: string }, typeof commitTrustedMessageSend, typeof TRUSTED_SEND_ACTION, typeof TRUSTED_SEND_SURFACE, [typeof TRUSTED_SEND_SURFACE] >; export type SharedChatMessage = | TrustedSentMessage | { origin: "imported"; body: string }; `, "/main.ts": ` import type { SharedChatMessage } from "./trusted.ts"; export interface SchemaRoot { messages: SharedChatMessage[]; } `, }, "/main.ts", "SchemaRoot", ); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const writeAuthorizedByClaims: unknown[] = []; const collectWriteAuthorizedBy = (value: unknown) => { if (!value || typeof value !== "object") { return; } const record = value as Record; if (record.ifc?.writeAuthorizedBy) { writeAuthorizedByClaims.push(record.ifc.writeAuthorizedBy); } for (const child of Object.values(record)) { if (Array.isArray(child)) { child.forEach(collectWriteAuthorizedBy); } else { collectWriteAuthorizedBy(child); } } }; collectWriteAuthorizedBy(schema); expect(writeAuthorizedByClaims).toContainEqual({ __ctWriterIdentityOf: { file: "/trusted.ts", path: ["commitTrustedMessageSend"], }, }); }); it("falls back to ordinary schema generation when a canonical alias expansion cannot be resolved", async () => { const code = ` type OpaqueInput = MaybeOpaque; type MaybeOpaque = T; interface SchemaRoot { value: OpaqueInput<{ title: string }>; } `; const { type, checker } = await getTypeFromCode(code, "SchemaRoot"); const schema = asObjectSchema( createSchemaTransformerV2().generateSchema(type, checker), ); const value = schema.properties?.value as any; expect(value.type).toBe("object"); expect(value.properties?.title?.type).toBe("string"); expect(value.ifc).toBeUndefined(); }); });