feat: add module schema discovery and validation
This commit is contained in:
@@ -19,6 +19,7 @@
|
||||
"typecheck": "tsc --noEmit --project tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"drizzle-orm": "0.45.2",
|
||||
"semver": "7.8.5",
|
||||
"zod": "4.4.3"
|
||||
},
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -24,10 +24,14 @@
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.5.3",
|
||||
"@types/node": "24.13.3",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"typescript": "7.0.2",
|
||||
"vitest": "4.1.10"
|
||||
},
|
||||
"ekklesia": {
|
||||
"layer": "module-sdk"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"drizzle-orm": "0.45.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import {
|
||||
type ModuleId,
|
||||
type ModuleSchemaDefinition,
|
||||
moduleTableName,
|
||||
moduleTablePrefix,
|
||||
parseModuleSchemaDefinition,
|
||||
} from "@ekklesia/contracts";
|
||||
import { pgTableCreator } from "drizzle-orm/pg-core";
|
||||
|
||||
export function createModuleTable(moduleId: ModuleId) {
|
||||
moduleTablePrefix(moduleId);
|
||||
return pgTableCreator((localName) => moduleTableName(moduleId, localName));
|
||||
}
|
||||
|
||||
export function defineModuleSchema<const Definition extends ModuleSchemaDefinition>(
|
||||
definition: Definition,
|
||||
): Readonly<Definition> {
|
||||
return parseModuleSchemaDefinition(definition) as Readonly<Definition>;
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "@ekklesia/contracts";
|
||||
export * from "./define-module-runtime.js";
|
||||
export * from "./define-module-schema.js";
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { getTableConfig, integer } from "drizzle-orm/pg-core";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createModuleTable, defineModuleSchema } from "../src/index.js";
|
||||
|
||||
describe("module schema authoring", () => {
|
||||
it("creates namespaced PostgreSQL tables and a typed frozen definition", () => {
|
||||
const moduleTable = createModuleTable("care-team");
|
||||
const members = moduleTable("members", { id: integer().primaryKey() });
|
||||
const definition = defineModuleSchema({
|
||||
moduleId: "care-team",
|
||||
tables: { members },
|
||||
});
|
||||
|
||||
expect(getTableConfig(members).name).toBe("care_team_members");
|
||||
expect(definition.tables.members).toBe(members);
|
||||
expect(Object.isFrozen(definition)).toBe(true);
|
||||
expect(Object.isFrozen(definition.tables)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects invalid module and logical table names", () => {
|
||||
expect(() => createModuleTable("Not Valid")).toThrow();
|
||||
const moduleTable = createModuleTable("example");
|
||||
expect(() => moduleTable("Not Valid", { id: integer() })).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user