feat: add module schema discovery and validation
CI / verify (pull_request) Successful in 24s
CI / infrastructure-smoke (pull_request) Successful in 20s

This commit is contained in:
ekklesia
2026-07-13 21:35:21 -05:00
parent 2465d9c1f7
commit 80b56b72b1
31 changed files with 1584 additions and 34 deletions
+1
View File
@@ -19,6 +19,7 @@
"typecheck": "tsc --noEmit --project tsconfig.json"
},
"dependencies": {
"drizzle-orm": "0.45.2",
"semver": "7.8.5",
"zod": "4.4.3"
},
+1
View File
@@ -2,4 +2,5 @@ export * from "./identifiers.js";
export * from "./module-lifecycle.js";
export * from "./module-manifest.js";
export * from "./module-runtime.js";
export * from "./module-schema.js";
export * from "./versions.js";
+94
View File
@@ -0,0 +1,94 @@
import { is } from "drizzle-orm";
import { type AnyPgTable, PgTable } from "drizzle-orm/pg-core";
import { z } from "zod";
import { type ModuleId, moduleIdSchema } from "./identifiers.js";
export const POSTGRES_IDENTIFIER_MAX_LENGTH = 63;
export const moduleTableLocalNameSchema = z
.string()
.min(1)
.regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u, "Must be a lowercase snake-case table name.");
export const physicalModuleTableNameSchema = moduleTableLocalNameSchema.max(
POSTGRES_IDENTIFIER_MAX_LENGTH,
`Must not exceed ${POSTGRES_IDENTIFIER_MAX_LENGTH} characters.`,
);
export interface ModuleSchemaDefinition<
Tables extends Readonly<Record<string, AnyPgTable>> = Readonly<Record<string, AnyPgTable>>,
> {
readonly moduleId: ModuleId;
readonly tables: Tables;
}
const schemaDefinitionKeys = new Set(["moduleId", "tables"]);
const drizzleTableIsAlias = Symbol.for("drizzle:IsAlias");
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function hasOnlyStringKeys(value: object, allowedKeys?: ReadonlySet<string>): boolean {
return Reflect.ownKeys(value).every(
(key) => typeof key === "string" && (!allowedKeys || allowedKeys.has(key)),
);
}
export function moduleTableNamespace(moduleId: ModuleId): string {
return moduleIdSchema.parse(moduleId).replaceAll("-", "_");
}
export function moduleTablePrefix(moduleId: ModuleId): string {
return `${moduleTableNamespace(moduleId)}_`;
}
export function moduleTableName(moduleId: ModuleId, localName: string): string {
const parsedLocalName = moduleTableLocalNameSchema.parse(localName);
const tableName = `${moduleTablePrefix(moduleId)}${parsedLocalName}`;
if (!physicalModuleTableNameSchema.safeParse(tableName).success) {
throw new RangeError("The namespaced PostgreSQL table name is invalid or too long.");
}
return tableName;
}
export function isModuleSchemaDefinition(value: unknown): value is ModuleSchemaDefinition {
try {
if (
!isRecord(value) ||
!hasOnlyStringKeys(value, schemaDefinitionKeys) ||
!moduleIdSchema.safeParse(value.moduleId).success ||
!isRecord(value.tables) ||
!hasOnlyStringKeys(value.tables)
) {
return false;
}
const tables = Object.values(value.tables);
return (
tables.length > 0 &&
tables.every(
(table) =>
is(table, PgTable) &&
(table as unknown as Record<PropertyKey, unknown>)[drizzleTableIsAlias] === false,
)
);
} catch {
return false;
}
}
export function parseModuleSchemaDefinition(value: unknown): ModuleSchemaDefinition {
if (!isModuleSchemaDefinition(value)) {
throw new TypeError("Invalid Ekklesia module schema definition.");
}
const tables = Object.freeze(
Object.fromEntries(
Object.entries(value.tables).sort(([left], [right]) =>
left < right ? -1 : left > right ? 1 : 0,
),
) as Record<string, AnyPgTable>,
);
return Object.freeze({ moduleId: value.moduleId, tables });
}
@@ -0,0 +1,54 @@
import { alias, getTableConfig, integer } from "drizzle-orm/pg-core";
import { describe, expect, it } from "vitest";
import {
moduleTableName,
parseModuleSchemaDefinition,
physicalModuleTableNameSchema,
} from "../src/index.js";
import { pgTable } from "drizzle-orm/pg-core";
describe("module schema contract", () => {
it("creates deterministic physical names from module and local identifiers", () => {
expect(moduleTableName("calendar", "events")).toBe("calendar_events");
expect(moduleTableName("care-team", "member_notes")).toBe("care_team_member_notes");
});
it("rejects unsafe logical names and PostgreSQL identifiers beyond 63 characters", () => {
expect(() => moduleTableName("calendar", "EventItems")).toThrow();
expect(() => moduleTableName("calendar", "event-items")).toThrow();
expect(physicalModuleTableNameSchema.safeParse("a".repeat(63)).success).toBe(true);
expect(physicalModuleTableNameSchema.safeParse("a".repeat(64)).success).toBe(false);
expect(() => moduleTableName("a".repeat(60), "rows")).toThrow(
"The namespaced PostgreSQL table name is invalid or too long.",
);
});
it("normalizes and freezes a typed schema definition without freezing its tables", () => {
const records = pgTable("example_records", { id: integer().primaryKey() });
const definition = parseModuleSchemaDefinition({
moduleId: "example",
tables: { records },
});
expect(definition.tables.records).toBe(records);
expect(getTableConfig(records).name).toBe("example_records");
expect(Object.isFrozen(definition)).toBe(true);
expect(Object.isFrozen(definition.tables)).toBe(true);
expect(Object.isFrozen(records)).toBe(false);
});
it("rejects malformed, empty, unknown, and non-PostgreSQL table definitions", () => {
const records = pgTable("example_records", { id: integer() });
const disguisedRecords = alias(records, "example_disguised_records");
expect(() => parseModuleSchemaDefinition({ moduleId: "example", tables: {} })).toThrow();
expect(() =>
parseModuleSchemaDefinition({ moduleId: "example", tables: { records: {} } }),
).toThrow();
expect(() =>
parseModuleSchemaDefinition({ moduleId: "example", tables: { records }, extra: true }),
).toThrow();
expect(() =>
parseModuleSchemaDefinition({ moduleId: "example", tables: { disguisedRecords } }),
).toThrow();
});
});