@almadar/server 2.0.9 → 2.1.1

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.
Files changed (105) hide show
  1. package/package.json +10 -4
  2. package/dist/contracts.d.ts +0 -174
  3. package/dist/contracts.d.ts.map +0 -1
  4. package/dist/deepagent/__tests__/memory.test.d.ts +0 -6
  5. package/dist/deepagent/__tests__/memory.test.d.ts.map +0 -1
  6. package/dist/deepagent/__tests__/session.test.d.ts +0 -6
  7. package/dist/deepagent/__tests__/session.test.d.ts.map +0 -1
  8. package/dist/deepagent/__tests__/skill-agent.test.d.ts +0 -6
  9. package/dist/deepagent/__tests__/skill-agent.test.d.ts.map +0 -1
  10. package/dist/deepagent/memory.d.ts +0 -17
  11. package/dist/deepagent/memory.d.ts.map +0 -1
  12. package/dist/deepagent/memory.js +0 -48
  13. package/dist/deepagent/memory.js.map +0 -1
  14. package/dist/deepagent/session.d.ts +0 -17
  15. package/dist/deepagent/session.d.ts.map +0 -1
  16. package/dist/deepagent/session.js +0 -68
  17. package/dist/deepagent/session.js.map +0 -1
  18. package/dist/deepagent/skill-agent.d.ts +0 -22
  19. package/dist/deepagent/skill-agent.d.ts.map +0 -1
  20. package/dist/deepagent/skill-agent.js +0 -114
  21. package/dist/deepagent/skill-agent.js.map +0 -1
  22. package/dist/index.d.ts +0 -42
  23. package/dist/index.d.ts.map +0 -1
  24. package/dist/index.js +0 -2460
  25. package/dist/index.js.map +0 -1
  26. package/dist/lib/db.d.ts +0 -36
  27. package/dist/lib/db.d.ts.map +0 -1
  28. package/dist/lib/debugRouter.d.ts +0 -21
  29. package/dist/lib/debugRouter.d.ts.map +0 -1
  30. package/dist/lib/env.d.ts +0 -16
  31. package/dist/lib/env.d.ts.map +0 -1
  32. package/dist/lib/eventBus.d.ts +0 -44
  33. package/dist/lib/eventBus.d.ts.map +0 -1
  34. package/dist/lib/eventBusTransport.d.ts +0 -143
  35. package/dist/lib/eventBusTransport.d.ts.map +0 -1
  36. package/dist/lib/eventPersistence.d.ts +0 -151
  37. package/dist/lib/eventPersistence.d.ts.map +0 -1
  38. package/dist/lib/index.d.ts +0 -6
  39. package/dist/lib/index.d.ts.map +0 -1
  40. package/dist/lib/index.js +0 -288
  41. package/dist/lib/index.js.map +0 -1
  42. package/dist/lib/logger.d.ts +0 -7
  43. package/dist/lib/logger.d.ts.map +0 -1
  44. package/dist/lib/serviceDiscovery.d.ts +0 -168
  45. package/dist/lib/serviceDiscovery.d.ts.map +0 -1
  46. package/dist/lib/websocket.d.ts +0 -41
  47. package/dist/lib/websocket.d.ts.map +0 -1
  48. package/dist/middleware/__tests__/multi-user.test.d.ts +0 -6
  49. package/dist/middleware/__tests__/multi-user.test.d.ts.map +0 -1
  50. package/dist/middleware/authenticateFirebase.d.ts +0 -4
  51. package/dist/middleware/authenticateFirebase.d.ts.map +0 -1
  52. package/dist/middleware/errorHandler.d.ts +0 -53
  53. package/dist/middleware/errorHandler.d.ts.map +0 -1
  54. package/dist/middleware/index.d.ts +0 -4
  55. package/dist/middleware/index.d.ts.map +0 -1
  56. package/dist/middleware/index.js +0 -284
  57. package/dist/middleware/index.js.map +0 -1
  58. package/dist/middleware/multi-user.d.ts +0 -34
  59. package/dist/middleware/multi-user.d.ts.map +0 -1
  60. package/dist/middleware/multi-user.js +0 -76
  61. package/dist/middleware/multi-user.js.map +0 -1
  62. package/dist/middleware/validation.d.ts +0 -15
  63. package/dist/middleware/validation.d.ts.map +0 -1
  64. package/dist/routes/__tests__/observability.test.d.ts +0 -6
  65. package/dist/routes/__tests__/observability.test.d.ts.map +0 -1
  66. package/dist/routes/observability.d.ts +0 -11
  67. package/dist/routes/observability.d.ts.map +0 -1
  68. package/dist/routes/observability.js +0 -62
  69. package/dist/routes/observability.js.map +0 -1
  70. package/dist/services/DataService.d.ts +0 -70
  71. package/dist/services/DataService.d.ts.map +0 -1
  72. package/dist/services/MockDataService.d.ts +0 -110
  73. package/dist/services/MockDataService.d.ts.map +0 -1
  74. package/dist/services/index.d.ts +0 -8
  75. package/dist/services/index.d.ts.map +0 -1
  76. package/dist/services/index.js +0 -735
  77. package/dist/services/index.js.map +0 -1
  78. package/dist/stores/ChangeSetStore.d.ts +0 -24
  79. package/dist/stores/ChangeSetStore.d.ts.map +0 -1
  80. package/dist/stores/SchemaProtectionService.d.ts +0 -23
  81. package/dist/stores/SchemaProtectionService.d.ts.map +0 -1
  82. package/dist/stores/SchemaStore.d.ts +0 -52
  83. package/dist/stores/SchemaStore.d.ts.map +0 -1
  84. package/dist/stores/SnapshotStore.d.ts +0 -26
  85. package/dist/stores/SnapshotStore.d.ts.map +0 -1
  86. package/dist/stores/ValidationStore.d.ts +0 -19
  87. package/dist/stores/ValidationStore.d.ts.map +0 -1
  88. package/dist/stores/firestoreFormat.d.ts +0 -21
  89. package/dist/stores/firestoreFormat.d.ts.map +0 -1
  90. package/dist/stores/index.d.ts +0 -14
  91. package/dist/stores/index.d.ts.map +0 -1
  92. package/dist/stores/index.js +0 -519
  93. package/dist/stores/index.js.map +0 -1
  94. package/dist/utils/index.d.ts +0 -9
  95. package/dist/utils/index.d.ts.map +0 -1
  96. package/dist/utils/index.js +0 -106
  97. package/dist/utils/index.js.map +0 -1
  98. package/dist/utils/queryFilters.d.ts +0 -87
  99. package/dist/utils/queryFilters.d.ts.map +0 -1
  100. package/dist/websocket/__tests__/state-sync.test.d.ts +0 -6
  101. package/dist/websocket/__tests__/state-sync.test.d.ts.map +0 -1
  102. package/dist/websocket/state-sync.d.ts +0 -39
  103. package/dist/websocket/state-sync.d.ts.map +0 -1
  104. package/dist/websocket/state-sync.js +0 -77
  105. package/dist/websocket/state-sync.js.map +0 -1
