adula 0.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +10 -0
- package/README.md +38 -2
- package/build/agent/AGENTS.template.md +28 -0
- package/build/agent/capabilities.md +60 -0
- package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
- package/build/agent/skills/idea-review/SKILL.md +31 -0
- package/build/agent/skills/module-review/SKILL.md +22 -0
- package/build/agent/skills/perf-review/SKILL.md +24 -0
- package/build/agent/skills/schema-review/SKILL.md +22 -0
- package/build/agent/skills/security-review/SKILL.md +24 -0
- package/build/agent/skills/ui-review/SKILL.md +22 -0
- package/build/commands/capabilities.d.ts +10 -0
- package/build/commands/capabilities.js +40 -0
- package/build/commands/doctor.d.ts +9 -0
- package/build/commands/doctor.js +72 -0
- package/build/commands/gaps.d.ts +12 -0
- package/build/commands/gaps.js +62 -0
- package/build/commands/install.d.ts +9 -0
- package/build/commands/install.js +105 -0
- package/build/commands/main.d.ts +8 -0
- package/build/commands/main.js +33 -0
- package/build/commands/module_add.d.ts +8 -0
- package/build/commands/module_add.js +57 -0
- package/build/commands/module_remove.d.ts +10 -0
- package/build/commands/module_remove.js +94 -0
- package/build/commands/resource.d.ts +8 -0
- package/build/commands/resource.js +29 -0
- package/build/commands/resource_snapshot.d.ts +15 -0
- package/build/commands/resource_snapshot.js +61 -0
- package/build/commands/storage_migrate.d.ts +12 -0
- package/build/commands/storage_migrate.js +39 -0
- package/build/commands/ui.d.ts +11 -0
- package/build/commands/ui.js +210 -0
- package/build/commands/upgrade.d.ts +15 -0
- package/build/commands/upgrade.js +34 -0
- package/build/configure.d.ts +2 -0
- package/build/configure.js +79 -0
- package/build/database/migrations/1770000000000_core.d.ts +5 -0
- package/build/database/migrations/1770000000000_core.js +10 -0
- package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
- package/build/database/migrations/1770000000001_attachments.js +10 -0
- package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
- package/build/database/migrations/1770000000002_saved_views.js +10 -0
- package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
- package/build/database/migrations/1770000000003_user_invitations.js +18 -0
- package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
- package/build/database/migrations/1770000000004_collaboration.js +10 -0
- package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
- package/build/database/migrations/1770000000005_assignments.js +10 -0
- package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
- package/build/database/migrations/1770000000006_messaging.js +10 -0
- package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
- package/build/database/migrations/1770000000007_webhooks.js +10 -0
- package/build/database/migrations/1770000000008_imports.d.ts +5 -0
- package/build/database/migrations/1770000000008_imports.js +10 -0
- package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
- package/build/database/migrations/1770000000010_workflows.js +10 -0
- package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
- package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
- package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
- package/build/database/migrations/1770000000012_role_keys.js +10 -0
- package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
- package/build/database/migrations/1770000000013_notification_targets.js +10 -0
- package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
- package/build/database/migrations/1770000000014_upload_grants.js +10 -0
- package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
- package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
- package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
- package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
- package/build/index.d.ts +80 -0
- package/build/index.js +49 -0
- package/build/providers/adula_provider.d.ts +6 -0
- package/build/providers/adula_provider.js +10 -0
- package/build/src/admin/contracts.d.ts +19 -0
- package/build/src/admin/contracts.js +115 -0
- package/build/src/admin/controller.d.ts +32 -0
- package/build/src/admin/controller.js +167 -0
- package/build/src/admin/errors.d.ts +5 -0
- package/build/src/admin/errors.js +9 -0
- package/build/src/admin/presentation.d.ts +28 -0
- package/build/src/admin/presentation.js +1 -0
- package/build/src/admin/record_title.d.ts +14 -0
- package/build/src/admin/record_title.js +50 -0
- package/build/src/admin/resource_service.d.ts +376 -0
- package/build/src/admin/resource_service.js +1448 -0
- package/build/src/attachments/attachment_service.d.ts +100 -0
- package/build/src/attachments/attachment_service.js +270 -0
- package/build/src/attachments/doctor.d.ts +4 -0
- package/build/src/attachments/doctor.js +28 -0
- package/build/src/attachments/storage_migrate.d.ts +39 -0
- package/build/src/attachments/storage_migrate.js +64 -0
- package/build/src/attachments/upload_grants.d.ts +44 -0
- package/build/src/attachments/upload_grants.js +105 -0
- package/build/src/auth/ability.d.ts +24 -0
- package/build/src/auth/ability.js +34 -0
- package/build/src/auth/actor_store.d.ts +14 -0
- package/build/src/auth/actor_store.js +70 -0
- package/build/src/auth/conditions.d.ts +26 -0
- package/build/src/auth/conditions.js +117 -0
- package/build/src/auth/packed_rules.d.ts +4 -0
- package/build/src/auth/packed_rules.js +13 -0
- package/build/src/auth/sql.d.ts +11 -0
- package/build/src/auth/sql.js +118 -0
- package/build/src/collaboration/assignments.d.ts +129 -0
- package/build/src/collaboration/assignments.js +333 -0
- package/build/src/collaboration/record_collaboration.d.ts +86 -0
- package/build/src/collaboration/record_collaboration.js +348 -0
- package/build/src/commands/agent_assets.d.ts +7 -0
- package/build/src/commands/agent_assets.js +66 -0
- package/build/src/commands/capabilities.d.ts +19 -0
- package/build/src/commands/capabilities.js +179 -0
- package/build/src/commands/doctor.d.ts +42 -0
- package/build/src/commands/doctor.js +375 -0
- package/build/src/commands/gap_report.d.ts +56 -0
- package/build/src/commands/gap_report.js +110 -0
- package/build/src/commands/generator.d.ts +1 -0
- package/build/src/commands/generator.js +70 -0
- package/build/src/commands/snapshot.d.ts +28 -0
- package/build/src/commands/snapshot.js +48 -0
- package/build/src/commands/source_markers.d.ts +11 -0
- package/build/src/commands/source_markers.js +41 -0
- package/build/src/core/activity.d.ts +43 -0
- package/build/src/core/activity.js +77 -0
- package/build/src/core/administration_guard.d.ts +3 -0
- package/build/src/core/administration_guard.js +39 -0
- package/build/src/core/health.d.ts +42 -0
- package/build/src/core/health.js +44 -0
- package/build/src/core/mail_test.d.ts +18 -0
- package/build/src/core/mail_test.js +88 -0
- package/build/src/core/message_templates.d.ts +83 -0
- package/build/src/core/message_templates.js +293 -0
- package/build/src/core/module_seed.d.ts +15 -0
- package/build/src/core/module_seed.js +31 -0
- package/build/src/core/notifications.d.ts +42 -0
- package/build/src/core/notifications.js +91 -0
- package/build/src/core/org_units.d.ts +30 -0
- package/build/src/core/org_units.js +123 -0
- package/build/src/core/roles.d.ts +98 -0
- package/build/src/core/roles.js +447 -0
- package/build/src/core/saved_views.d.ts +37 -0
- package/build/src/core/saved_views.js +164 -0
- package/build/src/core/settings.d.ts +29 -0
- package/build/src/core/settings.js +113 -0
- package/build/src/core/setup.d.ts +14 -0
- package/build/src/core/setup.js +89 -0
- package/build/src/core/ui_preferences.d.ts +12 -0
- package/build/src/core/ui_preferences.js +30 -0
- package/build/src/core/user_invitations.d.ts +23 -0
- package/build/src/core/user_invitations.js +144 -0
- package/build/src/core/users.d.ts +44 -0
- package/build/src/core/users.js +182 -0
- package/build/src/database/configure.d.ts +3 -0
- package/build/src/database/configure.js +41 -0
- package/build/src/database/schema.d.ts +52 -0
- package/build/src/database/schema.js +538 -0
- package/build/src/eslint/index.d.ts +3 -0
- package/build/src/eslint/index.js +90 -0
- package/build/src/events/adonis_jobs.d.ts +9 -0
- package/build/src/events/adonis_jobs.js +13 -0
- package/build/src/events/outbox.d.ts +19 -0
- package/build/src/events/outbox.js +33 -0
- package/build/src/events/record_mutation.d.ts +24 -0
- package/build/src/events/record_mutation.js +62 -0
- package/build/src/integrations/imports.d.ts +74 -0
- package/build/src/integrations/imports.js +333 -0
- package/build/src/integrations/inbound_webhooks.d.ts +94 -0
- package/build/src/integrations/inbound_webhooks.js +276 -0
- package/build/src/integrations/openapi.d.ts +39 -0
- package/build/src/integrations/openapi.js +323 -0
- package/build/src/integrations/print.d.ts +37 -0
- package/build/src/integrations/print.js +124 -0
- package/build/src/integrations/webhooks.d.ts +98 -0
- package/build/src/integrations/webhooks.js +298 -0
- package/build/src/mcp/tools.d.ts +8 -0
- package/build/src/mcp/tools.js +156 -0
- package/build/src/org/org_service.d.ts +2 -0
- package/build/src/org/org_service.js +16 -0
- package/build/src/resource/define_resource.d.ts +5 -0
- package/build/src/resource/define_resource.js +68 -0
- package/build/src/resource/registry.d.ts +12 -0
- package/build/src/resource/registry.js +101 -0
- package/build/src/resource/types.d.ts +155 -0
- package/build/src/resource/types.js +1 -0
- package/build/src/resource/values.d.ts +5 -0
- package/build/src/resource/values.js +88 -0
- package/build/src/services/backup.d.ts +14 -0
- package/build/src/services/backup.js +59 -0
- package/build/src/services/settings.d.ts +21 -0
- package/build/src/services/settings.js +30 -0
- package/build/src/upgrade/legacy.d.ts +27 -0
- package/build/src/upgrade/legacy.js +58 -0
- package/build/src/upgrade/rename.d.ts +17 -0
- package/build/src/upgrade/rename.js +94 -0
- package/build/src/version.d.ts +1 -0
- package/build/src/version.js +2 -0
- package/build/src/workflows/define_workflow.d.ts +124 -0
- package/build/src/workflows/define_workflow.js +123 -0
- package/build/src/workflows/engine.d.ts +141 -0
- package/build/src/workflows/engine.js +752 -0
- package/build/stubs/README.md +6 -0
- package/build/stubs/controller.stub +8 -0
- package/build/stubs/main.d.ts +5 -0
- package/build/stubs/main.js +5 -0
- package/build/stubs/main.ts +5 -0
- package/build/stubs/modules.stub +6 -0
- package/build/stubs/resource_contract.stub +1 -0
- package/build/stubs/resource_contract.txt +452 -0
- package/build/stubs/routes.stub +16 -0
- package/build/stubs/service.stub +9 -0
- package/package.json +95 -6
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Settings, notify } from './settings.js';
|
|
2
|
+
/** Check one complete recent snapshot; object existence is not a restore test. */
|
|
3
|
+
export function assessBackup(objects, now = Date.now(), prefix = 'adula') {
|
|
4
|
+
if (!/^adula(?:\/[a-zA-Z0-9_-]+)*$/.test(prefix))
|
|
5
|
+
throw new Error('Invalid backup prefix');
|
|
6
|
+
const root = prefix + '/';
|
|
7
|
+
const snapshots = new Map();
|
|
8
|
+
for (const object of objects) {
|
|
9
|
+
if (!object.key.startsWith(root))
|
|
10
|
+
continue;
|
|
11
|
+
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z)\/(database\.dump|uploads\.tar\.gz|SHA256SUMS|COMPLETE)$/.exec(object.key.slice(root.length));
|
|
12
|
+
const age = now - Date.parse(object.modifiedAt);
|
|
13
|
+
if (!match ||
|
|
14
|
+
!Number.isFinite(object.size) ||
|
|
15
|
+
(match[2] === 'COMPLETE' ? object.size < 0 : object.size <= 0) ||
|
|
16
|
+
!Number.isFinite(age) ||
|
|
17
|
+
age < 0 ||
|
|
18
|
+
age > 48 * 3600000)
|
|
19
|
+
continue;
|
|
20
|
+
const files = snapshots.get(match[1]) ?? new Set();
|
|
21
|
+
files.add(match[2]);
|
|
22
|
+
snapshots.set(match[1], files);
|
|
23
|
+
}
|
|
24
|
+
const healthy = [...snapshots.values()].some((files) => files.size === 4);
|
|
25
|
+
return {
|
|
26
|
+
healthy,
|
|
27
|
+
reason: healthy ? 'recent_complete_snapshot' : 'missing_recent_complete_snapshot',
|
|
28
|
+
checkedAt: new Date(now).toISOString(),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export async function verifyBackup(db, inspect, now = Date.now(), prefix = 'adula') {
|
|
32
|
+
let status;
|
|
33
|
+
try {
|
|
34
|
+
status = assessBackup(await inspect(), now, prefix);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
status = {
|
|
38
|
+
healthy: false,
|
|
39
|
+
reason: 'offsite_check_failed',
|
|
40
|
+
checkedAt: new Date(now).toISOString(),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
await db.transaction(async (trx) => {
|
|
44
|
+
await trx.raw('SELECT pg_advisory_xact_lock(?)', [19300210]);
|
|
45
|
+
const settings = new Settings(trx);
|
|
46
|
+
const previous = await settings.get('backup.health');
|
|
47
|
+
await settings.set('backup.health', status);
|
|
48
|
+
if (!status.healthy && (previous?.healthy !== false || previous.reason !== status.reason)) {
|
|
49
|
+
const admins = await trx('user_roles as ur')
|
|
50
|
+
.join('roles as r', 'r.id', 'ur.role_id')
|
|
51
|
+
.where('r.permission_level', '>=', 1)
|
|
52
|
+
.whereNull('ur.org_unit_id')
|
|
53
|
+
.distinct('ur.user_id');
|
|
54
|
+
for (const admin of admins)
|
|
55
|
+
await notify(trx, admin.user_id, 'تعذّر التحقق من النسخة الاحتياطية', 'تحقق من مخزن النسخ الخارجي ووجود نسخة كاملة خلال آخر 48 ساعة.');
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return status;
|
|
59
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
export declare class Settings {
|
|
3
|
+
private db;
|
|
4
|
+
constructor(db: Knex);
|
|
5
|
+
get<T>(key: string, scope?: string, scopeId?: string): Promise<T | undefined>;
|
|
6
|
+
set(key: string, value: unknown, scope?: string, scopeId?: string): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare function sequence(trx: Knex.Transaction, key: string): Promise<string>;
|
|
9
|
+
/** The record a notification is about; opening the notification opens the record. */
|
|
10
|
+
export type NotificationTarget = {
|
|
11
|
+
resource: string;
|
|
12
|
+
recordId: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function targetColumns(target?: NotificationTarget | null): {
|
|
15
|
+
resource?: undefined;
|
|
16
|
+
record_id?: undefined;
|
|
17
|
+
} | {
|
|
18
|
+
resource: string;
|
|
19
|
+
record_id: number;
|
|
20
|
+
};
|
|
21
|
+
export declare function notify(db: Knex, userId: number, title: string, body: string, target?: NotificationTarget | null): Promise<void>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export class Settings {
|
|
2
|
+
db;
|
|
3
|
+
constructor(db) {
|
|
4
|
+
this.db = db;
|
|
5
|
+
}
|
|
6
|
+
async get(key, scope = 'system', scopeId = '0') {
|
|
7
|
+
const row = await this.db('settings').where({ key, scope, scope_id: scopeId }).first('value');
|
|
8
|
+
return row?.value;
|
|
9
|
+
}
|
|
10
|
+
async set(key, value, scope = 'system', scopeId = '0') {
|
|
11
|
+
await this.db('settings')
|
|
12
|
+
.insert({ key, scope, scope_id: scopeId, value: JSON.stringify(value) })
|
|
13
|
+
.onConflict(['key', 'scope', 'scope_id'])
|
|
14
|
+
.merge(['value']);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function sequence(trx, key) {
|
|
18
|
+
const result = await trx.raw('INSERT INTO sequences (key,value) VALUES (?,1) ON CONFLICT (key) DO UPDATE SET value=sequences.value+1 RETURNING value', [key]);
|
|
19
|
+
return `${key}-${String(result.rows[0].value).padStart(6, '0')}`;
|
|
20
|
+
}
|
|
21
|
+
export function targetColumns(target) {
|
|
22
|
+
if (!target)
|
|
23
|
+
return {};
|
|
24
|
+
if (!/^[a-z][a-z0-9_]*$/.test(target.resource) || !Number.isSafeInteger(target.recordId))
|
|
25
|
+
throw new Error('Invalid notification target');
|
|
26
|
+
return { resource: target.resource, record_id: target.recordId };
|
|
27
|
+
}
|
|
28
|
+
export async function notify(db, userId, title, body, target) {
|
|
29
|
+
await db('notifications').insert({ user_id: userId, title, body, ...targetColumns(target) });
|
|
30
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Directory Lucid recorded for each 1.x core migration. */
|
|
2
|
+
export declare const LEGACY_MIGRATIONS_PATH = "node_modules/@adula/kit/build/database/migrations";
|
|
3
|
+
export declare const MIGRATIONS_PATH = "node_modules/adula/build/database/migrations";
|
|
4
|
+
/** Every core migration shipped before 2.0.0, by its 2.0 file name. */
|
|
5
|
+
export declare const MIGRATIONS_BEFORE_2_0: readonly ["1770000000000_core", "1770000000001_attachments", "1770000000002_saved_views", "1770000000003_user_invitations", "1770000000004_collaboration", "1770000000005_assignments", "1770000000006_messaging", "1770000000007_webhooks", "1770000000008_imports", "1770000000010_workflows", "1770000000011_managed_assignments", "1770000000012_role_keys", "1770000000013_notification_targets", "1770000000014_upload_grants", "1770000000015_inbound_webhooks"];
|
|
6
|
+
/** `1770000000000_core` -> the file name 1.x used for the same migration. */
|
|
7
|
+
export declare function legacyMigrationFile(name: string): string;
|
|
8
|
+
/** Recorded `adonis_schema.name` of a 1.x core migration -> its 2.0 name, or undefined. */
|
|
9
|
+
export declare function renamedMigration(recorded: string): string | undefined;
|
|
10
|
+
/** Database objects created by 1.x, with their 2.0 names. */
|
|
11
|
+
export declare const LEGACY_DATABASE: {
|
|
12
|
+
readonly authFunction: readonly ["kit_bump_auth_revision", "adula_bump_auth_revision"];
|
|
13
|
+
readonly authTrigger: readonly ["kit_invalidate_auth", "adula_invalidate_auth"];
|
|
14
|
+
readonly notificationSignal: readonly ["kit_notification_signal", "adula_notification_signal"];
|
|
15
|
+
readonly notificationChannel: readonly ["kit_notifications", "adula_notifications"];
|
|
16
|
+
readonly versionSetting: readonly ["kit.version", "adula.version"];
|
|
17
|
+
readonly listenerPrefix: readonly ["kit.", "adula."];
|
|
18
|
+
};
|
|
19
|
+
/** Application files 1.x created or read. */
|
|
20
|
+
export declare const LEGACY_FILES: {
|
|
21
|
+
readonly gaps: readonly [`${string}_GAPS.md`, "GAPS.md"];
|
|
22
|
+
};
|
|
23
|
+
/** Managed AGENTS.md block markers written by 1.x. */
|
|
24
|
+
export declare const LEGACY_MARKERS: {
|
|
25
|
+
readonly start: "<!-- adula-kit:start";
|
|
26
|
+
readonly end: "<!-- adula-kit:end -->";
|
|
27
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Names used by 1.x releases, published as `@adula/kit`. They exist only so that
|
|
3
|
+
* `adula:upgrade` and migration 016 can find and rename what 1.x installed; nothing
|
|
4
|
+
* else may read or write them. This file is the single allow-listed place for the
|
|
5
|
+
* retired name in the core package (`pnpm check:naming`).
|
|
6
|
+
*/
|
|
7
|
+
const RETIRED = 'kit';
|
|
8
|
+
/** Directory Lucid recorded for each 1.x core migration. */
|
|
9
|
+
export const LEGACY_MIGRATIONS_PATH = `node_modules/@adula/${RETIRED}/build/database/migrations`;
|
|
10
|
+
export const MIGRATIONS_PATH = 'node_modules/adula/build/database/migrations';
|
|
11
|
+
/** Every core migration shipped before 2.0.0, by its 2.0 file name. */
|
|
12
|
+
export const MIGRATIONS_BEFORE_2_0 = [
|
|
13
|
+
'1770000000000_core',
|
|
14
|
+
'1770000000001_attachments',
|
|
15
|
+
'1770000000002_saved_views',
|
|
16
|
+
'1770000000003_user_invitations',
|
|
17
|
+
'1770000000004_collaboration',
|
|
18
|
+
'1770000000005_assignments',
|
|
19
|
+
'1770000000006_messaging',
|
|
20
|
+
'1770000000007_webhooks',
|
|
21
|
+
'1770000000008_imports',
|
|
22
|
+
'1770000000010_workflows',
|
|
23
|
+
'1770000000011_managed_assignments',
|
|
24
|
+
'1770000000012_role_keys',
|
|
25
|
+
'1770000000013_notification_targets',
|
|
26
|
+
'1770000000014_upload_grants',
|
|
27
|
+
'1770000000015_inbound_webhooks',
|
|
28
|
+
];
|
|
29
|
+
/** `1770000000000_core` -> the file name 1.x used for the same migration. */
|
|
30
|
+
export function legacyMigrationFile(name) {
|
|
31
|
+
return name.replace(/^(\d{13})_/, `$1_${RETIRED}_`);
|
|
32
|
+
}
|
|
33
|
+
/** Recorded `adonis_schema.name` of a 1.x core migration -> its 2.0 name, or undefined. */
|
|
34
|
+
export function renamedMigration(recorded) {
|
|
35
|
+
if (!recorded.startsWith(`${LEGACY_MIGRATIONS_PATH}/`))
|
|
36
|
+
return undefined;
|
|
37
|
+
const file = recorded.slice(LEGACY_MIGRATIONS_PATH.length + 1);
|
|
38
|
+
const current = MIGRATIONS_BEFORE_2_0.find((name) => legacyMigrationFile(name) === file);
|
|
39
|
+
return current ? `${MIGRATIONS_PATH}/${current}` : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Database objects created by 1.x, with their 2.0 names. */
|
|
42
|
+
export const LEGACY_DATABASE = {
|
|
43
|
+
authFunction: [`${RETIRED}_bump_auth_revision`, 'adula_bump_auth_revision'],
|
|
44
|
+
authTrigger: [`${RETIRED}_invalidate_auth`, 'adula_invalidate_auth'],
|
|
45
|
+
notificationSignal: [`${RETIRED}_notification_signal`, 'adula_notification_signal'],
|
|
46
|
+
notificationChannel: [`${RETIRED}_notifications`, 'adula_notifications'],
|
|
47
|
+
versionSetting: [`${RETIRED}.version`, 'adula.version'],
|
|
48
|
+
listenerPrefix: [`${RETIRED}.`, 'adula.'],
|
|
49
|
+
};
|
|
50
|
+
/** Application files 1.x created or read. */
|
|
51
|
+
export const LEGACY_FILES = {
|
|
52
|
+
gaps: [`${RETIRED.toUpperCase()}_GAPS.md`, 'GAPS.md'],
|
|
53
|
+
};
|
|
54
|
+
/** Managed AGENTS.md block markers written by 1.x. */
|
|
55
|
+
export const LEGACY_MARKERS = {
|
|
56
|
+
start: `<!-- adula-${RETIRED}:start`,
|
|
57
|
+
end: `<!-- adula-${RETIRED}:end -->`,
|
|
58
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
/**
|
|
3
|
+
* Renames the `adonis_schema` rows a 1.x installation recorded under
|
|
4
|
+
* `node_modules/@adula/<1.x name>/...` to the 2.0 paths, in one transaction. Lucid
|
|
5
|
+
* would otherwise treat every core migration as pending. Idempotent: a renamed
|
|
6
|
+
* database has no legacy rows. An unknown legacy row aborts without changes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function renameRecordedMigrations(knex: Knex, table?: string): Promise<number>;
|
|
9
|
+
/** True while 1.x migration rows still wait for `adula:upgrade`. */
|
|
10
|
+
export declare function hasLegacyMigrations(knex: Knex, table?: string): Promise<boolean>;
|
|
11
|
+
/** Renames the 1.x gap log to GAPS.md unless the application already has one. */
|
|
12
|
+
export declare function renameLegacyFiles(root: string): Promise<string[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Renames the database objects, setting and listener names 1.x created. Runs from
|
|
15
|
+
* migration 016; every step is a no-op on a database created by 2.0.
|
|
16
|
+
*/
|
|
17
|
+
export declare function renameLegacyDatabaseObjects(knex: Knex): Promise<void>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { access, rename } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { AdulaError } from '../admin/errors.js';
|
|
4
|
+
import { LEGACY_DATABASE, LEGACY_FILES, LEGACY_MIGRATIONS_PATH, renamedMigration, } from './legacy.js';
|
|
5
|
+
/** LIKE pattern for names under the 1.x path; `_` and `%` inside the path are literal. */
|
|
6
|
+
const LEGACY_ROWS = `${LEGACY_MIGRATIONS_PATH.replace(/[\\%_]/g, '\\$&')}/%`;
|
|
7
|
+
/**
|
|
8
|
+
* Renames the `adonis_schema` rows a 1.x installation recorded under
|
|
9
|
+
* `node_modules/@adula/<1.x name>/...` to the 2.0 paths, in one transaction. Lucid
|
|
10
|
+
* would otherwise treat every core migration as pending. Idempotent: a renamed
|
|
11
|
+
* database has no legacy rows. An unknown legacy row aborts without changes.
|
|
12
|
+
*/
|
|
13
|
+
export async function renameRecordedMigrations(knex, table = 'adonis_schema') {
|
|
14
|
+
if (!(await knex.schema.hasTable(table)))
|
|
15
|
+
return 0;
|
|
16
|
+
return knex.transaction(async (trx) => {
|
|
17
|
+
const rows = await trx(table)
|
|
18
|
+
.where('name', 'like', LEGACY_ROWS)
|
|
19
|
+
.select('id', 'name')
|
|
20
|
+
.forUpdate();
|
|
21
|
+
const unknown = rows.filter((row) => !renamedMigration(row.name));
|
|
22
|
+
if (unknown.length)
|
|
23
|
+
throw new AdulaError(409, 'E_UNKNOWN_MIGRATION', `Unknown 1.x migrations: ${unknown.map((row) => row.name).join(', ')}`);
|
|
24
|
+
for (const row of rows)
|
|
25
|
+
await trx(table)
|
|
26
|
+
.where('id', row.id)
|
|
27
|
+
.update({ name: renamedMigration(row.name) });
|
|
28
|
+
return rows.length;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** True while 1.x migration rows still wait for `adula:upgrade`. */
|
|
32
|
+
export async function hasLegacyMigrations(knex, table = 'adonis_schema') {
|
|
33
|
+
if (!(await knex.schema.hasTable(table)))
|
|
34
|
+
return false;
|
|
35
|
+
return Boolean(await knex(table).where('name', 'like', LEGACY_ROWS).first('id'));
|
|
36
|
+
}
|
|
37
|
+
/** Renames the 1.x gap log to GAPS.md unless the application already has one. */
|
|
38
|
+
export async function renameLegacyFiles(root) {
|
|
39
|
+
const [legacy, current] = LEGACY_FILES.gaps;
|
|
40
|
+
const exists = (name) => access(join(root, name)).then(() => true, () => false);
|
|
41
|
+
if (!(await exists(legacy)) || (await exists(current)))
|
|
42
|
+
return [];
|
|
43
|
+
await rename(join(root, legacy), join(root, current));
|
|
44
|
+
return [`${legacy} -> ${current}`];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Renames the database objects, setting and listener names 1.x created. Runs from
|
|
48
|
+
* migration 016; every step is a no-op on a database created by 2.0.
|
|
49
|
+
*/
|
|
50
|
+
export async function renameLegacyDatabaseObjects(knex) {
|
|
51
|
+
const [oldFunction, newFunction] = LEGACY_DATABASE.authFunction;
|
|
52
|
+
const [oldTrigger, newTrigger] = LEGACY_DATABASE.authTrigger;
|
|
53
|
+
const [oldSignal, newSignal] = LEGACY_DATABASE.notificationSignal;
|
|
54
|
+
const [, newChannel] = LEGACY_DATABASE.notificationChannel;
|
|
55
|
+
const [oldVersion, newVersion] = LEGACY_DATABASE.versionSetting;
|
|
56
|
+
const [oldPrefix, newPrefix] = LEGACY_DATABASE.listenerPrefix;
|
|
57
|
+
// PostgreSQL has no ALTER FUNCTION IF EXISTS; look the 1.x function up in this schema.
|
|
58
|
+
const functionExists = async (name) => Boolean(await knex('pg_proc as p')
|
|
59
|
+
.join('pg_namespace as n', 'n.oid', 'p.pronamespace')
|
|
60
|
+
.where('p.proname', name)
|
|
61
|
+
.whereRaw('n.nspname = current_schema()')
|
|
62
|
+
.first('p.oid'));
|
|
63
|
+
if (await functionExists(oldFunction))
|
|
64
|
+
await knex.raw(`ALTER FUNCTION ${oldFunction}() RENAME TO ${newFunction}`);
|
|
65
|
+
const triggers = await knex('pg_trigger as t')
|
|
66
|
+
.join('pg_class as c', 'c.oid', 't.tgrelid')
|
|
67
|
+
.join('pg_namespace as n', 'n.oid', 'c.relnamespace')
|
|
68
|
+
.where('t.tgname', oldTrigger)
|
|
69
|
+
.whereRaw('n.nspname = current_schema()')
|
|
70
|
+
.select('c.relname as table');
|
|
71
|
+
for (const { table } of triggers)
|
|
72
|
+
await knex.raw('ALTER TRIGGER ?? ON ?? RENAME TO ??', [oldTrigger, table, newTrigger]);
|
|
73
|
+
if (await functionExists(oldSignal)) {
|
|
74
|
+
await knex.raw(`CREATE OR REPLACE FUNCTION ${newSignal}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_notify('${newChannel}', json_build_object('userId', NEW.user_id, 'id', NEW.id)::text); RETURN NULL; END $$`);
|
|
75
|
+
await knex.raw(`DROP TRIGGER IF EXISTS ${oldSignal} ON notifications`);
|
|
76
|
+
await knex.raw(`CREATE TRIGGER ${newSignal} AFTER INSERT ON notifications FOR EACH ROW EXECUTE FUNCTION ${newSignal}()`);
|
|
77
|
+
await knex.raw(`DROP FUNCTION ${oldSignal}()`);
|
|
78
|
+
}
|
|
79
|
+
await knex('settings')
|
|
80
|
+
.where('key', oldVersion)
|
|
81
|
+
.whereNotExists(knex('settings as current')
|
|
82
|
+
.where('current.key', newVersion)
|
|
83
|
+
.whereRaw('current.scope = settings.scope')
|
|
84
|
+
.whereRaw('current.scope_id = settings.scope_id')
|
|
85
|
+
.select(knex.raw('1')))
|
|
86
|
+
.update({ key: newVersion });
|
|
87
|
+
await knex('settings').where('key', oldVersion).delete();
|
|
88
|
+
await knex.raw(`UPDATE processed_events SET listener = ? || substr(listener, ?)
|
|
89
|
+
WHERE listener LIKE ? AND NOT EXISTS (
|
|
90
|
+
SELECT 1 FROM processed_events current
|
|
91
|
+
WHERE current.event_id = processed_events.event_id
|
|
92
|
+
AND current.listener = ? || substr(processed_events.listener, ?))`, [newPrefix, oldPrefix.length + 1, `${oldPrefix}%`, newPrefix, oldPrefix.length + 1]);
|
|
93
|
+
await knex('processed_events').where('listener', 'like', `${oldPrefix}%`).delete();
|
|
94
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ADULA_VERSION: string;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { type AnyStateMachine } from 'xstate';
|
|
2
|
+
import type { Knex } from 'knex';
|
|
3
|
+
import type { RecordData } from '../resource/types.js';
|
|
4
|
+
/** Everything a step callback may read: the current record and the run facts. */
|
|
5
|
+
export type StepContext = {
|
|
6
|
+
record: RecordData;
|
|
7
|
+
run: {
|
|
8
|
+
id: string;
|
|
9
|
+
resource: string;
|
|
10
|
+
recordId: number;
|
|
11
|
+
startedBy: number | null;
|
|
12
|
+
};
|
|
13
|
+
db: Knex;
|
|
14
|
+
};
|
|
15
|
+
export type Recipients = 'creator' | 'submitter'
|
|
16
|
+
/**
|
|
17
|
+
* The members of a role, addressed by its stable key (roles.key). A role without a
|
|
18
|
+
* key is still found by its display name, which administrators can rename.
|
|
19
|
+
*/
|
|
20
|
+
| {
|
|
21
|
+
role: string;
|
|
22
|
+
} | {
|
|
23
|
+
users: number[];
|
|
24
|
+
} | ((context: StepContext) => number[] | Promise<number[]>);
|
|
25
|
+
/** One decision an approver can take at a decision step (#42). */
|
|
26
|
+
export type DecisionOutcome = {
|
|
27
|
+
label: string;
|
|
28
|
+
next: string;
|
|
29
|
+
/** Whether the decision needs a comment; defaults to optional. */
|
|
30
|
+
comment?: 'optional' | 'required';
|
|
31
|
+
};
|
|
32
|
+
export type WorkflowStep = {
|
|
33
|
+
type: 'condition';
|
|
34
|
+
label?: string;
|
|
35
|
+
when: (record: RecordData) => boolean;
|
|
36
|
+
then: string;
|
|
37
|
+
else: string;
|
|
38
|
+
} | {
|
|
39
|
+
type: 'update';
|
|
40
|
+
label?: string;
|
|
41
|
+
values: RecordData | ((context: StepContext) => RecordData);
|
|
42
|
+
next: string;
|
|
43
|
+
} | {
|
|
44
|
+
type: 'notify';
|
|
45
|
+
label?: string;
|
|
46
|
+
to: Recipients;
|
|
47
|
+
/** A message template key; defaults to workflow.decided. */
|
|
48
|
+
template?: string;
|
|
49
|
+
variables?: (context: StepContext) => Record<string, unknown>;
|
|
50
|
+
next: string;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'approval';
|
|
53
|
+
label: string;
|
|
54
|
+
assignees: Recipients;
|
|
55
|
+
dueInDays?: number;
|
|
56
|
+
approve: string;
|
|
57
|
+
reject: string;
|
|
58
|
+
} | {
|
|
59
|
+
/**
|
|
60
|
+
* An approval with named outcomes, for example approve, reject and return. Each
|
|
61
|
+
* outcome names its next step (a later or an earlier one) and may require a comment.
|
|
62
|
+
* The submitted document stays locked: a decision never changes its fields.
|
|
63
|
+
*/
|
|
64
|
+
type: 'decision';
|
|
65
|
+
label: string;
|
|
66
|
+
assignees: Recipients;
|
|
67
|
+
dueInDays?: number;
|
|
68
|
+
outcomes: Record<string, DecisionOutcome>;
|
|
69
|
+
} | {
|
|
70
|
+
type: 'delay';
|
|
71
|
+
label?: string;
|
|
72
|
+
ms: number;
|
|
73
|
+
next: string;
|
|
74
|
+
} | {
|
|
75
|
+
type: 'http';
|
|
76
|
+
label?: string;
|
|
77
|
+
url: string | ((context: StepContext) => string);
|
|
78
|
+
body?: (context: StepContext) => unknown;
|
|
79
|
+
next: string;
|
|
80
|
+
} | {
|
|
81
|
+
type: 'end';
|
|
82
|
+
label?: string;
|
|
83
|
+
outcome: 'approved' | 'rejected' | 'completed';
|
|
84
|
+
/** Cancel the submitted document when the workflow ends (for example on rejection). */
|
|
85
|
+
cancelDocument?: boolean;
|
|
86
|
+
};
|
|
87
|
+
export type WorkflowInput = {
|
|
88
|
+
/** Lower-case letters, digits and underscores, starting with a letter (for example release_approval). */
|
|
89
|
+
name: string;
|
|
90
|
+
version: number;
|
|
91
|
+
resource: string;
|
|
92
|
+
label: string;
|
|
93
|
+
start: string;
|
|
94
|
+
/** Step names follow the workflow name rule (for example notify_approved). */
|
|
95
|
+
steps: Record<string, WorkflowStep>;
|
|
96
|
+
/** Failed step attempts before the run stops as failed (default 5). */
|
|
97
|
+
maxAttempts?: number;
|
|
98
|
+
};
|
|
99
|
+
export type WorkflowDefinition = WorkflowInput & {
|
|
100
|
+
machine: AnyStateMachine;
|
|
101
|
+
};
|
|
102
|
+
export type WorkflowEvent = {
|
|
103
|
+
type: 'EVALUATE';
|
|
104
|
+
record: RecordData;
|
|
105
|
+
} | {
|
|
106
|
+
type: 'DONE';
|
|
107
|
+
} | {
|
|
108
|
+
type: 'APPROVE';
|
|
109
|
+
} | {
|
|
110
|
+
type: 'REJECT';
|
|
111
|
+
} | {
|
|
112
|
+
type: 'DECIDE';
|
|
113
|
+
outcome: string;
|
|
114
|
+
};
|
|
115
|
+
export declare const WORKFLOW_NAME_RULE = "use lower-case letters, digits and underscores, starting with a letter";
|
|
116
|
+
/**
|
|
117
|
+
* Declares a versioned workflow. Steps compile to an XState machine; the engine
|
|
118
|
+
* performs each step's effect and asks the machine for the next step. Runs keep
|
|
119
|
+
* the version they started with, so publishing a new version never changes a
|
|
120
|
+
* running workflow (migrate explicitly with WorkflowEngine.migrateRuns).
|
|
121
|
+
*/
|
|
122
|
+
export declare function defineWorkflow(input: WorkflowInput): WorkflowDefinition;
|
|
123
|
+
/** The step reached from `current` by `event`, or an error if the step does not accept it. */
|
|
124
|
+
export declare function nextStep(definition: WorkflowDefinition, current: string, event: WorkflowEvent): string;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createMachine, getNextSnapshot } from 'xstate';
|
|
2
|
+
const IDENTIFIER = /^[a-z][a-z0-9_]*$/;
|
|
3
|
+
export const WORKFLOW_NAME_RULE = 'use lower-case letters, digits and underscores, starting with a letter';
|
|
4
|
+
/** Names the rule and a valid spelling, since dotted event-style names are a natural first try. */
|
|
5
|
+
function assertIdentifier(kind, value) {
|
|
6
|
+
if (IDENTIFIER.test(value))
|
|
7
|
+
return;
|
|
8
|
+
const suggestion = value
|
|
9
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
10
|
+
.toLowerCase()
|
|
11
|
+
.replace(/[^a-z0-9]+/g, '_')
|
|
12
|
+
.replace(/^[^a-z]+|_+$/g, '');
|
|
13
|
+
const example = IDENTIFIER.test(suggestion)
|
|
14
|
+
? suggestion
|
|
15
|
+
: kind === 'workflow'
|
|
16
|
+
? 'release_approval'
|
|
17
|
+
: 'notify_approved';
|
|
18
|
+
throw new Error(`Invalid ${kind} name "${value}": ${WORKFLOW_NAME_RULE} (for example ${example}).`);
|
|
19
|
+
}
|
|
20
|
+
function targets(step) {
|
|
21
|
+
switch (step.type) {
|
|
22
|
+
case 'condition':
|
|
23
|
+
return [step.then, step.else];
|
|
24
|
+
case 'approval':
|
|
25
|
+
return [step.approve, step.reject];
|
|
26
|
+
case 'decision':
|
|
27
|
+
return Object.values(step.outcomes).map((outcome) => outcome.next);
|
|
28
|
+
case 'end':
|
|
29
|
+
return [];
|
|
30
|
+
default:
|
|
31
|
+
return [step.next];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Declares a versioned workflow. Steps compile to an XState machine; the engine
|
|
36
|
+
* performs each step's effect and asks the machine for the next step. Runs keep
|
|
37
|
+
* the version they started with, so publishing a new version never changes a
|
|
38
|
+
* running workflow (migrate explicitly with WorkflowEngine.migrateRuns).
|
|
39
|
+
*/
|
|
40
|
+
export function defineWorkflow(input) {
|
|
41
|
+
assertIdentifier('workflow', input.name);
|
|
42
|
+
if (!Number.isInteger(input.version) || input.version < 1)
|
|
43
|
+
throw new Error('Workflow version must be a positive integer');
|
|
44
|
+
if (!(input.start in input.steps))
|
|
45
|
+
throw new Error(`Unknown start step: ${input.start}`);
|
|
46
|
+
const keys = Object.keys(input.steps);
|
|
47
|
+
for (const key of keys) {
|
|
48
|
+
assertIdentifier('step', key);
|
|
49
|
+
for (const target of targets(input.steps[key]))
|
|
50
|
+
if (!(target in input.steps))
|
|
51
|
+
throw new Error(`Step ${key} points to unknown step ${target}`);
|
|
52
|
+
const step = input.steps[key];
|
|
53
|
+
if (step.type === 'delay' && (!Number.isInteger(step.ms) || step.ms < 0))
|
|
54
|
+
throw new Error(`Step ${key} needs a non-negative integer delay`);
|
|
55
|
+
if (step.type === 'decision') {
|
|
56
|
+
const outcomes = Object.entries(step.outcomes ?? {});
|
|
57
|
+
if (outcomes.length < 2)
|
|
58
|
+
throw new Error(`Decision step ${key} needs at least two outcomes`);
|
|
59
|
+
for (const [name, outcome] of outcomes) {
|
|
60
|
+
if (!IDENTIFIER.test(name) || name.length > 20)
|
|
61
|
+
throw new Error(`Invalid outcome name "${name}" in step ${key}: ${WORKFLOW_NAME_RULE}, at most 20 characters`);
|
|
62
|
+
if (!outcome.label)
|
|
63
|
+
throw new Error(`Outcome ${name} of step ${key} needs a label`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!keys.some((key) => input.steps[key].type === 'end'))
|
|
68
|
+
throw new Error('A workflow needs at least one end step');
|
|
69
|
+
const machine = createMachine({
|
|
70
|
+
id: `${input.name}@${input.version}`,
|
|
71
|
+
initial: input.start,
|
|
72
|
+
states: Object.fromEntries(keys.map((key) => {
|
|
73
|
+
const step = input.steps[key];
|
|
74
|
+
switch (step.type) {
|
|
75
|
+
case 'condition':
|
|
76
|
+
return [
|
|
77
|
+
key,
|
|
78
|
+
{
|
|
79
|
+
on: {
|
|
80
|
+
EVALUATE: [
|
|
81
|
+
{
|
|
82
|
+
target: step.then,
|
|
83
|
+
guard: ({ event }) => event.type === 'EVALUATE' && step.when(event.record),
|
|
84
|
+
},
|
|
85
|
+
{ target: step.else },
|
|
86
|
+
],
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
];
|
|
90
|
+
case 'approval':
|
|
91
|
+
return [key, { on: { APPROVE: step.approve, REJECT: step.reject } }];
|
|
92
|
+
case 'decision':
|
|
93
|
+
return [
|
|
94
|
+
key,
|
|
95
|
+
{
|
|
96
|
+
on: {
|
|
97
|
+
DECIDE: Object.entries(step.outcomes).map(([name, outcome]) => ({
|
|
98
|
+
target: outcome.next,
|
|
99
|
+
guard: ({ event }) => event.type === 'DECIDE' && event.outcome === name,
|
|
100
|
+
})),
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
];
|
|
104
|
+
case 'end':
|
|
105
|
+
return [key, { type: 'final' }];
|
|
106
|
+
default:
|
|
107
|
+
return [key, { on: { DONE: step.next } }];
|
|
108
|
+
}
|
|
109
|
+
})),
|
|
110
|
+
});
|
|
111
|
+
return { ...input, machine };
|
|
112
|
+
}
|
|
113
|
+
/** The step reached from `current` by `event`, or an error if the step does not accept it. */
|
|
114
|
+
export function nextStep(definition, current, event) {
|
|
115
|
+
if (!(current in definition.steps))
|
|
116
|
+
throw new Error(`Step ${current} is not part of ${definition.name}@${definition.version}`);
|
|
117
|
+
const snapshot = definition.machine.resolveState({ value: current, context: {} });
|
|
118
|
+
const next = getNextSnapshot(definition.machine, snapshot, event);
|
|
119
|
+
const value = String(next.value);
|
|
120
|
+
if (value === current)
|
|
121
|
+
throw new Error(`Step ${current} does not accept ${event.type}`);
|
|
122
|
+
return value;
|
|
123
|
+
}
|