@objectstack/runtime 0.4.1 → 0.6.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.
@@ -0,0 +1,40 @@
1
+ import { Plugin, PluginContext } from '@objectstack/core';
2
+
3
+ /**
4
+ * Driver Plugin
5
+ *
6
+ * Generic plugin wrapper for ObjectQL drivers.
7
+ * Registers a driver with the ObjectQL engine.
8
+ *
9
+ * Dependencies: None (Registers service for ObjectQL to discover)
10
+ * Services: driver.{name}
11
+ *
12
+ * @example
13
+ * const memoryDriver = new InMemoryDriver();
14
+ * const driverPlugin = new DriverPlugin(memoryDriver, 'memory');
15
+ * kernel.use(driverPlugin);
16
+ */
17
+ export class DriverPlugin implements Plugin {
18
+ name: string;
19
+ version = '1.0.0';
20
+ // dependencies = ['com.objectstack.engine.objectql']; // Removed: Driver is a producer, not strictly a consumer during init
21
+
22
+ private driver: any;
23
+
24
+ constructor(driver: any, driverName?: string) {
25
+ this.driver = driver;
26
+ this.name = `com.objectstack.driver.${driverName || driver.name || 'unknown'}`;
27
+ }
28
+
29
+ async init(ctx: PluginContext) {
30
+ // Register driver as a service instead of directly to objectql
31
+ const serviceName = `driver.${this.driver.name || 'unknown'}`;
32
+ ctx.registerService(serviceName, this.driver);
33
+ ctx.logger.log(`[DriverPlugin] Registered driver service: ${serviceName}`);
34
+ }
35
+
36
+ async start(ctx: PluginContext) {
37
+ // Drivers don't need start phase, initialization happens in init
38
+ ctx.logger.log(`[DriverPlugin] Driver ready: ${this.driver.name || 'unknown'}`);
39
+ }
40
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,15 @@
1
1
  // Export core engine
2
- export { ObjectQL, SchemaRegistry } from '@objectstack/objectql';
3
- export { ObjectStackKernel } from './kernel';
4
- export { ObjectStackRuntimeProtocol } from './protocol';
2
+ export { ObjectQL, SchemaRegistry, ObjectStackProtocolImplementation } from '@objectstack/objectql';
3
+
4
+ // Export Kernels
5
+ export { ObjectKernel } from '@objectstack/core';
6
+
7
+ // Export Plugins
8
+ export { ObjectQLPlugin } from '@objectstack/objectql';
9
+ export { DriverPlugin } from './driver-plugin';
10
+ export { AppManifestPlugin } from './app-manifest-plugin';
11
+
12
+ // Export Types
13
+ export * from '@objectstack/core';
5
14
 
6
- export * from './types';
7
15
 
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Test file to verify capability contract interfaces
3
+ *
4
+ * This file demonstrates how plugins can implement the IHttpServer
5
+ * and IDataEngine interfaces without depending on concrete implementations.
6
+ */
7
+
8
+ import { IHttpServer, IDataEngine, RouteHandler, IHttpRequest, IHttpResponse, Middleware, DataEngineQueryOptions } from './index.js';
9
+
10
+ /**
11
+ * Example: Mock HTTP Server Plugin
12
+ *
13
+ * Shows how a plugin can implement the IHttpServer interface
14
+ * without depending on Express, Fastify, or any specific framework.
15
+ */
16
+ class MockHttpServer implements IHttpServer {
17
+ private routes: Map<string, { method: string; handler: RouteHandler }> = new Map();
18
+
19
+ get(path: string, handler: RouteHandler): void {
20
+ this.routes.set(`GET:${path}`, { method: 'GET', handler });
21
+ console.log(`✅ Registered GET ${path}`);
22
+ }
23
+
24
+ post(path: string, handler: RouteHandler): void {
25
+ this.routes.set(`POST:${path}`, { method: 'POST', handler });
26
+ console.log(`✅ Registered POST ${path}`);
27
+ }
28
+
29
+ put(path: string, handler: RouteHandler): void {
30
+ this.routes.set(`PUT:${path}`, { method: 'PUT', handler });
31
+ console.log(`✅ Registered PUT ${path}`);
32
+ }
33
+
34
+ delete(path: string, handler: RouteHandler): void {
35
+ this.routes.set(`DELETE:${path}`, { method: 'DELETE', handler });
36
+ console.log(`✅ Registered DELETE ${path}`);
37
+ }
38
+
39
+ patch(path: string, handler: RouteHandler): void {
40
+ this.routes.set(`PATCH:${path}`, { method: 'PATCH', handler });
41
+ console.log(`✅ Registered PATCH ${path}`);
42
+ }
43
+
44
+ use(path: string | Middleware, handler?: Middleware): void {
45
+ console.log(`✅ Registered middleware`);
46
+ }
47
+
48
+ async listen(port: number): Promise<void> {
49
+ console.log(`✅ Mock HTTP server listening on port ${port}`);
50
+ }
51
+
52
+ async close(): Promise<void> {
53
+ console.log(`✅ Mock HTTP server closed`);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Example: Mock Data Engine Plugin
59
+ *
60
+ * Shows how a plugin can implement the IDataEngine interface
61
+ * without depending on ObjectQL, Prisma, or any specific database.
62
+ */
63
+ class MockDataEngine implements IDataEngine {
64
+ private store: Map<string, Map<string, any>> = new Map();
65
+ private idCounter = 0;
66
+
67
+ async insert(objectName: string, data: any): Promise<any> {
68
+ if (!this.store.has(objectName)) {
69
+ this.store.set(objectName, new Map());
70
+ }
71
+
72
+ const id = `${objectName}_${++this.idCounter}`;
73
+ const record = { id, ...data };
74
+ this.store.get(objectName)!.set(id, record);
75
+
76
+ console.log(`✅ Inserted into ${objectName}:`, record);
77
+ return record;
78
+ }
79
+
80
+ async find(objectName: string, query?: DataEngineQueryOptions): Promise<any[]> {
81
+ const objectStore = this.store.get(objectName);
82
+ if (!objectStore) {
83
+ return [];
84
+ }
85
+
86
+ const results = Array.from(objectStore.values());
87
+ console.log(`✅ Found ${results.length} records in ${objectName}`);
88
+ return results;
89
+ }
90
+
91
+ async update(objectName: string, id: any, data: any): Promise<any> {
92
+ const objectStore = this.store.get(objectName);
93
+ if (!objectStore || !objectStore.has(id)) {
94
+ throw new Error(`Record ${id} not found in ${objectName}`);
95
+ }
96
+
97
+ const existing = objectStore.get(id);
98
+ const updated = { ...existing, ...data };
99
+ objectStore.set(id, updated);
100
+
101
+ console.log(`✅ Updated ${objectName}/${id}:`, updated);
102
+ return updated;
103
+ }
104
+
105
+ async delete(objectName: string, id: any): Promise<boolean> {
106
+ const objectStore = this.store.get(objectName);
107
+ if (!objectStore) {
108
+ return false;
109
+ }
110
+
111
+ const deleted = objectStore.delete(id);
112
+ console.log(`✅ Deleted ${objectName}/${id}: ${deleted}`);
113
+ return deleted;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Test the interfaces
119
+ */
120
+ async function testInterfaces() {
121
+ console.log('\n=== Testing IHttpServer Interface ===\n');
122
+
123
+ const httpServer: IHttpServer = new MockHttpServer();
124
+
125
+ // Register routes using the interface
126
+ httpServer.get('/api/users', async (req, res) => {
127
+ res.json({ users: [] });
128
+ });
129
+
130
+ httpServer.post('/api/users', async (req, res) => {
131
+ res.status(201).json({ id: 1, ...req.body });
132
+ });
133
+
134
+ await httpServer.listen(3000);
135
+
136
+ console.log('\n=== Testing IDataEngine Interface ===\n');
137
+
138
+ const dataEngine: IDataEngine = new MockDataEngine();
139
+
140
+ // Use the data engine interface
141
+ const user1 = await dataEngine.insert('user', {
142
+ name: 'John Doe',
143
+ email: 'john@example.com'
144
+ });
145
+
146
+ const user2 = await dataEngine.insert('user', {
147
+ name: 'Jane Smith',
148
+ email: 'jane@example.com'
149
+ });
150
+
151
+ const users = await dataEngine.find('user');
152
+ console.log(`Found ${users.length} users after inserts`);
153
+
154
+ const updatedUser = await dataEngine.update('user', user1.id, {
155
+ name: 'John Updated'
156
+ });
157
+ console.log(`Updated user:`, updatedUser);
158
+
159
+ const deleted = await dataEngine.delete('user', user2.id);
160
+ console.log(`Delete result: ${deleted}`);
161
+
162
+ console.log('\n✅ All interface tests passed!\n');
163
+
164
+ if (httpServer.close) {
165
+ await httpServer.close();
166
+ }
167
+ }
168
+
169
+ // Run tests
170
+ testInterfaces().catch(console.error);
package/dist/kernel.d.ts DELETED
@@ -1,142 +0,0 @@
1
- import { ObjectQL } from '@objectstack/objectql';
2
- /**
3
- * ObjectStack Kernel (Microkernel)
4
- *
5
- * The central container orchestrating the application lifecycle,
6
- * plugins, and the core ObjectQL engine.
7
- */
8
- export declare class ObjectStackKernel {
9
- ql: ObjectQL;
10
- private plugins;
11
- constructor(plugins?: any[]);
12
- start(): Promise<void>;
13
- seed(): Promise<void>;
14
- find(objectName: string, query: any): Promise<{
15
- value: any;
16
- count: any;
17
- }>;
18
- get(objectName: string, id: string): Promise<any>;
19
- create(objectName: string, data: any): Promise<any>;
20
- update(objectName: string, id: string, data: any): Promise<any>;
21
- delete(objectName: string, id: string): Promise<any>;
22
- getMetadata(objectName: string): {
23
- fields: Record<string, {
24
- type: "number" | "boolean" | "code" | "date" | "text" | "textarea" | "email" | "url" | "phone" | "password" | "markdown" | "html" | "richtext" | "currency" | "percent" | "datetime" | "time" | "toggle" | "select" | "multiselect" | "radio" | "checkboxes" | "lookup" | "master_detail" | "tree" | "image" | "file" | "avatar" | "video" | "audio" | "formula" | "summary" | "autonumber" | "location" | "address" | "json" | "color" | "rating" | "slider" | "signature" | "qrcode" | "progress" | "tags" | "vector";
25
- required: boolean;
26
- searchable: boolean;
27
- multiple: boolean;
28
- unique: boolean;
29
- deleteBehavior: "set_null" | "cascade" | "restrict";
30
- hidden: boolean;
31
- readonly: boolean;
32
- encryption: boolean;
33
- index: boolean;
34
- externalId: boolean;
35
- options?: {
36
- value: string;
37
- label: string;
38
- color?: string | undefined;
39
- default?: boolean | undefined;
40
- }[] | undefined;
41
- min?: number | undefined;
42
- max?: number | undefined;
43
- formula?: string | undefined;
44
- label?: string | undefined;
45
- precision?: number | undefined;
46
- name?: string | undefined;
47
- description?: string | undefined;
48
- format?: string | undefined;
49
- defaultValue?: any;
50
- maxLength?: number | undefined;
51
- minLength?: number | undefined;
52
- scale?: number | undefined;
53
- reference?: string | undefined;
54
- referenceFilters?: string[] | undefined;
55
- writeRequiresMasterRead?: boolean | undefined;
56
- expression?: string | undefined;
57
- summaryOperations?: {
58
- object: string;
59
- function: "count" | "sum" | "avg" | "min" | "max";
60
- field: string;
61
- } | undefined;
62
- language?: string | undefined;
63
- theme?: string | undefined;
64
- lineNumbers?: boolean | undefined;
65
- maxRating?: number | undefined;
66
- allowHalf?: boolean | undefined;
67
- displayMap?: boolean | undefined;
68
- allowGeocoding?: boolean | undefined;
69
- addressFormat?: "us" | "uk" | "international" | undefined;
70
- colorFormat?: "hex" | "rgb" | "rgba" | "hsl" | undefined;
71
- allowAlpha?: boolean | undefined;
72
- presetColors?: string[] | undefined;
73
- step?: number | undefined;
74
- showValue?: boolean | undefined;
75
- marks?: Record<string, string> | undefined;
76
- barcodeFormat?: "qr" | "ean13" | "ean8" | "code128" | "code39" | "upca" | "upce" | undefined;
77
- qrErrorCorrection?: "L" | "M" | "Q" | "H" | undefined;
78
- displayValue?: boolean | undefined;
79
- allowScanning?: boolean | undefined;
80
- currencyConfig?: {
81
- precision: number;
82
- currencyMode: "dynamic" | "fixed";
83
- defaultCurrency: string;
84
- } | undefined;
85
- vectorConfig?: {
86
- dimensions: number;
87
- distanceMetric: "cosine" | "euclidean" | "dotProduct" | "manhattan";
88
- normalized: boolean;
89
- indexed: boolean;
90
- indexType?: "flat" | "hnsw" | "ivfflat" | undefined;
91
- } | undefined;
92
- }>;
93
- name: string;
94
- active: boolean;
95
- isSystem: boolean;
96
- abstract: boolean;
97
- datasource: string;
98
- tags?: string[] | undefined;
99
- label?: string | undefined;
100
- description?: string | undefined;
101
- search?: {
102
- fields: string[];
103
- displayFields?: string[] | undefined;
104
- filters?: string[] | undefined;
105
- } | undefined;
106
- pluralLabel?: string | undefined;
107
- icon?: string | undefined;
108
- tableName?: string | undefined;
109
- indexes?: {
110
- fields: string[];
111
- type?: "hash" | "btree" | "gin" | "gist" | undefined;
112
- name?: string | undefined;
113
- unique?: boolean | undefined;
114
- }[] | undefined;
115
- validations?: any[] | undefined;
116
- titleFormat?: string | undefined;
117
- compactLayout?: string[] | undefined;
118
- enable?: {
119
- searchable: boolean;
120
- trackHistory: boolean;
121
- apiEnabled: boolean;
122
- files: boolean;
123
- feeds: boolean;
124
- activities: boolean;
125
- trash: boolean;
126
- mru: boolean;
127
- clone: boolean;
128
- apiMethods?: ("update" | "delete" | "get" | "list" | "create" | "upsert" | "bulk" | "aggregate" | "history" | "search" | "restore" | "purge" | "import" | "export")[] | undefined;
129
- } | undefined;
130
- };
131
- getView(objectName: string, viewType?: 'list' | 'form'): {
132
- type: string;
133
- title: string;
134
- columns: {
135
- field: string;
136
- label: string;
137
- width: number;
138
- }[];
139
- actions: string[];
140
- } | null;
141
- private ensureSchema;
142
- }
package/dist/kernel.js DELETED
@@ -1,157 +0,0 @@
1
- import { SchemaRegistry, ObjectQL } from '@objectstack/objectql';
2
- /**
3
- * ObjectStack Kernel (Microkernel)
4
- *
5
- * The central container orchestrating the application lifecycle,
6
- * plugins, and the core ObjectQL engine.
7
- */
8
- export class ObjectStackKernel {
9
- constructor(plugins = []) {
10
- // 1. Initialize Engine with Host Context (Simulated OS services)
11
- this.ql = new ObjectQL({
12
- env: process.env.NODE_ENV || 'development'
13
- });
14
- this.plugins = plugins;
15
- }
16
- async start() {
17
- console.log('[Kernel] Starting...');
18
- // 0. Register Provided Plugins
19
- for (const p of this.plugins) {
20
- // Check if it is a Runtime Plugin (System Capability)
21
- if ('onStart' in p || 'install' in p) {
22
- console.log(`[Kernel] Loading Runtime Plugin: ${p.name}`);
23
- if (p.install)
24
- await p.install({ engine: this });
25
- continue;
26
- }
27
- // Otherwise treat as App Manifest
28
- console.log(`[Kernel] Loading App Manifest: ${p.id || p.name}`);
29
- SchemaRegistry.registerPlugin(p);
30
- // Register Objects from App/Plugin
31
- if (p.objects) {
32
- for (const obj of p.objects) {
33
- SchemaRegistry.registerObject(obj);
34
- console.log(`[Kernel] Registered Object: ${obj.name}`);
35
- }
36
- }
37
- }
38
- // 1. Load Drivers (Default to Memory if none provided in plugins)
39
- // TODO: Detect driver from plugins. For now, we still hard load memory driver if needed?
40
- // In strict mode, user should pass driver in plugins array (DriverManifest).
41
- // check if driver is registered
42
- // For Backwards Compat / Easy Dev, try dynamic import of memory driver if installed
43
- try {
44
- // @ts-ignore
45
- const { InMemoryDriver } = await import('@objectstack/driver-memory');
46
- const driver = new InMemoryDriver();
47
- this.ql.registerDriver(driver);
48
- }
49
- catch (e) {
50
- // Ignore if not present
51
- }
52
- // 2. Initialize Engine
53
- await this.ql.init();
54
- // 3. Seed Data
55
- await this.seed();
56
- // 4. Start Runtime Plugins
57
- for (const p of this.plugins) {
58
- if (('onStart' in p) && typeof p.onStart === 'function') {
59
- console.log(`[Kernel] Starting Plugin: ${p.name}`);
60
- await p.onStart({ engine: this });
61
- }
62
- }
63
- }
64
- async seed() {
65
- // If no driver registered yet, this might fail or wait.
66
- // In real world, we wait for 'ready' event.
67
- try {
68
- // Mock System Table
69
- try {
70
- // We don't have SystemStatus defined in schema usually, skipping for general engine
71
- // await this.ql.insert('SystemStatus', { status: 'OK', uptime: 0 });
72
- }
73
- catch { }
74
- // Iterate over all registered plugins/apps and check for 'data' property in manifest
75
- const plugins = SchemaRegistry.getRegisteredTypes(); // This returns types like 'plugin', 'app'
76
- // This is a bit hacky because we don't have a direct "getAllManifests" API exposed easily
77
- // We will iterate known apps for now, or improve Registry API later.
78
- // Actually, SchemaRegistry.listItems('app') returns the manifests!
79
- const apps = [...SchemaRegistry.listItems('app'), ...SchemaRegistry.listItems('plugin')];
80
- for (const appItem of apps) {
81
- const app = appItem; // Cast to access data prop safely
82
- if (app.data && Array.isArray(app.data)) {
83
- console.log(`[Kernel] Seeding data for ${app.name || app.id}...`);
84
- for (const seed of app.data) {
85
- try {
86
- // Check if data exists
87
- const existing = await this.ql.find(seed.object, { top: 1 });
88
- if (existing.length === 0) {
89
- console.log(`[Kernel] Inserting ${seed.records.length} records into ${seed.object}`);
90
- for (const record of seed.records) {
91
- await this.ql.insert(seed.object, record);
92
- }
93
- }
94
- }
95
- catch (e) {
96
- console.warn(`[Kernel] Failed to seed ${seed.object}`, e);
97
- }
98
- }
99
- }
100
- }
101
- }
102
- catch (e) {
103
- console.warn('Seed failed (driver might not be ready):', e);
104
- }
105
- }
106
- // Forward methods to ObjectQL
107
- async find(objectName, query) {
108
- this.ensureSchema(objectName);
109
- const results = await this.ql.find(objectName, { top: 100 });
110
- return { value: results, count: results.length };
111
- }
112
- async get(objectName, id) {
113
- this.ensureSchema(objectName);
114
- // Find One
115
- const results = await this.ql.find(objectName, { top: 1 }); // Mock implementation
116
- return results[0];
117
- }
118
- async create(objectName, data) {
119
- this.ensureSchema(objectName);
120
- return this.ql.insert(objectName, data);
121
- }
122
- async update(objectName, id, data) {
123
- this.ensureSchema(objectName);
124
- return this.ql.update(objectName, id, data);
125
- }
126
- async delete(objectName, id) {
127
- this.ensureSchema(objectName);
128
- return this.ql.delete(objectName, id);
129
- }
130
- // [New Methods for ObjectUI]
131
- getMetadata(objectName) {
132
- return this.ensureSchema(objectName);
133
- }
134
- getView(objectName, viewType = 'list') {
135
- const schema = this.ensureSchema(objectName);
136
- // Auto-Scaffold Default View
137
- if (viewType === 'list') {
138
- return {
139
- type: 'datagrid',
140
- title: `${schema.label || objectName} List`,
141
- columns: Object.keys(schema.fields || {}).map(key => ({
142
- field: key,
143
- label: schema.fields?.[key]?.label || key,
144
- width: 150
145
- })),
146
- actions: ['create', 'edit', 'delete']
147
- };
148
- }
149
- return null;
150
- }
151
- ensureSchema(name) {
152
- const schema = SchemaRegistry.getObject(name);
153
- if (!schema)
154
- throw new Error(`Unknown object: ${name}`);
155
- return schema;
156
- }
157
- }
@@ -1,68 +0,0 @@
1
- import { ObjectStackKernel } from './kernel';
2
- export interface ApiRequest {
3
- params: Record<string, string>;
4
- query: Record<string, string | string[]>;
5
- body?: any;
6
- }
7
- export declare class ObjectStackRuntimeProtocol {
8
- private engine;
9
- constructor(engine: ObjectStackKernel);
10
- getDiscovery(): {
11
- name: string;
12
- version: string;
13
- environment: string;
14
- routes: {
15
- discovery: string;
16
- metadata: string;
17
- data: string;
18
- auth: string;
19
- ui: string;
20
- };
21
- capabilities: {
22
- search: boolean;
23
- files: boolean;
24
- };
25
- };
26
- getMetaTypes(): {
27
- data: {
28
- type: string;
29
- href: string;
30
- count: number;
31
- }[];
32
- };
33
- getMetaItems(typePlural: string): {
34
- data: {
35
- self: string;
36
- path?: string | undefined;
37
- id: any;
38
- name: any;
39
- label: any;
40
- type: any;
41
- icon: any;
42
- description: any;
43
- }[];
44
- };
45
- getMetaItem(typePlural: string, name: string): {};
46
- getUiView(objectName: string, type: 'list' | 'form'): {
47
- type: string;
48
- title: string;
49
- columns: {
50
- field: string;
51
- label: string;
52
- width: number;
53
- }[];
54
- actions: string[];
55
- };
56
- findData(objectName: string, query: any): Promise<{
57
- value: any;
58
- count: any;
59
- }>;
60
- queryData(objectName: string, body: any): Promise<{
61
- value: any;
62
- count: any;
63
- }>;
64
- getData(objectName: string, id: string): Promise<any>;
65
- createData(objectName: string, body: any): Promise<any>;
66
- updateData(objectName: string, id: string, body: any): Promise<any>;
67
- deleteData(objectName: string, id: string): Promise<any>;
68
- }