package/dist/index.js DELETED
@@ -1,2460 +0,0 @@
1
- import { z, ZodError } from 'zod';
2
- import dotenv from 'dotenv';
3
- import { Router } from 'express';
4
- import admin from 'firebase-admin';
5
- export { default as admin } from 'firebase-admin';
6
- import { faker } from '@faker-js/faker';
7
- import { WebSocketServer, WebSocket } from 'ws';
8
- import { diffSchemas, categorizeRemovals, detectPageContentReduction, isDestructiveChange, hasSignificantPageReduction, requiresConfirmation } from '@almadar/core';
9
- import { getObservabilityCollector, MemoryManager, SessionManager, getMultiUserManager, createWorkflowToolWrapper, createSkillAgent, createUserContext, getStateSyncManager } from '@almadar/agent';
10
-
11
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
12
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
13
- }) : x)(function(x) {
14
- if (typeof require !== "undefined") return require.apply(this, arguments);
15
- throw Error('Dynamic require of "' + x + '" is not supported');
16
- });
17
- dotenv.config();
18
- var envSchema = z.object({
19
- NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
20
- PORT: z.string().default("3030").transform((val) => parseInt(val, 10)),
21
- CORS_ORIGIN: z.string().default("http://localhost:5173").transform((val) => val.includes(",") ? val.split(",").map((s) => s.trim()) : val),
22
- // Database (Prisma/SQL) - optional
23
- DATABASE_URL: z.string().optional(),
24
- // Firebase/Firestore configuration
25
- FIREBASE_PROJECT_ID: z.string().optional(),
26
- FIREBASE_CLIENT_EMAIL: z.string().optional(),
27
- FIREBASE_PRIVATE_KEY: z.string().optional(),
28
- FIREBASE_SERVICE_ACCOUNT_PATH: z.string().optional(),
29
- FIRESTORE_EMULATOR_HOST: z.string().optional(),
30
- FIREBASE_AUTH_EMULATOR_HOST: z.string().optional(),
31
- // API configuration
32
- API_PREFIX: z.string().default("/api"),
33
- // Mock data configuration
34
- USE_MOCK_DATA: z.string().default("true").transform((v) => v === "true"),
35
- MOCK_SEED: z.string().optional().transform((v) => v ? parseInt(v, 10) : void 0)
36
- });
37
- var parsed = envSchema.safeParse(process.env);
38
- if (!parsed.success) {
39
- console.error("\u274C Invalid environment variables:", parsed.error.flatten().fieldErrors);
40
- throw new Error("Invalid environment variables");
41
- }
42
- var env = parsed.data;
43
-
44
- // src/lib/logger.ts
45
- var colors = {
46
- debug: "\x1B[36m",
47
- // Cyan
48
- info: "\x1B[32m",
49
- // Green
50
- warn: "\x1B[33m",
51
- // Yellow
52
- error: "\x1B[31m",
53
- // Red
54
- reset: "\x1B[0m"
55
- };
56
- var shouldLog = (level) => {
57
- const levels = ["debug", "info", "warn", "error"];
58
- const minLevel = env.NODE_ENV === "production" ? "info" : "debug";
59
- return levels.indexOf(level) >= levels.indexOf(minLevel);
60
- };
61
- var formatMessage = (level, message, meta) => {
62
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
63
- const color = colors[level];
64
- const prefix = `${color}[${level.toUpperCase()}]${colors.reset}`;
65
- const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
66
- return `${timestamp} ${prefix} ${message}${metaStr}`;
67
- };
68
- var logger = {
69
- debug: (message, meta) => {
70
- if (shouldLog("debug")) {
71
- console.log(formatMessage("debug", message, meta));
72
- }
73
- },
74
- info: (message, meta) => {
75
- if (shouldLog("info")) {
76
- console.log(formatMessage("info", message, meta));
77
- }
78
- },
79
- warn: (message, meta) => {
80
- if (shouldLog("warn")) {
81
- console.warn(formatMessage("warn", message, meta));
82
- }
83
- },
84
- error: (message, meta) => {
85
- if (shouldLog("error")) {
86
- console.error(formatMessage("error", message, meta));
87
- }
88
- }
89
- };
90
-
91
- // src/lib/eventBus.ts
92
- var MAX_EVENT_LOG = 200;
93
- var EventBus = class {
94
- handlers = /* @__PURE__ */ new Map();
95
- debug;
96
- eventLog = [];
97
- constructor(options) {
98
- this.debug = options?.debug ?? false;
99
- }
100
- on(event, handler) {
101
- if (!this.handlers.has(event)) {
102
- this.handlers.set(event, /* @__PURE__ */ new Set());
103
- }
104
- this.handlers.get(event).add(handler);
105
- return () => {
106
- this.handlers.get(event)?.delete(handler);
107
- };
108
- }
109
- off(event, handler) {
110
- this.handlers.get(event)?.delete(handler);
111
- }
112
- emit(event, payload, meta) {
113
- if (this.debug) {
114
- console.log(`[EventBus] Emitting ${event}:`, payload);
115
- }
116
- const handlers = this.handlers.get(event);
117
- const listenerCount = handlers?.size ?? 0;
118
- if (handlers) {
119
- handlers.forEach((handler) => {
120
- try {
121
- handler(payload, meta);
122
- } catch (err) {
123
- console.error(`[EventBus] Error in handler for ${event}:`, err);
124
- }
125
- });
126
- }
127
- let wildcardListenerCount = 0;
128
- if (event !== "*") {
129
- const wildcardHandlers = this.handlers.get("*");
130
- wildcardListenerCount = wildcardHandlers?.size ?? 0;
131
- if (wildcardHandlers) {
132
- wildcardHandlers.forEach((handler) => {
133
- try {
134
- handler({ type: event, payload, timestamp: Date.now() }, meta);
135
- } catch (err) {
136
- console.error(`[EventBus] Error in wildcard handler for ${event}:`, err);
137
- }
138
- });
139
- }
140
- }
141
- if (this.debug) {
142
- this.eventLog.push({
143
- event,
144
- payload,
145
- timestamp: Date.now(),
146
- listenerCount,
147
- wildcardListenerCount
148
- });
149
- if (this.eventLog.length > MAX_EVENT_LOG) {
150
- this.eventLog.splice(0, this.eventLog.length - MAX_EVENT_LOG);
151
- }
152
- }
153
- }
154
- getRecentEvents(limit = 50) {
155
- return this.eventLog.slice(-limit);
156
- }
157
- clearEventLog() {
158
- this.eventLog.length = 0;
159
- }
160
- getListenerCounts() {
161
- const counts = {};
162
- this.handlers.forEach((handlers, event) => {
163
- counts[event] = handlers.size;
164
- });
165
- return counts;
166
- }
167
- clear() {
168
- this.handlers.clear();
169
- this.eventLog.length = 0;
170
- }
171
- };
172
- var _serverEventBus = null;
173
- function getServerEventBus() {
174
- if (!_serverEventBus) {
175
- _serverEventBus = new EventBus({
176
- debug: process.env.NODE_ENV === "development"
177
- });
178
- }
179
- return _serverEventBus;
180
- }
181
- function resetServerEventBus() {
182
- _serverEventBus?.clear();
183
- _serverEventBus = null;
184
- }
185
- function emitEntityEvent(entityType, action, payload) {
186
- const eventType = `${entityType.toUpperCase()}_${action}`;
187
- getServerEventBus().emit(eventType, payload, { orbital: entityType });
188
- }
189
-
190
- // src/lib/eventBusTransport.ts
191
- var InMemoryTransport = class {
192
- async publish() {
193
- }
194
- async subscribe() {
195
- }
196
- async close() {
197
- }
198
- };
199
- var RedisTransport = class {
200
- channel;
201
- publishFn;
202
- subscribeFn;
203
- closeFn;
204
- constructor(options) {
205
- this.channel = options.channel ?? "almadar:events";
206
- this.publishFn = options.publishFn;
207
- this.subscribeFn = options.subscribeFn;
208
- this.closeFn = options.closeFn;
209
- }
210
- async publish(message) {
211
- const serialized = JSON.stringify(message);
212
- await this.publishFn(this.channel, serialized);
213
- }
214
- async subscribe(receiver) {
215
- await this.subscribeFn(this.channel, (raw) => {
216
- try {
217
- const message = JSON.parse(raw);
218
- receiver(message);
219
- } catch {
220
- console.error("[RedisTransport] Failed to parse message:", raw);
221
- }
222
- });
223
- }
224
- async close() {
225
- if (this.closeFn) {
226
- await this.closeFn();
227
- }
228
- }
229
- };
230
- var instanceCounter = 0;
231
- var DistributedEventBus = class {
232
- localBus;
233
- transport;
234
- instanceId;
235
- isRelaying = false;
236
- constructor(options) {
237
- this.localBus = new EventBus({ debug: options?.debug });
238
- this.transport = options?.transport ?? new InMemoryTransport();
239
- this.instanceId = `instance_${++instanceCounter}_${Date.now()}`;
240
- }
241
- /**
242
- * Initialize the transport subscription. Call once at startup.
243
- */
244
- async connect() {
245
- await this.transport.subscribe((message) => {
246
- if (message.sourceId === this.instanceId) {
247
- return;
248
- }
249
- this.isRelaying = true;
250
- try {
251
- this.localBus.emit(message.event, message.payload, message.meta);
252
- } finally {
253
- this.isRelaying = false;
254
- }
255
- });
256
- }
257
- /**
258
- * Emit an event locally and publish to transport for other processes.
259
- */
260
- emit(event, payload, meta) {
261
- this.localBus.emit(event, payload, meta);
262
- if (!this.isRelaying) {
263
- const message = {
264
- event,
265
- payload,
266
- meta,
267
- sourceId: this.instanceId,
268
- timestamp: Date.now()
269
- };
270
- this.transport.publish(message).catch((err) => {
271
- console.error("[DistributedEventBus] Transport publish error:", err);
272
- });
273
- }
274
- }
275
- /** Subscribe to an event */
276
- on(event, handler) {
277
- return this.localBus.on(event, handler);
278
- }
279
- /** Unsubscribe from an event */
280
- off(event, handler) {
281
- this.localBus.off(event, handler);
282
- }
283
- /** Get recent events (dev diagnostics) */
284
- getRecentEvents(limit) {
285
- return this.localBus.getRecentEvents(limit);
286
- }
287
- /** Clear event log */
288
- clearEventLog() {
289
- this.localBus.clearEventLog();
290
- }
291
- /** Get listener counts */
292
- getListenerCounts() {
293
- return this.localBus.getListenerCounts();
294
- }
295
- /** Clear all listeners and log */
296
- clear() {
297
- this.localBus.clear();
298
- }
299
- /** Disconnect transport */
300
- async disconnect() {
301
- await this.transport.close();
302
- }
303
- /** Get the instance ID (for debugging) */
304
- getInstanceId() {
305
- return this.instanceId;
306
- }
307
- };
308
-
309
- // src/lib/eventPersistence.ts
310
- var InMemoryEventStore = class {
311
- events = [];
312
- index = /* @__PURE__ */ new Map();
313
- async store(event) {
314
- this.events.push(event);
315
- this.index.set(event.id, event);
316
- }
317
- async query(filters) {
318
- let results = this.events;
319
- if (filters.eventName) {
320
- results = results.filter((e) => e.eventName === filters.eventName);
321
- }
322
- if (filters.source) {
323
- results = results.filter((e) => e.source === filters.source);
324
- }
325
- if (filters.traceId) {
326
- results = results.filter((e) => e.traceId === filters.traceId);
327
- }
328
- if (filters.after !== void 0) {
329
- results = results.filter((e) => e.timestamp > filters.after);
330
- }
331
- if (filters.before !== void 0) {
332
- results = results.filter((e) => e.timestamp < filters.before);
333
- }
334
- if (filters.order === "desc") {
335
- results = [...results].reverse();
336
- }
337
- if (filters.limit !== void 0 && filters.limit > 0) {
338
- results = results.slice(0, filters.limit);
339
- }
340
- return results;
341
- }
342
- async get(id) {
343
- return this.index.get(id) ?? null;
344
- }
345
- async deleteOlderThan(timestamp) {
346
- const before = this.events.length;
347
- this.events = this.events.filter((e) => e.timestamp >= timestamp);
348
- this.index.clear();
349
- for (const event of this.events) {
350
- this.index.set(event.id, event);
351
- }
352
- return before - this.events.length;
353
- }
354
- async count() {
355
- return this.events.length;
356
- }
357
- async clear() {
358
- this.events = [];
359
- this.index.clear();
360
- }
361
- };
362
- var idCounter = 0;
363
- var EventPersistence = class {
364
- store;
365
- options;
366
- cleanupTimer = null;
367
- constructor(options, store) {
368
- this.options = {
369
- enabled: options?.enabled ?? true,
370
- retentionMs: options?.retentionMs ?? 24 * 60 * 60 * 1e3,
371
- // 24 hours
372
- maxEvents: options?.maxEvents ?? 1e4,
373
- cleanupIntervalMs: options?.cleanupIntervalMs ?? 5 * 60 * 1e3,
374
- // 5 minutes
375
- defaultSource: options?.defaultSource ?? "unknown"
376
- };
377
- this.store = store ?? new InMemoryEventStore();
378
- }
379
- /**
380
- * Persist an event.
381
- */
382
- async persist(eventName, payload, meta) {
383
- const event = {
384
- id: `evt_${++idCounter}_${Date.now()}`,
385
- eventName,
386
- payload,
387
- source: meta?.source ?? this.options.defaultSource,
388
- timestamp: Date.now(),
389
- traceId: meta?.traceId ?? `trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
390
- meta: meta ? { ...meta } : void 0
391
- };
392
- if (this.options.enabled) {
393
- await this.store.store(event);
394
- }
395
- return event;
396
- }
397
- /**
398
- * Replay events matching the query filters.
399
- */
400
- async replay(query) {
401
- return this.store.query(query);
402
- }
403
- /**
404
- * Get a single event by ID.
405
- */
406
- async getEvent(id) {
407
- return this.store.get(id);
408
- }
409
- /**
410
- * Get event count.
411
- */
412
- async getEventCount() {
413
- return this.store.count();
414
- }
415
- /**
416
- * Run cleanup — delete events older than retention period.
417
- */
418
- async cleanup() {
419
- const cutoff = Date.now() - this.options.retentionMs;
420
- return this.store.deleteOlderThan(cutoff);
421
- }
422
- /**
423
- * Start periodic cleanup timer.
424
- */
425
- startCleanup() {
426
- if (this.cleanupTimer) return;
427
- this.cleanupTimer = setInterval(() => {
428
- this.cleanup().catch((err) => {
429
- console.error("[EventPersistence] Cleanup error:", err);
430
- });
431
- }, this.options.cleanupIntervalMs);
432
- }
433
- /**
434
- * Stop periodic cleanup timer.
435
- */
436
- stopCleanup() {
437
- if (this.cleanupTimer) {
438
- clearInterval(this.cleanupTimer);
439
- this.cleanupTimer = null;
440
- }
441
- }
442
- /**
443
- * Clear all persisted events.
444
- */
445
- async clear() {
446
- await this.store.clear();
447
- }
448
- /**
449
- * Get the underlying store (for testing or custom queries).
450
- */
451
- getStore() {
452
- return this.store;
453
- }
454
- };
455
- function initializeFirebase() {
456
- if (admin.apps.length > 0) {
457
- return admin.app();
458
- }
459
- const projectId = process.env.FIREBASE_PROJECT_ID;
460
- const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;
461
- if (emulatorHost) {
462
- const app = admin.initializeApp({
463
- projectId: projectId || "demo-project"
464
- });
465
- console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);
466
- return app;
467
- }
468
- const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
469
- if (serviceAccountPath) {
470
- const serviceAccount = __require(serviceAccountPath);
471
- return admin.initializeApp({
472
- credential: admin.credential.cert(serviceAccount),
473
- projectId
474
- });
475
- }
476
- const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
477
- const privateKey = process.env.FIREBASE_PRIVATE_KEY;
478
- if (projectId && clientEmail && privateKey) {
479
- return admin.initializeApp({
480
- credential: admin.credential.cert({
481
- projectId,
482
- clientEmail,
483
- privateKey: privateKey.replace(/\\n/g, "\n")
484
- }),
485
- projectId
486
- });
487
- }
488
- if (projectId) {
489
- return admin.initializeApp({
490
- credential: admin.credential.applicationDefault(),
491
- projectId
492
- });
493
- }
494
- throw new Error(
495
- "@almadar/server: Cannot initialize Firebase \u2014 no credentials found. Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST."
496
- );
497
- }
498
- function getApp() {
499
- if (admin.apps.length === 0) {
500
- throw new Error(
501
- "@almadar/server: Firebase Admin SDK is not initialized. Call initializeFirebase() or admin.initializeApp() before using @almadar/server."
502
- );
503
- }
504
- return admin.app();
505
- }
506
- function getFirestore() {
507
- return getApp().firestore();
508
- }
509
- function getAuth() {
510
- return getApp().auth();
511
- }
512
- var db = new Proxy({}, {
513
- get(_target, prop, receiver) {
514
- const firestore = getFirestore();
515
- const value = Reflect.get(firestore, prop, receiver);
516
- return typeof value === "function" ? value.bind(firestore) : value;
517
- }
518
- });
519
- var MockDataService = class {
520
- stores = /* @__PURE__ */ new Map();
521
- schemas = /* @__PURE__ */ new Map();
522
- idCounters = /* @__PURE__ */ new Map();
523
- constructor() {
524
- if (env.MOCK_SEED !== void 0) {
525
- faker.seed(env.MOCK_SEED);
526
- logger.info(`[Mock] Using seed: ${env.MOCK_SEED}`);
527
- }
528
- }
529
- // ============================================================================
530
- // Store Management
531
- // ============================================================================
532
- /**
533
- * Initialize store for an entity.
534
- */
535
- getStore(entityName) {
536
- const normalized = entityName.toLowerCase();
537
- if (!this.stores.has(normalized)) {
538
- this.stores.set(normalized, /* @__PURE__ */ new Map());
539
- this.idCounters.set(normalized, 0);
540
- }
541
- return this.stores.get(normalized);
542
- }
543
- /**
544
- * Generate next ID for an entity.
545
- */
546
- nextId(entityName) {
547
- const normalized = entityName.toLowerCase();
548
- const counter = (this.idCounters.get(normalized) ?? 0) + 1;
549
- this.idCounters.set(normalized, counter);
550
- return `mock-${normalized}-${counter}`;
551
- }
552
- // ============================================================================
553
- // Schema & Seeding
554
- // ============================================================================
555
- /**
556
- * Register an entity schema.
557
- */
558
- registerSchema(entityName, schema) {
559
- this.schemas.set(entityName.toLowerCase(), schema);
560
- }
561
- /**
562
- * Seed an entity with mock data.
563
- */
564
- seed(entityName, fields, count = 10) {
565
- const store = this.getStore(entityName);
566
- const normalized = entityName.toLowerCase();
567
- logger.info(`[Mock] Seeding ${count} ${entityName}...`);
568
- for (let i = 0; i < count; i++) {
569
- const item = this.generateMockItem(normalized, fields, i + 1);
570
- store.set(item.id, item);
571
- }
572
- }
573
- /**
574
- * Generate a single mock item based on field schemas.
575
- */
576
- generateMockItem(entityName, fields, index) {
577
- const id = this.nextId(entityName);
578
- const now = /* @__PURE__ */ new Date();
579
- const item = {
580
- id,
581
- createdAt: faker.date.past({ years: 1 }),
582
- updatedAt: now
583
- };
584
- for (const field of fields) {
585
- if (field.name === "id" || field.name === "createdAt" || field.name === "updatedAt") {
586
- continue;
587
- }
588
- item[field.name] = this.generateFieldValue(entityName, field, index);
589
- }
590
- return item;
591
- }
592
- /**
593
- * Generate a mock value for a field based on its schema.
594
- */
595
- generateFieldValue(entityName, field, index) {
596
- if (!field.required && Math.random() > 0.8) {
597
- return void 0;
598
- }
599
- switch (field.type) {
600
- case "string":
601
- return this.generateStringValue(entityName, field, index);
602
- case "number":
603
- return faker.number.int({
604
- min: field.min ?? 0,
605
- max: field.max ?? 1e3
606
- });
607
- case "boolean":
608
- return faker.datatype.boolean();
609
- case "date":
610
- return this.generateDateValue(field);
611
- case "enum":
612
- if (field.enumValues && field.enumValues.length > 0) {
613
- return faker.helpers.arrayElement(field.enumValues);
614
- }
615
- return null;
616
- case "relation":
617
- if (field.relatedEntity) {
618
- const relatedStore = this.stores.get(field.relatedEntity.toLowerCase());
619
- if (relatedStore && relatedStore.size > 0) {
620
- const ids = Array.from(relatedStore.keys());
621
- return faker.helpers.arrayElement(ids);
622
- }
623
- }
624
- return null;
625
- case "array":
626
- return [];
627
- default:
628
- return null;
629
- }
630
- }
631
- /**
632
- * Generate a string value based on field name heuristics.
633
- * Generic name/title fields use a clean readable format (e.g., "Title 1").
634
- * Specific fields (email, phone, etc.) use faker.
635
- */
636
- generateStringValue(_entityName, field, index) {
637
- const name = field.name.toLowerCase();
638
- if (field.enumValues && field.enumValues.length > 0) {
639
- return faker.helpers.arrayElement(field.enumValues);
640
- }
641
- if (name.includes("email")) return faker.internet.email();
642
- if (name === "name" || name === "fullname" || name === "full_name") return faker.person.fullName();
643
- if (name === "firstname" || name === "first_name") return faker.person.firstName();
644
- if (name === "lastname" || name === "last_name") return faker.person.lastName();
645
- if (name.includes("username") || name === "handle") return faker.internet.username();
646
- if (name.includes("phone") || name.includes("mobile") || name.includes("tel")) return faker.phone.number();
647
- if (name.includes("address") || name.includes("street")) return faker.location.streetAddress();
648
- if (name.includes("city")) return faker.location.city();
649
- if (name.includes("state") || name.includes("province")) return faker.location.state();
650
- if (name.includes("country")) return faker.location.country();
651
- if (name.includes("zip") || name.includes("postal")) return faker.location.zipCode();
652
- if (name === "title" || name === "headline" || name === "subject") return faker.lorem.sentence({ min: 3, max: 7 }).replace(/\.$/, "");
653
- if (name === "description" || name === "summary" || name === "bio" || name === "about") return faker.lorem.paragraph(2);
654
- if (name === "content" || name === "body" || name === "text") return faker.lorem.paragraphs(2);
655
- if (name === "excerpt" || name === "snippet" || name === "preview") return faker.lorem.sentence({ min: 8, max: 15 });
656
- if (name === "label" || name === "tag" || name === "category") return faker.word.noun();
657
- if (name === "note" || name === "comment" || name === "message" || name === "feedback") return faker.lorem.sentence();
658
- if (name === "status") return faker.helpers.arrayElement(["active", "pending", "completed", "draft", "archived"]);
659
- if (name === "priority") return faker.helpers.arrayElement(["low", "medium", "high", "critical"]);
660
- if (name === "type" || name === "kind") return faker.helpers.arrayElement(["standard", "premium", "basic", "custom"]);
661
- if (name === "role") return faker.helpers.arrayElement(["admin", "editor", "viewer", "member"]);
662
- if (name === "level" || name === "tier") return faker.helpers.arrayElement(["beginner", "intermediate", "advanced", "expert"]);
663
- if (name === "severity") return faker.helpers.arrayElement(["info", "warning", "error", "critical"]);
664
- if (name === "difficulty") return faker.helpers.arrayElement(["easy", "medium", "hard"]);
665
- if (name.includes("url") || name.includes("website") || name.includes("link")) return faker.internet.url();
666
- if (name.includes("avatar") || name.includes("image") || name.includes("photo") || name.includes("thumbnail")) return faker.image.avatar();
667
- if (name.includes("color") || name.includes("colour")) return faker.color.human();
668
- if (name.includes("uuid") || name === "guid") return faker.string.uuid();
669
- if (name.includes("icon")) return faker.helpers.arrayElement(["star", "heart", "check", "alert-circle", "info", "folder", "file", "user"]);
670
- if (name === "slug") return faker.helpers.slugify(faker.lorem.words(3));
671
- if (name === "company" || name === "organization" || name === "org") return faker.company.name();
672
- if (name === "department") return faker.commerce.department();
673
- if (name === "product" || name === "productname" || name === "product_name") return faker.commerce.productName();
674
- if (name === "brand") return faker.company.name();
675
- if (name === "sku" || name === "code") return faker.string.alphanumeric(8).toUpperCase();
676
- if (name === "currency") return faker.finance.currencyCode();
677
- if (name.includes("price") || name.includes("cost") || name.includes("amount")) return faker.commerce.price();
678
- if (name === "latitude" || name === "lat") return String(faker.location.latitude());
679
- if (name === "longitude" || name === "lng" || name === "lon") return String(faker.location.longitude());
680
- if (name === "location" || name === "place" || name === "venue") return `${faker.location.city()}, ${faker.location.country()}`;
681
- if (name === "region" || name === "zone" || name === "area") return faker.location.state();
682
- if (name === "ip" || name.includes("ipaddress") || name === "ip_address") return faker.internet.ip();
683
- if (name === "useragent" || name === "user_agent") return faker.internet.userAgent();
684
- if (name === "version" || name === "firmware") return faker.system.semver();
685
- if (name === "platform" || name === "os") return faker.helpers.arrayElement(["iOS", "Android", "Windows", "macOS", "Linux"]);
686
- if (name === "browser") return faker.helpers.arrayElement(["Chrome", "Firefox", "Safari", "Edge"]);
687
- if (name === "unit") return faker.helpers.arrayElement(["kg", "lb", "cm", "m", "L", "mL", "\xB0C", "\xB0F", "psi", "rpm"]);
688
- if (name === "metric") return faker.helpers.arrayElement(["temperature", "pressure", "humidity", "speed", "voltage"]);
689
- if (name === "operator") return faker.helpers.arrayElement(["gt", "lt", "eq", "gte", "lte"]);
690
- if (name === "format" || name === "mimetype" || name === "mime_type") return faker.system.mimeType();
691
- if (name === "extension" || name === "ext") return faker.system.fileExt();
692
- if (name === "filename" || name === "file_name") return faker.system.fileName();
693
- if (name.endsWith("id") || name.endsWith("_id")) return faker.string.alphanumeric(8).toUpperCase();
694
- if (name.endsWith("name") || name.endsWith("_name")) return faker.person.fullName();
695
- if (name.endsWith("type") || name.endsWith("_type")) return faker.helpers.arrayElement(["standard", "premium", "basic", "custom", "special"]);
696
- if (name.endsWith("date") || name.endsWith("_date") || name.endsWith("at")) return faker.date.recent({ days: 90 }).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
697
- if (name.endsWith("count") || name.endsWith("_count")) return String(faker.number.int({ min: 1, max: 100 }));
698
- if (name.includes("reason") || name.includes("detail")) return faker.lorem.sentence({ min: 4, max: 8 }).replace(/\.$/, "");
699
- if (name.includes("field") || name.includes("key") || name.includes("attribute")) return faker.word.noun();
700
- if (name.includes("value") || name.includes("result") || name.includes("output")) return faker.word.words({ count: { min: 1, max: 3 } });
701
- if (name.includes("direction") || name.includes("position") || name.includes("mode")) return faker.helpers.arrayElement(["left", "right", "center", "top", "bottom", "auto"]);
702
- return faker.word.words({ count: { min: 1, max: 3 } });
703
- }
704
- /**
705
- * Capitalize first letter of a string.
706
- */
707
- capitalizeFirst(str) {
708
- return str.charAt(0).toUpperCase() + str.slice(1);
709
- }
710
- /**
711
- * Generate a date value based on field name heuristics.
712
- */
713
- generateDateValue(field) {
714
- const name = field.name.toLowerCase();
715
- if (name.includes("created") || name.includes("start") || name.includes("birth")) {
716
- return faker.date.past({ years: 2 });
717
- }
718
- if (name.includes("updated") || name.includes("modified")) {
719
- return faker.date.recent({ days: 30 });
720
- }
721
- if (name.includes("deadline") || name.includes("due") || name.includes("end") || name.includes("expires")) {
722
- return faker.date.future({ years: 1 });
723
- }
724
- return faker.date.anytime();
725
- }
726
- // ============================================================================
727
- // CRUD Operations
728
- // ============================================================================
729
- /**
730
- * List all items of an entity.
731
- */
732
- list(entityName) {
733
- const store = this.getStore(entityName);
734
- return Array.from(store.values());
735
- }
736
- /**
737
- * Get a single item by ID.
738
- */
739
- getById(entityName, id) {
740
- const store = this.getStore(entityName);
741
- const item = store.get(id);
742
- return item ?? null;
743
- }
744
- /**
745
- * Create a new item.
746
- */
747
- create(entityName, data) {
748
- const store = this.getStore(entityName);
749
- const id = this.nextId(entityName);
750
- const now = /* @__PURE__ */ new Date();
751
- const item = {
752
- ...data,
753
- id,
754
- createdAt: now,
755
- updatedAt: now
756
- };
757
- store.set(id, item);
758
- return item;
759
- }
760
- /**
761
- * Update an existing item.
762
- */
763
- update(entityName, id, data) {
764
- const store = this.getStore(entityName);
765
- const existing = store.get(id);
766
- if (!existing) {
767
- return null;
768
- }
769
- const updated = {
770
- ...existing,
771
- ...data,
772
- id,
773
- // Preserve original ID
774
- updatedAt: /* @__PURE__ */ new Date()
775
- };
776
- store.set(id, updated);
777
- return updated;
778
- }
779
- /**
780
- * Delete an item.
781
- */
782
- delete(entityName, id) {
783
- const store = this.getStore(entityName);
784
- if (!store.has(id)) {
785
- return false;
786
- }
787
- store.delete(id);
788
- return true;
789
- }
790
- // ============================================================================
791
- // Utilities
792
- // ============================================================================
793
- /**
794
- * Clear all data for an entity.
795
- */
796
- clear(entityName) {
797
- const normalized = entityName.toLowerCase();
798
- this.stores.delete(normalized);
799
- this.idCounters.delete(normalized);
800
- }
801
- /**
802
- * Clear all data.
803
- */
804
- clearAll() {
805
- this.stores.clear();
806
- this.idCounters.clear();
807
- }
808
- /**
809
- * Get count of items for an entity.
810
- */
811
- count(entityName) {
812
- const store = this.getStore(entityName);
813
- return store.size;
814
- }
815
- };
816
- var _mockDataService = null;
817
- function getMockDataService() {
818
- if (!_mockDataService) {
819
- _mockDataService = new MockDataService();
820
- }
821
- return _mockDataService;
822
- }
823
- function resetMockDataService() {
824
- _mockDataService?.clearAll();
825
- _mockDataService = null;
826
- }
827
-
828
- // src/utils/queryFilters.ts
829
- var OPERATOR_MAP = {
830
- "eq": "==",
831
- "neq": "!=",
832
- "gt": ">",
833
- "gte": ">=",
834
- "lt": "<",
835
- "lte": "<=",
836
- "contains": "array-contains",
837
- "contains_any": "array-contains-any",
838
- "in": "in",
839
- "not_in": "not-in",
840
- // Date operators map to same comparison operators
841
- "date_eq": "==",
842
- "date_gte": ">=",
843
- "date_lte": "<="
844
- };
845
- var RESERVED_PARAMS = /* @__PURE__ */ new Set([
846
- "page",
847
- "pageSize",
848
- "limit",
849
- "offset",
850
- "search",
851
- "q",
852
- "sortBy",
853
- "sortOrder",
854
- "orderBy",
855
- "orderDirection"
856
- ]);
857
- function parseQueryFilters(query) {
858
- const filters = [];
859
- for (const [key, value] of Object.entries(query)) {
860
- if (RESERVED_PARAMS.has(key)) continue;
861
- if (value === void 0 || value === null || value === "") continue;
862
- const match = key.match(/^(.+)__(\w+)$/);
863
- if (match) {
864
- const [, field, op] = match;
865
- const firestoreOp = OPERATOR_MAP[op];
866
- if (firestoreOp) {
867
- filters.push({
868
- field,
869
- operator: firestoreOp,
870
- value: parseValue(value, op)
871
- });
872
- } else {
873
- filters.push({
874
- field: key,
875
- operator: "==",
876
- value: parseValue(value, "eq")
877
- });
878
- }
879
- } else {
880
- filters.push({
881
- field: key,
882
- operator: "==",
883
- value: parseValue(value, "eq")
884
- });
885
- }
886
- }
887
- return filters;
888
- }
889
- function parseValue(value, operator) {
890
- if (operator === "in" || operator === "not_in" || operator === "contains_any") {
891
- if (typeof value === "string") {
892
- return value.split(",").map((v) => v.trim());
893
- }
894
- if (Array.isArray(value)) {
895
- return value;
896
- }
897
- return [value];
898
- }
899
- if (typeof value === "string") {
900
- if (/^-?\d+(\.\d+)?$/.test(value)) {
901
- const num = parseFloat(value);
902
- if (!isNaN(num)) {
903
- return num;
904
- }
905
- }
906
- if (value === "true") return true;
907
- if (value === "false") return false;
908
- }
909
- return value;
910
- }
911
- function applyFiltersToQuery(collection, filters) {
912
- let query = collection;
913
- for (const filter of filters) {
914
- query = query.where(
915
- filter.field,
916
- filter.operator,
917
- filter.value
918
- );
919
- }
920
- return query;
921
- }
922
- function extractPaginationParams(query, defaults = {}) {
923
- return {
924
- page: parseInt(query.page, 10) || defaults.page || 1,
925
- pageSize: parseInt(query.pageSize, 10) || parseInt(query.limit, 10) || defaults.pageSize || 20,
926
- sortBy: query.sortBy || query.orderBy,
927
- sortOrder: query.sortOrder || query.orderDirection || defaults.sortOrder || "asc"
928
- };
929
- }
930
-
931
- // src/services/DataService.ts
932
- function applyFilterCondition(value, operator, filterValue) {
933
- if (value === null || value === void 0) {
934
- return operator === "!=" ? filterValue !== null : false;
935
- }
936
- switch (operator) {
937
- case "==":
938
- return value === filterValue;
939
- case "!=":
940
- return value !== filterValue;
941
- case ">":
942
- return value > filterValue;
943
- case ">=":
944
- return value >= filterValue;
945
- case "<":
946
- return value < filterValue;
947
- case "<=":
948
- return value <= filterValue;
949
- case "array-contains":
950
- return Array.isArray(value) && value.includes(filterValue);
951
- case "array-contains-any":
952
- return Array.isArray(value) && Array.isArray(filterValue) && filterValue.some((v) => value.includes(v));
953
- case "in":
954
- return Array.isArray(filterValue) && filterValue.includes(value);
955
- case "not-in":
956
- return Array.isArray(filterValue) && !filterValue.includes(value);
957
- default:
958
- return true;
959
- }
960
- }
961
- var MockDataServiceAdapter = class {
962
- async list(collection) {
963
- return getMockDataService().list(collection);
964
- }
965
- async listPaginated(collection, options = {}) {
966
- const {
967
- page = 1,
968
- pageSize = 20,
969
- search,
970
- searchFields,
971
- sortBy,
972
- sortOrder = "asc",
973
- filters
974
- } = options;
975
- let items = getMockDataService().list(collection);
976
- if (filters && filters.length > 0) {
977
- items = items.filter((item) => {
978
- const record = item;
979
- return filters.every((filter) => {
980
- const value = record[filter.field];
981
- return applyFilterCondition(value, filter.operator, filter.value);
982
- });
983
- });
984
- }
985
- if (search && search.trim()) {
986
- const searchLower = search.toLowerCase();
987
- items = items.filter((item) => {
988
- const record = item;
989
- const fieldsToSearch = searchFields || Object.keys(record);
990
- return fieldsToSearch.some((field) => {
991
- const value = record[field];
992
- if (value === null || value === void 0) return false;
993
- return String(value).toLowerCase().includes(searchLower);
994
- });
995
- });
996
- }
997
- if (sortBy) {
998
- items = [...items].sort((a, b) => {
999
- const aVal = a[sortBy];
1000
- const bVal = b[sortBy];
1001
- if (aVal === bVal) return 0;
1002
- if (aVal === null || aVal === void 0) return 1;
1003
- if (bVal === null || bVal === void 0) return -1;
1004
- const comparison = aVal < bVal ? -1 : 1;
1005
- return sortOrder === "asc" ? comparison : -comparison;
1006
- });
1007
- }
1008
- const total = items.length;
1009
- const totalPages = Math.ceil(total / pageSize);
1010
- const startIndex = (page - 1) * pageSize;
1011
- const data = items.slice(startIndex, startIndex + pageSize);
1012
- return { data, total, page, pageSize, totalPages };
1013
- }
1014
- async getById(collection, id) {
1015
- return getMockDataService().getById(collection, id);
1016
- }
1017
- async create(collection, data) {
1018
- return getMockDataService().create(collection, data);
1019
- }
1020
- async update(collection, id, data) {
1021
- return getMockDataService().update(collection, id, data);
1022
- }
1023
- async delete(collection, id) {
1024
- return getMockDataService().delete(collection, id);
1025
- }
1026
- async query(collection, filters) {
1027
- let items = getMockDataService().list(collection);
1028
- for (const filter of filters) {
1029
- items = items.filter((item) => {
1030
- const value = item[filter.field];
1031
- return applyFilterCondition(value, filter.op, filter.value);
1032
- });
1033
- }
1034
- return items;
1035
- }
1036
- getStore(collection) {
1037
- const adapter = this;
1038
- return {
1039
- async getById(id) {
1040
- return adapter.getById(collection, id);
1041
- },
1042
- async create(data) {
1043
- return adapter.create(collection, data);
1044
- },
1045
- async update(id, data) {
1046
- const result = await adapter.update(collection, id, data);
1047
- if (!result) throw new Error(`Entity ${id} not found in ${collection}`);
1048
- return result;
1049
- },
1050
- async delete(id) {
1051
- adapter.delete(collection, id);
1052
- },
1053
- async query(filters) {
1054
- return adapter.query(collection, filters);
1055
- }
1056
- };
1057
- }
1058
- };
1059
- var FirebaseDataService = class {
1060
- async list(collection) {
1061
- const snapshot = await db.collection(collection).get();
1062
- return snapshot.docs.map((doc) => ({
1063
- id: doc.id,
1064
- ...doc.data()
1065
- }));
1066
- }
1067
- async listPaginated(collection, options = {}) {
1068
- const {
1069
- page = 1,
1070
- pageSize = 20,
1071
- search,
1072
- searchFields,
1073
- sortBy,
1074
- sortOrder = "asc",
1075
- filters
1076
- } = options;
1077
- let query = db.collection(collection);
1078
- if (filters && filters.length > 0) {
1079
- query = applyFiltersToQuery(query, filters);
1080
- }
1081
- if (sortBy && !search) {
1082
- query = query.orderBy(sortBy, sortOrder);
1083
- }
1084
- const snapshot = await query.get();
1085
- let items = snapshot.docs.map((doc) => ({
1086
- id: doc.id,
1087
- ...doc.data()
1088
- }));
1089
- if (search && search.trim()) {
1090
- const searchLower = search.toLowerCase();
1091
- items = items.filter((item) => {
1092
- const record = item;
1093
- const fieldsToSearch = searchFields || Object.keys(record);
1094
- return fieldsToSearch.some((field) => {
1095
- const value = record[field];
1096
- if (value === null || value === void 0) return false;
1097
- return String(value).toLowerCase().includes(searchLower);
1098
- });
1099
- });
1100
- }
1101
- if (sortBy && search) {
1102
- items = [...items].sort((a, b) => {
1103
- const aVal = a[sortBy];
1104
- const bVal = b[sortBy];
1105
- if (aVal === bVal) return 0;
1106
- if (aVal === null || aVal === void 0) return 1;
1107
- if (bVal === null || bVal === void 0) return -1;
1108
- const comparison = aVal < bVal ? -1 : 1;
1109
- return sortOrder === "asc" ? comparison : -comparison;
1110
- });
1111
- }
1112
- const total = items.length;
1113
- const totalPages = Math.ceil(total / pageSize);
1114
- const startIndex = (page - 1) * pageSize;
1115
- const data = items.slice(startIndex, startIndex + pageSize);
1116
- return { data, total, page, pageSize, totalPages };
1117
- }
1118
- async getById(collection, id) {
1119
- const doc = await db.collection(collection).doc(id).get();
1120
- if (!doc.exists) {
1121
- return null;
1122
- }
1123
- return { id: doc.id, ...doc.data() };
1124
- }
1125
- async create(collection, data) {
1126
- const now = /* @__PURE__ */ new Date();
1127
- const docRef = await db.collection(collection).add({
1128
- ...data,
1129
- createdAt: now,
1130
- updatedAt: now
1131
- });
1132
- return {
1133
- ...data,
1134
- id: docRef.id,
1135
- createdAt: now,
1136
- updatedAt: now
1137
- };
1138
- }
1139
- async update(collection, id, data) {
1140
- const docRef = db.collection(collection).doc(id);
1141
- const doc = await docRef.get();
1142
- if (!doc.exists) {
1143
- return null;
1144
- }
1145
- const now = /* @__PURE__ */ new Date();
1146
- await docRef.update({
1147
- ...data,
1148
- updatedAt: now
1149
- });
1150
- return {
1151
- ...doc.data(),
1152
- ...data,
1153
- id,
1154
- updatedAt: now
1155
- };
1156
- }
1157
- async delete(collection, id) {
1158
- const docRef = db.collection(collection).doc(id);
1159
- const doc = await docRef.get();
1160
- if (!doc.exists) {
1161
- return false;
1162
- }
1163
- await docRef.delete();
1164
- return true;
1165
- }
1166
- async query(collection, filters) {
1167
- let query = db.collection(collection);
1168
- const memoryFilters = [];
1169
- for (const filter of filters) {
1170
- if (["==", "!=", "<", "<=", ">", ">=", "in", "not-in"].includes(filter.op)) {
1171
- query = query.where(filter.field, filter.op, filter.value);
1172
- } else {
1173
- memoryFilters.push(filter);
1174
- }
1175
- }
1176
- const snapshot = await query.get();
1177
- let items = snapshot.docs.map((doc) => ({
1178
- id: doc.id,
1179
- ...doc.data()
1180
- }));
1181
- for (const filter of memoryFilters) {
1182
- items = items.filter((item) => {
1183
- const value = item[filter.field];
1184
- return applyFilterCondition(value, filter.op, filter.value);
1185
- });
1186
- }
1187
- return items;
1188
- }
1189
- getStore(collection) {
1190
- const svc = this;
1191
- return {
1192
- async getById(id) {
1193
- return svc.getById(collection, id);
1194
- },
1195
- async create(data) {
1196
- return svc.create(collection, data);
1197
- },
1198
- async update(id, data) {
1199
- const result = await svc.update(collection, id, data);
1200
- if (!result) throw new Error(`Entity ${id} not found in ${collection}`);
1201
- return result;
1202
- },
1203
- async delete(id) {
1204
- await svc.delete(collection, id);
1205
- },
1206
- async query(filters) {
1207
- return svc.query(collection, filters);
1208
- }
1209
- };
1210
- }
1211
- };
1212
- function createDataService() {
1213
- if (env.USE_MOCK_DATA) {
1214
- logger.info("[DataService] Using MockDataService");
1215
- return new MockDataServiceAdapter();
1216
- }
1217
- logger.info("[DataService] Using FirebaseDataService");
1218
- return new FirebaseDataService();
1219
- }
1220
- var _dataService = null;
1221
- function getDataService() {
1222
- if (!_dataService) {
1223
- _dataService = createDataService();
1224
- }
1225
- return _dataService;
1226
- }
1227
- function resetDataService() {
1228
- _dataService = null;
1229
- }
1230
- function seedMockData(entities) {
1231
- if (!env.USE_MOCK_DATA) {
1232
- logger.info("[DataService] Mock mode disabled, skipping seed");
1233
- return;
1234
- }
1235
- logger.info("[DataService] Seeding mock data...");
1236
- for (const entity of entities) {
1237
- getMockDataService().seed(entity.name, entity.fields, entity.seedCount);
1238
- }
1239
- logger.info("[DataService] Mock data seeding complete");
1240
- }
1241
-
1242
- // src/lib/debugRouter.ts
1243
- function debugEventsRouter() {
1244
- const router2 = Router();
1245
- if (process.env.NODE_ENV !== "development") {
1246
- return router2;
1247
- }
1248
- router2.get("/event-log", (_req, res) => {
1249
- const limit = parseInt(String(_req.query.limit) || "50", 10);
1250
- const events = getServerEventBus().getRecentEvents(limit);
1251
- res.json({ count: events.length, events });
1252
- });
1253
- router2.delete("/event-log", (_req, res) => {
1254
- getServerEventBus().clearEventLog();
1255
- res.json({ cleared: true });
1256
- });
1257
- router2.get("/listeners", (_req, res) => {
1258
- const counts = getServerEventBus().getListenerCounts();
1259
- const total = Object.values(counts).reduce((sum, n) => sum + n, 0);
1260
- res.json({ total, events: counts });
1261
- });
1262
- router2.post("/seed", (req, res) => {
1263
- const { entities } = req.body;
1264
- if (!entities || !Array.isArray(entities)) {
1265
- res.status(400).json({ error: 'Body must have "entities" array' });
1266
- return;
1267
- }
1268
- const configs = entities.map((e) => ({
1269
- name: e.name,
1270
- fields: e.fields,
1271
- seedCount: e.seedCount ?? 5
1272
- }));
1273
- seedMockData(configs);
1274
- const summary = configs.map((c) => `${c.name}(${c.seedCount})`).join(", ");
1275
- res.json({ seeded: true, summary });
1276
- });
1277
- return router2;
1278
- }
1279
- var wss = null;
1280
- function setupEventBroadcast(server, path = "/ws/events") {
1281
- if (wss) {
1282
- logger.warn("[WebSocket] Server already initialized");
1283
- return wss;
1284
- }
1285
- wss = new WebSocketServer({ server, path });
1286
- logger.info(`[WebSocket] Server listening at ${path}`);
1287
- wss.on("connection", (ws, req) => {
1288
- const clientId = req.headers["sec-websocket-key"] || "unknown";
1289
- logger.debug(`[WebSocket] Client connected: ${clientId}`);
1290
- ws.send(
1291
- JSON.stringify({
1292
- type: "CONNECTED",
1293
- timestamp: Date.now(),
1294
- message: "Connected to event stream"
1295
- })
1296
- );
1297
- ws.on("message", (data) => {
1298
- try {
1299
- const message = JSON.parse(data.toString());
1300
- logger.debug(`[WebSocket] Received from ${clientId}:`, message);
1301
- if (message.type && message.payload) {
1302
- getServerEventBus().emit(message.type, message.payload, {
1303
- orbital: "client",
1304
- entity: clientId
1305
- });
1306
- }
1307
- } catch (error) {
1308
- logger.error(`[WebSocket] Failed to parse message:`, error);
1309
- }
1310
- });
1311
- ws.on("close", () => {
1312
- logger.debug(`[WebSocket] Client disconnected: ${clientId}`);
1313
- });
1314
- ws.on("error", (error) => {
1315
- logger.error(`[WebSocket] Client error:`, error);
1316
- });
1317
- });
1318
- getServerEventBus().on("*", (event) => {
1319
- if (!wss) return;
1320
- const typedEvent = event;
1321
- const message = JSON.stringify({
1322
- type: typedEvent.type,
1323
- payload: typedEvent.payload,
1324
- timestamp: typedEvent.timestamp,
1325
- source: typedEvent.source
1326
- });
1327
- let broadcastCount = 0;
1328
- wss.clients.forEach((client) => {
1329
- if (client.readyState === WebSocket.OPEN) {
1330
- client.send(message);
1331
- broadcastCount++;
1332
- }
1333
- });
1334
- if (broadcastCount > 0) {
1335
- logger.debug(`[WebSocket] Broadcast ${typedEvent.type} to ${broadcastCount} client(s)`);
1336
- }
1337
- });
1338
- return wss;
1339
- }
1340
- function getWebSocketServer() {
1341
- return wss;
1342
- }
1343
- function closeWebSocketServer() {
1344
- return new Promise((resolve, reject) => {
1345
- if (!wss) {
1346
- resolve();
1347
- return;
1348
- }
1349
- wss.close((err) => {
1350
- if (err) {
1351
- reject(err);
1352
- } else {
1353
- wss = null;
1354
- resolve();
1355
- }
1356
- });
1357
- });
1358
- }
1359
- function getConnectedClientCount() {
1360
- if (!wss) return 0;
1361
- return wss.clients.size;
1362
- }
1363
- var AppError = class extends Error {
1364
- constructor(statusCode, message, code) {
1365
- super(message);
1366
- this.statusCode = statusCode;
1367
- this.message = message;
1368
- this.code = code;
1369
- this.name = "AppError";
1370
- }
1371
- };
1372
- var NotFoundError = class extends AppError {
1373
- constructor(message = "Resource not found") {
1374
- super(404, message, "NOT_FOUND");
1375
- }
1376
- };
1377
- var ValidationError = class extends AppError {
1378
- constructor(message = "Validation failed") {
1379
- super(400, message, "VALIDATION_ERROR");
1380
- }
1381
- };
1382
- var UnauthorizedError = class extends AppError {
1383
- constructor(message = "Unauthorized") {
1384
- super(401, message, "UNAUTHORIZED");
1385
- }
1386
- };
1387
- var ForbiddenError = class extends AppError {
1388
- constructor(message = "Forbidden") {
1389
- super(403, message, "FORBIDDEN");
1390
- }
1391
- };
1392
- var ConflictError = class extends AppError {
1393
- constructor(message = "Resource conflict") {
1394
- super(409, message, "CONFLICT");
1395
- }
1396
- };
1397
- var errorHandler = (err, _req, res, _next) => {
1398
- logger.error("Error:", { name: err.name, message: err.message, stack: err.stack });
1399
- if (err instanceof ZodError) {
1400
- res.status(400).json({
1401
- success: false,
1402
- error: "Validation failed",
1403
- code: "VALIDATION_ERROR",
1404
- details: err.errors.map((e) => ({
1405
- path: e.path.join("."),
1406
- message: e.message
1407
- }))
1408
- });
1409
- return;
1410
- }
1411
- if (err instanceof AppError) {
1412
- res.status(err.statusCode).json({
1413
- success: false,
1414
- error: err.message,
1415
- code: err.code
1416
- });
1417
- return;
1418
- }
1419
- if (err.name === "FirebaseError" || err.name === "FirestoreError") {
1420
- res.status(500).json({
1421
- success: false,
1422
- error: "Database error",
1423
- code: "DATABASE_ERROR"
1424
- });
1425
- return;
1426
- }
1427
- res.status(500).json({
1428
- success: false,
1429
- error: "Internal server error",
1430
- code: "INTERNAL_ERROR"
1431
- });
1432
- };
1433
- var asyncHandler = (fn) => (req, res, next) => {
1434
- Promise.resolve(fn(req, res, next)).catch(next);
1435
- };
1436
- var notFoundHandler = (req, res) => {
1437
- res.status(404).json({
1438
- success: false,
1439
- error: `Route ${req.method} ${req.path} not found`,
1440
- code: "ROUTE_NOT_FOUND"
1441
- });
1442
- };
1443
- var validateBody = (schema) => async (req, res, next) => {
1444
- try {
1445
- req.body = await schema.parseAsync(req.body);
1446
- next();
1447
- } catch (error) {
1448
- if (error instanceof ZodError) {
1449
- res.status(400).json({
1450
- success: false,
1451
- error: "Validation failed",
1452
- code: "VALIDATION_ERROR",
1453
- details: error.errors.map((e) => ({
1454
- path: e.path.join("."),
1455
- message: e.message
1456
- }))
1457
- });
1458
- return;
1459
- }
1460
- next(error);
1461
- }
1462
- };
1463
- var validateQuery = (schema) => async (req, res, next) => {
1464
- try {
1465
- req.query = await schema.parseAsync(req.query);
1466
- next();
1467
- } catch (error) {
1468
- if (error instanceof ZodError) {
1469
- res.status(400).json({
1470
- success: false,
1471
- error: "Invalid query parameters",
1472
- code: "VALIDATION_ERROR",
1473
- details: error.errors.map((e) => ({
1474
- path: e.path.join("."),
1475
- message: e.message
1476
- }))
1477
- });
1478
- return;
1479
- }
1480
- next(error);
1481
- }
1482
- };
1483
- var validateParams = (schema) => async (req, res, next) => {
1484
- try {
1485
- req.params = await schema.parseAsync(req.params);
1486
- next();
1487
- } catch (error) {
1488
- if (error instanceof ZodError) {
1489
- res.status(400).json({
1490
- success: false,
1491
- error: "Invalid path parameters",
1492
- code: "VALIDATION_ERROR",
1493
- details: error.errors.map((e) => ({
1494
- path: e.path.join("."),
1495
- message: e.message
1496
- }))
1497
- });
1498
- return;
1499
- }
1500
- next(error);
1501
- }
1502
- };
1503
-
1504
- // src/middleware/authenticateFirebase.ts
1505
- var BEARER_PREFIX = "Bearer ";
1506
- var DEV_USER = {
1507
- uid: "dev-user-001",
1508
- email: "dev@localhost",
1509
- email_verified: true,
1510
- aud: "dev-project",
1511
- auth_time: Math.floor(Date.now() / 1e3),
1512
- exp: Math.floor(Date.now() / 1e3) + 3600,
1513
- iat: Math.floor(Date.now() / 1e3),
1514
- iss: "https://securetoken.google.com/dev-project",
1515
- sub: "dev-user-001",
1516
- firebase: {
1517
- identities: {},
1518
- sign_in_provider: "custom"
1519
- }
1520
- };
1521
- async function authenticateFirebase(req, res, next) {
1522
- const authorization = req.headers.authorization;
1523
- if (env.NODE_ENV === "development" && (!authorization || !authorization.startsWith(BEARER_PREFIX))) {
1524
- req.firebaseUser = DEV_USER;
1525
- res.locals.firebaseUser = DEV_USER;
1526
- return next();
1527
- }
1528
- try {
1529
- if (!authorization || !authorization.startsWith(BEARER_PREFIX)) {
1530
- return res.status(401).json({ error: "Authorization header missing or malformed" });
1531
- }
1532
- const token = authorization.slice(BEARER_PREFIX.length);
1533
- const decodedToken = await getAuth().verifyIdToken(token);
1534
- req.firebaseUser = decodedToken;
1535
- res.locals.firebaseUser = decodedToken;
1536
- return next();
1537
- } catch (error) {
1538
- console.error("Firebase authentication failed:", error);
1539
- return res.status(401).json({ error: "Unauthorized" });
1540
- }
1541
- }
1542
-
1543
- // src/stores/firestoreFormat.ts
1544
- function toFirestoreFormat(schema) {
1545
- const data = { ...schema };
1546
- if (schema.orbitals) {
1547
- data._orbitalsJson = JSON.stringify(schema.orbitals);
1548
- data.orbitalCount = schema.orbitals.length;
1549
- delete data.orbitals;
1550
- }
1551
- if (data.traits) {
1552
- const traits = data.traits;
1553
- data._traitsJson = JSON.stringify(traits);
1554
- data.traitCount = traits.length;
1555
- delete data.traits;
1556
- }
1557
- if (schema.services) {
1558
- data._servicesJson = JSON.stringify(schema.services);
1559
- data.serviceCount = schema.services.length;
1560
- delete data.services;
1561
- }
1562
- return data;
1563
- }
1564
- function fromFirestoreFormat(data) {
1565
- const result = { ...data };
1566
- if (result._orbitalsJson && typeof result._orbitalsJson === "string") {
1567
- try {
1568
- result.orbitals = JSON.parse(result._orbitalsJson);
1569
- delete result._orbitalsJson;
1570
- delete result.orbitalCount;
1571
- } catch (e) {
1572
- console.warn("[OrbitalStore] Failed to parse _orbitalsJson:", e);
1573
- result.orbitals = [];
1574
- }
1575
- }
1576
- if (result._traitsJson && typeof result._traitsJson === "string") {
1577
- try {
1578
- result.traits = JSON.parse(result._traitsJson);
1579
- delete result._traitsJson;
1580
- delete result.traitCount;
1581
- } catch (e) {
1582
- console.warn("[OrbitalStore] Failed to parse _traitsJson:", e);
1583
- }
1584
- }
1585
- if (result._servicesJson && typeof result._servicesJson === "string") {
1586
- try {
1587
- result.services = JSON.parse(result._servicesJson);
1588
- delete result._servicesJson;
1589
- delete result.serviceCount;
1590
- } catch (e) {
1591
- console.warn("[OrbitalStore] Failed to parse _servicesJson:", e);
1592
- }
1593
- }
1594
- return result;
1595
- }
1596
- var SchemaProtectionService = class {
1597
- /**
1598
- * Compare two schemas and detect destructive changes.
1599
- *
1600
- * Returns categorized removals including page content reductions.
1601
- */
1602
- compareSchemas(before, after) {
1603
- const changeSet = diffSchemas(before, after);
1604
- const removals = categorizeRemovals(changeSet);
1605
- const beforePages = before.orbitals?.flatMap((o) => o.pages || []) || [];
1606
- const afterPages = after.orbitals?.flatMap((o) => o.pages || []) || [];
1607
- const pageContentReductions = detectPageContentReduction(beforePages, afterPages);
1608
- removals.pageContentReductions = pageContentReductions;
1609
- const isDestructive = isDestructiveChange(changeSet) || hasSignificantPageReduction(pageContentReductions);
1610
- return { isDestructive, removals };
1611
- }
1612
- /** Check if critical removals require confirmation */
1613
- requiresConfirmation(removals) {
1614
- return requiresConfirmation(removals);
1615
- }
1616
- /** Check for significant page content reductions */
1617
- hasSignificantContentReduction(reductions) {
1618
- return hasSignificantPageReduction(reductions);
1619
- }
1620
- };
1621
-
1622
- // src/stores/SchemaStore.ts
1623
- var SCHEMA_CACHE_TTL_MS = 6e4;
1624
- var LIST_CACHE_TTL_MS = 3e4;
1625
- var SchemaStore = class {
1626
- appsCollection;
1627
- schemaCache = /* @__PURE__ */ new Map();
1628
- listCache = /* @__PURE__ */ new Map();
1629
- protectionService = new SchemaProtectionService();
1630
- snapshotStore = null;
1631
- constructor(appsCollection = "apps") {
1632
- this.appsCollection = appsCollection;
1633
- }
1634
- /** Set snapshot store for auto-snapshot on destructive saves */
1635
- setSnapshotStore(store) {
1636
- this.snapshotStore = store;
1637
- }
1638
- /** Get a schema by app ID */
1639
- async get(uid, appId) {
1640
- const cacheKey = `${uid}:${appId}`;
1641
- const cached = this.schemaCache.get(cacheKey);
1642
- if (cached && Date.now() - cached.timestamp < SCHEMA_CACHE_TTL_MS) {
1643
- return cached.schema;
1644
- }
1645
- try {
1646
- const db2 = getFirestore();
1647
- const appDoc = await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).get();
1648
- if (!appDoc.exists) return null;
1649
- const data = appDoc.data();
1650
- const hasOrbitals = data.orbitals || data._orbitalsJson;
1651
- if (!data.name || !hasOrbitals) return null;
1652
- const schema = fromFirestoreFormat(data);
1653
- this.schemaCache.set(cacheKey, { schema, timestamp: Date.now() });
1654
- return schema;
1655
- } catch (error) {
1656
- console.error("[SchemaStore] Error fetching schema:", error);
1657
- return null;
1658
- }
1659
- }
1660
- /**
1661
- * Save a schema (create or full replace).
1662
- *
1663
- * Features:
1664
- * - Detects destructive changes (removals)
1665
- * - Requires confirmation for critical removals
1666
- * - Auto-creates snapshots before destructive changes (if SnapshotStore attached)
1667
- */
1668
- async save(uid, appId, schema, options = {}) {
1669
- try {
1670
- const existingSchema = await this.get(uid, appId);
1671
- let snapshotId;
1672
- if (existingSchema && options.snapshotReason && this.snapshotStore) {
1673
- snapshotId = await this.snapshotStore.create(uid, appId, existingSchema, options.snapshotReason);
1674
- }
1675
- if (existingSchema && !options.skipProtection) {
1676
- const comparison = this.protectionService.compareSchemas(existingSchema, schema);
1677
- if (comparison.isDestructive) {
1678
- const { removals } = comparison;
1679
- const hasCriticalRemovals = this.protectionService.requiresConfirmation(removals);
1680
- const hasContentReductions = this.protectionService.hasSignificantContentReduction(
1681
- removals.pageContentReductions
1682
- );
1683
- if ((hasCriticalRemovals || hasContentReductions) && !options.confirmRemovals) {
1684
- return {
1685
- success: false,
1686
- requiresConfirmation: true,
1687
- removals: comparison.removals,
1688
- error: hasContentReductions ? "Page content reduction detected - confirmation required" : "Confirmation required for critical removals"
1689
- };
1690
- }
1691
- if (!snapshotId && this.snapshotStore && (removals.critical.length > 0 || removals.pageContentReductions.length > 0)) {
1692
- snapshotId = await this.snapshotStore.create(
1693
- uid,
1694
- appId,
1695
- existingSchema,
1696
- `auto_before_removal_${Date.now()}`
1697
- );
1698
- }
1699
- }
1700
- }
1701
- const firestoreData = toFirestoreFormat(schema);
1702
- const now = Date.now();
1703
- const docData = {
1704
- ...firestoreData,
1705
- _metadata: {
1706
- version: options.expectedVersion ? options.expectedVersion + 1 : 1,
1707
- updatedAt: now,
1708
- createdAt: existingSchema ? void 0 : now,
1709
- source: options.source || "manual"
1710
- }
1711
- };
1712
- const db2 = getFirestore();
1713
- await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData, { merge: true });
1714
- this.invalidateCache(uid, appId);
1715
- return { success: true, snapshotId };
1716
- } catch (error) {
1717
- console.error("[SchemaStore] Error saving schema:", error);
1718
- return {
1719
- success: false,
1720
- error: error instanceof Error ? error.message : "Unknown error"
1721
- };
1722
- }
1723
- }
1724
- /** Create a new app with initial schema */
1725
- async create(uid, metadata) {
1726
- const appId = `app-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1727
- const now = Date.now();
1728
- const schema = {
1729
- name: metadata.name,
1730
- description: metadata.description,
1731
- orbitals: []
1732
- };
1733
- const firestoreData = toFirestoreFormat(schema);
1734
- const docData = {
1735
- ...firestoreData,
1736
- _metadata: { version: 1, createdAt: now, updatedAt: now, source: "manual" }
1737
- };
1738
- const db2 = getFirestore();
1739
- await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData);
1740
- this.listCache.delete(uid);
1741
- return { appId, schema };
1742
- }
1743
- /** Delete an app */
1744
- async delete(uid, appId) {
1745
- try {
1746
- const db2 = getFirestore();
1747
- const ref = db2.doc(`users/${uid}/${this.appsCollection}/${appId}`);
1748
- const doc = await ref.get();
1749
- if (!doc.exists) return false;
1750
- await ref.delete();
1751
- this.invalidateCache(uid, appId);
1752
- return true;
1753
- } catch (error) {
1754
- console.error("[SchemaStore] Error deleting app:", error);
1755
- return false;
1756
- }
1757
- }
1758
- /** List all apps for a user */
1759
- async list(uid) {
1760
- const cached = this.listCache.get(uid);
1761
- if (cached && Date.now() - cached.timestamp < LIST_CACHE_TTL_MS) {
1762
- return cached.apps;
1763
- }
1764
- try {
1765
- const db2 = getFirestore();
1766
- const snapshot = await db2.collection(`users/${uid}/${this.appsCollection}`).select("name", "description", "domainContext", "_metadata", "orbitalCount", "traitCount").orderBy("_metadata.updatedAt", "desc").get();
1767
- const apps = snapshot.docs.map((doc) => {
1768
- const data = doc.data();
1769
- const metadata = data._metadata;
1770
- const orbitalCount = data.orbitalCount;
1771
- return {
1772
- id: doc.id,
1773
- name: data.name || "Untitled",
1774
- description: data.description,
1775
- updatedAt: metadata?.updatedAt || Date.now(),
1776
- createdAt: metadata?.createdAt || Date.now(),
1777
- stats: { entities: orbitalCount ?? 0, pages: 0, states: 0, events: 0, transitions: 0 },
1778
- domainContext: data.domainContext,
1779
- hasValidationErrors: false
1780
- };
1781
- });
1782
- this.listCache.set(uid, { apps, timestamp: Date.now() });
1783
- return apps;
1784
- } catch (error) {
1785
- console.error("[SchemaStore] Error listing apps:", error);
1786
- return [];
1787
- }
1788
- }
1789
- /** Compute stats from OrbitalSchema */
1790
- computeStats(schema) {
1791
- const orbitals = schema.orbitals || [];
1792
- const entities = orbitals.length;
1793
- const pages = orbitals.reduce((n, o) => n + (o.pages?.length || 0), 0);
1794
- const allTraits = [
1795
- ...schema.traits || [],
1796
- ...orbitals.flatMap(
1797
- (o) => (o.traits || []).filter((t) => typeof t !== "string" && "stateMachine" in t)
1798
- )
1799
- ];
1800
- return {
1801
- states: allTraits.flatMap((t) => t.stateMachine?.states || []).length,
1802
- events: allTraits.flatMap((t) => t.stateMachine?.events || []).length,
1803
- pages,
1804
- entities,
1805
- transitions: allTraits.flatMap((t) => t.stateMachine?.transitions || []).length
1806
- };
1807
- }
1808
- /** Invalidate caches for a specific app */
1809
- invalidateCache(uid, appId) {
1810
- this.schemaCache.delete(`${uid}:${appId}`);
1811
- this.listCache.delete(uid);
1812
- }
1813
- /** Clear all caches */
1814
- clearCaches() {
1815
- this.schemaCache.clear();
1816
- this.listCache.clear();
1817
- }
1818
- /** Get the collection path for an app */
1819
- getAppDocPath(uid, appId) {
1820
- return `users/${uid}/${this.appsCollection}/${appId}`;
1821
- }
1822
- /** Expose apps collection name for subcollection stores */
1823
- getAppsCollection() {
1824
- return this.appsCollection;
1825
- }
1826
- };
1827
-
1828
- // src/stores/SnapshotStore.ts
1829
- var SNAPSHOTS_COLLECTION = "snapshots";
1830
- var SnapshotStore = class {
1831
- appsCollection;
1832
- constructor(appsCollection = "apps") {
1833
- this.appsCollection = appsCollection;
1834
- }
1835
- getCollectionPath(uid, appId) {
1836
- return `users/${uid}/${this.appsCollection}/${appId}/${SNAPSHOTS_COLLECTION}`;
1837
- }
1838
- getAppDocPath(uid, appId) {
1839
- return `users/${uid}/${this.appsCollection}/${appId}`;
1840
- }
1841
- /** Create a snapshot of the current schema */
1842
- async create(uid, appId, schema, reason) {
1843
- const db2 = getFirestore();
1844
- const snapshotId = `snapshot_${Date.now()}`;
1845
- const snapshotDoc = {
1846
- id: snapshotId,
1847
- timestamp: Date.now(),
1848
- schema: toFirestoreFormat(schema),
1849
- reason
1850
- };
1851
- await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).set(snapshotDoc);
1852
- const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
1853
- const appDoc = await appDocRef.get();
1854
- const currentMeta = appDoc.data()?._historyMeta;
1855
- const updatedMeta = {
1856
- latestSnapshotId: snapshotId,
1857
- latestChangeSetId: currentMeta?.latestChangeSetId,
1858
- snapshotCount: (currentMeta?.snapshotCount || 0) + 1,
1859
- changeSetCount: currentMeta?.changeSetCount || 0
1860
- };
1861
- await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
1862
- return snapshotId;
1863
- }
1864
- /** Get all snapshots for an app (ordered by timestamp desc) */
1865
- async getAll(uid, appId) {
1866
- const db2 = getFirestore();
1867
- const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("timestamp", "desc").get();
1868
- return query.docs.map((doc) => doc.data());
1869
- }
1870
- /** Get a specific snapshot by ID */
1871
- async get(uid, appId, snapshotId) {
1872
- const db2 = getFirestore();
1873
- const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).get();
1874
- if (!doc.exists) return null;
1875
- return doc.data();
1876
- }
1877
- /** Delete a snapshot */
1878
- async delete(uid, appId, snapshotId) {
1879
- const db2 = getFirestore();
1880
- const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`);
1881
- const doc = await ref.get();
1882
- if (!doc.exists) return false;
1883
- await ref.delete();
1884
- const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
1885
- const appDoc = await appDocRef.get();
1886
- const currentMeta = appDoc.data()?._historyMeta;
1887
- if (currentMeta) {
1888
- const updatedMeta = {
1889
- ...currentMeta,
1890
- snapshotCount: Math.max(0, (currentMeta.snapshotCount || 1) - 1),
1891
- latestSnapshotId: currentMeta.latestSnapshotId === snapshotId ? void 0 : currentMeta.latestSnapshotId
1892
- };
1893
- await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
1894
- }
1895
- return true;
1896
- }
1897
- /** Get schema snapshot at a specific version */
1898
- async getByVersion(uid, appId, version) {
1899
- const db2 = getFirestore();
1900
- const query = await db2.collection(this.getCollectionPath(uid, appId)).where("version", "==", version).limit(1).get();
1901
- if (query.empty) return null;
1902
- const snapshot = query.docs[0].data();
1903
- return fromFirestoreFormat(snapshot.schema);
1904
- }
1905
- /** Get the schema from a snapshot (deserialized) */
1906
- getSchemaFromSnapshot(snapshot) {
1907
- return fromFirestoreFormat(snapshot.schema);
1908
- }
1909
- };
1910
-
1911
- // src/stores/ChangeSetStore.ts
1912
- var CHANGESETS_COLLECTION = "changesets";
1913
- var ChangeSetStore = class {
1914
- appsCollection;
1915
- constructor(appsCollection = "apps") {
1916
- this.appsCollection = appsCollection;
1917
- }
1918
- getCollectionPath(uid, appId) {
1919
- return `users/${uid}/${this.appsCollection}/${appId}/${CHANGESETS_COLLECTION}`;
1920
- }
1921
- getAppDocPath(uid, appId) {
1922
- return `users/${uid}/${this.appsCollection}/${appId}`;
1923
- }
1924
- /** Append a changeset to history */
1925
- async append(uid, appId, changeSet) {
1926
- const db2 = getFirestore();
1927
- await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSet.id}`).set(changeSet);
1928
- const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
1929
- const appDoc = await appDocRef.get();
1930
- const currentMeta = appDoc.data()?._historyMeta;
1931
- const updatedMeta = {
1932
- latestSnapshotId: currentMeta?.latestSnapshotId,
1933
- latestChangeSetId: changeSet.id,
1934
- snapshotCount: currentMeta?.snapshotCount || 0,
1935
- changeSetCount: (currentMeta?.changeSetCount || 0) + 1
1936
- };
1937
- await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
1938
- }
1939
- /** Get change history for an app (ordered by version desc) */
1940
- async getHistory(uid, appId) {
1941
- try {
1942
- const db2 = getFirestore();
1943
- const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("version", "desc").get();
1944
- return query.docs.map((doc) => doc.data());
1945
- } catch (error) {
1946
- console.error("[ChangeSetStore] Error getting change history:", error);
1947
- return [];
1948
- }
1949
- }
1950
- /** Get a specific changeset by ID */
1951
- async get(uid, appId, changeSetId) {
1952
- const db2 = getFirestore();
1953
- const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`).get();
1954
- if (!doc.exists) return null;
1955
- return doc.data();
1956
- }
1957
- /** Update a changeset's status */
1958
- async updateStatus(uid, appId, changeSetId, status) {
1959
- const db2 = getFirestore();
1960
- const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
1961
- const doc = await ref.get();
1962
- if (!doc.exists) return;
1963
- await ref.update({ status });
1964
- }
1965
- /** Delete a changeset */
1966
- async delete(uid, appId, changeSetId) {
1967
- const db2 = getFirestore();
1968
- const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
1969
- const doc = await ref.get();
1970
- if (!doc.exists) return false;
1971
- await ref.delete();
1972
- const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
1973
- const appDoc = await appDocRef.get();
1974
- const currentMeta = appDoc.data()?._historyMeta;
1975
- if (currentMeta) {
1976
- const updatedMeta = {
1977
- ...currentMeta,
1978
- changeSetCount: Math.max(0, (currentMeta.changeSetCount || 1) - 1),
1979
- latestChangeSetId: currentMeta.latestChangeSetId === changeSetId ? void 0 : currentMeta.latestChangeSetId
1980
- };
1981
- await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
1982
- }
1983
- return true;
1984
- }
1985
- };
1986
-
1987
- // src/stores/ValidationStore.ts
1988
- var VALIDATION_COLLECTION = "validation";
1989
- var VALIDATION_DOC_ID = "current";
1990
- var ValidationStore = class {
1991
- appsCollection;
1992
- constructor(appsCollection = "apps") {
1993
- this.appsCollection = appsCollection;
1994
- }
1995
- getDocPath(uid, appId) {
1996
- return `users/${uid}/${this.appsCollection}/${appId}/${VALIDATION_COLLECTION}/${VALIDATION_DOC_ID}`;
1997
- }
1998
- getAppDocPath(uid, appId) {
1999
- return `users/${uid}/${this.appsCollection}/${appId}`;
2000
- }
2001
- /** Save validation results */
2002
- async save(uid, appId, results) {
2003
- const db2 = getFirestore();
2004
- await db2.doc(this.getDocPath(uid, appId)).set(results);
2005
- const validationMeta = {
2006
- errorCount: results.errors?.length || 0,
2007
- warningCount: results.warnings?.length || 0,
2008
- validatedAt: results.validatedAt
2009
- };
2010
- await db2.doc(this.getAppDocPath(uid, appId)).set(
2011
- { _operational: { validationMeta } },
2012
- { merge: true }
2013
- );
2014
- }
2015
- /** Get validation results */
2016
- async get(uid, appId) {
2017
- try {
2018
- const db2 = getFirestore();
2019
- const doc = await db2.doc(this.getDocPath(uid, appId)).get();
2020
- if (!doc.exists) return null;
2021
- return doc.data();
2022
- } catch (error) {
2023
- console.error("[ValidationStore] Error getting validation results:", error);
2024
- return null;
2025
- }
2026
- }
2027
- /** Clear validation results */
2028
- async clear(uid, appId) {
2029
- const db2 = getFirestore();
2030
- const { FieldValue } = await import('firebase-admin/firestore');
2031
- await db2.doc(this.getDocPath(uid, appId)).delete();
2032
- await db2.doc(this.getAppDocPath(uid, appId)).update({
2033
- "_operational.validationMeta": FieldValue.delete()
2034
- });
2035
- }
2036
- };
2037
- var memoryManager = null;
2038
- function getMemoryManager() {
2039
- if (!memoryManager) {
2040
- memoryManager = new MemoryManager({
2041
- db,
2042
- usersCollection: "agent_memory_users",
2043
- projectsCollection: "agent_memory_projects",
2044
- generationsCollection: "agent_memory_generations",
2045
- patternsCollection: "agent_memory_patterns",
2046
- interruptsCollection: "agent_memory_interrupts",
2047
- feedbackCollection: "agent_memory_feedback",
2048
- checkpointsCollection: "agent_memory_checkpoints",
2049
- toolPreferencesCollection: "agent_memory_tool_preferences"
2050
- });
2051
- }
2052
- return memoryManager;
2053
- }
2054
- function resetMemoryManager() {
2055
- memoryManager = null;
2056
- }
2057
- var sessionManager = null;
2058
- function createFirestoreAdapter(firestore) {
2059
- return firestore;
2060
- }
2061
- function getSessionManager() {
2062
- if (!sessionManager) {
2063
- sessionManager = new SessionManager({
2064
- mode: "firestore",
2065
- firestoreDb: createFirestoreAdapter(db),
2066
- memoryManager: getMemoryManager(),
2067
- // Enable GAP-002D
2068
- compactionConfig: {
2069
- maxTokens: 15e4,
2070
- keepRecentMessages: 10,
2071
- strategy: "last"
2072
- }
2073
- });
2074
- }
2075
- return sessionManager;
2076
- }
2077
- function resetSessionManager() {
2078
- sessionManager = null;
2079
- }
2080
- async function createServerSkillAgent(options) {
2081
- const memoryManager2 = getMemoryManager();
2082
- getSessionManager();
2083
- const observability = getObservabilityCollector();
2084
- const multiUser = getMultiUserManager();
2085
- if (options.threadId) {
2086
- const access = multiUser.canAccessSession(options.threadId, {
2087
- userId: options.userId,
2088
- roles: ["user"]
2089
- });
2090
- if (!access.allowed) {
2091
- throw new Error(`Access denied: ${access.reason}`);
2092
- }
2093
- }
2094
- observability.startSession(options.threadId ?? "new", options.userId);
2095
- const workflowToolWrapper = createWorkflowToolWrapper({
2096
- maxRetries: 2,
2097
- enableTelemetry: true,
2098
- timeoutMs: 3e5
2099
- // 5 minutes
2100
- });
2101
- try {
2102
- const result = await createSkillAgent({
2103
- ...options,
2104
- memoryManager: memoryManager2,
2105
- // GAP-001: Enable memory
2106
- userId: options.userId,
2107
- // GAP-002D: Session → Memory sync
2108
- appId: options.appId,
2109
- toolWrapper: workflowToolWrapper.wrap
2110
- // Always use workflow wrapper for reliability
2111
- });
2112
- if (result.threadId) {
2113
- multiUser.assignSessionOwnership(result.threadId, options.userId);
2114
- }
2115
- observability.recordEvent({
2116
- type: "session_start",
2117
- sessionId: result.threadId,
2118
- userId: options.userId,
2119
- payload: { skill: options.skill }
2120
- });
2121
- return result;
2122
- } catch (error) {
2123
- observability.recordError(options.threadId ?? "new", error);
2124
- throw error;
2125
- }
2126
- }
2127
- async function multiUserMiddleware(req, res, next) {
2128
- const userId = req.user?.uid;
2129
- if (!userId) {
2130
- res.status(401).json({ error: "Authentication required" });
2131
- return;
2132
- }
2133
- req.userContext = createUserContext(userId, {
2134
- orgId: req.user?.orgId,
2135
- roles: req.user?.roles ?? ["user"]
2136
- });
2137
- const originalJson = res.json.bind(res);
2138
- res.json = (body) => {
2139
- if (body && typeof body === "object" && "threadId" in body) {
2140
- const multiUser = getMultiUserManager();
2141
- multiUser.assignSessionOwnership(
2142
- body.threadId,
2143
- userId
2144
- );
2145
- }
2146
- return originalJson(body);
2147
- };
2148
- next();
2149
- }
2150
- async function verifyFirebaseAuth(req, res, next) {
2151
- const authHeader = req.headers.authorization;
2152
- if (!authHeader?.startsWith("Bearer ")) {
2153
- res.status(401).json({ error: "No token provided" });
2154
- return;
2155
- }
2156
- const token = authHeader.split("Bearer ")[1];
2157
- try {
2158
- const decodedToken = await getAuth().verifyIdToken(token);
2159
- const user = await getAuth().getUser(decodedToken.uid);
2160
- req.user = {
2161
- uid: decodedToken.uid,
2162
- email: decodedToken.email,
2163
- roles: user.customClaims?.roles ?? ["user"],
2164
- orgId: user.customClaims?.orgId
2165
- };
2166
- next();
2167
- } catch (error) {
2168
- console.error("Token verification failed:", error);
2169
- res.status(401).json({ error: "Invalid token" });
2170
- }
2171
- }
2172
- function setupStateSyncWebSocket(io) {
2173
- const stateSync = getStateSyncManager();
2174
- io.use(async (socket, next) => {
2175
- try {
2176
- const token = socket.handshake.auth.token;
2177
- if (!token) {
2178
- return next(new Error("Authentication required"));
2179
- }
2180
- const decodedToken = await getAuth().verifyIdToken(token);
2181
- const user = await getAuth().getUser(decodedToken.uid);
2182
- socket.data.user = {
2183
- uid: decodedToken.uid,
2184
- roles: user.customClaims?.roles ?? ["user"],
2185
- orgId: user.customClaims?.orgId
2186
- };
2187
- next();
2188
- } catch (error) {
2189
- console.error("Socket auth failed:", error);
2190
- next(new Error("Invalid token"));
2191
- }
2192
- });
2193
- io.on("connection", (socket) => {
2194
- const userId = socket.data.user.uid;
2195
- const clientId = socket.handshake.auth.clientId;
2196
- console.log(`[StateSync] Client ${clientId} connected for user ${userId}`);
2197
- stateSync.updateConfig({ clientId });
2198
- socket.join(`user:${userId}`);
2199
- socket.on("stateChange", (...args) => {
2200
- const event = args[0];
2201
- const multiUser = getMultiUserManager();
2202
- if (!multiUser.isSessionOwner(event.threadId, userId)) {
2203
- socket.emit("error", { message: "Not session owner" });
2204
- return;
2205
- }
2206
- stateSync.receiveRemoteChange(event);
2207
- socket.to(`user:${userId}`).emit("remoteChange", event);
2208
- });
2209
- stateSync.on("syncRequired", (changes) => {
2210
- socket.emit("syncBatch", changes);
2211
- });
2212
- socket.on("disconnect", () => {
2213
- console.log(`[StateSync] Client ${clientId} disconnected`);
2214
- socket.leave(`user:${userId}`);
2215
- });
2216
- });
2217
- }
2218
-
2219
- // src/lib/serviceDiscovery.ts
2220
- var InMemoryServiceRegistry = class {
2221
- services = /* @__PURE__ */ new Map();
2222
- async register(service) {
2223
- this.services.set(service.instanceId, {
2224
- ...service,
2225
- registeredAt: Date.now(),
2226
- lastHeartbeat: Date.now()
2227
- });
2228
- }
2229
- async deregister(instanceId) {
2230
- this.services.delete(instanceId);
2231
- }
2232
- async heartbeat(instanceId) {
2233
- const service = this.services.get(instanceId);
2234
- if (service) {
2235
- service.lastHeartbeat = Date.now();
2236
- }
2237
- }
2238
- async updateStatus(instanceId, status) {
2239
- const service = this.services.get(instanceId);
2240
- if (service) {
2241
- service.status = status;
2242
- }
2243
- }
2244
- async getAll() {
2245
- return Array.from(this.services.values());
2246
- }
2247
- async getByName(name) {
2248
- return Array.from(this.services.values()).filter((s) => s.name === name);
2249
- }
2250
- async findListeners(event) {
2251
- return Array.from(this.services.values()).filter(
2252
- (s) => s.listens.includes(event) && s.status !== "stopping"
2253
- );
2254
- }
2255
- async findEmitters(event) {
2256
- return Array.from(this.services.values()).filter(
2257
- (s) => s.emits.includes(event) && s.status !== "stopping"
2258
- );
2259
- }
2260
- async cleanup(ttlMs) {
2261
- const cutoff = Date.now() - ttlMs;
2262
- let removed = 0;
2263
- for (const [id, service] of this.services) {
2264
- if (service.lastHeartbeat < cutoff) {
2265
- this.services.delete(id);
2266
- removed++;
2267
- }
2268
- }
2269
- return removed;
2270
- }
2271
- };
2272
- var ServiceDiscovery = class {
2273
- registry;
2274
- options;
2275
- cleanupTimer = null;
2276
- constructor(options, registry) {
2277
- this.options = {
2278
- heartbeatTtlMs: options?.heartbeatTtlMs ?? 6e4,
2279
- cleanupIntervalMs: options?.cleanupIntervalMs ?? 3e4
2280
- };
2281
- this.registry = registry ?? new InMemoryServiceRegistry();
2282
- }
2283
- /**
2284
- * Register a service with the registry.
2285
- */
2286
- async register(service) {
2287
- await this.registry.register({
2288
- ...service,
2289
- status: service.status ?? "starting",
2290
- registeredAt: Date.now(),
2291
- lastHeartbeat: Date.now()
2292
- });
2293
- }
2294
- /**
2295
- * Deregister a service.
2296
- */
2297
- async deregister(instanceId) {
2298
- await this.registry.deregister(instanceId);
2299
- }
2300
- /**
2301
- * Send heartbeat for a service.
2302
- */
2303
- async heartbeat(instanceId) {
2304
- await this.registry.heartbeat(instanceId);
2305
- }
2306
- /**
2307
- * Mark a service as ready.
2308
- */
2309
- async markReady(instanceId) {
2310
- await this.registry.updateStatus(instanceId, "ready");
2311
- }
2312
- /**
2313
- * Mark a service as degraded.
2314
- */
2315
- async markDegraded(instanceId) {
2316
- await this.registry.updateStatus(instanceId, "degraded");
2317
- }
2318
- /**
2319
- * Find all services that listen for a given event.
2320
- */
2321
- async findListeners(event) {
2322
- return this.registry.findListeners(event);
2323
- }
2324
- /**
2325
- * Find all services that emit a given event.
2326
- */
2327
- async findEmitters(event) {
2328
- return this.registry.findEmitters(event);
2329
- }
2330
- /**
2331
- * Get all registered services.
2332
- */
2333
- async getAll() {
2334
- return this.registry.getAll();
2335
- }
2336
- /**
2337
- * Get the full event topology (who emits what, who listens for what).
2338
- */
2339
- async getEventTopology() {
2340
- const services = await this.registry.getAll();
2341
- const eventMap = /* @__PURE__ */ new Map();
2342
- for (const service of services) {
2343
- for (const event of service.emits) {
2344
- if (!eventMap.has(event)) eventMap.set(event, { emitters: /* @__PURE__ */ new Set(), listeners: /* @__PURE__ */ new Set() });
2345
- eventMap.get(event).emitters.add(service.name);
2346
- }
2347
- for (const event of service.listens) {
2348
- if (!eventMap.has(event)) eventMap.set(event, { emitters: /* @__PURE__ */ new Set(), listeners: /* @__PURE__ */ new Set() });
2349
- eventMap.get(event).listeners.add(service.name);
2350
- }
2351
- }
2352
- const events = Array.from(eventMap.entries()).map(([event, { emitters, listeners }]) => ({
2353
- event,
2354
- emitters: Array.from(emitters),
2355
- listeners: Array.from(listeners)
2356
- }));
2357
- return { events };
2358
- }
2359
- /**
2360
- * Start periodic cleanup of expired services.
2361
- */
2362
- startCleanup() {
2363
- if (this.cleanupTimer) return;
2364
- this.cleanupTimer = setInterval(() => {
2365
- this.registry.cleanup(this.options.heartbeatTtlMs).catch((err) => {
2366
- console.error("[ServiceDiscovery] Cleanup error:", err);
2367
- });
2368
- }, this.options.cleanupIntervalMs);
2369
- }
2370
- /**
2371
- * Stop periodic cleanup.
2372
- */
2373
- stopCleanup() {
2374
- if (this.cleanupTimer) {
2375
- clearInterval(this.cleanupTimer);
2376
- this.cleanupTimer = null;
2377
- }
2378
- }
2379
- /**
2380
- * Get the underlying registry (for testing).
2381
- */
2382
- getRegistry() {
2383
- return this.registry;
2384
- }
2385
- };
2386
- var router = Router();
2387
- router.get("/metrics", async (req, res) => {
2388
- try {
2389
- const collector = getObservabilityCollector();
2390
- const snapshot = collector.getPerformanceSnapshot();
2391
- res.json(snapshot);
2392
- } catch (error) {
2393
- console.error("Metrics error:", error);
2394
- res.status(500).json({ error: "Failed to get metrics" });
2395
- }
2396
- });
2397
- router.get("/health", async (req, res) => {
2398
- try {
2399
- const collector = getObservabilityCollector();
2400
- const health = await collector.healthCheck();
2401
- const allHealthy = health.every((h) => h.status === "healthy");
2402
- res.status(allHealthy ? 200 : 503).json({
2403
- status: allHealthy ? "healthy" : "degraded",
2404
- timestamp: Date.now(),
2405
- checks: health
2406
- });
2407
- } catch (error) {
2408
- console.error("Health check error:", error);
2409
- res.status(500).json({
2410
- status: "unhealthy",
2411
- error: "Health check failed"
2412
- });
2413
- }
2414
- });
2415
- router.get("/sessions/:threadId/telemetry", async (req, res) => {
2416
- try {
2417
- const collector = getObservabilityCollector();
2418
- const telemetry = collector.getSessionTelemetry(req.params.threadId);
2419
- if (!telemetry) {
2420
- res.status(404).json({ error: "Session not found" });
2421
- return;
2422
- }
2423
- res.json(telemetry);
2424
- } catch (error) {
2425
- console.error("Telemetry error:", error);
2426
- res.status(500).json({ error: "Failed to get telemetry" });
2427
- }
2428
- });
2429
- router.get("/active-sessions", async (req, res) => {
2430
- try {
2431
- const collector = getObservabilityCollector();
2432
- const sessions = collector.getActiveSessions();
2433
- res.json(sessions);
2434
- } catch (error) {
2435
- console.error("Active sessions error:", error);
2436
- res.status(500).json({ error: "Failed to get active sessions" });
2437
- }
2438
- });
2439
- var observability_default = router;
2440
-
2441
- // src/index.ts
2442
- var dataService = new Proxy({}, {
2443
- get(_target, prop, receiver) {
2444
- return Reflect.get(getDataService(), prop, receiver);
2445
- }
2446
- });
2447
- var mockDataService = new Proxy({}, {
2448
- get(_target, prop, receiver) {
2449
- return Reflect.get(getMockDataService(), prop, receiver);
2450
- }
2451
- });
2452
- var serverEventBus = new Proxy({}, {
2453
- get(_target, prop, receiver) {
2454
- return Reflect.get(getServerEventBus(), prop, receiver);
2455
- }
2456
- });
2457
-
2458
- export { AppError, ChangeSetStore, ConflictError, DistributedEventBus, EventBus, EventPersistence, ForbiddenError, InMemoryEventStore, InMemoryServiceRegistry, InMemoryTransport, MockDataService, NotFoundError, RedisTransport, SchemaProtectionService, SchemaStore, ServiceDiscovery, SnapshotStore, UnauthorizedError, ValidationError, ValidationStore, applyFiltersToQuery, asyncHandler, authenticateFirebase, closeWebSocketServer, createServerSkillAgent, dataService, db, debugEventsRouter, emitEntityEvent, env, errorHandler, extractPaginationParams, fromFirestoreFormat, getMemoryManager as getAgentMemoryManager, getSessionManager as getAgentSessionManager, getAuth, getConnectedClientCount, getDataService, getFirestore, getMemoryManager, getMockDataService, getServerEventBus, getSessionManager, getWebSocketServer, initializeFirebase, logger, mockDataService, multiUserMiddleware, notFoundHandler, observability_default as observabilityRouter, parseQueryFilters, resetDataService, resetMemoryManager, resetMockDataService, resetServerEventBus, resetSessionManager, seedMockData, serverEventBus, setupEventBroadcast, setupStateSyncWebSocket, toFirestoreFormat, validateBody, validateParams, validateQuery, verifyFirebaseAuth };
2459
- //# sourceMappingURL=index.js.map
2460
- //# sourceMappingURL=index.js.map