@almadar/server 2.1.0 → 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.
- package/package.json +1 -1
- package/dist/contracts.d.ts +0 -174
- package/dist/contracts.d.ts.map +0 -1
- package/dist/deepagent/__tests__/memory.test.d.ts +0 -6
- package/dist/deepagent/__tests__/memory.test.d.ts.map +0 -1
- package/dist/deepagent/__tests__/session.test.d.ts +0 -6
- package/dist/deepagent/__tests__/session.test.d.ts.map +0 -1
- package/dist/deepagent/__tests__/skill-agent.test.d.ts +0 -6
- package/dist/deepagent/__tests__/skill-agent.test.d.ts.map +0 -1
- package/dist/deepagent/memory.d.ts +0 -17
- package/dist/deepagent/memory.d.ts.map +0 -1
- package/dist/deepagent/memory.js +0 -48
- package/dist/deepagent/memory.js.map +0 -1
- package/dist/deepagent/session.d.ts +0 -17
- package/dist/deepagent/session.d.ts.map +0 -1
- package/dist/deepagent/session.js +0 -68
- package/dist/deepagent/session.js.map +0 -1
- package/dist/deepagent/skill-agent.d.ts +0 -22
- package/dist/deepagent/skill-agent.d.ts.map +0 -1
- package/dist/deepagent/skill-agent.js +0 -114
- package/dist/deepagent/skill-agent.js.map +0 -1
- package/dist/index.js +0 -2598
- package/dist/index.js.map +0 -1
- package/dist/lib/db.d.ts +0 -36
- package/dist/lib/db.d.ts.map +0 -1
- package/dist/lib/debugRouter.d.ts +0 -21
- package/dist/lib/debugRouter.d.ts.map +0 -1
- package/dist/lib/env.d.ts +0 -16
- package/dist/lib/env.d.ts.map +0 -1
- package/dist/lib/eventBus.d.ts +0 -44
- package/dist/lib/eventBus.d.ts.map +0 -1
- package/dist/lib/eventBusTransport.d.ts +0 -143
- package/dist/lib/eventBusTransport.d.ts.map +0 -1
- package/dist/lib/eventPersistence.d.ts +0 -151
- package/dist/lib/eventPersistence.d.ts.map +0 -1
- package/dist/lib/index.d.ts +0 -6
- package/dist/lib/index.d.ts.map +0 -1
- package/dist/lib/index.js +0 -288
- package/dist/lib/index.js.map +0 -1
- package/dist/lib/logger.d.ts +0 -7
- package/dist/lib/logger.d.ts.map +0 -1
- package/dist/lib/serviceDiscovery.d.ts +0 -168
- package/dist/lib/serviceDiscovery.d.ts.map +0 -1
- package/dist/lib/websocket.d.ts +0 -41
- package/dist/lib/websocket.d.ts.map +0 -1
- package/dist/middleware/__tests__/multi-user.test.d.ts +0 -6
- package/dist/middleware/__tests__/multi-user.test.d.ts.map +0 -1
- package/dist/middleware/authenticateFirebase.d.ts +0 -4
- package/dist/middleware/authenticateFirebase.d.ts.map +0 -1
- package/dist/middleware/errorHandler.d.ts +0 -53
- package/dist/middleware/errorHandler.d.ts.map +0 -1
- package/dist/middleware/index.d.ts +0 -4
- package/dist/middleware/index.d.ts.map +0 -1
- package/dist/middleware/index.js +0 -284
- package/dist/middleware/index.js.map +0 -1
- package/dist/middleware/multi-user.d.ts +0 -34
- package/dist/middleware/multi-user.d.ts.map +0 -1
- package/dist/middleware/multi-user.js +0 -76
- package/dist/middleware/multi-user.js.map +0 -1
- package/dist/middleware/validation.d.ts +0 -15
- package/dist/middleware/validation.d.ts.map +0 -1
- package/dist/routes/__tests__/observability.test.d.ts +0 -6
- package/dist/routes/__tests__/observability.test.d.ts.map +0 -1
- package/dist/routes/observability.d.ts +0 -11
- package/dist/routes/observability.d.ts.map +0 -1
- package/dist/routes/observability.js +0 -62
- package/dist/routes/observability.js.map +0 -1
- package/dist/services/DataService.d.ts +0 -70
- package/dist/services/DataService.d.ts.map +0 -1
- package/dist/services/MockDataService.d.ts +0 -110
- package/dist/services/MockDataService.d.ts.map +0 -1
- package/dist/services/index.d.ts +0 -8
- package/dist/services/index.d.ts.map +0 -1
- package/dist/services/index.js +0 -735
- package/dist/services/index.js.map +0 -1
- package/dist/stores/ChangeSetStore.d.ts +0 -24
- package/dist/stores/ChangeSetStore.d.ts.map +0 -1
- package/dist/stores/SchemaProtectionService.d.ts +0 -23
- package/dist/stores/SchemaProtectionService.d.ts.map +0 -1
- package/dist/stores/SchemaStore.d.ts +0 -52
- package/dist/stores/SchemaStore.d.ts.map +0 -1
- package/dist/stores/SnapshotStore.d.ts +0 -26
- package/dist/stores/SnapshotStore.d.ts.map +0 -1
- package/dist/stores/ValidationStore.d.ts +0 -19
- package/dist/stores/ValidationStore.d.ts.map +0 -1
- package/dist/stores/firestoreFormat.d.ts +0 -21
- package/dist/stores/firestoreFormat.d.ts.map +0 -1
- package/dist/stores/index.d.ts +0 -14
- package/dist/stores/index.d.ts.map +0 -1
- package/dist/stores/index.js +0 -519
- package/dist/stores/index.js.map +0 -1
- package/dist/utils/index.d.ts +0 -9
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/index.js +0 -106
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/queryFilters.d.ts +0 -87
- package/dist/utils/queryFilters.d.ts.map +0 -1
- package/dist/websocket/__tests__/state-sync.test.d.ts +0 -6
- package/dist/websocket/__tests__/state-sync.test.d.ts.map +0 -1
- package/dist/websocket/state-sync.d.ts +0 -39
- package/dist/websocket/state-sync.d.ts.map +0 -1
- package/dist/websocket/state-sync.js +0 -77
- package/dist/websocket/state-sync.js.map +0 -1
package/dist/stores/index.js
DELETED
|
@@ -1,519 +0,0 @@
|
|
|
1
|
-
import admin from 'firebase-admin';
|
|
2
|
-
import { diffSchemas, categorizeRemovals, detectPageContentReduction, isDestructiveChange, hasSignificantPageReduction, requiresConfirmation } from '@almadar/core';
|
|
3
|
-
|
|
4
|
-
// src/stores/firestoreFormat.ts
|
|
5
|
-
function toFirestoreFormat(schema) {
|
|
6
|
-
const data = { ...schema };
|
|
7
|
-
if (schema.orbitals) {
|
|
8
|
-
data._orbitalsJson = JSON.stringify(schema.orbitals);
|
|
9
|
-
data.orbitalCount = schema.orbitals.length;
|
|
10
|
-
delete data.orbitals;
|
|
11
|
-
}
|
|
12
|
-
if (data.traits) {
|
|
13
|
-
const traits = data.traits;
|
|
14
|
-
data._traitsJson = JSON.stringify(traits);
|
|
15
|
-
data.traitCount = traits.length;
|
|
16
|
-
delete data.traits;
|
|
17
|
-
}
|
|
18
|
-
if (schema.services) {
|
|
19
|
-
data._servicesJson = JSON.stringify(schema.services);
|
|
20
|
-
data.serviceCount = schema.services.length;
|
|
21
|
-
delete data.services;
|
|
22
|
-
}
|
|
23
|
-
return data;
|
|
24
|
-
}
|
|
25
|
-
function fromFirestoreFormat(data) {
|
|
26
|
-
const result = { ...data };
|
|
27
|
-
if (result._orbitalsJson && typeof result._orbitalsJson === "string") {
|
|
28
|
-
try {
|
|
29
|
-
result.orbitals = JSON.parse(result._orbitalsJson);
|
|
30
|
-
delete result._orbitalsJson;
|
|
31
|
-
delete result.orbitalCount;
|
|
32
|
-
} catch (e) {
|
|
33
|
-
console.warn("[OrbitalStore] Failed to parse _orbitalsJson:", e);
|
|
34
|
-
result.orbitals = [];
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
if (result._traitsJson && typeof result._traitsJson === "string") {
|
|
38
|
-
try {
|
|
39
|
-
result.traits = JSON.parse(result._traitsJson);
|
|
40
|
-
delete result._traitsJson;
|
|
41
|
-
delete result.traitCount;
|
|
42
|
-
} catch (e) {
|
|
43
|
-
console.warn("[OrbitalStore] Failed to parse _traitsJson:", e);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (result._servicesJson && typeof result._servicesJson === "string") {
|
|
47
|
-
try {
|
|
48
|
-
result.services = JSON.parse(result._servicesJson);
|
|
49
|
-
delete result._servicesJson;
|
|
50
|
-
delete result.serviceCount;
|
|
51
|
-
} catch (e) {
|
|
52
|
-
console.warn("[OrbitalStore] Failed to parse _servicesJson:", e);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return result;
|
|
56
|
-
}
|
|
57
|
-
function getApp() {
|
|
58
|
-
if (admin.apps.length === 0) {
|
|
59
|
-
throw new Error(
|
|
60
|
-
"@almadar/server: Firebase Admin SDK is not initialized. Call initializeFirebase() or admin.initializeApp() before using @almadar/server."
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
return admin.app();
|
|
64
|
-
}
|
|
65
|
-
function getFirestore() {
|
|
66
|
-
return getApp().firestore();
|
|
67
|
-
}
|
|
68
|
-
new Proxy({}, {
|
|
69
|
-
get(_target, prop, receiver) {
|
|
70
|
-
const firestore = getFirestore();
|
|
71
|
-
const value = Reflect.get(firestore, prop, receiver);
|
|
72
|
-
return typeof value === "function" ? value.bind(firestore) : value;
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
var SchemaProtectionService = class {
|
|
76
|
-
/**
|
|
77
|
-
* Compare two schemas and detect destructive changes.
|
|
78
|
-
*
|
|
79
|
-
* Returns categorized removals including page content reductions.
|
|
80
|
-
*/
|
|
81
|
-
compareSchemas(before, after) {
|
|
82
|
-
const changeSet = diffSchemas(before, after);
|
|
83
|
-
const removals = categorizeRemovals(changeSet);
|
|
84
|
-
const beforePages = before.orbitals?.flatMap((o) => o.pages || []) || [];
|
|
85
|
-
const afterPages = after.orbitals?.flatMap((o) => o.pages || []) || [];
|
|
86
|
-
const pageContentReductions = detectPageContentReduction(beforePages, afterPages);
|
|
87
|
-
removals.pageContentReductions = pageContentReductions;
|
|
88
|
-
const isDestructive = isDestructiveChange(changeSet) || hasSignificantPageReduction(pageContentReductions);
|
|
89
|
-
return { isDestructive, removals };
|
|
90
|
-
}
|
|
91
|
-
/** Check if critical removals require confirmation */
|
|
92
|
-
requiresConfirmation(removals) {
|
|
93
|
-
return requiresConfirmation(removals);
|
|
94
|
-
}
|
|
95
|
-
/** Check for significant page content reductions */
|
|
96
|
-
hasSignificantContentReduction(reductions) {
|
|
97
|
-
return hasSignificantPageReduction(reductions);
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
// src/stores/SchemaStore.ts
|
|
102
|
-
var SCHEMA_CACHE_TTL_MS = 6e4;
|
|
103
|
-
var LIST_CACHE_TTL_MS = 3e4;
|
|
104
|
-
var SchemaStore = class {
|
|
105
|
-
appsCollection;
|
|
106
|
-
schemaCache = /* @__PURE__ */ new Map();
|
|
107
|
-
listCache = /* @__PURE__ */ new Map();
|
|
108
|
-
protectionService = new SchemaProtectionService();
|
|
109
|
-
snapshotStore = null;
|
|
110
|
-
constructor(appsCollection = "apps") {
|
|
111
|
-
this.appsCollection = appsCollection;
|
|
112
|
-
}
|
|
113
|
-
/** Set snapshot store for auto-snapshot on destructive saves */
|
|
114
|
-
setSnapshotStore(store) {
|
|
115
|
-
this.snapshotStore = store;
|
|
116
|
-
}
|
|
117
|
-
/** Get a schema by app ID */
|
|
118
|
-
async get(uid, appId) {
|
|
119
|
-
const cacheKey = `${uid}:${appId}`;
|
|
120
|
-
const cached = this.schemaCache.get(cacheKey);
|
|
121
|
-
if (cached && Date.now() - cached.timestamp < SCHEMA_CACHE_TTL_MS) {
|
|
122
|
-
return cached.schema;
|
|
123
|
-
}
|
|
124
|
-
try {
|
|
125
|
-
const db2 = getFirestore();
|
|
126
|
-
const appDoc = await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).get();
|
|
127
|
-
if (!appDoc.exists) return null;
|
|
128
|
-
const data = appDoc.data();
|
|
129
|
-
const hasOrbitals = data.orbitals || data._orbitalsJson;
|
|
130
|
-
if (!data.name || !hasOrbitals) return null;
|
|
131
|
-
const schema = fromFirestoreFormat(data);
|
|
132
|
-
this.schemaCache.set(cacheKey, { schema, timestamp: Date.now() });
|
|
133
|
-
return schema;
|
|
134
|
-
} catch (error) {
|
|
135
|
-
console.error("[SchemaStore] Error fetching schema:", error);
|
|
136
|
-
return null;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Save a schema (create or full replace).
|
|
141
|
-
*
|
|
142
|
-
* Features:
|
|
143
|
-
* - Detects destructive changes (removals)
|
|
144
|
-
* - Requires confirmation for critical removals
|
|
145
|
-
* - Auto-creates snapshots before destructive changes (if SnapshotStore attached)
|
|
146
|
-
*/
|
|
147
|
-
async save(uid, appId, schema, options = {}) {
|
|
148
|
-
try {
|
|
149
|
-
const existingSchema = await this.get(uid, appId);
|
|
150
|
-
let snapshotId;
|
|
151
|
-
if (existingSchema && options.snapshotReason && this.snapshotStore) {
|
|
152
|
-
snapshotId = await this.snapshotStore.create(uid, appId, existingSchema, options.snapshotReason);
|
|
153
|
-
}
|
|
154
|
-
if (existingSchema && !options.skipProtection) {
|
|
155
|
-
const comparison = this.protectionService.compareSchemas(existingSchema, schema);
|
|
156
|
-
if (comparison.isDestructive) {
|
|
157
|
-
const { removals } = comparison;
|
|
158
|
-
const hasCriticalRemovals = this.protectionService.requiresConfirmation(removals);
|
|
159
|
-
const hasContentReductions = this.protectionService.hasSignificantContentReduction(
|
|
160
|
-
removals.pageContentReductions
|
|
161
|
-
);
|
|
162
|
-
if ((hasCriticalRemovals || hasContentReductions) && !options.confirmRemovals) {
|
|
163
|
-
return {
|
|
164
|
-
success: false,
|
|
165
|
-
requiresConfirmation: true,
|
|
166
|
-
removals: comparison.removals,
|
|
167
|
-
error: hasContentReductions ? "Page content reduction detected - confirmation required" : "Confirmation required for critical removals"
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
if (!snapshotId && this.snapshotStore && (removals.critical.length > 0 || removals.pageContentReductions.length > 0)) {
|
|
171
|
-
snapshotId = await this.snapshotStore.create(
|
|
172
|
-
uid,
|
|
173
|
-
appId,
|
|
174
|
-
existingSchema,
|
|
175
|
-
`auto_before_removal_${Date.now()}`
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
const firestoreData = toFirestoreFormat(schema);
|
|
181
|
-
const now = Date.now();
|
|
182
|
-
const docData = {
|
|
183
|
-
...firestoreData,
|
|
184
|
-
_metadata: {
|
|
185
|
-
version: options.expectedVersion ? options.expectedVersion + 1 : 1,
|
|
186
|
-
updatedAt: now,
|
|
187
|
-
createdAt: existingSchema ? void 0 : now,
|
|
188
|
-
source: options.source || "manual"
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
const db2 = getFirestore();
|
|
192
|
-
await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData, { merge: true });
|
|
193
|
-
this.invalidateCache(uid, appId);
|
|
194
|
-
return { success: true, snapshotId };
|
|
195
|
-
} catch (error) {
|
|
196
|
-
console.error("[SchemaStore] Error saving schema:", error);
|
|
197
|
-
return {
|
|
198
|
-
success: false,
|
|
199
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
/** Create a new app with initial schema */
|
|
204
|
-
async create(uid, metadata) {
|
|
205
|
-
const appId = `app-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
206
|
-
const now = Date.now();
|
|
207
|
-
const schema = {
|
|
208
|
-
name: metadata.name,
|
|
209
|
-
description: metadata.description,
|
|
210
|
-
orbitals: []
|
|
211
|
-
};
|
|
212
|
-
const firestoreData = toFirestoreFormat(schema);
|
|
213
|
-
const docData = {
|
|
214
|
-
...firestoreData,
|
|
215
|
-
_metadata: { version: 1, createdAt: now, updatedAt: now, source: "manual" }
|
|
216
|
-
};
|
|
217
|
-
const db2 = getFirestore();
|
|
218
|
-
await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData);
|
|
219
|
-
this.listCache.delete(uid);
|
|
220
|
-
return { appId, schema };
|
|
221
|
-
}
|
|
222
|
-
/** Delete an app */
|
|
223
|
-
async delete(uid, appId) {
|
|
224
|
-
try {
|
|
225
|
-
const db2 = getFirestore();
|
|
226
|
-
const ref = db2.doc(`users/${uid}/${this.appsCollection}/${appId}`);
|
|
227
|
-
const doc = await ref.get();
|
|
228
|
-
if (!doc.exists) return false;
|
|
229
|
-
await ref.delete();
|
|
230
|
-
this.invalidateCache(uid, appId);
|
|
231
|
-
return true;
|
|
232
|
-
} catch (error) {
|
|
233
|
-
console.error("[SchemaStore] Error deleting app:", error);
|
|
234
|
-
return false;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
/** List all apps for a user */
|
|
238
|
-
async list(uid) {
|
|
239
|
-
const cached = this.listCache.get(uid);
|
|
240
|
-
if (cached && Date.now() - cached.timestamp < LIST_CACHE_TTL_MS) {
|
|
241
|
-
return cached.apps;
|
|
242
|
-
}
|
|
243
|
-
try {
|
|
244
|
-
const db2 = getFirestore();
|
|
245
|
-
const snapshot = await db2.collection(`users/${uid}/${this.appsCollection}`).select("name", "description", "domainContext", "_metadata", "orbitalCount", "traitCount").orderBy("_metadata.updatedAt", "desc").get();
|
|
246
|
-
const apps = snapshot.docs.map((doc) => {
|
|
247
|
-
const data = doc.data();
|
|
248
|
-
const metadata = data._metadata;
|
|
249
|
-
const orbitalCount = data.orbitalCount;
|
|
250
|
-
return {
|
|
251
|
-
id: doc.id,
|
|
252
|
-
name: data.name || "Untitled",
|
|
253
|
-
description: data.description,
|
|
254
|
-
updatedAt: metadata?.updatedAt || Date.now(),
|
|
255
|
-
createdAt: metadata?.createdAt || Date.now(),
|
|
256
|
-
stats: { entities: orbitalCount ?? 0, pages: 0, states: 0, events: 0, transitions: 0 },
|
|
257
|
-
domainContext: data.domainContext,
|
|
258
|
-
hasValidationErrors: false
|
|
259
|
-
};
|
|
260
|
-
});
|
|
261
|
-
this.listCache.set(uid, { apps, timestamp: Date.now() });
|
|
262
|
-
return apps;
|
|
263
|
-
} catch (error) {
|
|
264
|
-
console.error("[SchemaStore] Error listing apps:", error);
|
|
265
|
-
return [];
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
/** Compute stats from OrbitalSchema */
|
|
269
|
-
computeStats(schema) {
|
|
270
|
-
const orbitals = schema.orbitals || [];
|
|
271
|
-
const entities = orbitals.length;
|
|
272
|
-
const pages = orbitals.reduce((n, o) => n + (o.pages?.length || 0), 0);
|
|
273
|
-
const allTraits = [
|
|
274
|
-
...schema.traits || [],
|
|
275
|
-
...orbitals.flatMap(
|
|
276
|
-
(o) => (o.traits || []).filter((t) => typeof t !== "string" && "stateMachine" in t)
|
|
277
|
-
)
|
|
278
|
-
];
|
|
279
|
-
return {
|
|
280
|
-
states: allTraits.flatMap((t) => t.stateMachine?.states || []).length,
|
|
281
|
-
events: allTraits.flatMap((t) => t.stateMachine?.events || []).length,
|
|
282
|
-
pages,
|
|
283
|
-
entities,
|
|
284
|
-
transitions: allTraits.flatMap((t) => t.stateMachine?.transitions || []).length
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
/** Invalidate caches for a specific app */
|
|
288
|
-
invalidateCache(uid, appId) {
|
|
289
|
-
this.schemaCache.delete(`${uid}:${appId}`);
|
|
290
|
-
this.listCache.delete(uid);
|
|
291
|
-
}
|
|
292
|
-
/** Clear all caches */
|
|
293
|
-
clearCaches() {
|
|
294
|
-
this.schemaCache.clear();
|
|
295
|
-
this.listCache.clear();
|
|
296
|
-
}
|
|
297
|
-
/** Get the collection path for an app */
|
|
298
|
-
getAppDocPath(uid, appId) {
|
|
299
|
-
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
300
|
-
}
|
|
301
|
-
/** Expose apps collection name for subcollection stores */
|
|
302
|
-
getAppsCollection() {
|
|
303
|
-
return this.appsCollection;
|
|
304
|
-
}
|
|
305
|
-
};
|
|
306
|
-
|
|
307
|
-
// src/stores/SnapshotStore.ts
|
|
308
|
-
var SNAPSHOTS_COLLECTION = "snapshots";
|
|
309
|
-
var SnapshotStore = class {
|
|
310
|
-
appsCollection;
|
|
311
|
-
constructor(appsCollection = "apps") {
|
|
312
|
-
this.appsCollection = appsCollection;
|
|
313
|
-
}
|
|
314
|
-
getCollectionPath(uid, appId) {
|
|
315
|
-
return `users/${uid}/${this.appsCollection}/${appId}/${SNAPSHOTS_COLLECTION}`;
|
|
316
|
-
}
|
|
317
|
-
getAppDocPath(uid, appId) {
|
|
318
|
-
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
319
|
-
}
|
|
320
|
-
/** Create a snapshot of the current schema */
|
|
321
|
-
async create(uid, appId, schema, reason) {
|
|
322
|
-
const db2 = getFirestore();
|
|
323
|
-
const snapshotId = `snapshot_${Date.now()}`;
|
|
324
|
-
const snapshotDoc = {
|
|
325
|
-
id: snapshotId,
|
|
326
|
-
timestamp: Date.now(),
|
|
327
|
-
schema: toFirestoreFormat(schema),
|
|
328
|
-
reason
|
|
329
|
-
};
|
|
330
|
-
await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).set(snapshotDoc);
|
|
331
|
-
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
332
|
-
const appDoc = await appDocRef.get();
|
|
333
|
-
const currentMeta = appDoc.data()?._historyMeta;
|
|
334
|
-
const updatedMeta = {
|
|
335
|
-
latestSnapshotId: snapshotId,
|
|
336
|
-
latestChangeSetId: currentMeta?.latestChangeSetId,
|
|
337
|
-
snapshotCount: (currentMeta?.snapshotCount || 0) + 1,
|
|
338
|
-
changeSetCount: currentMeta?.changeSetCount || 0
|
|
339
|
-
};
|
|
340
|
-
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
341
|
-
return snapshotId;
|
|
342
|
-
}
|
|
343
|
-
/** Get all snapshots for an app (ordered by timestamp desc) */
|
|
344
|
-
async getAll(uid, appId) {
|
|
345
|
-
const db2 = getFirestore();
|
|
346
|
-
const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("timestamp", "desc").get();
|
|
347
|
-
return query.docs.map((doc) => doc.data());
|
|
348
|
-
}
|
|
349
|
-
/** Get a specific snapshot by ID */
|
|
350
|
-
async get(uid, appId, snapshotId) {
|
|
351
|
-
const db2 = getFirestore();
|
|
352
|
-
const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).get();
|
|
353
|
-
if (!doc.exists) return null;
|
|
354
|
-
return doc.data();
|
|
355
|
-
}
|
|
356
|
-
/** Delete a snapshot */
|
|
357
|
-
async delete(uid, appId, snapshotId) {
|
|
358
|
-
const db2 = getFirestore();
|
|
359
|
-
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`);
|
|
360
|
-
const doc = await ref.get();
|
|
361
|
-
if (!doc.exists) return false;
|
|
362
|
-
await ref.delete();
|
|
363
|
-
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
364
|
-
const appDoc = await appDocRef.get();
|
|
365
|
-
const currentMeta = appDoc.data()?._historyMeta;
|
|
366
|
-
if (currentMeta) {
|
|
367
|
-
const updatedMeta = {
|
|
368
|
-
...currentMeta,
|
|
369
|
-
snapshotCount: Math.max(0, (currentMeta.snapshotCount || 1) - 1),
|
|
370
|
-
latestSnapshotId: currentMeta.latestSnapshotId === snapshotId ? void 0 : currentMeta.latestSnapshotId
|
|
371
|
-
};
|
|
372
|
-
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
373
|
-
}
|
|
374
|
-
return true;
|
|
375
|
-
}
|
|
376
|
-
/** Get schema snapshot at a specific version */
|
|
377
|
-
async getByVersion(uid, appId, version) {
|
|
378
|
-
const db2 = getFirestore();
|
|
379
|
-
const query = await db2.collection(this.getCollectionPath(uid, appId)).where("version", "==", version).limit(1).get();
|
|
380
|
-
if (query.empty) return null;
|
|
381
|
-
const snapshot = query.docs[0].data();
|
|
382
|
-
return fromFirestoreFormat(snapshot.schema);
|
|
383
|
-
}
|
|
384
|
-
/** Get the schema from a snapshot (deserialized) */
|
|
385
|
-
getSchemaFromSnapshot(snapshot) {
|
|
386
|
-
return fromFirestoreFormat(snapshot.schema);
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
|
|
390
|
-
// src/stores/ChangeSetStore.ts
|
|
391
|
-
var CHANGESETS_COLLECTION = "changesets";
|
|
392
|
-
var ChangeSetStore = class {
|
|
393
|
-
appsCollection;
|
|
394
|
-
constructor(appsCollection = "apps") {
|
|
395
|
-
this.appsCollection = appsCollection;
|
|
396
|
-
}
|
|
397
|
-
getCollectionPath(uid, appId) {
|
|
398
|
-
return `users/${uid}/${this.appsCollection}/${appId}/${CHANGESETS_COLLECTION}`;
|
|
399
|
-
}
|
|
400
|
-
getAppDocPath(uid, appId) {
|
|
401
|
-
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
402
|
-
}
|
|
403
|
-
/** Append a changeset to history */
|
|
404
|
-
async append(uid, appId, changeSet) {
|
|
405
|
-
const db2 = getFirestore();
|
|
406
|
-
await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSet.id}`).set(changeSet);
|
|
407
|
-
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
408
|
-
const appDoc = await appDocRef.get();
|
|
409
|
-
const currentMeta = appDoc.data()?._historyMeta;
|
|
410
|
-
const updatedMeta = {
|
|
411
|
-
latestSnapshotId: currentMeta?.latestSnapshotId,
|
|
412
|
-
latestChangeSetId: changeSet.id,
|
|
413
|
-
snapshotCount: currentMeta?.snapshotCount || 0,
|
|
414
|
-
changeSetCount: (currentMeta?.changeSetCount || 0) + 1
|
|
415
|
-
};
|
|
416
|
-
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
417
|
-
}
|
|
418
|
-
/** Get change history for an app (ordered by version desc) */
|
|
419
|
-
async getHistory(uid, appId) {
|
|
420
|
-
try {
|
|
421
|
-
const db2 = getFirestore();
|
|
422
|
-
const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("version", "desc").get();
|
|
423
|
-
return query.docs.map((doc) => doc.data());
|
|
424
|
-
} catch (error) {
|
|
425
|
-
console.error("[ChangeSetStore] Error getting change history:", error);
|
|
426
|
-
return [];
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
/** Get a specific changeset by ID */
|
|
430
|
-
async get(uid, appId, changeSetId) {
|
|
431
|
-
const db2 = getFirestore();
|
|
432
|
-
const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`).get();
|
|
433
|
-
if (!doc.exists) return null;
|
|
434
|
-
return doc.data();
|
|
435
|
-
}
|
|
436
|
-
/** Update a changeset's status */
|
|
437
|
-
async updateStatus(uid, appId, changeSetId, status) {
|
|
438
|
-
const db2 = getFirestore();
|
|
439
|
-
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
|
|
440
|
-
const doc = await ref.get();
|
|
441
|
-
if (!doc.exists) return;
|
|
442
|
-
await ref.update({ status });
|
|
443
|
-
}
|
|
444
|
-
/** Delete a changeset */
|
|
445
|
-
async delete(uid, appId, changeSetId) {
|
|
446
|
-
const db2 = getFirestore();
|
|
447
|
-
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
|
|
448
|
-
const doc = await ref.get();
|
|
449
|
-
if (!doc.exists) return false;
|
|
450
|
-
await ref.delete();
|
|
451
|
-
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
452
|
-
const appDoc = await appDocRef.get();
|
|
453
|
-
const currentMeta = appDoc.data()?._historyMeta;
|
|
454
|
-
if (currentMeta) {
|
|
455
|
-
const updatedMeta = {
|
|
456
|
-
...currentMeta,
|
|
457
|
-
changeSetCount: Math.max(0, (currentMeta.changeSetCount || 1) - 1),
|
|
458
|
-
latestChangeSetId: currentMeta.latestChangeSetId === changeSetId ? void 0 : currentMeta.latestChangeSetId
|
|
459
|
-
};
|
|
460
|
-
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
461
|
-
}
|
|
462
|
-
return true;
|
|
463
|
-
}
|
|
464
|
-
};
|
|
465
|
-
|
|
466
|
-
// src/stores/ValidationStore.ts
|
|
467
|
-
var VALIDATION_COLLECTION = "validation";
|
|
468
|
-
var VALIDATION_DOC_ID = "current";
|
|
469
|
-
var ValidationStore = class {
|
|
470
|
-
appsCollection;
|
|
471
|
-
constructor(appsCollection = "apps") {
|
|
472
|
-
this.appsCollection = appsCollection;
|
|
473
|
-
}
|
|
474
|
-
getDocPath(uid, appId) {
|
|
475
|
-
return `users/${uid}/${this.appsCollection}/${appId}/${VALIDATION_COLLECTION}/${VALIDATION_DOC_ID}`;
|
|
476
|
-
}
|
|
477
|
-
getAppDocPath(uid, appId) {
|
|
478
|
-
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
479
|
-
}
|
|
480
|
-
/** Save validation results */
|
|
481
|
-
async save(uid, appId, results) {
|
|
482
|
-
const db2 = getFirestore();
|
|
483
|
-
await db2.doc(this.getDocPath(uid, appId)).set(results);
|
|
484
|
-
const validationMeta = {
|
|
485
|
-
errorCount: results.errors?.length || 0,
|
|
486
|
-
warningCount: results.warnings?.length || 0,
|
|
487
|
-
validatedAt: results.validatedAt
|
|
488
|
-
};
|
|
489
|
-
await db2.doc(this.getAppDocPath(uid, appId)).set(
|
|
490
|
-
{ _operational: { validationMeta } },
|
|
491
|
-
{ merge: true }
|
|
492
|
-
);
|
|
493
|
-
}
|
|
494
|
-
/** Get validation results */
|
|
495
|
-
async get(uid, appId) {
|
|
496
|
-
try {
|
|
497
|
-
const db2 = getFirestore();
|
|
498
|
-
const doc = await db2.doc(this.getDocPath(uid, appId)).get();
|
|
499
|
-
if (!doc.exists) return null;
|
|
500
|
-
return doc.data();
|
|
501
|
-
} catch (error) {
|
|
502
|
-
console.error("[ValidationStore] Error getting validation results:", error);
|
|
503
|
-
return null;
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
/** Clear validation results */
|
|
507
|
-
async clear(uid, appId) {
|
|
508
|
-
const db2 = getFirestore();
|
|
509
|
-
const { FieldValue } = await import('firebase-admin/firestore');
|
|
510
|
-
await db2.doc(this.getDocPath(uid, appId)).delete();
|
|
511
|
-
await db2.doc(this.getAppDocPath(uid, appId)).update({
|
|
512
|
-
"_operational.validationMeta": FieldValue.delete()
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
};
|
|
516
|
-
|
|
517
|
-
export { ChangeSetStore, SchemaProtectionService, SchemaStore, SnapshotStore, ValidationStore, fromFirestoreFormat, toFirestoreFormat };
|
|
518
|
-
//# sourceMappingURL=index.js.map
|
|
519
|
-
//# sourceMappingURL=index.js.map
|
package/dist/stores/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stores/firestoreFormat.ts","../../src/lib/db.ts","../../src/stores/SchemaProtectionService.ts","../../src/stores/SchemaStore.ts","../../src/stores/SnapshotStore.ts","../../src/stores/ChangeSetStore.ts","../../src/stores/ValidationStore.ts"],"names":["db"],"mappings":";;;;AAeO,SAAS,kBAAkB,MAAA,EAAgD;AAChF,EAAA,MAAM,IAAA,GAAO,EAAE,GAAI,MAAA,EAA8C;AAGjE,EAAA,IAAI,OAAO,QAAA,EAAU;AACnB,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA;AACnD,IAAA,IAAA,CAAK,YAAA,GAAe,OAAO,QAAA,CAAS,MAAA;AACpC,IAAA,OAAO,IAAA,CAAK,QAAA;AAAA,EACd;AAGA,EAAA,IAAI,KAAK,MAAA,EAAQ;AACf,IAAA,MAAM,SAAS,IAAA,CAAK,MAAA;AACpB,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AACxC,IAAA,IAAA,CAAK,aAAa,MAAA,CAAO,MAAA;AACzB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAGA,EAAA,IAAI,OAAO,QAAA,EAAU;AACnB,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA;AACnD,IAAA,IAAA,CAAK,YAAA,GAAe,OAAO,QAAA,CAAS,MAAA;AACpC,IAAA,OAAO,IAAA,CAAK,QAAA;AAAA,EACd;AAEA,EAAA,OAAO,IAAA;AACT;AAOO,SAAS,oBAAoB,IAAA,EAA8C;AAChF,EAAA,MAAM,MAAA,GAAS,EAAE,GAAG,IAAA,EAAK;AAGzB,EAAA,IAAI,MAAA,CAAO,aAAA,IAAiB,OAAO,MAAA,CAAO,kBAAkB,QAAA,EAAU;AACpE,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,QAAA,GAAW,IAAA,CAAK,KA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A,EAAK,KAAK,CAAC,CAAA,CAAE,GAAA,EAAI;AAC1D,MAAA,IAAI,CAAC,GAAA,CAAI,MAAA,EAAQ,OAAO,IAAA;AACxB,MAAA,OAAO,IAAI,IAAA,EAAK;AAAA,IAClB,SAAS,KAAA,EAAO;AACd,MAAA,OAAA,CAAQ,KAAA,CAAM,uDAAuD,KAAK,CAAA;AAC1E,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,KAAA,CAAM,GAAA,EAAa,KAAA,EAA8B;AACrD,IAAA,MAAMA,MAAK,YAAA,EAAa;AACxB,IAAA,MAAM,EAAE,UAAA,EAAW,GAAI,MAAM,OAAO,0BAA0B,CAAA;AAE9D,IAAA,MAAMA,GAAAA,CAAG,IAAI,IAAA,CAAK,UAAA,CAAW,KAAK,KAAK,CAAC,EAAE,MAAA,EAAO;AAEjD,IAAA,MAAMA,GAAAA,CAAG,IAAI,IAAA,CAAK,aAAA,CAAc,KAAK,KAAK,CAAC,EAAE,MAAA,CAAO;AAAA,MAClD,6BAAA,EAA+B,WAAW,MAAA;AAAO,KAClD,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Firestore Serialization Utilities\n *\n * Handles the Firestore 20-level depth limit by serializing deeply nested\n * OrbitalSchema fields (orbitals, traits, services) to JSON strings.\n */\n\nimport type { OrbitalSchema } from '@almadar/core';\n\n/**\n * Convert OrbitalSchema to Firestore-safe format.\n *\n * Serializes orbitals, traits, and services to JSON strings to avoid\n * Firestore's 20-level nesting limit.\n */\nexport function toFirestoreFormat(schema: OrbitalSchema): Record<string, unknown> {\n const data = { ...(schema as unknown as Record<string, unknown>) };\n\n // Serialize orbitals array to JSON string\n if (schema.orbitals) {\n data._orbitalsJson = JSON.stringify(schema.orbitals);\n data.orbitalCount = schema.orbitals.length;\n delete data.orbitals;\n }\n\n // Serialize traits array to JSON string (if present at schema level)\n if (data.traits) {\n const traits = data.traits as unknown[];\n data._traitsJson = JSON.stringify(traits);\n data.traitCount = traits.length;\n delete data.traits;\n }\n\n // Serialize services array to JSON string\n if (schema.services) {\n data._servicesJson = JSON.stringify(schema.services);\n data.serviceCount = schema.services.length;\n delete data.services;\n }\n\n return data;\n}\n\n/**\n * Convert Firestore document back to OrbitalSchema.\n *\n * Deserializes JSON strings back to arrays.\n */\nexport function fromFirestoreFormat(data: Record<string, unknown>): OrbitalSchema {\n const result = { ...data };\n\n // Restore orbitals from _orbitalsJson\n if (result._orbitalsJson && typeof result._orbitalsJson === 'string') {\n try {\n result.orbitals = JSON.parse(result._orbitalsJson);\n delete result._orbitalsJson;\n delete result.orbitalCount;\n } catch (e) {\n console.warn('[OrbitalStore] Failed to parse _orbitalsJson:', e);\n result.orbitals = [];\n }\n }\n\n // Restore traits from _traitsJson\n if (result._traitsJson && typeof result._traitsJson === 'string') {\n try {\n result.traits = JSON.parse(result._traitsJson);\n delete result._traitsJson;\n delete result.traitCount;\n } catch (e) {\n console.warn('[OrbitalStore] Failed to parse _traitsJson:', e);\n }\n }\n\n // Restore services from _servicesJson\n if (result._servicesJson && typeof result._servicesJson === 'string') {\n try {\n result.services = JSON.parse(result._servicesJson);\n delete result._servicesJson;\n delete result.serviceCount;\n } catch (e) {\n console.warn('[OrbitalStore] Failed to parse _servicesJson:', e);\n }\n }\n\n return result as unknown as OrbitalSchema;\n}\n","/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // Dynamic require for JSON service account file at runtime\n const serviceAccount = require(serviceAccountPath) as Record<string, unknown>;\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * SchemaProtectionService - Detects destructive schema changes\n *\n * Uses real diff functions from @almadar/core to detect and categorize\n * removals, page content reductions, and other destructive changes.\n */\n\nimport type { OrbitalSchema, CategorizedRemovals, PageContentReduction } from '@almadar/core';\nimport {\n diffSchemas,\n isDestructiveChange,\n categorizeRemovals,\n requiresConfirmation,\n detectPageContentReduction,\n hasSignificantPageReduction,\n} from '@almadar/core';\n\nexport class SchemaProtectionService {\n /**\n * Compare two schemas and detect destructive changes.\n *\n * Returns categorized removals including page content reductions.\n */\n compareSchemas(\n before: OrbitalSchema,\n after: OrbitalSchema,\n ): {\n isDestructive: boolean;\n removals: CategorizedRemovals;\n } {\n const changeSet = diffSchemas(before, after);\n const removals = categorizeRemovals(changeSet);\n\n // Detect page content reductions (implicit removals)\n const beforePages = before.orbitals?.flatMap((o) => o.pages || []) || [];\n const afterPages = after.orbitals?.flatMap((o) => o.pages || []) || [];\n const pageContentReductions = detectPageContentReduction(beforePages, afterPages);\n removals.pageContentReductions = pageContentReductions;\n\n const isDestructive =\n isDestructiveChange(changeSet) ||\n hasSignificantPageReduction(pageContentReductions);\n\n return { isDestructive, removals };\n }\n\n /** Check if critical removals require confirmation */\n requiresConfirmation(removals: CategorizedRemovals): boolean {\n return requiresConfirmation(removals);\n }\n\n /** Check for significant page content reductions */\n hasSignificantContentReduction(reductions: PageContentReduction[]): boolean {\n return hasSignificantPageReduction(reductions);\n }\n}\n","/**\n * SchemaStore - Firestore CRUD for OrbitalSchema documents\n *\n * Handles schema get/save/create/delete/list with caching\n * and Firestore serialization.\n */\n\nimport type { OrbitalSchema, StatsView, AppSummary, SaveOptions, SaveResult } from '@almadar/core';\nimport { getFirestore } from '../lib/db.js';\nimport { toFirestoreFormat, fromFirestoreFormat } from './firestoreFormat.js';\nimport { SchemaProtectionService } from './SchemaProtectionService.js';\nimport type { SnapshotStore } from './SnapshotStore.js';\n\nconst SCHEMA_CACHE_TTL_MS = 60_000;\nconst LIST_CACHE_TTL_MS = 30_000;\n\nexport class SchemaStore {\n private appsCollection: string;\n private schemaCache = new Map<string, { schema: OrbitalSchema; timestamp: number }>();\n private listCache = new Map<string, { apps: AppSummary[]; timestamp: number }>();\n private protectionService = new SchemaProtectionService();\n private snapshotStore: SnapshotStore | null = null;\n\n constructor(appsCollection = 'apps') {\n this.appsCollection = appsCollection;\n }\n\n /** Set snapshot store for auto-snapshot on destructive saves */\n setSnapshotStore(store: SnapshotStore): void {\n this.snapshotStore = store;\n }\n\n /** Get a schema by app ID */\n async get(uid: string, appId: string): Promise<OrbitalSchema | null> {\n const cacheKey = `${uid}:${appId}`;\n const cached = this.schemaCache.get(cacheKey);\n if (cached && Date.now() - cached.timestamp < SCHEMA_CACHE_TTL_MS) {\n return cached.schema;\n }\n\n try {\n const db = getFirestore();\n const appDoc = await db.doc(`users/${uid}/${this.appsCollection}/${appId}`).get();\n\n if (!appDoc.exists) return null;\n\n const data = appDoc.data() as Record<string, unknown>;\n const hasOrbitals = data.orbitals || data._orbitalsJson;\n if (!data.name || !hasOrbitals) return null;\n\n const schema = fromFirestoreFormat(data);\n this.schemaCache.set(cacheKey, { schema, timestamp: Date.now() });\n return schema;\n } catch (error) {\n console.error('[SchemaStore] Error fetching schema:', error);\n return null;\n }\n }\n\n /**\n * Save a schema (create or full replace).\n *\n * Features:\n * - Detects destructive changes (removals)\n * - Requires confirmation for critical removals\n * - Auto-creates snapshots before destructive changes (if SnapshotStore attached)\n */\n async save(\n uid: string,\n appId: string,\n schema: OrbitalSchema,\n options: SaveOptions = {},\n ): Promise<SaveResult> {\n try {\n const existingSchema = await this.get(uid, appId);\n let snapshotId: string | undefined;\n\n // Create snapshot if snapshotReason provided\n if (existingSchema && options.snapshotReason && this.snapshotStore) {\n snapshotId = await this.snapshotStore.create(uid, appId, existingSchema, options.snapshotReason);\n }\n\n // Check for destructive changes (unless skipProtection)\n if (existingSchema && !options.skipProtection) {\n const comparison = this.protectionService.compareSchemas(existingSchema, schema);\n\n if (comparison.isDestructive) {\n const { removals } = comparison;\n const hasCriticalRemovals = this.protectionService.requiresConfirmation(removals);\n const hasContentReductions = this.protectionService.hasSignificantContentReduction(\n removals.pageContentReductions,\n );\n\n if ((hasCriticalRemovals || hasContentReductions) && !options.confirmRemovals) {\n return {\n success: false,\n requiresConfirmation: true,\n removals: comparison.removals,\n error: hasContentReductions\n ? 'Page content reduction detected - confirmation required'\n : 'Confirmation required for critical removals',\n };\n }\n\n // Auto-snapshot before destructive change\n if (\n !snapshotId &&\n this.snapshotStore &&\n (removals.critical.length > 0 || removals.pageContentReductions.length > 0)\n ) {\n snapshotId = await this.snapshotStore.create(\n uid,\n appId,\n existingSchema,\n `auto_before_removal_${Date.now()}`,\n );\n }\n }\n }\n\n const firestoreData = toFirestoreFormat(schema);\n const now = Date.now();\n const docData = {\n ...firestoreData,\n _metadata: {\n version: options.expectedVersion ? options.expectedVersion + 1 : 1,\n updatedAt: now,\n createdAt: existingSchema ? undefined : now,\n source: options.source || 'manual',\n },\n };\n\n const db = getFirestore();\n await db.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData, { merge: true });\n\n this.invalidateCache(uid, appId);\n return { success: true, snapshotId };\n } catch (error) {\n console.error('[SchemaStore] Error saving schema:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n /** Create a new app with initial schema */\n async create(\n uid: string,\n metadata: { name: string; description?: string },\n ): Promise<{ appId: string; schema: OrbitalSchema }> {\n const appId = `app-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const now = Date.now();\n\n const schema: OrbitalSchema = {\n name: metadata.name,\n description: metadata.description,\n orbitals: [],\n };\n\n const firestoreData = toFirestoreFormat(schema);\n const docData = {\n ...firestoreData,\n _metadata: { version: 1, createdAt: now, updatedAt: now, source: 'manual' as const },\n };\n\n const db = getFirestore();\n await db.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData);\n this.listCache.delete(uid);\n\n return { appId, schema };\n }\n\n /** Delete an app */\n async delete(uid: string, appId: string): Promise<boolean> {\n try {\n const db = getFirestore();\n const ref = db.doc(`users/${uid}/${this.appsCollection}/${appId}`);\n const doc = await ref.get();\n if (!doc.exists) return false;\n\n await ref.delete();\n this.invalidateCache(uid, appId);\n return true;\n } catch (error) {\n console.error('[SchemaStore] Error deleting app:', error);\n return false;\n }\n }\n\n /** List all apps for a user */\n async list(uid: string): Promise<AppSummary[]> {\n const cached = this.listCache.get(uid);\n if (cached && Date.now() - cached.timestamp < LIST_CACHE_TTL_MS) {\n return cached.apps;\n }\n\n try {\n const db = getFirestore();\n const snapshot = await db\n .collection(`users/${uid}/${this.appsCollection}`)\n .select('name', 'description', 'domainContext', '_metadata', 'orbitalCount', 'traitCount')\n .orderBy('_metadata.updatedAt', 'desc')\n .get();\n\n const apps: AppSummary[] = snapshot.docs.map((doc) => {\n const data = doc.data();\n const metadata = data._metadata as { version?: number; createdAt?: number; updatedAt?: number } | undefined;\n const orbitalCount = data.orbitalCount as number | undefined;\n\n return {\n id: doc.id,\n name: (data.name as string) || 'Untitled',\n description: data.description as string | undefined,\n updatedAt: metadata?.updatedAt || Date.now(),\n createdAt: metadata?.createdAt || Date.now(),\n stats: { entities: orbitalCount ?? 0, pages: 0, states: 0, events: 0, transitions: 0 },\n domainContext: data.domainContext as string | undefined,\n hasValidationErrors: false,\n };\n });\n\n this.listCache.set(uid, { apps, timestamp: Date.now() });\n return apps;\n } catch (error) {\n console.error('[SchemaStore] Error listing apps:', error);\n return [];\n }\n }\n\n /** Compute stats from OrbitalSchema */\n computeStats(schema: OrbitalSchema): StatsView {\n const orbitals = schema.orbitals || [];\n const entities = orbitals.length;\n const pages = orbitals.reduce((n, o) => n + (o.pages?.length || 0), 0);\n\n const allTraits = [\n ...((schema as unknown as Record<string, unknown>).traits as unknown[] || []),\n ...orbitals.flatMap((o) =>\n (o.traits || []).filter((t) => typeof t !== 'string' && 'stateMachine' in t),\n ),\n ] as Array<{ stateMachine?: { states?: unknown[]; events?: unknown[]; transitions?: unknown[] } }>;\n\n return {\n states: allTraits.flatMap((t) => t.stateMachine?.states || []).length,\n events: allTraits.flatMap((t) => t.stateMachine?.events || []).length,\n pages,\n entities,\n transitions: allTraits.flatMap((t) => t.stateMachine?.transitions || []).length,\n };\n }\n\n /** Invalidate caches for a specific app */\n invalidateCache(uid: string, appId: string): void {\n this.schemaCache.delete(`${uid}:${appId}`);\n this.listCache.delete(uid);\n }\n\n /** Clear all caches */\n clearCaches(): void {\n this.schemaCache.clear();\n this.listCache.clear();\n }\n\n /** Get the collection path for an app */\n getAppDocPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}`;\n }\n\n /** Expose apps collection name for subcollection stores */\n getAppsCollection(): string {\n return this.appsCollection;\n }\n}\n","/**\n * SnapshotStore - Firestore CRUD for schema snapshots\n *\n * Snapshots are full copies of the schema at a point in time,\n * stored in subcollection: users/{uid}/apps/{appId}/snapshots/{snapshotId}\n */\n\nimport type { OrbitalSchema, SnapshotDocument, HistoryMeta } from '@almadar/core';\nimport { getFirestore } from '../lib/db.js';\nimport { toFirestoreFormat, fromFirestoreFormat } from './firestoreFormat.js';\n\nconst SNAPSHOTS_COLLECTION = 'snapshots';\n\nexport class SnapshotStore {\n private appsCollection: string;\n\n constructor(appsCollection = 'apps') {\n this.appsCollection = appsCollection;\n }\n\n private getCollectionPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}/${SNAPSHOTS_COLLECTION}`;\n }\n\n private getAppDocPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}`;\n }\n\n /** Create a snapshot of the current schema */\n async create(\n uid: string,\n appId: string,\n schema: OrbitalSchema,\n reason: string,\n ): Promise<string> {\n const db = getFirestore();\n const snapshotId = `snapshot_${Date.now()}`;\n\n const snapshotDoc: SnapshotDocument = {\n id: snapshotId,\n timestamp: Date.now(),\n schema: toFirestoreFormat(schema),\n reason,\n };\n\n await db.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).set(snapshotDoc);\n\n // Update history metadata\n const appDocRef = db.doc(this.getAppDocPath(uid, appId));\n const appDoc = await appDocRef.get();\n const currentMeta = appDoc.data()?._historyMeta as HistoryMeta | undefined;\n\n const updatedMeta: HistoryMeta = {\n latestSnapshotId: snapshotId,\n latestChangeSetId: currentMeta?.latestChangeSetId,\n snapshotCount: (currentMeta?.snapshotCount || 0) + 1,\n changeSetCount: currentMeta?.changeSetCount || 0,\n };\n\n await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });\n return snapshotId;\n }\n\n /** Get all snapshots for an app (ordered by timestamp desc) */\n async getAll(uid: string, appId: string): Promise<SnapshotDocument[]> {\n const db = getFirestore();\n const query = await db\n .collection(this.getCollectionPath(uid, appId))\n .orderBy('timestamp', 'desc')\n .get();\n\n return query.docs.map((doc) => doc.data() as SnapshotDocument);\n }\n\n /** Get a specific snapshot by ID */\n async get(uid: string, appId: string, snapshotId: string): Promise<SnapshotDocument | null> {\n const db = getFirestore();\n const doc = await db.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).get();\n if (!doc.exists) return null;\n return doc.data() as SnapshotDocument;\n }\n\n /** Delete a snapshot */\n async delete(uid: string, appId: string, snapshotId: string): Promise<boolean> {\n const db = getFirestore();\n const ref = db.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`);\n const doc = await ref.get();\n if (!doc.exists) return false;\n\n await ref.delete();\n\n // Update history metadata\n const appDocRef = db.doc(this.getAppDocPath(uid, appId));\n const appDoc = await appDocRef.get();\n const currentMeta = appDoc.data()?._historyMeta as HistoryMeta | undefined;\n\n if (currentMeta) {\n const updatedMeta: HistoryMeta = {\n ...currentMeta,\n snapshotCount: Math.max(0, (currentMeta.snapshotCount || 1) - 1),\n latestSnapshotId:\n currentMeta.latestSnapshotId === snapshotId ? undefined : currentMeta.latestSnapshotId,\n };\n await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });\n }\n\n return true;\n }\n\n /** Get schema snapshot at a specific version */\n async getByVersion(uid: string, appId: string, version: number): Promise<OrbitalSchema | null> {\n const db = getFirestore();\n const query = await db\n .collection(this.getCollectionPath(uid, appId))\n .where('version', '==', version)\n .limit(1)\n .get();\n\n if (query.empty) return null;\n const snapshot = query.docs[0].data() as SnapshotDocument;\n return fromFirestoreFormat(snapshot.schema as Record<string, unknown>);\n }\n\n /** Get the schema from a snapshot (deserialized) */\n getSchemaFromSnapshot(snapshot: SnapshotDocument): OrbitalSchema {\n return fromFirestoreFormat(snapshot.schema as Record<string, unknown>);\n }\n}\n","/**\n * ChangeSetStore - Firestore CRUD for schema changesets\n *\n * Changesets track changes made to the schema over time,\n * stored in subcollection: users/{uid}/apps/{appId}/changesets/{changeSetId}\n */\n\nimport type { ChangeSetDocument, HistoryMeta } from '@almadar/core';\nimport { getFirestore } from '../lib/db.js';\n\nconst CHANGESETS_COLLECTION = 'changesets';\n\nexport class ChangeSetStore {\n private appsCollection: string;\n\n constructor(appsCollection = 'apps') {\n this.appsCollection = appsCollection;\n }\n\n private getCollectionPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}/${CHANGESETS_COLLECTION}`;\n }\n\n private getAppDocPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}`;\n }\n\n /** Append a changeset to history */\n async append(uid: string, appId: string, changeSet: ChangeSetDocument): Promise<void> {\n const db = getFirestore();\n\n await db.doc(`${this.getCollectionPath(uid, appId)}/${changeSet.id}`).set(changeSet);\n\n // Update history metadata\n const appDocRef = db.doc(this.getAppDocPath(uid, appId));\n const appDoc = await appDocRef.get();\n const currentMeta = appDoc.data()?._historyMeta as HistoryMeta | undefined;\n\n const updatedMeta: HistoryMeta = {\n latestSnapshotId: currentMeta?.latestSnapshotId,\n latestChangeSetId: changeSet.id,\n snapshotCount: currentMeta?.snapshotCount || 0,\n changeSetCount: (currentMeta?.changeSetCount || 0) + 1,\n };\n\n await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });\n }\n\n /** Get change history for an app (ordered by version desc) */\n async getHistory(uid: string, appId: string): Promise<ChangeSetDocument[]> {\n try {\n const db = getFirestore();\n const query = await db\n .collection(this.getCollectionPath(uid, appId))\n .orderBy('version', 'desc')\n .get();\n\n return query.docs.map((doc) => doc.data() as ChangeSetDocument);\n } catch (error) {\n console.error('[ChangeSetStore] Error getting change history:', error);\n return [];\n }\n }\n\n /** Get a specific changeset by ID */\n async get(uid: string, appId: string, changeSetId: string): Promise<ChangeSetDocument | null> {\n const db = getFirestore();\n const doc = await db.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`).get();\n if (!doc.exists) return null;\n return doc.data() as ChangeSetDocument;\n }\n\n /** Update a changeset's status */\n async updateStatus(\n uid: string,\n appId: string,\n changeSetId: string,\n status: 'applied' | 'reverted' | 'pending',\n ): Promise<void> {\n const db = getFirestore();\n const ref = db.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);\n const doc = await ref.get();\n if (!doc.exists) return;\n await ref.update({ status });\n }\n\n /** Delete a changeset */\n async delete(uid: string, appId: string, changeSetId: string): Promise<boolean> {\n const db = getFirestore();\n const ref = db.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);\n const doc = await ref.get();\n if (!doc.exists) return false;\n\n await ref.delete();\n\n // Update history metadata\n const appDocRef = db.doc(this.getAppDocPath(uid, appId));\n const appDoc = await appDocRef.get();\n const currentMeta = appDoc.data()?._historyMeta as HistoryMeta | undefined;\n\n if (currentMeta) {\n const updatedMeta: HistoryMeta = {\n ...currentMeta,\n changeSetCount: Math.max(0, (currentMeta.changeSetCount || 1) - 1),\n latestChangeSetId:\n currentMeta.latestChangeSetId === changeSetId ? undefined : currentMeta.latestChangeSetId,\n };\n await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });\n }\n\n return true;\n }\n}\n","/**\n * ValidationStore - Firestore CRUD for validation results\n *\n * Validation results stored at: users/{uid}/apps/{appId}/validation/current\n */\n\nimport type { ValidationResults, ValidationMeta } from '@almadar/core';\nimport { getFirestore } from '../lib/db.js';\n\nconst VALIDATION_COLLECTION = 'validation';\nconst VALIDATION_DOC_ID = 'current';\n\nexport class ValidationStore {\n private appsCollection: string;\n\n constructor(appsCollection = 'apps') {\n this.appsCollection = appsCollection;\n }\n\n private getDocPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}/${VALIDATION_COLLECTION}/${VALIDATION_DOC_ID}`;\n }\n\n private getAppDocPath(uid: string, appId: string): string {\n return `users/${uid}/${this.appsCollection}/${appId}`;\n }\n\n /** Save validation results */\n async save(uid: string, appId: string, results: ValidationResults): Promise<void> {\n const db = getFirestore();\n\n await db.doc(this.getDocPath(uid, appId)).set(results);\n\n // Update validation metadata in main document\n const validationMeta: ValidationMeta = {\n errorCount: results.errors?.length || 0,\n warningCount: results.warnings?.length || 0,\n validatedAt: results.validatedAt,\n };\n\n await db.doc(this.getAppDocPath(uid, appId)).set(\n { _operational: { validationMeta } },\n { merge: true },\n );\n }\n\n /** Get validation results */\n async get(uid: string, appId: string): Promise<ValidationResults | null> {\n try {\n const db = getFirestore();\n const doc = await db.doc(this.getDocPath(uid, appId)).get();\n if (!doc.exists) return null;\n return doc.data() as ValidationResults;\n } catch (error) {\n console.error('[ValidationStore] Error getting validation results:', error);\n return null;\n }\n }\n\n /** Clear validation results */\n async clear(uid: string, appId: string): Promise<void> {\n const db = getFirestore();\n const { FieldValue } = await import('firebase-admin/firestore');\n\n await db.doc(this.getDocPath(uid, appId)).delete();\n\n await db.doc(this.getAppDocPath(uid, appId)).update({\n '_operational.validationMeta': FieldValue.delete(),\n });\n }\n}\n"]}
|
package/dist/utils/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,cAAc,mBAAmB,CAAC"}
|