feat: add Dashboard navigation as presentation configuration
Phase 6D pass 1. The shell's navigation was a flat list of module ids, which is not a usable experience — and the obvious fix carries an obvious trap. Letting a module declare its folder, or modelling "Media" as something Livestream and Video belong to, turns a rendering preference into architecture: a folder becomes an owner, membership starts to look like a dependency, and the flat module graph acquires a hierarchy nobody decided on. So the rule comes first: a Dashboard group is a label on a rendering bucket. No manifest, no version, no artifact, no API, no lifecycle; nothing depends on it. Livestream depends on Video because it calls Video's functionality, and that orders startup. Livestream is shown under Media, and that orders nothing. No parent module, child module, owning module, or group-derived dependency appears anywhere in the contracts. No manifest change and no version 5. `manifest.name` has been required since version 1 and already is the module's product identity, so the shell renders "Livestream" instead of `livestream` with nothing added. `suggestedGroup` is deliberately deferred rather than shipped: it would force a hard manifest-version cutover for a hint, and its only correct semantics needs initialization logic that risks a suggestion overwriting an administrator's decision. Defaulting and ownership are different things. Two Core tables (migration 0003) hold groups and placements — server-side, because a church configures its Dashboard rather than one browser; platform-global, because no organization model exists to scope them to. `group_id` is `on delete set null`, so deleting a group ungroups its modules and a dangling reference is impossible. `module_id` carries no foreign key, because modules are packages rather than rows, so a placement for an uninstalled module is retained and restores its position on reinstall. `resolveDashboardNavigation` is a pure function of configuration plus the mountable set: an unplaced module is ungrouped and visible with no initialization write, an absent module renders nothing, empty groups are kept, and ordering is total with the module id as final tie-break. `GET /api/v1/dashboard/navigation` returns the resolved view, layered on top of the host-neutral module UI inventory rather than merged into it — each generic descriptor is embedded untouched, so a standalone host never inherits Dashboard semantics. Reading needs the permission the inventory already needs; organizing needs the new platform permission `core.dashboard.navigation.manage` through a narrow, idempotent, closed-validation mutation contract. No editor UI. The flatness rule is executable: a test discovers real fixtures with a genuine dependency, arranges them four ways including both in one folder and the dependency inverted in presentation, and asserts discovery order, dependency declarations, and the module set stay byte-identical. The end-to-end test organizes a real installation through the real API, mounts a module from inside a group, moves it, and asserts the navigation entry is byte-identical across the move and still mounts the same artifact. The shell's client for the generic inventory became dead code and was removed rather than kept speculatively; the endpoint itself is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
ac5b2b7f6c
commit
bd34c9c714
@@ -2,7 +2,11 @@ import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: ["./src/identity/schema.ts", "./src/authorization/schema.ts"],
|
||||
schema: [
|
||||
"./src/identity/schema.ts",
|
||||
"./src/authorization/schema.ts",
|
||||
"./src/dashboard/schema.ts",
|
||||
],
|
||||
out: "./drizzle",
|
||||
migrations: {
|
||||
prefix: "index",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
CREATE TABLE "ekklesia_core_dashboard_group" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"label" text NOT NULL,
|
||||
"sort_order" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "ekklesia_core_dashboard_group_id_check" CHECK (length("ekklesia_core_dashboard_group"."id") > 0),
|
||||
CONSTRAINT "ekklesia_core_dashboard_group_label_check" CHECK (length(btrim("ekklesia_core_dashboard_group"."label")) > 0)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "ekklesia_core_dashboard_placement" (
|
||||
"module_id" text PRIMARY KEY NOT NULL,
|
||||
"group_id" text,
|
||||
"sort_order" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "ekklesia_core_dashboard_placement_module_check" CHECK (length("ekklesia_core_dashboard_placement"."module_id") > 0)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "ekklesia_core_dashboard_placement" ADD CONSTRAINT "ekklesia_core_dashboard_placement_group_id_ekklesia_core_dashboard_group_id_fk" FOREIGN KEY ("group_id") REFERENCES "public"."ekklesia_core_dashboard_group"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "ekklesia_core_dashboard_group_order_idx" ON "ekklesia_core_dashboard_group" USING btree ("sort_order","id");--> statement-breakpoint
|
||||
CREATE INDEX "ekklesia_core_dashboard_placement_group_idx" ON "ekklesia_core_dashboard_placement" USING btree ("group_id","sort_order");
|
||||
@@ -0,0 +1,870 @@
|
||||
{
|
||||
"id": "fd5d1b32-781c-43ed-9d53-98bd5d395e6a",
|
||||
"prevId": "fac36f3d-7551-42df-a967-aad65c2fe7f9",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.ekklesia_core_account": {
|
||||
"name": "ekklesia_core_account",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"account_id": {
|
||||
"name": "account_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"provider_id": {
|
||||
"name": "provider_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"access_token": {
|
||||
"name": "access_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_token": {
|
||||
"name": "refresh_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"id_token": {
|
||||
"name": "id_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"access_token_expires_at": {
|
||||
"name": "access_token_expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_token_expires_at": {
|
||||
"name": "refresh_token_expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"scope": {
|
||||
"name": "scope",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"password": {
|
||||
"name": "password",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_account_user_id_idx": {
|
||||
"name": "ekklesia_core_account_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ekklesia_core_account_user_id_ekklesia_core_user_id_fk": {
|
||||
"name": "ekklesia_core_account_user_id_ekklesia_core_user_id_fk",
|
||||
"tableFrom": "ekklesia_core_account",
|
||||
"tableTo": "ekklesia_core_user",
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_session": {
|
||||
"name": "ekklesia_core_session",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"token": {
|
||||
"name": "token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"ip_address": {
|
||||
"name": "ip_address",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"user_agent": {
|
||||
"name": "user_agent",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_session_user_id_idx": {
|
||||
"name": "ekklesia_core_session_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ekklesia_core_session_user_id_ekklesia_core_user_id_fk": {
|
||||
"name": "ekklesia_core_session_user_id_ekklesia_core_user_id_fk",
|
||||
"tableFrom": "ekklesia_core_session",
|
||||
"tableTo": "ekklesia_core_user",
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"ekklesia_core_session_token_unique": {
|
||||
"name": "ekklesia_core_session_token_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": ["token"]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_user": {
|
||||
"name": "ekklesia_core_user",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"email_verified": {
|
||||
"name": "email_verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"image": {
|
||||
"name": "image",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"ekklesia_core_user_email_unique": {
|
||||
"name": "ekklesia_core_user_email_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": ["email"]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_verification": {
|
||||
"name": "ekklesia_core_verification",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"identifier": {
|
||||
"name": "identifier",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_verification_identifier_idx": {
|
||||
"name": "ekklesia_core_verification_identifier_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "identifier",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_authorization_audit": {
|
||||
"name": "ekklesia_core_authorization_audit",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"action": {
|
||||
"name": "action",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"actor_type": {
|
||||
"name": "actor_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"actor_id": {
|
||||
"name": "actor_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"subject_user_id": {
|
||||
"name": "subject_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"permission_id": {
|
||||
"name": "permission_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"scope": {
|
||||
"name": "scope",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"grant_id": {
|
||||
"name": "grant_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_authorization_audit_subject_idx": {
|
||||
"name": "ekklesia_core_authorization_audit_subject_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "subject_user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_authorization_audit_action_check": {
|
||||
"name": "ekklesia_core_authorization_audit_action_check",
|
||||
"value": "\"ekklesia_core_authorization_audit\".\"action\" in ('grant.create', 'grant.revoke', 'platform_owner.grant', 'platform_owner.revoke')"
|
||||
},
|
||||
"ekklesia_core_authorization_audit_actor_type_check": {
|
||||
"name": "ekklesia_core_authorization_audit_actor_type_check",
|
||||
"value": "\"ekklesia_core_authorization_audit\".\"actor_type\" in ('user', 'system')"
|
||||
},
|
||||
"ekklesia_core_authorization_audit_scope_check": {
|
||||
"name": "ekklesia_core_authorization_audit_scope_check",
|
||||
"value": "\"ekklesia_core_authorization_audit\".\"scope\" is null or length(\"ekklesia_core_authorization_audit\".\"scope\") > 0"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_grant": {
|
||||
"name": "ekklesia_core_grant",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"permission_id": {
|
||||
"name": "permission_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"scope": {
|
||||
"name": "scope",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"source_kind": {
|
||||
"name": "source_kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"source_ref": {
|
||||
"name": "source_ref",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"created_by_actor_type": {
|
||||
"name": "created_by_actor_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_by_actor_id": {
|
||||
"name": "created_by_actor_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_at": {
|
||||
"name": "revoked_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_by_actor_type": {
|
||||
"name": "revoked_by_actor_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_by_actor_id": {
|
||||
"name": "revoked_by_actor_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_grant_user_permission_idx": {
|
||||
"name": "ekklesia_core_grant_user_permission_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "permission_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ekklesia_core_grant_user_id_ekklesia_core_user_id_fk": {
|
||||
"name": "ekklesia_core_grant_user_id_ekklesia_core_user_id_fk",
|
||||
"tableFrom": "ekklesia_core_grant",
|
||||
"tableTo": "ekklesia_core_user",
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_grant_source_kind_check": {
|
||||
"name": "ekklesia_core_grant_source_kind_check",
|
||||
"value": "\"ekklesia_core_grant\".\"source_kind\" in ('explicit', 'relationship')"
|
||||
},
|
||||
"ekklesia_core_grant_created_actor_type_check": {
|
||||
"name": "ekklesia_core_grant_created_actor_type_check",
|
||||
"value": "\"ekklesia_core_grant\".\"created_by_actor_type\" in ('user', 'system')"
|
||||
},
|
||||
"ekklesia_core_grant_revoked_actor_type_check": {
|
||||
"name": "ekklesia_core_grant_revoked_actor_type_check",
|
||||
"value": "\"ekklesia_core_grant\".\"revoked_by_actor_type\" is null or \"ekklesia_core_grant\".\"revoked_by_actor_type\" in ('user', 'system')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_platform_owner": {
|
||||
"name": "ekklesia_core_platform_owner",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"granted_at": {
|
||||
"name": "granted_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"granted_by_actor_type": {
|
||||
"name": "granted_by_actor_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"granted_by_actor_id": {
|
||||
"name": "granted_by_actor_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_at": {
|
||||
"name": "revoked_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_by_actor_type": {
|
||||
"name": "revoked_by_actor_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revoked_by_actor_id": {
|
||||
"name": "revoked_by_actor_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"ekklesia_core_platform_owner_user_id_ekklesia_core_user_id_fk": {
|
||||
"name": "ekklesia_core_platform_owner_user_id_ekklesia_core_user_id_fk",
|
||||
"tableFrom": "ekklesia_core_platform_owner",
|
||||
"tableTo": "ekklesia_core_user",
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_platform_owner_granted_actor_type_check": {
|
||||
"name": "ekklesia_core_platform_owner_granted_actor_type_check",
|
||||
"value": "\"ekklesia_core_platform_owner\".\"granted_by_actor_type\" in ('user', 'system')"
|
||||
},
|
||||
"ekklesia_core_platform_owner_revoked_actor_type_check": {
|
||||
"name": "ekklesia_core_platform_owner_revoked_actor_type_check",
|
||||
"value": "\"ekklesia_core_platform_owner\".\"revoked_by_actor_type\" is null or \"ekklesia_core_platform_owner\".\"revoked_by_actor_type\" in ('user', 'system')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_platform_owner_bootstrap": {
|
||||
"name": "ekklesia_core_platform_owner_bootstrap",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"consumed_at": {
|
||||
"name": "consumed_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"consumed_for_user_id": {
|
||||
"name": "consumed_for_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_platform_owner_bootstrap_singleton_check": {
|
||||
"name": "ekklesia_core_platform_owner_bootstrap_singleton_check",
|
||||
"value": "\"ekklesia_core_platform_owner_bootstrap\".\"id\" = 'singleton'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_dashboard_group": {
|
||||
"name": "ekklesia_core_dashboard_group",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"label": {
|
||||
"name": "label",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "sort_order",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_dashboard_group_order_idx": {
|
||||
"name": "ekklesia_core_dashboard_group_order_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "sort_order",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_dashboard_group_id_check": {
|
||||
"name": "ekklesia_core_dashboard_group_id_check",
|
||||
"value": "length(\"ekklesia_core_dashboard_group\".\"id\") > 0"
|
||||
},
|
||||
"ekklesia_core_dashboard_group_label_check": {
|
||||
"name": "ekklesia_core_dashboard_group_label_check",
|
||||
"value": "length(btrim(\"ekklesia_core_dashboard_group\".\"label\")) > 0"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ekklesia_core_dashboard_placement": {
|
||||
"name": "ekklesia_core_dashboard_placement",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"module_id": {
|
||||
"name": "module_id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"group_id": {
|
||||
"name": "group_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "sort_order",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ekklesia_core_dashboard_placement_group_idx": {
|
||||
"name": "ekklesia_core_dashboard_placement_group_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "group_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "sort_order",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ekklesia_core_dashboard_placement_group_id_ekklesia_core_dashboard_group_id_fk": {
|
||||
"name": "ekklesia_core_dashboard_placement_group_id_ekklesia_core_dashboard_group_id_fk",
|
||||
"tableFrom": "ekklesia_core_dashboard_placement",
|
||||
"tableTo": "ekklesia_core_dashboard_group",
|
||||
"columnsFrom": ["group_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ekklesia_core_dashboard_placement_module_check": {
|
||||
"name": "ekklesia_core_dashboard_placement_module_check",
|
||||
"value": "length(\"ekklesia_core_dashboard_placement\".\"module_id\") > 0"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@
|
||||
"destructive": {
|
||||
"mode": "none"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "0003_dashboard_navigation_tables",
|
||||
"destructive": {
|
||||
"mode": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -22,6 +22,13 @@
|
||||
"when": 1785104670124,
|
||||
"tag": "0002_authorization_integrity",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1787408382271,
|
||||
"tag": "0003_dashboard_navigation_tables",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@
|
||||
"types": "./dist/modules/index.d.ts",
|
||||
"import": "./dist/modules/index.js"
|
||||
},
|
||||
"./dashboard": {
|
||||
"types": "./dist/dashboard/index.d.ts",
|
||||
"import": "./dist/dashboard/index.js"
|
||||
},
|
||||
"./migrations": {
|
||||
"types": "./dist/migrations/index.d.ts",
|
||||
"import": "./dist/migrations/index.js"
|
||||
|
||||
@@ -98,6 +98,19 @@ export const CORE_AUTHORIZATION_GRANTS_MANAGE: PermissionId = parsePermissionId(
|
||||
*/
|
||||
export const CORE_MODULES_UI_READ: PermissionId = parsePermissionId("core.modules.ui.read");
|
||||
|
||||
/**
|
||||
* Restricted: reorganizing the Dashboard is an administrative action, not something every signed-in
|
||||
* user may do. It is deliberately a **platform** permission and never a module's own — grouping is
|
||||
* Ekklesia's presentation configuration, so no module may gate, grant, or influence it (ADR 0027).
|
||||
*
|
||||
* Holding it confers no module authority whatsoever. Moving a module into a folder changes a
|
||||
* presentation row; it grants nobody access to that module's data, and every module route stays
|
||||
* enforced against its own declared permission exactly as before.
|
||||
*/
|
||||
export const CORE_DASHBOARD_NAVIGATION_MANAGE: PermissionId = parsePermissionId(
|
||||
"core.dashboard.navigation.manage",
|
||||
);
|
||||
|
||||
/**
|
||||
* Core's own declarations, exported in deeply immutable form so a trusted composer (the module
|
||||
* integration layer, `core/src/modules/permissions.ts`) can build one combined registry from
|
||||
@@ -116,6 +129,11 @@ export const CORE_PERMISSION_DECLARATIONS: readonly PermissionDeclaration[] = Ob
|
||||
description: "List the installed module UIs a browser host may mount.",
|
||||
id: CORE_MODULES_UI_READ,
|
||||
}),
|
||||
Object.freeze({
|
||||
baseline: "restricted" as const,
|
||||
description: "Organize the Dashboard: create, rename, order, and delete navigation groups.",
|
||||
id: CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./navigation.js";
|
||||
export * from "./schema.js";
|
||||
export * from "./store.js";
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { DashboardConfiguration } from "./store.js";
|
||||
|
||||
/**
|
||||
* One module as the Dashboard needs to present it: its identity, its administrator-visible name,
|
||||
* and nothing about where it lives on disk.
|
||||
*
|
||||
* `name` is the module's own `manifest.name` — its product identity, which every manifest has
|
||||
* already required since version 1. The Dashboard renders it rather than the module id, and a module
|
||||
* declaring it is *not* the module declaring its navigation: a name answers "what is this product
|
||||
* called", while a group answers "where does this church want it", and only the second is
|
||||
* configuration an administrator owns.
|
||||
*/
|
||||
export interface DashboardNavigationModule {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface DashboardNavigationGroupView<Module extends DashboardNavigationModule> {
|
||||
/** The stable key, unchanged by a rename. Callers use it to address the group, never to display. */
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly order: number;
|
||||
readonly modules: readonly Module[];
|
||||
}
|
||||
|
||||
export interface DashboardNavigationView<Module extends DashboardNavigationModule> {
|
||||
readonly groups: readonly DashboardNavigationGroupView<Module>[];
|
||||
/**
|
||||
* Modules that belong to no group: those an administrator deliberately placed outside every group,
|
||||
* and those never configured at all — a newly installed module, most importantly. Both render
|
||||
* here, which is what guarantees a new module is visible the moment it is discovered, with no
|
||||
* initialization write, no manual database edit, and no migration.
|
||||
*/
|
||||
readonly ungrouped: readonly Module[];
|
||||
}
|
||||
|
||||
/** Placed modules first, in the administrator's order; never-configured modules after them, by id.
|
||||
* A newcomer therefore appears without interrupting an ordering someone chose, and the module id is
|
||||
* always the final tie-break, so two modules sharing a `sortOrder` still order identically on every
|
||||
* request and in every process. */
|
||||
interface SortKey {
|
||||
readonly configured: 0 | 1;
|
||||
readonly order: number;
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
function compareSortKeys(left: SortKey, right: SortKey): number {
|
||||
if (left.configured !== right.configured) {
|
||||
return left.configured - right.configured;
|
||||
}
|
||||
if (left.order !== right.order) {
|
||||
return left.order - right.order;
|
||||
}
|
||||
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves stored Dashboard configuration against the modules that are actually mountable right now.
|
||||
*
|
||||
* Pure and synchronous: no database, no filesystem, no clock, no module code. It is given the stored
|
||||
* arrangement and the current module set and returns what to render, so every rule below is
|
||||
* directly testable without PostgreSQL.
|
||||
*
|
||||
* ## The rules, exactly
|
||||
*
|
||||
* - **A module with no placement is ungrouped and visible.** Nothing is written to make that true.
|
||||
* Installing a module is enough to see it; an administrator moves it afterwards if they want to.
|
||||
* - **A stored placement for a module that is not installed renders nothing, and is retained.** The
|
||||
* store keeps the row, so uninstalling and reinstalling a module restores its position rather than
|
||||
* silently resetting it. A dead navigation entry never appears.
|
||||
* - **A placement naming a group that no longer exists cannot occur** — the schema's
|
||||
* `on delete set null` makes the module ungrouped when its group is deleted — but if one somehow
|
||||
* did, it is treated as ungrouped rather than dropped, so no module can be made invisible by a
|
||||
* configuration inconsistency.
|
||||
* - **Empty groups are kept.** A group an administrator created and has not filled yet, or whose
|
||||
* only module is temporarily uninstalled, still renders; hiding it would look like the group had
|
||||
* been deleted.
|
||||
* - **Ordering is total.** Groups by `(order, id)`; modules by `(configured, order, id)`. Colliding
|
||||
* order values never produce a nondeterministic result.
|
||||
*
|
||||
* ## What this function structurally cannot do
|
||||
*
|
||||
* It never reads a manifest, a dependency, a capability, an entrypoint, or a permission, and it
|
||||
* returns no edge between two modules. Two modules sharing a group are exactly as related as two
|
||||
* modules that do not: grouping is a rendering decision computed here, downstream of everything that
|
||||
* decides what a module *is* (ADR 0027). Nothing upstream — discovery, dependency ordering, runtime
|
||||
* startup, authorization — ever calls this.
|
||||
*/
|
||||
export function resolveDashboardNavigation<Module extends DashboardNavigationModule>(
|
||||
configuration: DashboardConfiguration,
|
||||
mountableModules: readonly Module[],
|
||||
): DashboardNavigationView<Module> {
|
||||
const placementsByModuleId = new Map(
|
||||
configuration.placements.map((placement) => [placement.moduleId, placement] as const),
|
||||
);
|
||||
const groupIds = new Set(configuration.groups.map((group) => group.id));
|
||||
|
||||
const modulesByGroupId = new Map<string, Array<{ key: SortKey; module: Module }>>();
|
||||
const ungrouped: Array<{ key: SortKey; module: Module }> = [];
|
||||
|
||||
for (const module of mountableModules) {
|
||||
const placement = placementsByModuleId.get(module.id);
|
||||
const key: SortKey = {
|
||||
configured: placement ? 0 : 1,
|
||||
id: module.id,
|
||||
order: placement?.sortOrder ?? 0,
|
||||
};
|
||||
const groupId =
|
||||
placement?.groupId !== undefined &&
|
||||
placement.groupId !== null &&
|
||||
groupIds.has(placement.groupId)
|
||||
? placement.groupId
|
||||
: undefined;
|
||||
if (groupId === undefined) {
|
||||
ungrouped.push({ key, module });
|
||||
continue;
|
||||
}
|
||||
const bucket = modulesByGroupId.get(groupId);
|
||||
if (bucket) {
|
||||
bucket.push({ key, module });
|
||||
} else {
|
||||
modulesByGroupId.set(groupId, [{ key, module }]);
|
||||
}
|
||||
}
|
||||
|
||||
const sortModules = (entries: Array<{ key: SortKey; module: Module }>): readonly Module[] =>
|
||||
Object.freeze(
|
||||
[...entries]
|
||||
.sort((left, right) => compareSortKeys(left.key, right.key))
|
||||
.map((entry) => entry.module),
|
||||
);
|
||||
|
||||
const groups = [...configuration.groups]
|
||||
.sort((left, right) =>
|
||||
left.sortOrder !== right.sortOrder
|
||||
? left.sortOrder - right.sortOrder
|
||||
: left.id < right.id
|
||||
? -1
|
||||
: left.id > right.id
|
||||
? 1
|
||||
: 0,
|
||||
)
|
||||
.map((group) =>
|
||||
Object.freeze({
|
||||
id: group.id,
|
||||
label: group.label,
|
||||
modules: sortModules(modulesByGroupId.get(group.id) ?? []),
|
||||
order: group.sortOrder,
|
||||
}),
|
||||
);
|
||||
|
||||
return Object.freeze({
|
||||
groups: Object.freeze(groups),
|
||||
ungrouped: sortModules(ungrouped),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { check, index, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
||||
|
||||
/**
|
||||
* Core-owned storage for how the Ekklesia Dashboard *presents* installed modules.
|
||||
*
|
||||
* This is presentation configuration, and it is deliberately the only thing here. A group owns no
|
||||
* tables, no migrations, no routes, and no lifecycle; it never participates in dependency
|
||||
* resolution, discovery order, or module startup. **Modules stay flat** (ADR 0021): there is no
|
||||
* parent module, no child module, no owning module, and nothing in this schema is ever read by
|
||||
* anything that decides what a module may do or when it starts. Moving a module between groups
|
||||
* changes a row here and nothing else.
|
||||
*
|
||||
* Core stores this; it renders nothing. `surfaces/shell` decides what the arrangement looks like.
|
||||
*
|
||||
* Platform-global, because Ekklesia has no organization or tenant model to scope it to. When one
|
||||
* exists, these two tables gain a scope column; inventing a second notion of organization here to
|
||||
* anticipate it would be worse than adding a column later.
|
||||
*
|
||||
* Table and index names are explicit and namespaced exactly like `core/src/authorization/schema.ts`,
|
||||
* so ownership is unambiguous inside the shared public PostgreSQL schema.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A Dashboard navigation group — "Media", "Planning", "Sunday Production".
|
||||
*
|
||||
* `id` is an **opaque, stable key**, never displayed and never re-derived from `label`. Renaming a
|
||||
* group changes only `label`, so every placement pointing at it survives untouched; that invariant
|
||||
* is what keeps a rename from silently re-organizing the Dashboard. A slug is used rather than a
|
||||
* generated UUID purely so the configuration API and its tests stay legible — it carries no meaning
|
||||
* the platform reads.
|
||||
*
|
||||
* There is no parent group column. Nesting is deliberately out of scope, and leaving the shape flat
|
||||
* is what keeps it out.
|
||||
*/
|
||||
export const ekklesiaCoreDashboardGroup = pgTable(
|
||||
"ekklesia_core_dashboard_group",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
label: text("label").notNull(),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index("ekklesia_core_dashboard_group_order_idx").on(table.sortOrder, table.id),
|
||||
// Defense in depth beneath the application-layer identifier and label contracts, which never
|
||||
// produce either of these: an empty id would be an unaddressable group, and an empty or
|
||||
// whitespace-only label would render as a blank heading no administrator could find again.
|
||||
check("ekklesia_core_dashboard_group_id_check", sql`length(${table.id}) > 0`),
|
||||
check("ekklesia_core_dashboard_group_label_check", sql`length(btrim(${table.label})) > 0`),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Where one module sits in the Dashboard. One row per module at most — the primary key enforces it
|
||||
* — so a module can never be placed in two groups, which is the database-level expression of "one
|
||||
* level of grouping, and no module ownership graph."
|
||||
*
|
||||
* `group_id` is nullable and that is a real state, not a missing value: **ungrouped is a placement**,
|
||||
* chosen by an administrator who ordered a module outside every group. A module with no row at all
|
||||
* is a different state — never configured — and both render in the same ungrouped area (see
|
||||
* `../dashboard/navigation.js` for the exact ordering rule).
|
||||
*
|
||||
* `on delete set null` is what makes group deletion safe: deleting a group cannot leave a dangling
|
||||
* reference, and its modules become ungrouped rather than disappearing. That is enforced by the
|
||||
* database, not by application cleanup that could be skipped.
|
||||
*
|
||||
* `module_id` deliberately carries **no foreign key to any module**, because modules are not rows —
|
||||
* they are packages discovered on disk at startup. A placement for a module that is not installed
|
||||
* is therefore normal and is retained: uninstalling and reinstalling a module keeps its position
|
||||
* rather than silently resetting it. Nothing renders such a row (see `resolveDashboardNavigation`).
|
||||
*/
|
||||
export const ekklesiaCoreDashboardPlacement = pgTable(
|
||||
"ekklesia_core_dashboard_placement",
|
||||
{
|
||||
moduleId: text("module_id").primaryKey(),
|
||||
groupId: text("group_id").references(() => ekklesiaCoreDashboardGroup.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index("ekklesia_core_dashboard_placement_group_idx").on(table.groupId, table.sortOrder),
|
||||
check("ekklesia_core_dashboard_placement_module_check", sql`length(${table.moduleId}) > 0`),
|
||||
],
|
||||
);
|
||||
|
||||
/** Explicit map passed to Drizzle, mirroring `authorizationSchema`'s explicit-mapping style. */
|
||||
export const dashboardSchema = {
|
||||
dashboardGroup: ekklesiaCoreDashboardGroup,
|
||||
dashboardPlacement: ekklesiaCoreDashboardPlacement,
|
||||
} as const;
|
||||
@@ -0,0 +1,314 @@
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import type { Pool } from "pg";
|
||||
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
import {
|
||||
dashboardSchema,
|
||||
ekklesiaCoreDashboardGroup,
|
||||
ekklesiaCoreDashboardPlacement,
|
||||
} from "./schema.js";
|
||||
|
||||
export type DashboardDrizzleDatabase = NodePgDatabase<typeof dashboardSchema>;
|
||||
|
||||
/**
|
||||
* A typed Drizzle view over an externally owned pool, exactly like `createAuthorizationDrizzleView`:
|
||||
* it never constructs, registers an error listener on, or closes a pool. The caller owns the pool
|
||||
* once, however many typed views it creates over it.
|
||||
*/
|
||||
export function createDashboardDrizzleView(pool: Pool): DashboardDrizzleDatabase {
|
||||
return drizzle(pool, { schema: dashboardSchema });
|
||||
}
|
||||
|
||||
/** Bounds every stored ordering value. Wide enough that an administrator never runs out of room
|
||||
* between two entries, small enough that a client cannot store a value that surprises a later
|
||||
* integer column. Enforced identically by the store and by the HTTP surface, so there is one bound
|
||||
* rather than two that could drift. */
|
||||
export const DASHBOARD_SORT_ORDER_MIN = 0;
|
||||
export const DASHBOARD_SORT_ORDER_MAX = 1_000_000;
|
||||
|
||||
/** The label an administrator sees. Bounded like every other operator-facing string in the
|
||||
* platform; `moduleManifestSchema.name` uses the same ceiling. */
|
||||
export const DASHBOARD_GROUP_LABEL_MAX_LENGTH = 120;
|
||||
|
||||
/** Lowercase kebab-case, matching `moduleIdSchema`'s grammar so the platform has one identifier
|
||||
* shape rather than two. Opaque: never displayed, never parsed for meaning, never re-derived from a
|
||||
* label. */
|
||||
const GROUP_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
|
||||
const GROUP_ID_MAX_LENGTH = 64;
|
||||
|
||||
/** The one identifier grammar for both a group id and a placement's module id, exported so the HTTP
|
||||
* boundary rejects malformed input with a request error *before* reaching the store rather than
|
||||
* relying on mapping a store failure back to a status code — and so there is one grammar rather
|
||||
* than two that could drift. */
|
||||
export function isValidDashboardIdentifier(value: unknown): value is string {
|
||||
return (
|
||||
typeof value === "string" && value.length <= GROUP_ID_MAX_LENGTH && GROUP_ID_PATTERN.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
/** The one label rule, exported for the same reason. Returns the trimmed value the store would
|
||||
* persist, or `undefined` when the label is empty, whitespace-only, or too long. */
|
||||
export function normalizeDashboardGroupLabel(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length === 0 || trimmed.length > DASHBOARD_GROUP_LABEL_MAX_LENGTH
|
||||
? undefined
|
||||
: trimmed;
|
||||
}
|
||||
|
||||
export type DashboardStoreErrorCode =
|
||||
| "DASHBOARD_GROUP_ID_INVALID"
|
||||
| "DASHBOARD_GROUP_LABEL_INVALID"
|
||||
| "DASHBOARD_GROUP_NOT_FOUND"
|
||||
| "DASHBOARD_MODULE_ID_INVALID"
|
||||
| "DASHBOARD_SORT_ORDER_INVALID"
|
||||
| "DASHBOARD_READ_FAILED"
|
||||
| "DASHBOARD_WRITE_FAILED";
|
||||
|
||||
const storeErrorMessages: Readonly<Record<DashboardStoreErrorCode, string>> = Object.freeze({
|
||||
DASHBOARD_GROUP_ID_INVALID: "A Dashboard group identifier must be lowercase kebab-case.",
|
||||
DASHBOARD_GROUP_LABEL_INVALID: "A Dashboard group label must be non-empty and bounded.",
|
||||
DASHBOARD_GROUP_NOT_FOUND: "The Dashboard group was not found.",
|
||||
DASHBOARD_MODULE_ID_INVALID: "A Dashboard placement module identifier is invalid.",
|
||||
DASHBOARD_READ_FAILED: "The Dashboard navigation configuration could not be read.",
|
||||
DASHBOARD_SORT_ORDER_INVALID: "A Dashboard ordering value is out of range.",
|
||||
DASHBOARD_WRITE_FAILED: "The Dashboard navigation configuration could not be saved.",
|
||||
});
|
||||
|
||||
/** Never carries the underlying database error, SQL text, host, or stack — matching
|
||||
* `AuthorizationStoreError` exactly. */
|
||||
export class DashboardStoreError extends Error {
|
||||
readonly code: DashboardStoreErrorCode;
|
||||
|
||||
constructor(code: DashboardStoreErrorCode) {
|
||||
super(storeErrorMessages[code]);
|
||||
this.name = "DashboardStoreError";
|
||||
this.code = code;
|
||||
this.stack = `${this.name}: ${this.message}`;
|
||||
Object.freeze(this);
|
||||
}
|
||||
}
|
||||
|
||||
/** A stored group. `label` is what an administrator sees; `id` is the stable key placements point
|
||||
* at, and a rename never touches it. */
|
||||
export interface DashboardGroupRecord {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly sortOrder: number;
|
||||
}
|
||||
|
||||
/** Where one module sits. `groupId: null` is a real, chosen state — deliberately ungrouped — and is
|
||||
* distinct from having no record at all, which means never configured. */
|
||||
export interface DashboardPlacementRecord {
|
||||
readonly moduleId: string;
|
||||
readonly groupId: string | null;
|
||||
readonly sortOrder: number;
|
||||
}
|
||||
|
||||
/** The complete stored arrangement. Contains no module facts whatsoever: resolving it against the
|
||||
* modules that actually exist is `resolveDashboardNavigation`'s job, not the store's. */
|
||||
export interface DashboardConfiguration {
|
||||
readonly groups: readonly DashboardGroupRecord[];
|
||||
readonly placements: readonly DashboardPlacementRecord[];
|
||||
}
|
||||
|
||||
export interface UpsertDashboardGroupInput {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly sortOrder: number;
|
||||
}
|
||||
|
||||
export interface SetDashboardPlacementInput {
|
||||
readonly moduleId: string;
|
||||
/** `null` places the module in the ungrouped area deliberately. A group id that does not exist is
|
||||
* rejected rather than stored, so a placement can never point at a group that was never created. */
|
||||
readonly groupId: string | null;
|
||||
readonly sortOrder: number;
|
||||
}
|
||||
|
||||
export interface DashboardStore {
|
||||
/** The whole stored arrangement, in deterministic order. Small by nature — one row per group and
|
||||
* at most one per module — so it is read whole rather than paginated. */
|
||||
readConfiguration(): Promise<DashboardConfiguration>;
|
||||
/** Creates the group or replaces its label and order. Idempotent: the same input twice leaves the
|
||||
* same single row, and placements pointing at it are untouched either way. */
|
||||
upsertGroup(input: UpsertDashboardGroupInput): Promise<DashboardGroupRecord>;
|
||||
/** Deletes a group. Its placements become ungrouped through the schema's `on delete set null`, so
|
||||
* no dangling reference is possible and no module is lost. */
|
||||
deleteGroup(groupId: string): Promise<void>;
|
||||
/** Creates or replaces one module's placement. */
|
||||
setPlacement(input: SetDashboardPlacementInput): Promise<DashboardPlacementRecord>;
|
||||
}
|
||||
|
||||
function assertValidGroupId(value: string): void {
|
||||
if (!isValidDashboardIdentifier(value)) {
|
||||
throw new DashboardStoreError("DASHBOARD_GROUP_ID_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function assertValidModuleId(value: string): void {
|
||||
if (!isValidDashboardIdentifier(value)) {
|
||||
throw new DashboardStoreError("DASHBOARD_MODULE_ID_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function normalizedLabel(value: string): string {
|
||||
const trimmed = normalizeDashboardGroupLabel(value);
|
||||
if (trimmed === undefined) {
|
||||
throw new DashboardStoreError("DASHBOARD_GROUP_LABEL_INVALID");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function assertValidSortOrder(value: number): void {
|
||||
if (
|
||||
!Number.isSafeInteger(value) ||
|
||||
value < DASHBOARD_SORT_ORDER_MIN ||
|
||||
value > DASHBOARD_SORT_ORDER_MAX
|
||||
) {
|
||||
throw new DashboardStoreError("DASHBOARD_SORT_ORDER_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function rethrowAsStoreError(error: unknown, code: DashboardStoreErrorCode): never {
|
||||
if (error instanceof DashboardStoreError) {
|
||||
throw error;
|
||||
}
|
||||
throw new DashboardStoreError(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Core's persistence for Dashboard navigation configuration.
|
||||
*
|
||||
* Validation lives here rather than only at the HTTP boundary, so the invariants hold for any
|
||||
* caller: identifiers are checked against one grammar, labels are trimmed and bounded, ordering is
|
||||
* a bounded safe integer, and a placement may only name a group that exists. Nothing here reads,
|
||||
* imports, or reasons about a module — a placement is a `module_id` string and no more — which is
|
||||
* what keeps grouping structurally incapable of influencing discovery, dependency resolution, or
|
||||
* startup order.
|
||||
*/
|
||||
export function createDashboardStore(db: DashboardDrizzleDatabase): DashboardStore {
|
||||
return Object.freeze({
|
||||
async readConfiguration(): Promise<DashboardConfiguration> {
|
||||
try {
|
||||
const [groups, placements] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: ekklesiaCoreDashboardGroup.id,
|
||||
label: ekklesiaCoreDashboardGroup.label,
|
||||
sortOrder: ekklesiaCoreDashboardGroup.sortOrder,
|
||||
})
|
||||
.from(ekklesiaCoreDashboardGroup)
|
||||
.orderBy(asc(ekklesiaCoreDashboardGroup.sortOrder), asc(ekklesiaCoreDashboardGroup.id)),
|
||||
db
|
||||
.select({
|
||||
groupId: ekklesiaCoreDashboardPlacement.groupId,
|
||||
moduleId: ekklesiaCoreDashboardPlacement.moduleId,
|
||||
sortOrder: ekklesiaCoreDashboardPlacement.sortOrder,
|
||||
})
|
||||
.from(ekklesiaCoreDashboardPlacement)
|
||||
.orderBy(
|
||||
asc(ekklesiaCoreDashboardPlacement.sortOrder),
|
||||
asc(ekklesiaCoreDashboardPlacement.moduleId),
|
||||
),
|
||||
]);
|
||||
return Object.freeze({
|
||||
groups: Object.freeze(groups.map((group) => Object.freeze({ ...group }))),
|
||||
placements: Object.freeze(placements.map((placement) => Object.freeze({ ...placement }))),
|
||||
});
|
||||
} catch (error) {
|
||||
rethrowAsStoreError(error, "DASHBOARD_READ_FAILED");
|
||||
}
|
||||
},
|
||||
|
||||
async upsertGroup(input: UpsertDashboardGroupInput): Promise<DashboardGroupRecord> {
|
||||
assertValidGroupId(input.id);
|
||||
const label = normalizedLabel(input.label);
|
||||
assertValidSortOrder(input.sortOrder);
|
||||
try {
|
||||
// A rename updates `label` and `sort_order` only. `id` is the conflict target, so it is
|
||||
// never rewritten and every placement pointing at this group keeps pointing at it.
|
||||
const [row] = await db
|
||||
.insert(ekklesiaCoreDashboardGroup)
|
||||
.values({ id: input.id, label, sortOrder: input.sortOrder })
|
||||
.onConflictDoUpdate({
|
||||
set: { label, sortOrder: input.sortOrder, updatedAt: new Date() },
|
||||
target: ekklesiaCoreDashboardGroup.id,
|
||||
})
|
||||
.returning({
|
||||
id: ekklesiaCoreDashboardGroup.id,
|
||||
label: ekklesiaCoreDashboardGroup.label,
|
||||
sortOrder: ekklesiaCoreDashboardGroup.sortOrder,
|
||||
});
|
||||
if (!row) {
|
||||
throw new DashboardStoreError("DASHBOARD_WRITE_FAILED");
|
||||
}
|
||||
return Object.freeze(row);
|
||||
} catch (error) {
|
||||
rethrowAsStoreError(error, "DASHBOARD_WRITE_FAILED");
|
||||
}
|
||||
},
|
||||
|
||||
async deleteGroup(groupId: string): Promise<void> {
|
||||
assertValidGroupId(groupId);
|
||||
try {
|
||||
const deleted = await db
|
||||
.delete(ekklesiaCoreDashboardGroup)
|
||||
.where(eq(ekklesiaCoreDashboardGroup.id, groupId))
|
||||
.returning({ id: ekklesiaCoreDashboardGroup.id });
|
||||
if (deleted.length === 0) {
|
||||
throw new DashboardStoreError("DASHBOARD_GROUP_NOT_FOUND");
|
||||
}
|
||||
} catch (error) {
|
||||
rethrowAsStoreError(error, "DASHBOARD_WRITE_FAILED");
|
||||
}
|
||||
},
|
||||
|
||||
async setPlacement(input: SetDashboardPlacementInput): Promise<DashboardPlacementRecord> {
|
||||
assertValidModuleId(input.moduleId);
|
||||
assertValidSortOrder(input.sortOrder);
|
||||
if (input.groupId !== null) {
|
||||
assertValidGroupId(input.groupId);
|
||||
}
|
||||
try {
|
||||
// Checked in the application rather than left to the foreign key so the caller gets
|
||||
// `DASHBOARD_GROUP_NOT_FOUND` instead of a driver error. The foreign key remains the
|
||||
// authority: a group deleted concurrently still fails the insert rather than storing a
|
||||
// dangling reference.
|
||||
if (input.groupId !== null) {
|
||||
const existing = await db
|
||||
.select({ id: ekklesiaCoreDashboardGroup.id })
|
||||
.from(ekklesiaCoreDashboardGroup)
|
||||
.where(eq(ekklesiaCoreDashboardGroup.id, input.groupId))
|
||||
.limit(1);
|
||||
if (existing.length === 0) {
|
||||
throw new DashboardStoreError("DASHBOARD_GROUP_NOT_FOUND");
|
||||
}
|
||||
}
|
||||
const [row] = await db
|
||||
.insert(ekklesiaCoreDashboardPlacement)
|
||||
.values({
|
||||
groupId: input.groupId,
|
||||
moduleId: input.moduleId,
|
||||
sortOrder: input.sortOrder,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
set: { groupId: input.groupId, sortOrder: input.sortOrder, updatedAt: new Date() },
|
||||
target: ekklesiaCoreDashboardPlacement.moduleId,
|
||||
})
|
||||
.returning({
|
||||
groupId: ekklesiaCoreDashboardPlacement.groupId,
|
||||
moduleId: ekklesiaCoreDashboardPlacement.moduleId,
|
||||
sortOrder: ekklesiaCoreDashboardPlacement.sortOrder,
|
||||
});
|
||||
if (!row) {
|
||||
throw new DashboardStoreError("DASHBOARD_WRITE_FAILED");
|
||||
}
|
||||
return Object.freeze(row);
|
||||
} catch (error) {
|
||||
rethrowAsStoreError(error, "DASHBOARD_WRITE_FAILED");
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -14,6 +14,16 @@ import type { DiscoveredModule } from "./discovery.js";
|
||||
export interface PublishableModuleUi {
|
||||
readonly moduleId: string;
|
||||
readonly version: string;
|
||||
/**
|
||||
* The module's own `manifest.name` — its product identity, required by every manifest version and
|
||||
* therefore available without any manifest change (ADR 0027).
|
||||
*
|
||||
* Carried here so a host can render something a person recognizes instead of a module id. It is
|
||||
* presentation *identity*, not presentation *placement*: a module says what it is called, while
|
||||
* where it appears in a Dashboard is configuration an administrator owns. Nothing about grouping,
|
||||
* ordering, or navigation belongs on this record.
|
||||
*/
|
||||
readonly name: string;
|
||||
readonly artifactPath: string;
|
||||
/**
|
||||
* The module's own manifest-declared permissions, carried here so a publisher can compute the
|
||||
@@ -92,6 +102,7 @@ export function createModuleUiPublicationRegistry(
|
||||
Object.freeze({
|
||||
artifactPath,
|
||||
moduleId: module.manifest.id,
|
||||
name: module.manifest.name,
|
||||
// Already deeply frozen by discovery; copied into a fresh frozen array so a caller holding
|
||||
// this record can never reach the manifest object graph itself.
|
||||
permissions: Object.freeze([...module.manifest.permissions]),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { parsePermissionId } from "@ekklesia/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CORE_AUTHORIZATION_GRANTS_MANAGE,
|
||||
CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
CORE_MODULES_UI_READ,
|
||||
CORE_PERMISSION_DECLARATIONS,
|
||||
CORE_PERMISSION_REGISTRY,
|
||||
@@ -100,10 +101,20 @@ describe("CORE_PERMISSION_REGISTRY", () => {
|
||||
expect(declaration?.id).toBe("core.modules.ui.read");
|
||||
});
|
||||
|
||||
it("contains exactly these two permissions and no others", () => {
|
||||
it("registers core.dashboard.navigation.manage as restricted", () => {
|
||||
const declaration = CORE_PERMISSION_REGISTRY.get(CORE_DASHBOARD_NAVIGATION_MANAGE);
|
||||
expect(declaration).toBeDefined();
|
||||
// Reorganizing the Dashboard is administrative, not something every signed-in user may do —
|
||||
// unlike merely reading which module UIs exist (ADR 0027).
|
||||
expect(declaration?.baseline).toBe("restricted");
|
||||
expect(declaration?.id).toBe("core.dashboard.navigation.manage");
|
||||
});
|
||||
|
||||
it("contains exactly these three permissions and no others", () => {
|
||||
expect(CORE_PERMISSION_REGISTRY.declarations.map((declaration) => declaration.id)).toEqual([
|
||||
CORE_AUTHORIZATION_GRANTS_MANAGE,
|
||||
CORE_MODULES_UI_READ,
|
||||
CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -121,10 +132,16 @@ describe("CORE_PERMISSION_DECLARATIONS", () => {
|
||||
description: "List the installed module UIs a browser host may mount.",
|
||||
id: CORE_MODULES_UI_READ,
|
||||
},
|
||||
{
|
||||
baseline: "restricted",
|
||||
description: "Organize the Dashboard: create, rename, order, and delete navigation groups.",
|
||||
id: CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
},
|
||||
]);
|
||||
expect(Object.isFrozen(CORE_PERMISSION_DECLARATIONS)).toBe(true);
|
||||
expect(Object.isFrozen(CORE_PERMISSION_DECLARATIONS[0])).toBe(true);
|
||||
expect(Object.isFrozen(CORE_PERMISSION_DECLARATIONS[1])).toBe(true);
|
||||
expect(Object.isFrozen(CORE_PERMISSION_DECLARATIONS[2])).toBe(true);
|
||||
});
|
||||
|
||||
it("matches exactly what CORE_PERMISSION_REGISTRY exposes as its own declarations, so a composer building on top of it never diverges from what Core itself registers", () => {
|
||||
|
||||
@@ -173,6 +173,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
|
||||
"core:0000_identity_core_tables",
|
||||
"core:0001_authorization_core_tables",
|
||||
"core:0002_authorization_integrity",
|
||||
"core:0003_dashboard_navigation_tables",
|
||||
]);
|
||||
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
|
||||
} finally {
|
||||
@@ -207,7 +208,7 @@ describe.sequential("live Core authorization store", () => {
|
||||
const scope: AuthorizationScope = parseAuthorizationScope("calendar-event:123");
|
||||
const actor = createUserActor("authz_user_two"); // an operator/admin user distinct from the subject
|
||||
|
||||
it("applies a fresh migration and creates exactly the three authorization tables with their constraints", async () => {
|
||||
it("applies a fresh migration and creates exactly the expected Core tables with their constraints", async () => {
|
||||
database = await createDisposableDatabase("fresh");
|
||||
await applyCoreMigrations(database.url);
|
||||
|
||||
@@ -218,9 +219,13 @@ describe.sequential("live Core authorization store", () => {
|
||||
where table_schema = 'public' and table_name like 'ekklesia_core_%'
|
||||
order by table_name`,
|
||||
);
|
||||
// The complete Core schema after every migration, asserted exactly so a new table is a
|
||||
// deliberate change here rather than an unnoticed one.
|
||||
expect(tables.map((row) => row.table_name)).toEqual([
|
||||
"ekklesia_core_account",
|
||||
"ekklesia_core_authorization_audit",
|
||||
"ekklesia_core_dashboard_group",
|
||||
"ekklesia_core_dashboard_placement",
|
||||
"ekklesia_core_grant",
|
||||
"ekklesia_core_migrations",
|
||||
"ekklesia_core_platform_owner",
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { type DashboardConfiguration, resolveDashboardNavigation } from "../src/dashboard/index.js";
|
||||
import {
|
||||
createModuleUiPublicationRegistry,
|
||||
type DiscoveredModule,
|
||||
discoverModules,
|
||||
} from "../src/modules/index.js";
|
||||
|
||||
/**
|
||||
* The executable form of the architecture's central rule: **Dashboard grouping is presentation
|
||||
* configuration and can never become module structure** (ADR 0021, ADR 0027).
|
||||
*
|
||||
* These run real discovery over real fixtures, including a genuine module dependency, and then
|
||||
* arrange those modules into folders in several different ways. Everything discovery decides —
|
||||
* which modules exist, what depends on what, and the order they must start in — has to come out
|
||||
* byte-identical every time. A future change that let a group influence any of that fails here.
|
||||
*/
|
||||
const temporaryDirectories: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporaryDirectories
|
||||
.splice(0)
|
||||
.map((directory) => rm(directory, { force: true, recursive: true })),
|
||||
);
|
||||
});
|
||||
|
||||
interface ModuleFixture {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
/** A *real* technical dependency — one module calling another's functionality — expressed through
|
||||
* the existing module dependency contract, which is the only kind of module relationship that
|
||||
* exists. */
|
||||
readonly dependsOn?: string;
|
||||
}
|
||||
|
||||
async function createModule(modulesDirectory: string, fixture: ModuleFixture): Promise<void> {
|
||||
const moduleDirectory = path.join(modulesDirectory, fixture.id);
|
||||
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
|
||||
await mkdir(path.join(moduleDirectory, "dist/ui"), { recursive: true });
|
||||
await writeFile(
|
||||
path.join(moduleDirectory, "package.json"),
|
||||
JSON.stringify({
|
||||
ekklesia: { layer: "module" },
|
||||
name: `@test/module-${fixture.id}`,
|
||||
type: "module",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(moduleDirectory, "ekklesia.module.json"),
|
||||
JSON.stringify({
|
||||
compatibility: { moduleSdk: "^0.1.0", platform: "^0.1.0" },
|
||||
...(fixture.dependsOn
|
||||
? { dependencies: { modules: { required: { [fixture.dependsOn]: "^1.0.0" } } } }
|
||||
: {}),
|
||||
entrypoints: { server: "./dist/server/index.js", ui: "./dist/ui/index.js" },
|
||||
id: fixture.id,
|
||||
manifestVersion: 4,
|
||||
name: fixture.name,
|
||||
version: "1.0.0",
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(moduleDirectory, "dist/server/index.js"),
|
||||
`export default { id: ${JSON.stringify(fixture.id)}, version: "1.0.0" };`,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(moduleDirectory, "dist/ui/index.js"),
|
||||
`export default { id: ${JSON.stringify(fixture.id)}, version: "1.0.0", mount() {} };\n`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Livestream genuinely depends on Video — it calls Video's functionality — so discovery must order
|
||||
* Video first. Calendar depends on nothing. This is the *only* kind of relationship modules have. */
|
||||
async function discoverFixtures(): Promise<readonly DiscoveredModule[]> {
|
||||
const modulesDirectory = await mkdtemp(path.join(tmpdir(), "ekklesia-flat-modules-"));
|
||||
temporaryDirectories.push(modulesDirectory);
|
||||
await createModule(modulesDirectory, { id: "video", name: "Video" });
|
||||
await createModule(modulesDirectory, {
|
||||
dependsOn: "video",
|
||||
id: "livestream",
|
||||
name: "Livestream",
|
||||
});
|
||||
await createModule(modulesDirectory, { id: "calendar", name: "Calendar" });
|
||||
return discoverModules({
|
||||
moduleSdkVersion: "0.1.0",
|
||||
modulesDirectory,
|
||||
platformVersion: "0.1.0",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Four arrangements of the same three modules, including the one the architecture warns about:
|
||||
* Livestream and Video together under "Media", which must **not** create a Media module or a
|
||||
* dependency between them.
|
||||
*/
|
||||
const arrangements: ReadonlyArray<readonly [string, DashboardConfiguration]> = [
|
||||
["nothing configured", { groups: [], placements: [] }],
|
||||
[
|
||||
"Media over Planning",
|
||||
{
|
||||
groups: [
|
||||
{ id: "media", label: "Media", sortOrder: 10 },
|
||||
{ id: "planning", label: "Planning", sortOrder: 20 },
|
||||
],
|
||||
placements: [
|
||||
{ groupId: "media", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 20 },
|
||||
{ groupId: "planning", moduleId: "calendar", sortOrder: 10 },
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"Livestream moved to Sunday Production, away from Video",
|
||||
{
|
||||
groups: [
|
||||
{ id: "media", label: "Media", sortOrder: 10 },
|
||||
{ id: "sunday-production", label: "Sunday Production", sortOrder: 5 },
|
||||
],
|
||||
placements: [
|
||||
{ groupId: "sunday-production", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 10 },
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"the dependency inverted in presentation: Video grouped under Livestream's folder alone",
|
||||
{
|
||||
groups: [{ id: "streaming", label: "Streaming", sortOrder: 1 }],
|
||||
placements: [{ groupId: "streaming", moduleId: "video", sortOrder: 10 }],
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
describe("Dashboard grouping never becomes module structure", () => {
|
||||
it("orders discovery by real dependencies, which is the only module relationship", async () => {
|
||||
const discovered = await discoverFixtures();
|
||||
|
||||
// Video before Livestream because Livestream *depends* on it — not because of any folder.
|
||||
expect(discovered.map((module) => module.manifest.id)).toEqual([
|
||||
"calendar",
|
||||
"video",
|
||||
"livestream",
|
||||
]);
|
||||
expect(
|
||||
discovered.find((module) => module.manifest.id === "livestream")?.manifest.dependencies,
|
||||
).toMatchObject({ modules: { required: { video: "^1.0.0" } } });
|
||||
});
|
||||
|
||||
it("leaves discovery, dependencies, and start order identical under every arrangement", async () => {
|
||||
const discovered = await discoverFixtures();
|
||||
const registry = createModuleUiPublicationRegistry(discovered);
|
||||
// The exact facts the runtime consumes, captured before any Dashboard configuration exists.
|
||||
const baseline = JSON.stringify(
|
||||
discovered.map((module) => ({
|
||||
capabilities: module.manifest.capabilities,
|
||||
dependencies: module.manifest.dependencies,
|
||||
id: module.manifest.id,
|
||||
permissions: module.manifest.permissions,
|
||||
version: module.manifest.version,
|
||||
})),
|
||||
);
|
||||
|
||||
for (const [label, configuration] of arrangements) {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration,
|
||||
registry.list().map((entry) => ({ id: entry.moduleId, name: entry.name })),
|
||||
);
|
||||
|
||||
// Discovery order — which is module *startup* order — is untouched by presentation.
|
||||
expect(
|
||||
discovered.map((module) => module.manifest.id),
|
||||
label,
|
||||
).toEqual(["calendar", "video", "livestream"]);
|
||||
// So is every fact the runtime reads.
|
||||
expect(
|
||||
JSON.stringify(
|
||||
discovered.map((module) => ({
|
||||
capabilities: module.manifest.capabilities,
|
||||
dependencies: module.manifest.dependencies,
|
||||
id: module.manifest.id,
|
||||
permissions: module.manifest.permissions,
|
||||
version: module.manifest.version,
|
||||
})),
|
||||
),
|
||||
label,
|
||||
).toBe(baseline);
|
||||
// And every module is still rendered exactly once, whatever the folders say.
|
||||
expect(
|
||||
[...view.groups.flatMap((group) => group.modules), ...view.ungrouped]
|
||||
.map((entry) => entry.id)
|
||||
.sort(),
|
||||
label,
|
||||
).toEqual(["calendar", "livestream", "video"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("never invents a module for a group, however the group is named", async () => {
|
||||
const discovered = await discoverFixtures();
|
||||
const registry = createModuleUiPublicationRegistry(discovered);
|
||||
const [, mediaArrangement] = arrangements[1] as readonly [string, DashboardConfiguration];
|
||||
|
||||
const view = resolveDashboardNavigation(
|
||||
mediaArrangement,
|
||||
registry.list().map((entry) => ({ id: entry.moduleId, name: entry.name })),
|
||||
);
|
||||
|
||||
// "Media" and "Planning" are group labels. There is no `media` module, no manifest for one, no
|
||||
// artifact, no API root, no permission, and nothing depends on one.
|
||||
const moduleIds = discovered.map((module) => module.manifest.id);
|
||||
expect(moduleIds).toEqual(["calendar", "video", "livestream"]);
|
||||
for (const groupId of view.groups.map((group) => group.id)) {
|
||||
expect(moduleIds).not.toContain(groupId);
|
||||
expect(registry.resolve(groupId, "1.0.0")).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the publication record free of any grouping, ordering, or navigation field", async () => {
|
||||
const registry = createModuleUiPublicationRegistry(await discoverFixtures());
|
||||
|
||||
const published = registry.resolve("livestream", "1.0.0");
|
||||
|
||||
// The record a host mounts from carries identity, the validated artifact, declared permissions,
|
||||
// and the module's own name — never a group, an order, a parent, or a folder.
|
||||
expect(Object.keys(published ?? {}).sort()).toEqual([
|
||||
"artifactPath",
|
||||
"moduleId",
|
||||
"name",
|
||||
"permissions",
|
||||
"version",
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes the display name from the module's own manifest, not from any folder", async () => {
|
||||
const registry = createModuleUiPublicationRegistry(await discoverFixtures());
|
||||
|
||||
expect(registry.list().map((entry) => [entry.moduleId, entry.name])).toEqual([
|
||||
["calendar", "Calendar"],
|
||||
["video", "Video"],
|
||||
["livestream", "Livestream"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,283 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
type DashboardConfiguration,
|
||||
type DashboardNavigationModule,
|
||||
resolveDashboardNavigation,
|
||||
} from "../src/dashboard/index.js";
|
||||
|
||||
function module(id: string, name = id): DashboardNavigationModule {
|
||||
return { id, name };
|
||||
}
|
||||
|
||||
function configuration(
|
||||
groups: ReadonlyArray<{ id: string; label: string; sortOrder: number }>,
|
||||
placements: ReadonlyArray<{ moduleId: string; groupId: string | null; sortOrder: number }>,
|
||||
): DashboardConfiguration {
|
||||
return { groups, placements };
|
||||
}
|
||||
|
||||
const media = { id: "media", label: "Media", sortOrder: 10 };
|
||||
const planning = { id: "planning", label: "Planning", sortOrder: 20 };
|
||||
|
||||
describe("resolving Dashboard navigation", () => {
|
||||
it("groups modules exactly where the configuration places them", () => {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[media, planning],
|
||||
[
|
||||
{ groupId: "media", moduleId: "livestream", sortOrder: 20 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 10 },
|
||||
{ groupId: "planning", moduleId: "calendar", sortOrder: 10 },
|
||||
],
|
||||
),
|
||||
[
|
||||
module("calendar", "Calendar"),
|
||||
module("livestream", "Livestream"),
|
||||
module("video", "Video"),
|
||||
],
|
||||
);
|
||||
|
||||
expect(
|
||||
view.groups.map((group) => [group.label, group.modules.map((entry) => entry.name)]),
|
||||
).toEqual([
|
||||
["Media", ["Video", "Livestream"]],
|
||||
["Planning", ["Calendar"]],
|
||||
]);
|
||||
expect(view.ungrouped).toEqual([]);
|
||||
});
|
||||
|
||||
it("shows a newly discovered module without any stored placement", () => {
|
||||
// The rule that makes installing a module sufficient to see it: no initialization write, no
|
||||
// manual database edit, no migration.
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration([media], [{ groupId: "media", moduleId: "video", sortOrder: 10 }]),
|
||||
[module("video", "Video"), module("roster", "Roster")],
|
||||
);
|
||||
|
||||
expect(view.groups[0]?.modules.map((entry) => entry.id)).toEqual(["video"]);
|
||||
expect(view.ungrouped.map((entry) => entry.id)).toEqual(["roster"]);
|
||||
});
|
||||
|
||||
it("keeps a deliberately ungrouped module distinct from an unconfigured one, and orders both", () => {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[],
|
||||
[
|
||||
{ groupId: null, moduleId: "video", sortOrder: 20 },
|
||||
{ groupId: null, moduleId: "calendar", sortOrder: 10 },
|
||||
],
|
||||
),
|
||||
[module("roster"), module("video"), module("calendar")],
|
||||
);
|
||||
|
||||
// Placed-and-ungrouped first, in the administrator's order; never-configured after, by id — so a
|
||||
// newcomer never interrupts an ordering someone chose.
|
||||
expect(view.ungrouped.map((entry) => entry.id)).toEqual(["calendar", "video", "roster"]);
|
||||
});
|
||||
|
||||
it("omits a stored placement whose module is not installed", () => {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[media],
|
||||
[
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "uninstalled", sortOrder: 20 },
|
||||
],
|
||||
),
|
||||
[module("video", "Video")],
|
||||
);
|
||||
|
||||
// No dead entry renders, and the caller's configuration is untouched — the record survives for a
|
||||
// reinstall.
|
||||
expect(view.groups[0]?.modules.map((entry) => entry.id)).toEqual(["video"]);
|
||||
expect(view.ungrouped).toEqual([]);
|
||||
});
|
||||
|
||||
it("restores a reinstalled module to the position its retained placement describes", () => {
|
||||
const stored = configuration(
|
||||
[media],
|
||||
[
|
||||
{ groupId: "media", moduleId: "livestream", sortOrder: 5 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 10 },
|
||||
],
|
||||
);
|
||||
|
||||
const whileUninstalled = resolveDashboardNavigation(stored, [module("video", "Video")]);
|
||||
const afterReinstall = resolveDashboardNavigation(stored, [
|
||||
module("video", "Video"),
|
||||
module("livestream", "Livestream"),
|
||||
]);
|
||||
|
||||
expect(whileUninstalled.groups[0]?.modules.map((entry) => entry.id)).toEqual(["video"]);
|
||||
expect(afterReinstall.groups[0]?.modules.map((entry) => entry.id)).toEqual([
|
||||
"livestream",
|
||||
"video",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an empty group rather than hiding it", () => {
|
||||
const view = resolveDashboardNavigation(configuration([media, planning], []), []);
|
||||
|
||||
expect(view.groups.map((group) => group.id)).toEqual(["media", "planning"]);
|
||||
expect(view.groups.every((group) => group.modules.length === 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a placement naming a missing group as ungrouped rather than losing the module", () => {
|
||||
// The schema's `on delete set null` makes this unreachable in practice; the resolver still
|
||||
// refuses to let a configuration inconsistency make a module invisible.
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration([], [{ groupId: "deleted-group", moduleId: "video", sortOrder: 10 }]),
|
||||
[module("video", "Video")],
|
||||
);
|
||||
|
||||
expect(view.groups).toEqual([]);
|
||||
expect(view.ungrouped.map((entry) => entry.id)).toEqual(["video"]);
|
||||
});
|
||||
|
||||
it("orders deterministically when order values collide", () => {
|
||||
const collided = configuration(
|
||||
[
|
||||
{ id: "zebra", label: "Zebra", sortOrder: 10 },
|
||||
{ id: "alpha", label: "Alpha", sortOrder: 10 },
|
||||
],
|
||||
[
|
||||
{ groupId: "alpha", moduleId: "video", sortOrder: 0 },
|
||||
{ groupId: "alpha", moduleId: "calendar", sortOrder: 0 },
|
||||
{ groupId: "alpha", moduleId: "roster", sortOrder: 0 },
|
||||
],
|
||||
);
|
||||
const modules = [module("roster"), module("video"), module("calendar")];
|
||||
|
||||
const first = resolveDashboardNavigation(collided, modules);
|
||||
// A different input order must not change the output: the tie-break is the identifier, never
|
||||
// arrival order.
|
||||
const second = resolveDashboardNavigation(collided, [...modules].reverse());
|
||||
|
||||
expect(first.groups.map((group) => group.id)).toEqual(["alpha", "zebra"]);
|
||||
expect(first.groups[0]?.modules.map((entry) => entry.id)).toEqual([
|
||||
"calendar",
|
||||
"roster",
|
||||
"video",
|
||||
]);
|
||||
expect(JSON.stringify(second)).toBe(JSON.stringify(first));
|
||||
});
|
||||
|
||||
it("is empty and usable with no configuration and no modules", () => {
|
||||
const view = resolveDashboardNavigation(configuration([], []), []);
|
||||
|
||||
expect(view.groups).toEqual([]);
|
||||
expect(view.ungrouped).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns a frozen view no caller can mutate", () => {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration([media], [{ groupId: "media", moduleId: "video", sortOrder: 10 }]),
|
||||
[module("video", "Video")],
|
||||
);
|
||||
|
||||
expect(Object.isFrozen(view)).toBe(true);
|
||||
expect(Object.isFrozen(view.groups)).toBe(true);
|
||||
expect(Object.isFrozen(view.groups[0])).toBe(true);
|
||||
expect(Object.isFrozen(view.ungrouped)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Dashboard grouping is presentation and nothing else", () => {
|
||||
const modules = [
|
||||
module("livestream", "Livestream"),
|
||||
module("video", "Video"),
|
||||
module("calendar", "Calendar"),
|
||||
];
|
||||
|
||||
it("creates no module, no parent, and no relationship from a shared group", () => {
|
||||
const view = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[media],
|
||||
[
|
||||
{ groupId: "media", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 20 },
|
||||
],
|
||||
),
|
||||
modules,
|
||||
);
|
||||
|
||||
// "Media" is a label on a rendering bucket. It is not a module: nothing in the view carries a
|
||||
// module id, version, artifact, or API root for it, and no entry names another module.
|
||||
const rendered = JSON.parse(JSON.stringify(view)) as unknown;
|
||||
expect(view.groups[0]?.modules.map((entry) => entry.id)).toEqual(["livestream", "video"]);
|
||||
expect(modules.map((entry) => entry.id)).not.toContain("media");
|
||||
for (const entry of view.groups.flatMap((group) => group.modules)) {
|
||||
// A navigation entry describes exactly one module and never references a second one.
|
||||
expect(Object.keys(entry).sort()).toEqual(["id", "name"]);
|
||||
}
|
||||
expect(JSON.stringify(rendered)).not.toContain("parent");
|
||||
expect(JSON.stringify(rendered)).not.toContain("depends");
|
||||
});
|
||||
|
||||
it("changes only placement when a module moves to a different group", () => {
|
||||
const before = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[media],
|
||||
[
|
||||
{ groupId: "media", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 20 },
|
||||
],
|
||||
),
|
||||
modules,
|
||||
);
|
||||
const after = resolveDashboardNavigation(
|
||||
configuration(
|
||||
[media, { id: "sunday-production", label: "Sunday Production", sortOrder: 5 }],
|
||||
[
|
||||
{ groupId: "sunday-production", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "video", sortOrder: 20 },
|
||||
],
|
||||
),
|
||||
modules,
|
||||
);
|
||||
|
||||
const findLivestream = (view: typeof before) =>
|
||||
[...view.groups.flatMap((group) => group.modules), ...view.ungrouped].find(
|
||||
(entry) => entry.id === "livestream",
|
||||
);
|
||||
|
||||
// The module object itself is identical across the move: same identity, same name, and — in the
|
||||
// API layer above this — the same embedded mount descriptor.
|
||||
expect(findLivestream(after)).toEqual(findLivestream(before));
|
||||
expect(before.groups.find((group) => group.id === "media")?.modules.map((m) => m.id)).toEqual([
|
||||
"livestream",
|
||||
"video",
|
||||
]);
|
||||
expect(after.groups.find((group) => group.id === "media")?.modules.map((m) => m.id)).toEqual([
|
||||
"video",
|
||||
]);
|
||||
expect(
|
||||
after.groups.find((group) => group.id === "sunday-production")?.modules.map((m) => m.id),
|
||||
).toEqual(["livestream"]);
|
||||
});
|
||||
|
||||
it("renders the same module set whatever the arrangement", () => {
|
||||
const arrangements: readonly DashboardConfiguration[] = [
|
||||
configuration([], []),
|
||||
configuration([media], [{ groupId: "media", moduleId: "livestream", sortOrder: 10 }]),
|
||||
configuration(
|
||||
[media, planning],
|
||||
[
|
||||
{ groupId: "planning", moduleId: "livestream", sortOrder: 10 },
|
||||
{ groupId: "media", moduleId: "calendar", sortOrder: 10 },
|
||||
{ groupId: null, moduleId: "video", sortOrder: 10 },
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
for (const arrangement of arrangements) {
|
||||
const view = resolveDashboardNavigation(arrangement, modules);
|
||||
const rendered = [...view.groups.flatMap((group) => group.modules), ...view.ungrouped]
|
||||
.map((entry) => entry.id)
|
||||
.sort();
|
||||
// Every module is rendered exactly once, in every arrangement. Grouping can never add,
|
||||
// remove, duplicate, or hide a module.
|
||||
expect(rendered).toEqual(["calendar", "livestream", "video"]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,415 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, type QueryResultRow } from "pg";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
createDashboardDrizzleView,
|
||||
createDashboardStore,
|
||||
type DashboardStore,
|
||||
DashboardStoreError,
|
||||
resolveDashboardNavigation,
|
||||
} from "../src/dashboard/index.js";
|
||||
import { createValidatedPostgresPool } from "../src/database/index.js";
|
||||
import {
|
||||
applyModuleMigrations,
|
||||
createPostgresMigrationDatabase,
|
||||
discoverAllMigrations,
|
||||
} from "../src/migrations/index.js";
|
||||
|
||||
/**
|
||||
* The Dashboard navigation store against real PostgreSQL.
|
||||
*
|
||||
* The unit suites prove the resolution rules; this proves the things only a database can: that the
|
||||
* migration really creates these tables, that configuration survives a completely new connection,
|
||||
* that `on delete set null` really ungroups a deleted group's modules, and that a placement can
|
||||
* never point at a group that does not exist. The in-memory double used by the API route tests
|
||||
* deliberately reproduces only two of those behaviours, so this file is where they are actually
|
||||
* established rather than assumed.
|
||||
*/
|
||||
const integrationDatabaseUrlEnvironment = "EKKLESIA_MIGRATION_TEST_DATABASE_URL";
|
||||
const coreMigrationsDirectory = path.join(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"..",
|
||||
"drizzle",
|
||||
);
|
||||
const trackedDatabases = new Set<string>();
|
||||
let databaseCounter = 0;
|
||||
|
||||
class IntegrationHarnessError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "IntegrationHarnessError";
|
||||
this.stack = `${this.name}: ${this.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
function harnessError(message: string): IntegrationHarnessError {
|
||||
return new IntegrationHarnessError(message);
|
||||
}
|
||||
|
||||
function baseDatabaseUrl(): string {
|
||||
const value = process.env[integrationDatabaseUrlEnvironment];
|
||||
if (typeof value !== "string" || value.trim() === "") {
|
||||
throw harnessError("The Dashboard integration database is not configured.");
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") {
|
||||
throw new TypeError("Unsupported protocol.");
|
||||
}
|
||||
} catch {
|
||||
throw harnessError("The Dashboard integration database configuration is invalid.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function quoteDatabaseName(databaseName: string): string {
|
||||
if (!/^[a-z][a-z0-9_]{0,62}$/u.test(databaseName)) {
|
||||
throw harnessError("The generated integration database name is invalid.");
|
||||
}
|
||||
return `"${databaseName}"`;
|
||||
}
|
||||
|
||||
function makeDatabaseName(label: string): string {
|
||||
const safeLabel = label
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9]+/gu, "_")
|
||||
.replaceAll(/^_+|_+$/gu, "")
|
||||
.slice(0, 14);
|
||||
databaseCounter += 1;
|
||||
return `ekk_dash_${process.pid}_${databaseCounter}_${safeLabel || "scenario"}_${randomBytes(4).toString("hex")}`;
|
||||
}
|
||||
|
||||
function databaseUrl(databaseName: string): string {
|
||||
const parsed = new URL(baseDatabaseUrl());
|
||||
parsed.pathname = `/${databaseName}`;
|
||||
parsed.searchParams.delete("application_name");
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
async function openAdministrativeClient(connectionString: string): Promise<Client> {
|
||||
const client = new Client({ connectionString });
|
||||
client.on("error", () => undefined);
|
||||
try {
|
||||
await client.connect();
|
||||
return client;
|
||||
} catch {
|
||||
try {
|
||||
await client.end();
|
||||
} catch {
|
||||
// The public harness failure stays static when connection cleanup also fails.
|
||||
}
|
||||
throw harnessError("The Dashboard integration database connection failed.");
|
||||
}
|
||||
}
|
||||
|
||||
async function safeQuery<Row extends QueryResultRow>(
|
||||
client: Client,
|
||||
text: string,
|
||||
values: unknown[] = [],
|
||||
): Promise<readonly Row[]> {
|
||||
try {
|
||||
const result = await client.query<Row>(text, values);
|
||||
return result.rows;
|
||||
} catch {
|
||||
throw harnessError("An integration database administration operation failed.");
|
||||
}
|
||||
}
|
||||
|
||||
async function safeEnd(client: Client): Promise<void> {
|
||||
try {
|
||||
await client.end();
|
||||
} catch {
|
||||
throw harnessError("An integration database connection could not be closed.");
|
||||
}
|
||||
}
|
||||
|
||||
async function dropDatabase(databaseName: string): Promise<void> {
|
||||
const admin = await openAdministrativeClient(baseDatabaseUrl());
|
||||
try {
|
||||
await safeQuery(
|
||||
admin,
|
||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
|
||||
[databaseName],
|
||||
);
|
||||
await safeQuery(
|
||||
admin,
|
||||
`DROP DATABASE IF EXISTS ${quoteDatabaseName(databaseName)} WITH (FORCE)`,
|
||||
);
|
||||
trackedDatabases.delete(databaseName);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
}
|
||||
|
||||
async function createDisposableDatabase(label: string): Promise<{ name: string; url: string }> {
|
||||
const name = makeDatabaseName(label);
|
||||
const admin = await openAdministrativeClient(baseDatabaseUrl());
|
||||
try {
|
||||
await safeQuery(admin, `CREATE DATABASE ${quoteDatabaseName(name)} TEMPLATE template0`);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
trackedDatabases.add(name);
|
||||
return { name, url: databaseUrl(name) };
|
||||
}
|
||||
|
||||
async function applyCoreMigrations(url: string): Promise<void> {
|
||||
const emptyModulesDirectory = await mkdtemp(path.join(tmpdir(), "ekklesia-dash-no-modules-"));
|
||||
try {
|
||||
const aggregate = await discoverAllMigrations({
|
||||
coreMigrationsDirectory,
|
||||
moduleDiscovery: {
|
||||
moduleSdkVersion: "0.1.0",
|
||||
modulesDirectory: emptyModulesDirectory,
|
||||
platformVersion: "0.1.0",
|
||||
},
|
||||
});
|
||||
expect(aggregate.migrations.map((entry) => entry.identity)).toEqual([
|
||||
"core:0000_identity_core_tables",
|
||||
"core:0001_authorization_core_tables",
|
||||
"core:0002_authorization_integrity",
|
||||
"core:0003_dashboard_navigation_tables",
|
||||
]);
|
||||
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
|
||||
} finally {
|
||||
await rm(emptyModulesDirectory, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
for (const databaseName of [...trackedDatabases]) {
|
||||
await dropDatabase(databaseName).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
describe.sequential("live Core Dashboard navigation store", () => {
|
||||
let database: { name: string; url: string };
|
||||
let admin: Client;
|
||||
let store: DashboardStore;
|
||||
let close: () => Promise<void>;
|
||||
|
||||
it("creates exactly the two Dashboard tables, with their constraints", async () => {
|
||||
database = await createDisposableDatabase("fresh");
|
||||
await applyCoreMigrations(database.url);
|
||||
admin = await openAdministrativeClient(database.url);
|
||||
|
||||
const tables = await safeQuery<{ table_name: string }>(
|
||||
admin,
|
||||
`select table_name from information_schema.tables
|
||||
where table_schema = 'public' and table_name like 'ekklesia_core_dashboard%'
|
||||
order by table_name`,
|
||||
);
|
||||
const constraints = await safeQuery<{ constraint_name: string; delete_rule: string }>(
|
||||
admin,
|
||||
`select rc.constraint_name, rc.delete_rule
|
||||
from information_schema.referential_constraints rc
|
||||
join information_schema.table_constraints tc
|
||||
on tc.constraint_name = rc.constraint_name
|
||||
where tc.table_name = 'ekklesia_core_dashboard_placement'`,
|
||||
);
|
||||
|
||||
expect(tables.map((table) => table.table_name)).toEqual([
|
||||
"ekklesia_core_dashboard_group",
|
||||
"ekklesia_core_dashboard_placement",
|
||||
]);
|
||||
// The database, not the application, is what guarantees a deleted group leaves no dangling
|
||||
// reference.
|
||||
expect(constraints.map((constraint) => constraint.delete_rule)).toEqual(["SET NULL"]);
|
||||
|
||||
const handle = createValidatedPostgresPool(database.url);
|
||||
close = handle.close;
|
||||
store = createDashboardStore(createDashboardDrizzleView(handle.pool));
|
||||
});
|
||||
|
||||
it("starts empty, so an installation with no configuration is a normal state", async () => {
|
||||
expect(await store.readConfiguration()).toEqual({ groups: [], placements: [] });
|
||||
});
|
||||
|
||||
it("persists groups and placements, and reads them back in deterministic order", async () => {
|
||||
await store.upsertGroup({ id: "planning", label: "Planning", sortOrder: 20 });
|
||||
await store.upsertGroup({ id: "media", label: "Media", sortOrder: 10 });
|
||||
await store.setPlacement({ groupId: "media", moduleId: "livestream", sortOrder: 20 });
|
||||
await store.setPlacement({ groupId: "media", moduleId: "video", sortOrder: 10 });
|
||||
await store.setPlacement({ groupId: "planning", moduleId: "calendar", sortOrder: 10 });
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
|
||||
expect(configuration.groups.map((group) => group.id)).toEqual(["media", "planning"]);
|
||||
expect(configuration.placements.map((placement) => placement.moduleId)).toEqual([
|
||||
"calendar",
|
||||
"video",
|
||||
"livestream",
|
||||
]);
|
||||
});
|
||||
|
||||
it("survives a completely new connection, so a church configures its Dashboard once", async () => {
|
||||
// A different pool, as a restarted process would use — nothing is cached in the old one.
|
||||
const reopened = createValidatedPostgresPool(database.url);
|
||||
try {
|
||||
const configuration = await createDashboardStore(
|
||||
createDashboardDrizzleView(reopened.pool),
|
||||
).readConfiguration();
|
||||
const view = resolveDashboardNavigation(configuration, [
|
||||
{ id: "livestream", name: "Livestream" },
|
||||
{ id: "video", name: "Video" },
|
||||
{ id: "calendar", name: "Calendar" },
|
||||
]);
|
||||
|
||||
expect(
|
||||
view.groups.map((group) => [group.label, group.modules.map((entry) => entry.name)]),
|
||||
).toEqual([
|
||||
["Media", ["Video", "Livestream"]],
|
||||
["Planning", ["Calendar"]],
|
||||
]);
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("renames a group without disturbing a single placement", async () => {
|
||||
const before = await store.readConfiguration();
|
||||
|
||||
await store.upsertGroup({ id: "media", label: "Media & Streaming", sortOrder: 10 });
|
||||
const after = await store.readConfiguration();
|
||||
|
||||
expect(after.groups.find((group) => group.id === "media")?.label).toBe("Media & Streaming");
|
||||
// The stable id is what placements point at, so a rename can never re-organize the Dashboard.
|
||||
expect(after.placements).toEqual(before.placements);
|
||||
});
|
||||
|
||||
it("re-orders a group and a module in place, without creating duplicates", async () => {
|
||||
await store.upsertGroup({ id: "media", label: "Media & Streaming", sortOrder: 30 });
|
||||
await store.setPlacement({ groupId: "media", moduleId: "video", sortOrder: 99 });
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
|
||||
expect(configuration.groups).toHaveLength(2);
|
||||
expect(configuration.groups.map((group) => group.id)).toEqual(["planning", "media"]);
|
||||
expect(configuration.placements.filter((entry) => entry.moduleId === "video")).toHaveLength(1);
|
||||
expect(configuration.placements.find((entry) => entry.moduleId === "video")?.sortOrder).toBe(
|
||||
99,
|
||||
);
|
||||
});
|
||||
|
||||
it("moves a module between groups by changing exactly one row", async () => {
|
||||
await store.upsertGroup({ id: "sunday-production", label: "Sunday Production", sortOrder: 5 });
|
||||
await store.setPlacement({
|
||||
groupId: "sunday-production",
|
||||
moduleId: "livestream",
|
||||
sortOrder: 10,
|
||||
});
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
|
||||
expect(configuration.placements.find((entry) => entry.moduleId === "livestream")?.groupId).toBe(
|
||||
"sunday-production",
|
||||
);
|
||||
// Video did not move.
|
||||
expect(configuration.placements.find((entry) => entry.moduleId === "video")?.groupId).toBe(
|
||||
"media",
|
||||
);
|
||||
});
|
||||
|
||||
it("ungroups a module deliberately, which is distinct from having no record", async () => {
|
||||
await store.setPlacement({ groupId: null, moduleId: "calendar", sortOrder: 7 });
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
const calendar = configuration.placements.find((entry) => entry.moduleId === "calendar");
|
||||
|
||||
expect(calendar).toEqual({ groupId: null, moduleId: "calendar", sortOrder: 7 });
|
||||
});
|
||||
|
||||
it("ungroups a deleted group's modules instead of leaving a dangling reference", async () => {
|
||||
await store.deleteGroup("sunday-production");
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
const groupIds = new Set(configuration.groups.map((group) => group.id));
|
||||
|
||||
expect(groupIds.has("sunday-production")).toBe(false);
|
||||
expect(
|
||||
configuration.placements.find((entry) => entry.moduleId === "livestream")?.groupId,
|
||||
).toBeNull();
|
||||
// No placement anywhere names a group that no longer exists.
|
||||
for (const placement of configuration.placements) {
|
||||
if (placement.groupId !== null) {
|
||||
expect(groupIds.has(placement.groupId)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a placement naming a group that was never created", async () => {
|
||||
await expect(
|
||||
store.setPlacement({ groupId: "not-a-group", moduleId: "video", sortOrder: 10 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_GROUP_NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("refuses to delete a group that does not exist", async () => {
|
||||
await expect(store.deleteGroup("not-a-group")).rejects.toMatchObject({
|
||||
code: "DASHBOARD_GROUP_NOT_FOUND",
|
||||
});
|
||||
});
|
||||
|
||||
it("stores a placement for a module that is not installed, and renders nothing for it", async () => {
|
||||
await store.upsertGroup({ id: "media", label: "Media & Streaming", sortOrder: 30 });
|
||||
await store.setPlacement({ groupId: "media", moduleId: "uninstalled", sortOrder: 1 });
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
const view = resolveDashboardNavigation(configuration, [{ id: "video", name: "Video" }]);
|
||||
|
||||
// Retained, so a reinstall restores the position...
|
||||
expect(configuration.placements.map((entry) => entry.moduleId)).toContain("uninstalled");
|
||||
// ...and never rendered while the module is absent.
|
||||
expect(
|
||||
[...view.groups.flatMap((group) => group.modules), ...view.ungrouped].map(
|
||||
(entry) => entry.id,
|
||||
),
|
||||
).toEqual(["video"]);
|
||||
});
|
||||
|
||||
it("rejects malformed input before it reaches the database", async () => {
|
||||
await expect(
|
||||
store.upsertGroup({ id: "Not Kebab Case", label: "Nope", sortOrder: 0 }),
|
||||
).rejects.toBeInstanceOf(DashboardStoreError);
|
||||
await expect(
|
||||
store.upsertGroup({ id: "media", label: " ", sortOrder: 0 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_GROUP_LABEL_INVALID" });
|
||||
await expect(
|
||||
store.upsertGroup({ id: "media", label: "x".repeat(121), sortOrder: 0 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_GROUP_LABEL_INVALID" });
|
||||
await expect(
|
||||
store.upsertGroup({ id: "media", label: "Media", sortOrder: -1 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_SORT_ORDER_INVALID" });
|
||||
await expect(
|
||||
store.setPlacement({ groupId: null, moduleId: "Not Valid", sortOrder: 0 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_MODULE_ID_INVALID" });
|
||||
await expect(
|
||||
store.setPlacement({ groupId: null, moduleId: "video", sortOrder: 1.5 }),
|
||||
).rejects.toMatchObject({ code: "DASHBOARD_SORT_ORDER_INVALID" });
|
||||
});
|
||||
|
||||
it("trims a stored label rather than persisting surrounding whitespace", async () => {
|
||||
await store.upsertGroup({ id: "planning", label: " Planning ", sortOrder: 20 });
|
||||
|
||||
const configuration = await store.readConfiguration();
|
||||
|
||||
expect(configuration.groups.find((group) => group.id === "planning")?.label).toBe("Planning");
|
||||
});
|
||||
|
||||
it("leaks no database detail in a sanitized failure", async () => {
|
||||
await close();
|
||||
|
||||
const error = await store.readConfiguration().catch((caught: unknown) => caught);
|
||||
const text = `${String(error)}\n${(error as Error).stack ?? ""}`;
|
||||
|
||||
expect(error).toMatchObject({ code: "DASHBOARD_READ_FAILED" });
|
||||
expect(text).not.toContain(database.name);
|
||||
expect(text).not.toContain("select");
|
||||
expect(text).not.toContain("ekklesia_core_dashboard");
|
||||
await safeEnd(admin);
|
||||
await dropDatabase(database.name);
|
||||
});
|
||||
});
|
||||
@@ -78,7 +78,7 @@ Modules
|
||||
✓ Dependency graph valid
|
||||
Dependency order is empty.
|
||||
✓ Permission registry composed
|
||||
2 permissions registered
|
||||
3 permissions registered
|
||||
|
||||
Data definitions
|
||||
✓ Schemas validated
|
||||
|
||||
@@ -2,6 +2,7 @@ import { type PermissionBaseline, parseModuleManifest } from "@ekklesia/contract
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CORE_AUTHORIZATION_GRANTS_MANAGE,
|
||||
CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
CORE_MODULES_UI_READ,
|
||||
CORE_PERMISSION_DECLARATIONS,
|
||||
PermissionRegistryError,
|
||||
@@ -67,8 +68,9 @@ describe("composePlatformPermissionRegistry", () => {
|
||||
expect(registry.has(CORE_MODULES_UI_READ)).toBe(true);
|
||||
expect(registry.has("calendar.events.read")).toBe(true);
|
||||
expect(registry.has("people.directory.read")).toBe(true);
|
||||
// Core's own two declarations plus one from each module.
|
||||
expect(registry.declarations).toHaveLength(4);
|
||||
expect(registry.has(CORE_DASHBOARD_NAVIGATION_MANAGE)).toBe(true);
|
||||
// Core's own three declarations plus one from each module.
|
||||
expect(registry.declarations).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("preserves deterministic order: Core first, then modules in the supplied order, then declarations in manifest order", () => {
|
||||
@@ -85,6 +87,7 @@ describe("composePlatformPermissionRegistry", () => {
|
||||
expect(registry.declarations.map((declaration) => declaration.id)).toEqual([
|
||||
CORE_AUTHORIZATION_GRANTS_MANAGE,
|
||||
CORE_MODULES_UI_READ,
|
||||
CORE_DASHBOARD_NAVIGATION_MANAGE,
|
||||
"calendar.events.read",
|
||||
"calendar.events.write",
|
||||
"people.directory.read",
|
||||
|
||||
Reference in New Issue
Block a user