@objectstack/runtime 1.0.4 → 1.0.5

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/dist/index.js CHANGED
@@ -1,16 +1,1549 @@
1
- // Export Kernels
2
- export { ObjectKernel } from '@objectstack/core';
3
- // Export Runtime
4
- export { Runtime } from './runtime.js';
5
- // Export Plugins
6
- export { DriverPlugin } from './driver-plugin.js';
7
- export { AppPlugin } from './app-plugin.js';
8
- export { createApiRegistryPlugin } from './api-registry-plugin.js';
9
- // Export HTTP Server Components
10
- export { HttpServer } from './http-server.js';
11
- export { HttpDispatcher } from './http-dispatcher.js';
12
- export { RestServer } from './rest-server.js';
13
- export { RouteManager, RouteGroupBuilder } from './route-manager.js';
14
- export { MiddlewareManager } from './middleware.js';
15
- // Export Types
16
- export * from '@objectstack/core';
1
+ // src/index.ts
2
+ import { ObjectKernel as ObjectKernel3 } from "@objectstack/core";
3
+
4
+ // src/runtime.ts
5
+ import { ObjectKernel } from "@objectstack/core";
6
+
7
+ // src/route-manager.ts
8
+ var RouteManager = class {
9
+ constructor(server) {
10
+ this.server = server;
11
+ this.routes = /* @__PURE__ */ new Map();
12
+ }
13
+ /**
14
+ * Register a route
15
+ * @param entry - Route entry with method, path, handler, and metadata
16
+ */
17
+ register(entry) {
18
+ if (typeof entry.handler === "string") {
19
+ throw new Error(
20
+ `String-based route handlers are not supported yet. Received handler identifier "${entry.handler}". Please provide a RouteHandler function instead.`
21
+ );
22
+ }
23
+ const handler = entry.handler;
24
+ const routeEntry = {
25
+ method: entry.method,
26
+ path: entry.path,
27
+ handler,
28
+ metadata: entry.metadata,
29
+ security: entry.security
30
+ };
31
+ const key = this.getRouteKey(entry.method, entry.path);
32
+ this.routes.set(key, routeEntry);
33
+ this.registerWithServer(routeEntry);
34
+ }
35
+ /**
36
+ * Register multiple routes
37
+ * @param entries - Array of route entries
38
+ */
39
+ registerMany(entries) {
40
+ entries.forEach((entry) => this.register(entry));
41
+ }
42
+ /**
43
+ * Unregister a route
44
+ * @param method - HTTP method
45
+ * @param path - Route path
46
+ */
47
+ unregister(method, path) {
48
+ const key = this.getRouteKey(method, path);
49
+ this.routes.delete(key);
50
+ }
51
+ /**
52
+ * Get route by method and path
53
+ * @param method - HTTP method
54
+ * @param path - Route path
55
+ */
56
+ get(method, path) {
57
+ const key = this.getRouteKey(method, path);
58
+ return this.routes.get(key);
59
+ }
60
+ /**
61
+ * Get all routes
62
+ */
63
+ getAll() {
64
+ return Array.from(this.routes.values());
65
+ }
66
+ /**
67
+ * Get routes by method
68
+ * @param method - HTTP method
69
+ */
70
+ getByMethod(method) {
71
+ return this.getAll().filter((route) => route.method === method);
72
+ }
73
+ /**
74
+ * Get routes by path prefix
75
+ * @param prefix - Path prefix
76
+ */
77
+ getByPrefix(prefix) {
78
+ return this.getAll().filter((route) => route.path.startsWith(prefix));
79
+ }
80
+ /**
81
+ * Get routes by tag
82
+ * @param tag - Tag name
83
+ */
84
+ getByTag(tag) {
85
+ return this.getAll().filter(
86
+ (route) => route.metadata?.tags?.includes(tag)
87
+ );
88
+ }
89
+ /**
90
+ * Create a route group with common prefix
91
+ * @param prefix - Common path prefix
92
+ * @param configure - Function to configure routes in the group
93
+ */
94
+ group(prefix, configure) {
95
+ const builder = new RouteGroupBuilder(this, prefix);
96
+ configure(builder);
97
+ }
98
+ /**
99
+ * Get route count
100
+ */
101
+ count() {
102
+ return this.routes.size;
103
+ }
104
+ /**
105
+ * Clear all routes
106
+ */
107
+ clear() {
108
+ this.routes.clear();
109
+ }
110
+ /**
111
+ * Get route key for storage
112
+ */
113
+ getRouteKey(method, path) {
114
+ return `${method}:${path}`;
115
+ }
116
+ /**
117
+ * Register route with underlying server
118
+ */
119
+ registerWithServer(entry) {
120
+ const { method, path, handler } = entry;
121
+ switch (method) {
122
+ case "GET":
123
+ this.server.get(path, handler);
124
+ break;
125
+ case "POST":
126
+ this.server.post(path, handler);
127
+ break;
128
+ case "PUT":
129
+ this.server.put(path, handler);
130
+ break;
131
+ case "DELETE":
132
+ this.server.delete(path, handler);
133
+ break;
134
+ case "PATCH":
135
+ this.server.patch(path, handler);
136
+ break;
137
+ default:
138
+ throw new Error(`Unsupported HTTP method: ${method}`);
139
+ }
140
+ }
141
+ };
142
+ var RouteGroupBuilder = class {
143
+ constructor(manager, prefix) {
144
+ this.manager = manager;
145
+ this.prefix = prefix;
146
+ }
147
+ /**
148
+ * Register GET route in group
149
+ */
150
+ get(path, handler, metadata) {
151
+ this.manager.register({
152
+ method: "GET",
153
+ path: this.resolvePath(path),
154
+ handler,
155
+ metadata
156
+ });
157
+ return this;
158
+ }
159
+ /**
160
+ * Register POST route in group
161
+ */
162
+ post(path, handler, metadata) {
163
+ this.manager.register({
164
+ method: "POST",
165
+ path: this.resolvePath(path),
166
+ handler,
167
+ metadata
168
+ });
169
+ return this;
170
+ }
171
+ /**
172
+ * Register PUT route in group
173
+ */
174
+ put(path, handler, metadata) {
175
+ this.manager.register({
176
+ method: "PUT",
177
+ path: this.resolvePath(path),
178
+ handler,
179
+ metadata
180
+ });
181
+ return this;
182
+ }
183
+ /**
184
+ * Register PATCH route in group
185
+ */
186
+ patch(path, handler, metadata) {
187
+ this.manager.register({
188
+ method: "PATCH",
189
+ path: this.resolvePath(path),
190
+ handler,
191
+ metadata
192
+ });
193
+ return this;
194
+ }
195
+ /**
196
+ * Register DELETE route in group
197
+ */
198
+ delete(path, handler, metadata) {
199
+ this.manager.register({
200
+ method: "DELETE",
201
+ path: this.resolvePath(path),
202
+ handler,
203
+ metadata
204
+ });
205
+ return this;
206
+ }
207
+ /**
208
+ * Resolve full path with prefix
209
+ */
210
+ resolvePath(path) {
211
+ const normalizedPrefix = this.prefix.endsWith("/") ? this.prefix.slice(0, -1) : this.prefix;
212
+ const normalizedPath = path.startsWith("/") ? path : "/" + path;
213
+ return normalizedPrefix + normalizedPath;
214
+ }
215
+ };
216
+
217
+ // src/rest-server.ts
218
+ var RestServer = class {
219
+ constructor(server, protocol, config = {}) {
220
+ this.protocol = protocol;
221
+ this.config = this.normalizeConfig(config);
222
+ this.routeManager = new RouteManager(server);
223
+ }
224
+ /**
225
+ * Normalize configuration with defaults
226
+ */
227
+ normalizeConfig(config) {
228
+ const api = config.api ?? {};
229
+ const crud = config.crud ?? {};
230
+ const metadata = config.metadata ?? {};
231
+ const batch = config.batch ?? {};
232
+ const routes = config.routes ?? {};
233
+ return {
234
+ api: {
235
+ version: api.version ?? "v1",
236
+ basePath: api.basePath ?? "/api",
237
+ apiPath: api.apiPath,
238
+ enableCrud: api.enableCrud ?? true,
239
+ enableMetadata: api.enableMetadata ?? true,
240
+ enableBatch: api.enableBatch ?? true,
241
+ enableDiscovery: api.enableDiscovery ?? true,
242
+ documentation: api.documentation,
243
+ responseFormat: api.responseFormat
244
+ },
245
+ crud: {
246
+ operations: crud.operations ?? {
247
+ create: true,
248
+ read: true,
249
+ update: true,
250
+ delete: true,
251
+ list: true
252
+ },
253
+ patterns: crud.patterns,
254
+ dataPrefix: crud.dataPrefix ?? "/data",
255
+ objectParamStyle: crud.objectParamStyle ?? "path"
256
+ },
257
+ metadata: {
258
+ prefix: metadata.prefix ?? "/meta",
259
+ enableCache: metadata.enableCache ?? true,
260
+ cacheTtl: metadata.cacheTtl ?? 3600,
261
+ endpoints: metadata.endpoints ?? {
262
+ types: true,
263
+ items: true,
264
+ item: true,
265
+ schema: true
266
+ }
267
+ },
268
+ batch: {
269
+ maxBatchSize: batch.maxBatchSize ?? 200,
270
+ enableBatchEndpoint: batch.enableBatchEndpoint ?? true,
271
+ operations: batch.operations ?? {
272
+ createMany: true,
273
+ updateMany: true,
274
+ deleteMany: true,
275
+ upsertMany: true
276
+ },
277
+ defaultAtomic: batch.defaultAtomic ?? true
278
+ },
279
+ routes: {
280
+ includeObjects: routes.includeObjects,
281
+ excludeObjects: routes.excludeObjects,
282
+ nameTransform: routes.nameTransform ?? "none",
283
+ overrides: routes.overrides
284
+ }
285
+ };
286
+ }
287
+ /**
288
+ * Get the full API base path
289
+ */
290
+ getApiBasePath() {
291
+ const { api } = this.config;
292
+ return api.apiPath ?? `${api.basePath}/${api.version}`;
293
+ }
294
+ /**
295
+ * Register all REST API routes
296
+ */
297
+ registerRoutes() {
298
+ const basePath = this.getApiBasePath();
299
+ if (this.config.api.enableDiscovery) {
300
+ this.registerDiscoveryEndpoints(basePath);
301
+ }
302
+ if (this.config.api.enableMetadata) {
303
+ this.registerMetadataEndpoints(basePath);
304
+ }
305
+ if (this.config.api.enableCrud) {
306
+ this.registerCrudEndpoints(basePath);
307
+ }
308
+ if (this.config.api.enableBatch) {
309
+ this.registerBatchEndpoints(basePath);
310
+ }
311
+ }
312
+ /**
313
+ * Register discovery endpoints
314
+ */
315
+ registerDiscoveryEndpoints(basePath) {
316
+ this.routeManager.register({
317
+ method: "GET",
318
+ path: basePath,
319
+ handler: async (_req, res) => {
320
+ try {
321
+ const discovery = await this.protocol.getDiscovery({});
322
+ res.json(discovery);
323
+ } catch (error) {
324
+ res.status(500).json({ error: error.message });
325
+ }
326
+ },
327
+ metadata: {
328
+ summary: "Get API discovery information",
329
+ tags: ["discovery"]
330
+ }
331
+ });
332
+ }
333
+ /**
334
+ * Register metadata endpoints
335
+ */
336
+ registerMetadataEndpoints(basePath) {
337
+ const { metadata } = this.config;
338
+ const metaPath = `${basePath}${metadata.prefix}`;
339
+ if (metadata.endpoints.types !== false) {
340
+ this.routeManager.register({
341
+ method: "GET",
342
+ path: metaPath,
343
+ handler: async (_req, res) => {
344
+ try {
345
+ const types = await this.protocol.getMetaTypes({});
346
+ res.json(types);
347
+ } catch (error) {
348
+ res.status(500).json({ error: error.message });
349
+ }
350
+ },
351
+ metadata: {
352
+ summary: "List all metadata types",
353
+ tags: ["metadata"]
354
+ }
355
+ });
356
+ }
357
+ if (metadata.endpoints.items !== false) {
358
+ this.routeManager.register({
359
+ method: "GET",
360
+ path: `${metaPath}/:type`,
361
+ handler: async (req, res) => {
362
+ try {
363
+ const items = await this.protocol.getMetaItems({ type: req.params.type });
364
+ res.json(items);
365
+ } catch (error) {
366
+ res.status(404).json({ error: error.message });
367
+ }
368
+ },
369
+ metadata: {
370
+ summary: "List metadata items of a type",
371
+ tags: ["metadata"]
372
+ }
373
+ });
374
+ }
375
+ if (metadata.endpoints.item !== false) {
376
+ this.routeManager.register({
377
+ method: "GET",
378
+ path: `${metaPath}/:type/:name`,
379
+ handler: async (req, res) => {
380
+ try {
381
+ if (metadata.enableCache && this.protocol.getMetaItemCached) {
382
+ const cacheRequest = {
383
+ ifNoneMatch: req.headers["if-none-match"],
384
+ ifModifiedSince: req.headers["if-modified-since"]
385
+ };
386
+ const result = await this.protocol.getMetaItemCached({
387
+ type: req.params.type,
388
+ name: req.params.name,
389
+ cacheRequest
390
+ });
391
+ if (result.notModified) {
392
+ res.status(304).send();
393
+ return;
394
+ }
395
+ if (result.etag) {
396
+ const etagValue = result.etag.weak ? `W/"${result.etag.value}"` : `"${result.etag.value}"`;
397
+ res.header("ETag", etagValue);
398
+ }
399
+ if (result.lastModified) {
400
+ res.header("Last-Modified", new Date(result.lastModified).toUTCString());
401
+ }
402
+ if (result.cacheControl) {
403
+ const directives = result.cacheControl.directives.join(", ");
404
+ const maxAge = result.cacheControl.maxAge ? `, max-age=${result.cacheControl.maxAge}` : "";
405
+ res.header("Cache-Control", directives + maxAge);
406
+ }
407
+ res.json(result.data);
408
+ } else {
409
+ const item = await this.protocol.getMetaItem({ type: req.params.type, name: req.params.name });
410
+ res.json(item);
411
+ }
412
+ } catch (error) {
413
+ res.status(404).json({ error: error.message });
414
+ }
415
+ },
416
+ metadata: {
417
+ summary: "Get specific metadata item",
418
+ tags: ["metadata"]
419
+ }
420
+ });
421
+ }
422
+ this.routeManager.register({
423
+ method: "PUT",
424
+ path: `${metaPath}/:type/:name`,
425
+ handler: async (req, res) => {
426
+ try {
427
+ if (!this.protocol.saveMetaItem) {
428
+ res.status(501).json({ error: "Save operation not supported by protocol implementation" });
429
+ return;
430
+ }
431
+ const result = await this.protocol.saveMetaItem({
432
+ type: req.params.type,
433
+ name: req.params.name,
434
+ item: req.body
435
+ });
436
+ res.json(result);
437
+ } catch (error) {
438
+ res.status(400).json({ error: error.message });
439
+ }
440
+ },
441
+ metadata: {
442
+ summary: "Save specific metadata item",
443
+ tags: ["metadata"]
444
+ }
445
+ });
446
+ }
447
+ /**
448
+ * Register CRUD endpoints for data operations
449
+ */
450
+ registerCrudEndpoints(basePath) {
451
+ const { crud } = this.config;
452
+ const dataPath = `${basePath}${crud.dataPrefix}`;
453
+ const operations = crud.operations;
454
+ if (operations.list) {
455
+ this.routeManager.register({
456
+ method: "GET",
457
+ path: `${dataPath}/:object`,
458
+ handler: async (req, res) => {
459
+ try {
460
+ const result = await this.protocol.findData({
461
+ object: req.params.object,
462
+ query: req.query
463
+ });
464
+ res.json(result);
465
+ } catch (error) {
466
+ res.status(400).json({ error: error.message });
467
+ }
468
+ },
469
+ metadata: {
470
+ summary: "Query records",
471
+ tags: ["data", "crud"]
472
+ }
473
+ });
474
+ }
475
+ if (operations.read) {
476
+ this.routeManager.register({
477
+ method: "GET",
478
+ path: `${dataPath}/:object/:id`,
479
+ handler: async (req, res) => {
480
+ try {
481
+ const result = await this.protocol.getData({
482
+ object: req.params.object,
483
+ id: req.params.id
484
+ });
485
+ res.json(result);
486
+ } catch (error) {
487
+ res.status(404).json({ error: error.message });
488
+ }
489
+ },
490
+ metadata: {
491
+ summary: "Get record by ID",
492
+ tags: ["data", "crud"]
493
+ }
494
+ });
495
+ }
496
+ if (operations.create) {
497
+ this.routeManager.register({
498
+ method: "POST",
499
+ path: `${dataPath}/:object`,
500
+ handler: async (req, res) => {
501
+ try {
502
+ const result = await this.protocol.createData({
503
+ object: req.params.object,
504
+ data: req.body
505
+ });
506
+ res.status(201).json(result);
507
+ } catch (error) {
508
+ res.status(400).json({ error: error.message });
509
+ }
510
+ },
511
+ metadata: {
512
+ summary: "Create record",
513
+ tags: ["data", "crud"]
514
+ }
515
+ });
516
+ }
517
+ if (operations.update) {
518
+ this.routeManager.register({
519
+ method: "PATCH",
520
+ path: `${dataPath}/:object/:id`,
521
+ handler: async (req, res) => {
522
+ try {
523
+ const result = await this.protocol.updateData({
524
+ object: req.params.object,
525
+ id: req.params.id,
526
+ data: req.body
527
+ });
528
+ res.json(result);
529
+ } catch (error) {
530
+ res.status(400).json({ error: error.message });
531
+ }
532
+ },
533
+ metadata: {
534
+ summary: "Update record",
535
+ tags: ["data", "crud"]
536
+ }
537
+ });
538
+ }
539
+ if (operations.delete) {
540
+ this.routeManager.register({
541
+ method: "DELETE",
542
+ path: `${dataPath}/:object/:id`,
543
+ handler: async (req, res) => {
544
+ try {
545
+ const result = await this.protocol.deleteData({
546
+ object: req.params.object,
547
+ id: req.params.id
548
+ });
549
+ res.json(result);
550
+ } catch (error) {
551
+ res.status(400).json({ error: error.message });
552
+ }
553
+ },
554
+ metadata: {
555
+ summary: "Delete record",
556
+ tags: ["data", "crud"]
557
+ }
558
+ });
559
+ }
560
+ }
561
+ /**
562
+ * Register batch operation endpoints
563
+ */
564
+ registerBatchEndpoints(basePath) {
565
+ const { crud, batch } = this.config;
566
+ const dataPath = `${basePath}${crud.dataPrefix}`;
567
+ const operations = batch.operations;
568
+ if (batch.enableBatchEndpoint && this.protocol.batchData) {
569
+ this.routeManager.register({
570
+ method: "POST",
571
+ path: `${dataPath}/:object/batch`,
572
+ handler: async (req, res) => {
573
+ try {
574
+ const result = await this.protocol.batchData({
575
+ object: req.params.object,
576
+ request: req.body
577
+ });
578
+ res.json(result);
579
+ } catch (error) {
580
+ res.status(400).json({ error: error.message });
581
+ }
582
+ },
583
+ metadata: {
584
+ summary: "Batch operations",
585
+ tags: ["data", "batch"]
586
+ }
587
+ });
588
+ }
589
+ if (operations.createMany && this.protocol.createManyData) {
590
+ this.routeManager.register({
591
+ method: "POST",
592
+ path: `${dataPath}/:object/createMany`,
593
+ handler: async (req, res) => {
594
+ try {
595
+ const result = await this.protocol.createManyData({
596
+ object: req.params.object,
597
+ records: req.body || []
598
+ });
599
+ res.status(201).json(result);
600
+ } catch (error) {
601
+ res.status(400).json({ error: error.message });
602
+ }
603
+ },
604
+ metadata: {
605
+ summary: "Create multiple records",
606
+ tags: ["data", "batch"]
607
+ }
608
+ });
609
+ }
610
+ if (operations.updateMany && this.protocol.updateManyData) {
611
+ this.routeManager.register({
612
+ method: "POST",
613
+ path: `${dataPath}/:object/updateMany`,
614
+ handler: async (req, res) => {
615
+ try {
616
+ const result = await this.protocol.updateManyData({
617
+ object: req.params.object,
618
+ ...req.body
619
+ });
620
+ res.json(result);
621
+ } catch (error) {
622
+ res.status(400).json({ error: error.message });
623
+ }
624
+ },
625
+ metadata: {
626
+ summary: "Update multiple records",
627
+ tags: ["data", "batch"]
628
+ }
629
+ });
630
+ }
631
+ if (operations.deleteMany && this.protocol.deleteManyData) {
632
+ this.routeManager.register({
633
+ method: "POST",
634
+ path: `${dataPath}/:object/deleteMany`,
635
+ handler: async (req, res) => {
636
+ try {
637
+ const result = await this.protocol.deleteManyData({
638
+ object: req.params.object,
639
+ ...req.body
640
+ });
641
+ res.json(result);
642
+ } catch (error) {
643
+ res.status(400).json({ error: error.message });
644
+ }
645
+ },
646
+ metadata: {
647
+ summary: "Delete multiple records",
648
+ tags: ["data", "batch"]
649
+ }
650
+ });
651
+ }
652
+ }
653
+ /**
654
+ * Get the route manager
655
+ */
656
+ getRouteManager() {
657
+ return this.routeManager;
658
+ }
659
+ /**
660
+ * Get all registered routes
661
+ */
662
+ getRoutes() {
663
+ return this.routeManager.getAll();
664
+ }
665
+ };
666
+
667
+ // src/api-registry-plugin.ts
668
+ function createApiRegistryPlugin(config = {}) {
669
+ return {
670
+ name: "com.objectstack.runtime.api-registry",
671
+ version: "1.0.0",
672
+ init: async (_ctx) => {
673
+ },
674
+ start: async (ctx) => {
675
+ const serverService = config.serverServiceName || "http.server";
676
+ const protocolService = config.protocolServiceName || "protocol";
677
+ let server;
678
+ let protocol;
679
+ try {
680
+ server = ctx.getService(serverService);
681
+ } catch (e) {
682
+ }
683
+ try {
684
+ protocol = ctx.getService(protocolService);
685
+ } catch (e) {
686
+ }
687
+ if (!server) {
688
+ ctx.logger.warn(`ApiRegistryPlugin: HTTP Server service '${serverService}' not found. REST routes skipped.`);
689
+ return;
690
+ }
691
+ if (!protocol) {
692
+ ctx.logger.warn(`ApiRegistryPlugin: Protocol service '${protocolService}' not found. REST routes skipped.`);
693
+ return;
694
+ }
695
+ ctx.logger.info("Hydrating REST API from Protocol...");
696
+ try {
697
+ const restServer = new RestServer(server, protocol, config.api);
698
+ restServer.registerRoutes();
699
+ ctx.logger.info("REST API successfully registered");
700
+ } catch (err) {
701
+ ctx.logger.error("Failed to register REST API routes", { error: err.message });
702
+ throw err;
703
+ }
704
+ }
705
+ };
706
+ }
707
+
708
+ // src/runtime.ts
709
+ var Runtime = class {
710
+ constructor(config = {}) {
711
+ this.kernel = new ObjectKernel(config.kernel);
712
+ if (config.server) {
713
+ this.kernel.registerService("http.server", config.server);
714
+ }
715
+ this.kernel.use(createApiRegistryPlugin(config.api));
716
+ }
717
+ /**
718
+ * Register a plugin
719
+ */
720
+ use(plugin) {
721
+ this.kernel.use(plugin);
722
+ return this;
723
+ }
724
+ /**
725
+ * Start the runtime
726
+ * 1. Initializes all plugins (init phase)
727
+ * 2. Starts all plugins (start phase)
728
+ */
729
+ async start() {
730
+ await this.kernel.bootstrap();
731
+ return this;
732
+ }
733
+ /**
734
+ * Get the kernel instance
735
+ */
736
+ getKernel() {
737
+ return this.kernel;
738
+ }
739
+ };
740
+
741
+ // src/driver-plugin.ts
742
+ var DriverPlugin = class {
743
+ constructor(driver, driverName) {
744
+ this.version = "1.0.0";
745
+ this.init = async (ctx) => {
746
+ const serviceName = `driver.${this.driver.name || "unknown"}`;
747
+ ctx.registerService(serviceName, this.driver);
748
+ ctx.logger.info("Driver service registered", {
749
+ serviceName,
750
+ driverName: this.driver.name,
751
+ driverVersion: this.driver.version
752
+ });
753
+ };
754
+ this.start = async (ctx) => {
755
+ ctx.logger.debug("Driver plugin started", { driverName: this.driver.name || "unknown" });
756
+ };
757
+ this.driver = driver;
758
+ this.name = `com.objectstack.driver.${driverName || driver.name || "unknown"}`;
759
+ }
760
+ };
761
+
762
+ // src/app-plugin.ts
763
+ var AppPlugin = class {
764
+ constructor(bundle) {
765
+ this.init = async (ctx) => {
766
+ const sys = this.bundle.manifest || this.bundle;
767
+ const appId = sys.id || sys.name;
768
+ ctx.logger.info("Registering App Service", {
769
+ appId,
770
+ pluginName: this.name,
771
+ version: this.version
772
+ });
773
+ const serviceName = `app.${appId}`;
774
+ const servicePayload = this.bundle.manifest ? { ...this.bundle.manifest, ...this.bundle } : this.bundle;
775
+ ctx.registerService(serviceName, servicePayload);
776
+ };
777
+ this.start = async (ctx) => {
778
+ const sys = this.bundle.manifest || this.bundle;
779
+ const appId = sys.id || sys.name;
780
+ const ql = ctx.getService("objectql");
781
+ if (!ql) {
782
+ ctx.logger.warn("ObjectQL engine service not found", {
783
+ appName: this.name,
784
+ appId
785
+ });
786
+ return;
787
+ }
788
+ ctx.logger.debug("Retrieved ObjectQL engine service", { appId });
789
+ const runtime = this.bundle.default || this.bundle;
790
+ if (runtime && typeof runtime.onEnable === "function") {
791
+ ctx.logger.info("Executing runtime.onEnable", {
792
+ appName: this.name,
793
+ appId
794
+ });
795
+ const hostContext = {
796
+ ...ctx,
797
+ ql,
798
+ logger: ctx.logger,
799
+ drivers: {
800
+ register: (driver) => {
801
+ ctx.logger.debug("Registering driver via app runtime", {
802
+ driverName: driver.name,
803
+ appId
804
+ });
805
+ ql.registerDriver(driver);
806
+ }
807
+ }
808
+ };
809
+ await runtime.onEnable(hostContext);
810
+ ctx.logger.debug("Runtime.onEnable completed", { appId });
811
+ } else {
812
+ ctx.logger.debug("No runtime.onEnable function found", { appId });
813
+ }
814
+ };
815
+ this.bundle = bundle;
816
+ const sys = bundle.manifest || bundle;
817
+ const appId = sys.id || sys.name || "unnamed-app";
818
+ this.name = `plugin.app.${appId}`;
819
+ this.version = sys.version;
820
+ }
821
+ };
822
+
823
+ // src/http-server.ts
824
+ var HttpServer = class {
825
+ /**
826
+ * Create an HTTP server wrapper
827
+ * @param server - The underlying server implementation (Hono, Express, etc.)
828
+ */
829
+ constructor(server) {
830
+ this.server = server;
831
+ this.routes = /* @__PURE__ */ new Map();
832
+ this.middlewares = [];
833
+ }
834
+ /**
835
+ * Register a GET route handler
836
+ * @param path - Route path (e.g., '/api/users/:id')
837
+ * @param handler - Route handler function
838
+ */
839
+ get(path, handler) {
840
+ const key = `GET:${path}`;
841
+ this.routes.set(key, handler);
842
+ this.server.get(path, handler);
843
+ }
844
+ /**
845
+ * Register a POST route handler
846
+ * @param path - Route path
847
+ * @param handler - Route handler function
848
+ */
849
+ post(path, handler) {
850
+ const key = `POST:${path}`;
851
+ this.routes.set(key, handler);
852
+ this.server.post(path, handler);
853
+ }
854
+ /**
855
+ * Register a PUT route handler
856
+ * @param path - Route path
857
+ * @param handler - Route handler function
858
+ */
859
+ put(path, handler) {
860
+ const key = `PUT:${path}`;
861
+ this.routes.set(key, handler);
862
+ this.server.put(path, handler);
863
+ }
864
+ /**
865
+ * Register a DELETE route handler
866
+ * @param path - Route path
867
+ * @param handler - Route handler function
868
+ */
869
+ delete(path, handler) {
870
+ const key = `DELETE:${path}`;
871
+ this.routes.set(key, handler);
872
+ this.server.delete(path, handler);
873
+ }
874
+ /**
875
+ * Register a PATCH route handler
876
+ * @param path - Route path
877
+ * @param handler - Route handler function
878
+ */
879
+ patch(path, handler) {
880
+ const key = `PATCH:${path}`;
881
+ this.routes.set(key, handler);
882
+ this.server.patch(path, handler);
883
+ }
884
+ /**
885
+ * Register middleware
886
+ * @param path - Optional path to apply middleware to (if omitted, applies globally)
887
+ * @param handler - Middleware function
888
+ */
889
+ use(path, handler) {
890
+ if (typeof path === "function") {
891
+ this.middlewares.push(path);
892
+ this.server.use(path);
893
+ } else if (handler) {
894
+ this.middlewares.push(handler);
895
+ this.server.use(path, handler);
896
+ }
897
+ }
898
+ /**
899
+ * Start the HTTP server
900
+ * @param port - Port number to listen on
901
+ * @returns Promise that resolves when server is ready
902
+ */
903
+ async listen(port) {
904
+ await this.server.listen(port);
905
+ }
906
+ /**
907
+ * Stop the HTTP server
908
+ * @returns Promise that resolves when server is stopped
909
+ */
910
+ async close() {
911
+ if (this.server.close) {
912
+ await this.server.close();
913
+ }
914
+ }
915
+ /**
916
+ * Get registered routes
917
+ * @returns Map of route keys to handlers
918
+ */
919
+ getRoutes() {
920
+ return new Map(this.routes);
921
+ }
922
+ /**
923
+ * Get registered middlewares
924
+ * @returns Array of middleware functions
925
+ */
926
+ getMiddlewares() {
927
+ return [...this.middlewares];
928
+ }
929
+ };
930
+
931
+ // src/http-dispatcher.ts
932
+ import { getEnv } from "@objectstack/core";
933
+ import { CoreServiceName } from "@objectstack/spec/system";
934
+ var HttpDispatcher = class {
935
+ // Casting to any to access dynamic props like broker, services, graphql
936
+ constructor(kernel) {
937
+ this.kernel = kernel;
938
+ }
939
+ success(data, meta) {
940
+ return {
941
+ status: 200,
942
+ body: { success: true, data, meta }
943
+ };
944
+ }
945
+ error(message, code = 500, details) {
946
+ return {
947
+ status: code,
948
+ body: { success: false, error: { message, code, details } }
949
+ };
950
+ }
951
+ ensureBroker() {
952
+ if (!this.kernel.broker) {
953
+ throw { statusCode: 500, message: "Kernel Broker not available" };
954
+ }
955
+ return this.kernel.broker;
956
+ }
957
+ /**
958
+ * Generates the discovery JSON response for the API root
959
+ */
960
+ getDiscoveryInfo(prefix) {
961
+ const services = this.getServicesMap();
962
+ const hasGraphQL = !!(services[CoreServiceName.enum.graphql] || this.kernel.graphql);
963
+ const hasSearch = !!services[CoreServiceName.enum.search];
964
+ const hasWebSockets = !!services[CoreServiceName.enum.realtime];
965
+ const hasFiles = !!(services[CoreServiceName.enum["file-storage"]] || services["storage"]?.supportsFiles);
966
+ const hasAnalytics = !!services[CoreServiceName.enum.analytics];
967
+ const hasHub = !!services[CoreServiceName.enum.hub];
968
+ return {
969
+ name: "ObjectOS",
970
+ version: "1.0.0",
971
+ environment: getEnv("NODE_ENV", "development"),
972
+ routes: {
973
+ data: `${prefix}/data`,
974
+ metadata: `${prefix}/metadata`,
975
+ auth: `${prefix}/auth`,
976
+ graphql: hasGraphQL ? `${prefix}/graphql` : void 0,
977
+ storage: hasFiles ? `${prefix}/storage` : void 0,
978
+ analytics: hasAnalytics ? `${prefix}/analytics` : void 0,
979
+ hub: hasHub ? `${prefix}/hub` : void 0
980
+ },
981
+ features: {
982
+ graphql: hasGraphQL,
983
+ search: hasSearch,
984
+ websockets: hasWebSockets,
985
+ files: hasFiles,
986
+ analytics: hasAnalytics,
987
+ hub: hasHub
988
+ },
989
+ locale: {
990
+ default: "en",
991
+ supported: ["en", "zh-CN"],
992
+ timezone: "UTC"
993
+ }
994
+ };
995
+ }
996
+ /**
997
+ * Handles GraphQL requests
998
+ */
999
+ async handleGraphQL(body, context) {
1000
+ if (!body || !body.query) {
1001
+ throw { statusCode: 400, message: "Missing query in request body" };
1002
+ }
1003
+ if (typeof this.kernel.graphql !== "function") {
1004
+ throw { statusCode: 501, message: "GraphQL service not available" };
1005
+ }
1006
+ return this.kernel.graphql(body.query, body.variables, {
1007
+ request: context.request
1008
+ });
1009
+ }
1010
+ /**
1011
+ * Handles Auth requests
1012
+ * path: sub-path after /auth/
1013
+ */
1014
+ async handleAuth(path, method, body, context) {
1015
+ const authService = this.getService(CoreServiceName.enum.auth);
1016
+ if (authService && typeof authService.handler === "function") {
1017
+ const response = await authService.handler(context.request, context.response);
1018
+ return { handled: true, result: response };
1019
+ }
1020
+ const normalizedPath = path.replace(/^\/+/, "");
1021
+ if (normalizedPath === "login" && method.toUpperCase() === "POST") {
1022
+ const broker = this.ensureBroker();
1023
+ const data = await broker.call("auth.login", body, { request: context.request });
1024
+ return { handled: true, response: { status: 200, body: data } };
1025
+ }
1026
+ return { handled: false };
1027
+ }
1028
+ /**
1029
+ * Handles Metadata requests
1030
+ * Standard: /metadata/:type/:name
1031
+ * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object)
1032
+ */
1033
+ async handleMetadata(path, context, method, body) {
1034
+ const broker = this.ensureBroker();
1035
+ const parts = path.replace(/^\/+/, "").split("/").filter(Boolean);
1036
+ if (parts[0] === "types") {
1037
+ return { handled: true, response: this.success({ types: ["objects", "apps", "plugins"] }) };
1038
+ }
1039
+ if (parts.length === 2) {
1040
+ const [type, name] = parts;
1041
+ if (method === "PUT" && body) {
1042
+ const protocol = this.kernel?.context?.getService ? this.kernel.context.getService("protocol") : null;
1043
+ if (protocol && typeof protocol.saveMetaItem === "function") {
1044
+ try {
1045
+ const result = await protocol.saveMetaItem({ type, name, item: body });
1046
+ return { handled: true, response: this.success(result) };
1047
+ } catch (e) {
1048
+ return { handled: true, response: this.error(e.message, 400) };
1049
+ }
1050
+ }
1051
+ try {
1052
+ const data = await broker.call("metadata.saveItem", { type, name, item: body }, { request: context.request });
1053
+ return { handled: true, response: this.success(data) };
1054
+ } catch (e) {
1055
+ return { handled: true, response: this.error(e.message || "Save not supported", 501) };
1056
+ }
1057
+ }
1058
+ try {
1059
+ if (type === "objects") {
1060
+ const data2 = await broker.call("metadata.getObject", { objectName: name }, { request: context.request });
1061
+ return { handled: true, response: this.success(data2) };
1062
+ }
1063
+ const data = await broker.call(`metadata.get${this.capitalize(type.slice(0, -1))}`, { name }, { request: context.request });
1064
+ return { handled: true, response: this.success(data) };
1065
+ } catch (e) {
1066
+ return { handled: true, response: this.error(e.message, 404) };
1067
+ }
1068
+ }
1069
+ if (parts.length === 1) {
1070
+ const typeOrName = parts[0];
1071
+ if (["objects", "apps", "plugins"].includes(typeOrName)) {
1072
+ if (typeOrName === "objects") {
1073
+ const data3 = await broker.call("metadata.objects", {}, { request: context.request });
1074
+ return { handled: true, response: this.success(data3) };
1075
+ }
1076
+ const data2 = await broker.call(`metadata.${typeOrName}`, {}, { request: context.request });
1077
+ return { handled: true, response: this.success(data2) };
1078
+ }
1079
+ const data = await broker.call("metadata.getObject", { objectName: typeOrName }, { request: context.request });
1080
+ return { handled: true, response: this.success(data) };
1081
+ }
1082
+ if (parts.length === 0) {
1083
+ const data = await broker.call("metadata.objects", {}, { request: context.request });
1084
+ return { handled: true, response: this.success(data) };
1085
+ }
1086
+ return { handled: false };
1087
+ }
1088
+ /**
1089
+ * Handles Data requests
1090
+ * path: sub-path after /data/ (e.g. "contacts", "contacts/123", "contacts/query")
1091
+ */
1092
+ async handleData(path, method, body, query, context) {
1093
+ const broker = this.ensureBroker();
1094
+ const parts = path.replace(/^\/+/, "").split("/");
1095
+ const objectName = parts[0];
1096
+ if (!objectName) {
1097
+ return { handled: true, response: this.error("Object name required", 400) };
1098
+ }
1099
+ const m = method.toUpperCase();
1100
+ if (parts.length > 1) {
1101
+ const action = parts[1];
1102
+ if (action === "query" && m === "POST") {
1103
+ const result = await broker.call("data.query", { object: objectName, ...body }, { request: context.request });
1104
+ return { handled: true, response: this.success(result.data, { count: result.count, limit: body.limit, skip: body.skip }) };
1105
+ }
1106
+ if (action === "batch" && m === "POST") {
1107
+ const result = await broker.call("data.batch", { object: objectName, ...body }, { request: context.request });
1108
+ return { handled: true, response: this.success(result) };
1109
+ }
1110
+ if (parts.length === 2 && m === "GET") {
1111
+ const id = parts[1];
1112
+ const data = await broker.call("data.get", { object: objectName, id, ...query }, { request: context.request });
1113
+ return { handled: true, response: this.success(data) };
1114
+ }
1115
+ if (parts.length === 2 && m === "PATCH") {
1116
+ const id = parts[1];
1117
+ const data = await broker.call("data.update", { object: objectName, id, data: body }, { request: context.request });
1118
+ return { handled: true, response: this.success(data) };
1119
+ }
1120
+ if (parts.length === 2 && m === "DELETE") {
1121
+ const id = parts[1];
1122
+ await broker.call("data.delete", { object: objectName, id }, { request: context.request });
1123
+ return { handled: true, response: this.success({ id, deleted: true }) };
1124
+ }
1125
+ } else {
1126
+ if (m === "GET") {
1127
+ const result = await broker.call("data.query", { object: objectName, filters: query }, { request: context.request });
1128
+ return { handled: true, response: this.success(result.data, { count: result.count }) };
1129
+ }
1130
+ if (m === "POST") {
1131
+ const data = await broker.call("data.create", { object: objectName, data: body }, { request: context.request });
1132
+ const res = this.success(data);
1133
+ res.status = 201;
1134
+ return { handled: true, response: res };
1135
+ }
1136
+ }
1137
+ return { handled: false };
1138
+ }
1139
+ /**
1140
+ * Handles Analytics requests
1141
+ * path: sub-path after /analytics/
1142
+ */
1143
+ async handleAnalytics(path, method, body, context) {
1144
+ const analyticsService = this.getService(CoreServiceName.enum.analytics);
1145
+ if (!analyticsService) return { handled: false };
1146
+ const m = method.toUpperCase();
1147
+ const subPath = path.replace(/^\/+/, "");
1148
+ if (subPath === "query" && m === "POST") {
1149
+ const result = await analyticsService.query(body, { request: context.request });
1150
+ return { handled: true, response: this.success(result) };
1151
+ }
1152
+ if (subPath === "meta" && m === "GET") {
1153
+ const result = await analyticsService.getMetadata({ request: context.request });
1154
+ return { handled: true, response: this.success(result) };
1155
+ }
1156
+ if (subPath === "sql" && m === "POST") {
1157
+ const result = await analyticsService.generateSql(body, { request: context.request });
1158
+ return { handled: true, response: this.success(result) };
1159
+ }
1160
+ return { handled: false };
1161
+ }
1162
+ /**
1163
+ * Handles Hub requests
1164
+ * path: sub-path after /hub/
1165
+ */
1166
+ async handleHub(path, method, body, query, context) {
1167
+ const hubService = this.getService(CoreServiceName.enum.hub);
1168
+ if (!hubService) return { handled: false };
1169
+ const m = method.toUpperCase();
1170
+ const parts = path.replace(/^\/+/, "").split("/");
1171
+ if (parts.length > 0) {
1172
+ const resource = parts[0];
1173
+ const actionBase = resource.endsWith("s") ? resource.slice(0, -1) : resource;
1174
+ const id = parts[1];
1175
+ try {
1176
+ if (parts.length === 1) {
1177
+ if (m === "GET") {
1178
+ const capitalizedAction = "list" + this.capitalize(resource);
1179
+ if (typeof hubService[capitalizedAction] === "function") {
1180
+ const result = await hubService[capitalizedAction](query, { request: context.request });
1181
+ return { handled: true, response: this.success(result) };
1182
+ }
1183
+ }
1184
+ if (m === "POST") {
1185
+ const capitalizedAction = "create" + this.capitalize(actionBase);
1186
+ if (typeof hubService[capitalizedAction] === "function") {
1187
+ const result = await hubService[capitalizedAction](body, { request: context.request });
1188
+ return { handled: true, response: this.success(result) };
1189
+ }
1190
+ }
1191
+ } else if (parts.length === 2) {
1192
+ if (m === "GET") {
1193
+ const capitalizedAction = "get" + this.capitalize(actionBase);
1194
+ if (typeof hubService[capitalizedAction] === "function") {
1195
+ const result = await hubService[capitalizedAction](id, { request: context.request });
1196
+ return { handled: true, response: this.success(result) };
1197
+ }
1198
+ }
1199
+ if (m === "PATCH" || m === "PUT") {
1200
+ const capitalizedAction = "update" + this.capitalize(actionBase);
1201
+ if (typeof hubService[capitalizedAction] === "function") {
1202
+ const result = await hubService[capitalizedAction](id, body, { request: context.request });
1203
+ return { handled: true, response: this.success(result) };
1204
+ }
1205
+ }
1206
+ if (m === "DELETE") {
1207
+ const capitalizedAction = "delete" + this.capitalize(actionBase);
1208
+ if (typeof hubService[capitalizedAction] === "function") {
1209
+ const result = await hubService[capitalizedAction](id, { request: context.request });
1210
+ return { handled: true, response: this.success(result) };
1211
+ }
1212
+ }
1213
+ }
1214
+ } catch (e) {
1215
+ return { handled: true, response: this.error(e.message, 500) };
1216
+ }
1217
+ }
1218
+ return { handled: false };
1219
+ }
1220
+ /**
1221
+ * Handles Storage requests
1222
+ * path: sub-path after /storage/
1223
+ */
1224
+ async handleStorage(path, method, file, context) {
1225
+ const storageService = this.getService(CoreServiceName.enum["file-storage"]) || this.kernel.services?.["file-storage"];
1226
+ if (!storageService) {
1227
+ return { handled: true, response: this.error("File storage not configured", 501) };
1228
+ }
1229
+ const m = method.toUpperCase();
1230
+ const parts = path.replace(/^\/+/, "").split("/");
1231
+ if (parts[0] === "upload" && m === "POST") {
1232
+ if (!file) {
1233
+ return { handled: true, response: this.error("No file provided", 400) };
1234
+ }
1235
+ const result = await storageService.upload(file, { request: context.request });
1236
+ return { handled: true, response: this.success(result) };
1237
+ }
1238
+ if (parts[0] === "file" && parts[1] && m === "GET") {
1239
+ const id = parts[1];
1240
+ const result = await storageService.download(id, { request: context.request });
1241
+ if (result.url && result.redirect) {
1242
+ return { handled: true, result: { type: "redirect", url: result.url } };
1243
+ }
1244
+ if (result.stream) {
1245
+ return {
1246
+ handled: true,
1247
+ result: {
1248
+ type: "stream",
1249
+ stream: result.stream,
1250
+ headers: {
1251
+ "Content-Type": result.mimeType || "application/octet-stream",
1252
+ "Content-Length": result.size
1253
+ }
1254
+ }
1255
+ };
1256
+ }
1257
+ return { handled: true, response: this.success(result) };
1258
+ }
1259
+ return { handled: false };
1260
+ }
1261
+ /**
1262
+ * Handles Automation requests
1263
+ * path: sub-path after /automation/
1264
+ */
1265
+ async handleAutomation(path, method, body, context) {
1266
+ const automationService = this.getService(CoreServiceName.enum.automation);
1267
+ if (!automationService) return { handled: false };
1268
+ const m = method.toUpperCase();
1269
+ const parts = path.replace(/^\/+/, "").split("/");
1270
+ if (parts[0] === "trigger" && parts[1] && m === "POST") {
1271
+ const triggerName = parts[1];
1272
+ if (typeof automationService.trigger === "function") {
1273
+ const result = await automationService.trigger(triggerName, body, { request: context.request });
1274
+ return { handled: true, response: this.success(result) };
1275
+ }
1276
+ }
1277
+ return { handled: false };
1278
+ }
1279
+ getServicesMap() {
1280
+ if (this.kernel.services instanceof Map) {
1281
+ return Object.fromEntries(this.kernel.services);
1282
+ }
1283
+ return this.kernel.services || {};
1284
+ }
1285
+ getService(name) {
1286
+ if (typeof this.kernel.getService === "function") {
1287
+ return this.kernel.getService(name);
1288
+ }
1289
+ const services = this.getServicesMap();
1290
+ return services[name];
1291
+ }
1292
+ capitalize(s) {
1293
+ return s.charAt(0).toUpperCase() + s.slice(1);
1294
+ }
1295
+ /**
1296
+ * Main Dispatcher Entry Point
1297
+ * Routes the request to the appropriate handler based on path and precedence
1298
+ */
1299
+ async dispatch(method, path, body, query, context) {
1300
+ const cleanPath = path.replace(/\/$/, "");
1301
+ if (cleanPath.startsWith("/auth")) {
1302
+ return this.handleAuth(cleanPath.substring(5), method, body, context);
1303
+ }
1304
+ if (cleanPath.startsWith("/metadata")) {
1305
+ return this.handleMetadata(cleanPath.substring(9), context);
1306
+ }
1307
+ if (cleanPath.startsWith("/data")) {
1308
+ return this.handleData(cleanPath.substring(5), method, body, query, context);
1309
+ }
1310
+ if (cleanPath.startsWith("/graphql")) {
1311
+ if (method === "POST") return this.handleGraphQL(body, context);
1312
+ }
1313
+ if (cleanPath.startsWith("/storage")) {
1314
+ return this.handleStorage(cleanPath.substring(8), method, body, context);
1315
+ }
1316
+ if (cleanPath.startsWith("/automation")) {
1317
+ return this.handleAutomation(cleanPath.substring(11), method, body, context);
1318
+ }
1319
+ if (cleanPath.startsWith("/analytics")) {
1320
+ return this.handleAnalytics(cleanPath.substring(10), method, body, context);
1321
+ }
1322
+ if (cleanPath.startsWith("/hub")) {
1323
+ return this.handleHub(cleanPath.substring(4), method, body, query, context);
1324
+ }
1325
+ if (cleanPath === "/openapi.json" && method === "GET") {
1326
+ const broker = this.ensureBroker();
1327
+ try {
1328
+ const result2 = await broker.call("metadata.generateOpenApi", {}, { request: context.request });
1329
+ return { handled: true, response: this.success(result2) };
1330
+ } catch (e) {
1331
+ }
1332
+ }
1333
+ const result = await this.handleApiEndpoint(cleanPath, method, body, query, context);
1334
+ if (result.handled) return result;
1335
+ return { handled: false };
1336
+ }
1337
+ /**
1338
+ * Handles Custom API Endpoints defined in metadata
1339
+ */
1340
+ async handleApiEndpoint(path, method, body, query, context) {
1341
+ const broker = this.ensureBroker();
1342
+ try {
1343
+ const endpoint = await broker.call("metadata.matchEndpoint", { path, method });
1344
+ if (endpoint) {
1345
+ if (endpoint.type === "flow") {
1346
+ const result = await broker.call("automation.runFlow", {
1347
+ flowId: endpoint.target,
1348
+ inputs: { ...query, ...body, _request: context.request }
1349
+ });
1350
+ return { handled: true, response: this.success(result) };
1351
+ }
1352
+ if (endpoint.type === "script") {
1353
+ const result = await broker.call("automation.runScript", {
1354
+ scriptName: endpoint.target,
1355
+ context: { ...query, ...body, request: context.request }
1356
+ }, { request: context.request });
1357
+ return { handled: true, response: this.success(result) };
1358
+ }
1359
+ if (endpoint.type === "object_operation") {
1360
+ if (endpoint.objectParams) {
1361
+ const { object, operation } = endpoint.objectParams;
1362
+ if (operation === "find") {
1363
+ const result = await broker.call("data.query", { object, filters: query }, { request: context.request });
1364
+ return { handled: true, response: this.success(result.data, { count: result.count }) };
1365
+ }
1366
+ if (operation === "get" && query.id) {
1367
+ const result = await broker.call("data.get", { object, id: query.id }, { request: context.request });
1368
+ return { handled: true, response: this.success(result) };
1369
+ }
1370
+ if (operation === "create") {
1371
+ const result = await broker.call("data.create", { object, data: body }, { request: context.request });
1372
+ return { handled: true, response: this.success(result) };
1373
+ }
1374
+ }
1375
+ }
1376
+ if (endpoint.type === "proxy") {
1377
+ return {
1378
+ handled: true,
1379
+ response: {
1380
+ status: 200,
1381
+ body: { proxy: true, target: endpoint.target, note: "Proxy execution requires http-client service" }
1382
+ }
1383
+ };
1384
+ }
1385
+ }
1386
+ } catch (e) {
1387
+ }
1388
+ return { handled: false };
1389
+ }
1390
+ };
1391
+
1392
+ // src/middleware.ts
1393
+ var MiddlewareManager = class {
1394
+ constructor() {
1395
+ this.middlewares = /* @__PURE__ */ new Map();
1396
+ }
1397
+ /**
1398
+ * Register middleware with configuration
1399
+ * @param config - Middleware configuration
1400
+ * @param middleware - Middleware function
1401
+ */
1402
+ register(config, middleware) {
1403
+ const entry = {
1404
+ name: config.name,
1405
+ type: config.type,
1406
+ middleware,
1407
+ order: config.order ?? 100,
1408
+ enabled: config.enabled ?? true,
1409
+ paths: config.paths
1410
+ };
1411
+ this.middlewares.set(config.name, entry);
1412
+ }
1413
+ /**
1414
+ * Unregister middleware by name
1415
+ * @param name - Middleware name
1416
+ */
1417
+ unregister(name) {
1418
+ this.middlewares.delete(name);
1419
+ }
1420
+ /**
1421
+ * Enable middleware by name
1422
+ * @param name - Middleware name
1423
+ */
1424
+ enable(name) {
1425
+ const entry = this.middlewares.get(name);
1426
+ if (entry) {
1427
+ entry.enabled = true;
1428
+ }
1429
+ }
1430
+ /**
1431
+ * Disable middleware by name
1432
+ * @param name - Middleware name
1433
+ */
1434
+ disable(name) {
1435
+ const entry = this.middlewares.get(name);
1436
+ if (entry) {
1437
+ entry.enabled = false;
1438
+ }
1439
+ }
1440
+ /**
1441
+ * Get middleware entry by name
1442
+ * @param name - Middleware name
1443
+ */
1444
+ get(name) {
1445
+ return this.middlewares.get(name);
1446
+ }
1447
+ /**
1448
+ * Get all middleware entries
1449
+ */
1450
+ getAll() {
1451
+ return Array.from(this.middlewares.values());
1452
+ }
1453
+ /**
1454
+ * Get middleware by type
1455
+ * @param type - Middleware type
1456
+ */
1457
+ getByType(type) {
1458
+ return this.getAll().filter((entry) => entry.type === type);
1459
+ }
1460
+ /**
1461
+ * Get middleware chain sorted by order
1462
+ * Returns only enabled middleware
1463
+ */
1464
+ getMiddlewareChain() {
1465
+ return this.getAll().filter((entry) => entry.enabled).sort((a, b) => a.order - b.order).map((entry) => entry.middleware);
1466
+ }
1467
+ /**
1468
+ * Get middleware chain with path filtering
1469
+ * @param path - Request path to match against
1470
+ */
1471
+ getMiddlewareChainForPath(path) {
1472
+ return this.getAll().filter((entry) => {
1473
+ if (!entry.enabled) return false;
1474
+ if (entry.paths) {
1475
+ if (entry.paths.exclude) {
1476
+ const excluded = entry.paths.exclude.some(
1477
+ (pattern) => this.matchPath(path, pattern)
1478
+ );
1479
+ if (excluded) return false;
1480
+ }
1481
+ if (entry.paths.include) {
1482
+ const included = entry.paths.include.some(
1483
+ (pattern) => this.matchPath(path, pattern)
1484
+ );
1485
+ if (!included) return false;
1486
+ }
1487
+ }
1488
+ return true;
1489
+ }).sort((a, b) => a.order - b.order).map((entry) => entry.middleware);
1490
+ }
1491
+ /**
1492
+ * Match path against pattern (simple glob matching)
1493
+ * @param path - Request path
1494
+ * @param pattern - Pattern to match (supports * wildcard)
1495
+ */
1496
+ matchPath(path, pattern) {
1497
+ const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, ".");
1498
+ const regex = new RegExp(`^${regexPattern}$`);
1499
+ return regex.test(path);
1500
+ }
1501
+ /**
1502
+ * Clear all middleware
1503
+ */
1504
+ clear() {
1505
+ this.middlewares.clear();
1506
+ }
1507
+ /**
1508
+ * Get middleware count
1509
+ */
1510
+ count() {
1511
+ return this.middlewares.size;
1512
+ }
1513
+ /**
1514
+ * Create a composite middleware from the chain
1515
+ * This can be used to apply all middleware at once
1516
+ */
1517
+ createCompositeMiddleware() {
1518
+ const chain = this.getMiddlewareChain();
1519
+ return async (req, res, next) => {
1520
+ let index = 0;
1521
+ const executeNext = async () => {
1522
+ if (index >= chain.length) {
1523
+ await next();
1524
+ return;
1525
+ }
1526
+ const middleware = chain[index++];
1527
+ await middleware(req, res, executeNext);
1528
+ };
1529
+ await executeNext();
1530
+ };
1531
+ }
1532
+ };
1533
+
1534
+ // src/index.ts
1535
+ export * from "@objectstack/core";
1536
+ export {
1537
+ AppPlugin,
1538
+ DriverPlugin,
1539
+ HttpDispatcher,
1540
+ HttpServer,
1541
+ MiddlewareManager,
1542
+ ObjectKernel3 as ObjectKernel,
1543
+ RestServer,
1544
+ RouteGroupBuilder,
1545
+ RouteManager,
1546
+ Runtime,
1547
+ createApiRegistryPlugin
1548
+ };
1549
+ //# sourceMappingURL=index.js.map