@almadar/server 1.0.13 → 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -0
- package/dist/index.js +497 -1
- package/dist/index.js.map +1 -1
- package/dist/stores/index.d.ts +167 -0
- package/dist/stores/index.js +594 -0
- package/dist/stores/index.js.map +1 -0
- package/package.json +7 -2
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import admin from 'firebase-admin';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import dotenv from 'dotenv';
|
|
4
|
+
import { diffSchemas, categorizeRemovals, detectPageContentReduction, isDestructiveChange, hasSignificantPageReduction, requiresConfirmation } from '@almadar/core';
|
|
5
|
+
|
|
6
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
7
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
8
|
+
}) : x)(function(x) {
|
|
9
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
10
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
// src/stores/firestoreFormat.ts
|
|
14
|
+
function toFirestoreFormat(schema) {
|
|
15
|
+
const data = { ...schema };
|
|
16
|
+
if (schema.orbitals) {
|
|
17
|
+
data._orbitalsJson = JSON.stringify(schema.orbitals);
|
|
18
|
+
data.orbitalCount = schema.orbitals.length;
|
|
19
|
+
delete data.orbitals;
|
|
20
|
+
}
|
|
21
|
+
if (data.traits) {
|
|
22
|
+
const traits = data.traits;
|
|
23
|
+
data._traitsJson = JSON.stringify(traits);
|
|
24
|
+
data.traitCount = traits.length;
|
|
25
|
+
delete data.traits;
|
|
26
|
+
}
|
|
27
|
+
if (schema.services) {
|
|
28
|
+
data._servicesJson = JSON.stringify(schema.services);
|
|
29
|
+
data.serviceCount = schema.services.length;
|
|
30
|
+
delete data.services;
|
|
31
|
+
}
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
function fromFirestoreFormat(data) {
|
|
35
|
+
const result = { ...data };
|
|
36
|
+
if (result._orbitalsJson && typeof result._orbitalsJson === "string") {
|
|
37
|
+
try {
|
|
38
|
+
result.orbitals = JSON.parse(result._orbitalsJson);
|
|
39
|
+
delete result._orbitalsJson;
|
|
40
|
+
delete result.orbitalCount;
|
|
41
|
+
} catch (e) {
|
|
42
|
+
console.warn("[OrbitalStore] Failed to parse _orbitalsJson:", e);
|
|
43
|
+
result.orbitals = [];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (result._traitsJson && typeof result._traitsJson === "string") {
|
|
47
|
+
try {
|
|
48
|
+
result.traits = JSON.parse(result._traitsJson);
|
|
49
|
+
delete result._traitsJson;
|
|
50
|
+
delete result.traitCount;
|
|
51
|
+
} catch (e) {
|
|
52
|
+
console.warn("[OrbitalStore] Failed to parse _traitsJson:", e);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (result._servicesJson && typeof result._servicesJson === "string") {
|
|
56
|
+
try {
|
|
57
|
+
result.services = JSON.parse(result._servicesJson);
|
|
58
|
+
delete result._servicesJson;
|
|
59
|
+
delete result.serviceCount;
|
|
60
|
+
} catch (e) {
|
|
61
|
+
console.warn("[OrbitalStore] Failed to parse _servicesJson:", e);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
dotenv.config();
|
|
67
|
+
var envSchema = z.object({
|
|
68
|
+
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
|
|
69
|
+
PORT: z.string().default("3030").transform((val) => parseInt(val, 10)),
|
|
70
|
+
CORS_ORIGIN: z.string().default("http://localhost:5173").transform((val) => val.includes(",") ? val.split(",").map((s) => s.trim()) : val),
|
|
71
|
+
// Database (Prisma/SQL) - optional
|
|
72
|
+
DATABASE_URL: z.string().optional(),
|
|
73
|
+
// Firebase/Firestore configuration
|
|
74
|
+
FIREBASE_PROJECT_ID: z.string().optional(),
|
|
75
|
+
FIREBASE_CLIENT_EMAIL: z.string().optional(),
|
|
76
|
+
FIREBASE_PRIVATE_KEY: z.string().optional(),
|
|
77
|
+
FIREBASE_SERVICE_ACCOUNT_PATH: z.string().optional(),
|
|
78
|
+
FIRESTORE_EMULATOR_HOST: z.string().optional(),
|
|
79
|
+
FIREBASE_AUTH_EMULATOR_HOST: z.string().optional(),
|
|
80
|
+
// API configuration
|
|
81
|
+
API_PREFIX: z.string().default("/api"),
|
|
82
|
+
// Mock data configuration
|
|
83
|
+
USE_MOCK_DATA: z.string().default("true").transform((v) => v === "true"),
|
|
84
|
+
MOCK_SEED: z.string().optional().transform((v) => v ? parseInt(v, 10) : void 0)
|
|
85
|
+
});
|
|
86
|
+
var parsed = envSchema.safeParse(process.env);
|
|
87
|
+
if (!parsed.success) {
|
|
88
|
+
console.error("\u274C Invalid environment variables:", parsed.error.flatten().fieldErrors);
|
|
89
|
+
throw new Error("Invalid environment variables");
|
|
90
|
+
}
|
|
91
|
+
var env = parsed.data;
|
|
92
|
+
|
|
93
|
+
// src/lib/db.ts
|
|
94
|
+
var firebaseApp = null;
|
|
95
|
+
function initializeFirebase() {
|
|
96
|
+
if (firebaseApp) {
|
|
97
|
+
return firebaseApp;
|
|
98
|
+
}
|
|
99
|
+
if (admin.apps.length > 0) {
|
|
100
|
+
firebaseApp = admin.apps[0];
|
|
101
|
+
return firebaseApp;
|
|
102
|
+
}
|
|
103
|
+
if (env.FIRESTORE_EMULATOR_HOST) {
|
|
104
|
+
firebaseApp = admin.initializeApp({
|
|
105
|
+
projectId: env.FIREBASE_PROJECT_ID || "demo-project"
|
|
106
|
+
});
|
|
107
|
+
console.log(`\u{1F527} Firebase Admin initialized for emulator: ${env.FIRESTORE_EMULATOR_HOST}`);
|
|
108
|
+
return firebaseApp;
|
|
109
|
+
}
|
|
110
|
+
const serviceAccountPath = env.FIREBASE_SERVICE_ACCOUNT_PATH;
|
|
111
|
+
if (serviceAccountPath) {
|
|
112
|
+
const serviceAccount = __require(serviceAccountPath);
|
|
113
|
+
firebaseApp = admin.initializeApp({
|
|
114
|
+
credential: admin.credential.cert(serviceAccount),
|
|
115
|
+
projectId: env.FIREBASE_PROJECT_ID
|
|
116
|
+
});
|
|
117
|
+
} else if (env.FIREBASE_PROJECT_ID && env.FIREBASE_CLIENT_EMAIL && env.FIREBASE_PRIVATE_KEY) {
|
|
118
|
+
firebaseApp = admin.initializeApp({
|
|
119
|
+
credential: admin.credential.cert({
|
|
120
|
+
projectId: env.FIREBASE_PROJECT_ID,
|
|
121
|
+
clientEmail: env.FIREBASE_CLIENT_EMAIL,
|
|
122
|
+
privateKey: env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n")
|
|
123
|
+
}),
|
|
124
|
+
projectId: env.FIREBASE_PROJECT_ID
|
|
125
|
+
});
|
|
126
|
+
} else if (env.FIREBASE_PROJECT_ID) {
|
|
127
|
+
firebaseApp = admin.initializeApp({
|
|
128
|
+
credential: admin.credential.applicationDefault(),
|
|
129
|
+
projectId: env.FIREBASE_PROJECT_ID
|
|
130
|
+
});
|
|
131
|
+
} else {
|
|
132
|
+
firebaseApp = admin.initializeApp({
|
|
133
|
+
projectId: "demo-project"
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return firebaseApp;
|
|
137
|
+
}
|
|
138
|
+
function getFirestore() {
|
|
139
|
+
const app = initializeFirebase();
|
|
140
|
+
const db2 = app.firestore();
|
|
141
|
+
if (env.FIRESTORE_EMULATOR_HOST) {
|
|
142
|
+
db2.settings({
|
|
143
|
+
host: env.FIRESTORE_EMULATOR_HOST,
|
|
144
|
+
ssl: false
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return db2;
|
|
148
|
+
}
|
|
149
|
+
getFirestore();
|
|
150
|
+
var SchemaProtectionService = class {
|
|
151
|
+
/**
|
|
152
|
+
* Compare two schemas and detect destructive changes.
|
|
153
|
+
*
|
|
154
|
+
* Returns categorized removals including page content reductions.
|
|
155
|
+
*/
|
|
156
|
+
compareSchemas(before, after) {
|
|
157
|
+
const changeSet = diffSchemas(before, after);
|
|
158
|
+
const removals = categorizeRemovals(changeSet);
|
|
159
|
+
const beforePages = before.orbitals?.flatMap((o) => o.pages || []) || [];
|
|
160
|
+
const afterPages = after.orbitals?.flatMap((o) => o.pages || []) || [];
|
|
161
|
+
const pageContentReductions = detectPageContentReduction(beforePages, afterPages);
|
|
162
|
+
removals.pageContentReductions = pageContentReductions;
|
|
163
|
+
const isDestructive = isDestructiveChange(changeSet) || hasSignificantPageReduction(pageContentReductions);
|
|
164
|
+
return { isDestructive, removals };
|
|
165
|
+
}
|
|
166
|
+
/** Check if critical removals require confirmation */
|
|
167
|
+
requiresConfirmation(removals) {
|
|
168
|
+
return requiresConfirmation(removals);
|
|
169
|
+
}
|
|
170
|
+
/** Check for significant page content reductions */
|
|
171
|
+
hasSignificantContentReduction(reductions) {
|
|
172
|
+
return hasSignificantPageReduction(reductions);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// src/stores/SchemaStore.ts
|
|
177
|
+
var SCHEMA_CACHE_TTL_MS = 6e4;
|
|
178
|
+
var LIST_CACHE_TTL_MS = 3e4;
|
|
179
|
+
var SchemaStore = class {
|
|
180
|
+
appsCollection;
|
|
181
|
+
schemaCache = /* @__PURE__ */ new Map();
|
|
182
|
+
listCache = /* @__PURE__ */ new Map();
|
|
183
|
+
protectionService = new SchemaProtectionService();
|
|
184
|
+
snapshotStore = null;
|
|
185
|
+
constructor(appsCollection = "apps") {
|
|
186
|
+
this.appsCollection = appsCollection;
|
|
187
|
+
}
|
|
188
|
+
/** Set snapshot store for auto-snapshot on destructive saves */
|
|
189
|
+
setSnapshotStore(store) {
|
|
190
|
+
this.snapshotStore = store;
|
|
191
|
+
}
|
|
192
|
+
/** Get a schema by app ID */
|
|
193
|
+
async get(uid, appId) {
|
|
194
|
+
const cacheKey = `${uid}:${appId}`;
|
|
195
|
+
const cached = this.schemaCache.get(cacheKey);
|
|
196
|
+
if (cached && Date.now() - cached.timestamp < SCHEMA_CACHE_TTL_MS) {
|
|
197
|
+
return cached.schema;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const db2 = getFirestore();
|
|
201
|
+
const appDoc = await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).get();
|
|
202
|
+
if (!appDoc.exists) return null;
|
|
203
|
+
const data = appDoc.data();
|
|
204
|
+
const hasOrbitals = data.orbitals || data._orbitalsJson;
|
|
205
|
+
if (!data.name || !hasOrbitals) return null;
|
|
206
|
+
const schema = fromFirestoreFormat(data);
|
|
207
|
+
this.schemaCache.set(cacheKey, { schema, timestamp: Date.now() });
|
|
208
|
+
return schema;
|
|
209
|
+
} catch (error) {
|
|
210
|
+
console.error("[SchemaStore] Error fetching schema:", error);
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Save a schema (create or full replace).
|
|
216
|
+
*
|
|
217
|
+
* Features:
|
|
218
|
+
* - Detects destructive changes (removals)
|
|
219
|
+
* - Requires confirmation for critical removals
|
|
220
|
+
* - Auto-creates snapshots before destructive changes (if SnapshotStore attached)
|
|
221
|
+
*/
|
|
222
|
+
async save(uid, appId, schema, options = {}) {
|
|
223
|
+
try {
|
|
224
|
+
const existingSchema = await this.get(uid, appId);
|
|
225
|
+
let snapshotId;
|
|
226
|
+
if (existingSchema && options.snapshotReason && this.snapshotStore) {
|
|
227
|
+
snapshotId = await this.snapshotStore.create(uid, appId, existingSchema, options.snapshotReason);
|
|
228
|
+
}
|
|
229
|
+
if (existingSchema && !options.skipProtection) {
|
|
230
|
+
const comparison = this.protectionService.compareSchemas(existingSchema, schema);
|
|
231
|
+
if (comparison.isDestructive) {
|
|
232
|
+
const { removals } = comparison;
|
|
233
|
+
const hasCriticalRemovals = this.protectionService.requiresConfirmation(removals);
|
|
234
|
+
const hasContentReductions = this.protectionService.hasSignificantContentReduction(
|
|
235
|
+
removals.pageContentReductions
|
|
236
|
+
);
|
|
237
|
+
if ((hasCriticalRemovals || hasContentReductions) && !options.confirmRemovals) {
|
|
238
|
+
return {
|
|
239
|
+
success: false,
|
|
240
|
+
requiresConfirmation: true,
|
|
241
|
+
removals: comparison.removals,
|
|
242
|
+
error: hasContentReductions ? "Page content reduction detected - confirmation required" : "Confirmation required for critical removals"
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
if (!snapshotId && this.snapshotStore && (removals.critical.length > 0 || removals.pageContentReductions.length > 0)) {
|
|
246
|
+
snapshotId = await this.snapshotStore.create(
|
|
247
|
+
uid,
|
|
248
|
+
appId,
|
|
249
|
+
existingSchema,
|
|
250
|
+
`auto_before_removal_${Date.now()}`
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const firestoreData = toFirestoreFormat(schema);
|
|
256
|
+
const now = Date.now();
|
|
257
|
+
const docData = {
|
|
258
|
+
...firestoreData,
|
|
259
|
+
_metadata: {
|
|
260
|
+
version: options.expectedVersion ? options.expectedVersion + 1 : 1,
|
|
261
|
+
updatedAt: now,
|
|
262
|
+
createdAt: existingSchema ? void 0 : now,
|
|
263
|
+
source: options.source || "manual"
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const db2 = getFirestore();
|
|
267
|
+
await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData, { merge: true });
|
|
268
|
+
this.invalidateCache(uid, appId);
|
|
269
|
+
return { success: true, snapshotId };
|
|
270
|
+
} catch (error) {
|
|
271
|
+
console.error("[SchemaStore] Error saving schema:", error);
|
|
272
|
+
return {
|
|
273
|
+
success: false,
|
|
274
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** Create a new app with initial schema */
|
|
279
|
+
async create(uid, metadata) {
|
|
280
|
+
const appId = `app-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
const schema = {
|
|
283
|
+
name: metadata.name,
|
|
284
|
+
description: metadata.description,
|
|
285
|
+
orbitals: []
|
|
286
|
+
};
|
|
287
|
+
const firestoreData = toFirestoreFormat(schema);
|
|
288
|
+
const docData = {
|
|
289
|
+
...firestoreData,
|
|
290
|
+
_metadata: { version: 1, createdAt: now, updatedAt: now, source: "manual" }
|
|
291
|
+
};
|
|
292
|
+
const db2 = getFirestore();
|
|
293
|
+
await db2.doc(`users/${uid}/${this.appsCollection}/${appId}`).set(docData);
|
|
294
|
+
this.listCache.delete(uid);
|
|
295
|
+
return { appId, schema };
|
|
296
|
+
}
|
|
297
|
+
/** Delete an app */
|
|
298
|
+
async delete(uid, appId) {
|
|
299
|
+
try {
|
|
300
|
+
const db2 = getFirestore();
|
|
301
|
+
const ref = db2.doc(`users/${uid}/${this.appsCollection}/${appId}`);
|
|
302
|
+
const doc = await ref.get();
|
|
303
|
+
if (!doc.exists) return false;
|
|
304
|
+
await ref.delete();
|
|
305
|
+
this.invalidateCache(uid, appId);
|
|
306
|
+
return true;
|
|
307
|
+
} catch (error) {
|
|
308
|
+
console.error("[SchemaStore] Error deleting app:", error);
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/** List all apps for a user */
|
|
313
|
+
async list(uid) {
|
|
314
|
+
const cached = this.listCache.get(uid);
|
|
315
|
+
if (cached && Date.now() - cached.timestamp < LIST_CACHE_TTL_MS) {
|
|
316
|
+
return cached.apps;
|
|
317
|
+
}
|
|
318
|
+
try {
|
|
319
|
+
const db2 = getFirestore();
|
|
320
|
+
const snapshot = await db2.collection(`users/${uid}/${this.appsCollection}`).select("name", "description", "domainContext", "_metadata", "orbitalCount", "traitCount").orderBy("_metadata.updatedAt", "desc").get();
|
|
321
|
+
const apps = snapshot.docs.map((doc) => {
|
|
322
|
+
const data = doc.data();
|
|
323
|
+
const metadata = data._metadata;
|
|
324
|
+
const orbitalCount = data.orbitalCount;
|
|
325
|
+
return {
|
|
326
|
+
id: doc.id,
|
|
327
|
+
name: data.name || "Untitled",
|
|
328
|
+
description: data.description,
|
|
329
|
+
updatedAt: metadata?.updatedAt || Date.now(),
|
|
330
|
+
createdAt: metadata?.createdAt || Date.now(),
|
|
331
|
+
stats: { entities: orbitalCount ?? 0, pages: 0, states: 0, events: 0, transitions: 0 },
|
|
332
|
+
domainContext: data.domainContext,
|
|
333
|
+
hasValidationErrors: false
|
|
334
|
+
};
|
|
335
|
+
});
|
|
336
|
+
this.listCache.set(uid, { apps, timestamp: Date.now() });
|
|
337
|
+
return apps;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
console.error("[SchemaStore] Error listing apps:", error);
|
|
340
|
+
return [];
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/** Compute stats from OrbitalSchema */
|
|
344
|
+
computeStats(schema) {
|
|
345
|
+
const orbitals = schema.orbitals || [];
|
|
346
|
+
const entities = orbitals.length;
|
|
347
|
+
const pages = orbitals.reduce((n, o) => n + (o.pages?.length || 0), 0);
|
|
348
|
+
const allTraits = [
|
|
349
|
+
...schema.traits || [],
|
|
350
|
+
...orbitals.flatMap(
|
|
351
|
+
(o) => (o.traits || []).filter((t) => typeof t !== "string" && "stateMachine" in t)
|
|
352
|
+
)
|
|
353
|
+
];
|
|
354
|
+
return {
|
|
355
|
+
states: allTraits.flatMap((t) => t.stateMachine?.states || []).length,
|
|
356
|
+
events: allTraits.flatMap((t) => t.stateMachine?.events || []).length,
|
|
357
|
+
pages,
|
|
358
|
+
entities,
|
|
359
|
+
transitions: allTraits.flatMap((t) => t.stateMachine?.transitions || []).length
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
/** Invalidate caches for a specific app */
|
|
363
|
+
invalidateCache(uid, appId) {
|
|
364
|
+
this.schemaCache.delete(`${uid}:${appId}`);
|
|
365
|
+
this.listCache.delete(uid);
|
|
366
|
+
}
|
|
367
|
+
/** Clear all caches */
|
|
368
|
+
clearCaches() {
|
|
369
|
+
this.schemaCache.clear();
|
|
370
|
+
this.listCache.clear();
|
|
371
|
+
}
|
|
372
|
+
/** Get the collection path for an app */
|
|
373
|
+
getAppDocPath(uid, appId) {
|
|
374
|
+
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
375
|
+
}
|
|
376
|
+
/** Expose apps collection name for subcollection stores */
|
|
377
|
+
getAppsCollection() {
|
|
378
|
+
return this.appsCollection;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
// src/stores/SnapshotStore.ts
|
|
383
|
+
var SNAPSHOTS_COLLECTION = "snapshots";
|
|
384
|
+
var SnapshotStore = class {
|
|
385
|
+
appsCollection;
|
|
386
|
+
constructor(appsCollection = "apps") {
|
|
387
|
+
this.appsCollection = appsCollection;
|
|
388
|
+
}
|
|
389
|
+
getCollectionPath(uid, appId) {
|
|
390
|
+
return `users/${uid}/${this.appsCollection}/${appId}/${SNAPSHOTS_COLLECTION}`;
|
|
391
|
+
}
|
|
392
|
+
getAppDocPath(uid, appId) {
|
|
393
|
+
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
394
|
+
}
|
|
395
|
+
/** Create a snapshot of the current schema */
|
|
396
|
+
async create(uid, appId, schema, reason) {
|
|
397
|
+
const db2 = getFirestore();
|
|
398
|
+
const snapshotId = `snapshot_${Date.now()}`;
|
|
399
|
+
const snapshotDoc = {
|
|
400
|
+
id: snapshotId,
|
|
401
|
+
timestamp: Date.now(),
|
|
402
|
+
schema: toFirestoreFormat(schema),
|
|
403
|
+
reason
|
|
404
|
+
};
|
|
405
|
+
await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).set(snapshotDoc);
|
|
406
|
+
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
407
|
+
const appDoc = await appDocRef.get();
|
|
408
|
+
const currentMeta = appDoc.data()?._historyMeta;
|
|
409
|
+
const updatedMeta = {
|
|
410
|
+
latestSnapshotId: snapshotId,
|
|
411
|
+
latestChangeSetId: currentMeta?.latestChangeSetId,
|
|
412
|
+
snapshotCount: (currentMeta?.snapshotCount || 0) + 1,
|
|
413
|
+
changeSetCount: currentMeta?.changeSetCount || 0
|
|
414
|
+
};
|
|
415
|
+
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
416
|
+
return snapshotId;
|
|
417
|
+
}
|
|
418
|
+
/** Get all snapshots for an app (ordered by timestamp desc) */
|
|
419
|
+
async getAll(uid, appId) {
|
|
420
|
+
const db2 = getFirestore();
|
|
421
|
+
const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("timestamp", "desc").get();
|
|
422
|
+
return query.docs.map((doc) => doc.data());
|
|
423
|
+
}
|
|
424
|
+
/** Get a specific snapshot by ID */
|
|
425
|
+
async get(uid, appId, snapshotId) {
|
|
426
|
+
const db2 = getFirestore();
|
|
427
|
+
const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`).get();
|
|
428
|
+
if (!doc.exists) return null;
|
|
429
|
+
return doc.data();
|
|
430
|
+
}
|
|
431
|
+
/** Delete a snapshot */
|
|
432
|
+
async delete(uid, appId, snapshotId) {
|
|
433
|
+
const db2 = getFirestore();
|
|
434
|
+
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${snapshotId}`);
|
|
435
|
+
const doc = await ref.get();
|
|
436
|
+
if (!doc.exists) return false;
|
|
437
|
+
await ref.delete();
|
|
438
|
+
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
439
|
+
const appDoc = await appDocRef.get();
|
|
440
|
+
const currentMeta = appDoc.data()?._historyMeta;
|
|
441
|
+
if (currentMeta) {
|
|
442
|
+
const updatedMeta = {
|
|
443
|
+
...currentMeta,
|
|
444
|
+
snapshotCount: Math.max(0, (currentMeta.snapshotCount || 1) - 1),
|
|
445
|
+
latestSnapshotId: currentMeta.latestSnapshotId === snapshotId ? void 0 : currentMeta.latestSnapshotId
|
|
446
|
+
};
|
|
447
|
+
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
448
|
+
}
|
|
449
|
+
return true;
|
|
450
|
+
}
|
|
451
|
+
/** Get schema snapshot at a specific version */
|
|
452
|
+
async getByVersion(uid, appId, version) {
|
|
453
|
+
const db2 = getFirestore();
|
|
454
|
+
const query = await db2.collection(this.getCollectionPath(uid, appId)).where("version", "==", version).limit(1).get();
|
|
455
|
+
if (query.empty) return null;
|
|
456
|
+
const snapshot = query.docs[0].data();
|
|
457
|
+
return fromFirestoreFormat(snapshot.schema);
|
|
458
|
+
}
|
|
459
|
+
/** Get the schema from a snapshot (deserialized) */
|
|
460
|
+
getSchemaFromSnapshot(snapshot) {
|
|
461
|
+
return fromFirestoreFormat(snapshot.schema);
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
// src/stores/ChangeSetStore.ts
|
|
466
|
+
var CHANGESETS_COLLECTION = "changesets";
|
|
467
|
+
var ChangeSetStore = class {
|
|
468
|
+
appsCollection;
|
|
469
|
+
constructor(appsCollection = "apps") {
|
|
470
|
+
this.appsCollection = appsCollection;
|
|
471
|
+
}
|
|
472
|
+
getCollectionPath(uid, appId) {
|
|
473
|
+
return `users/${uid}/${this.appsCollection}/${appId}/${CHANGESETS_COLLECTION}`;
|
|
474
|
+
}
|
|
475
|
+
getAppDocPath(uid, appId) {
|
|
476
|
+
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
477
|
+
}
|
|
478
|
+
/** Append a changeset to history */
|
|
479
|
+
async append(uid, appId, changeSet) {
|
|
480
|
+
const db2 = getFirestore();
|
|
481
|
+
await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSet.id}`).set(changeSet);
|
|
482
|
+
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
483
|
+
const appDoc = await appDocRef.get();
|
|
484
|
+
const currentMeta = appDoc.data()?._historyMeta;
|
|
485
|
+
const updatedMeta = {
|
|
486
|
+
latestSnapshotId: currentMeta?.latestSnapshotId,
|
|
487
|
+
latestChangeSetId: changeSet.id,
|
|
488
|
+
snapshotCount: currentMeta?.snapshotCount || 0,
|
|
489
|
+
changeSetCount: (currentMeta?.changeSetCount || 0) + 1
|
|
490
|
+
};
|
|
491
|
+
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
492
|
+
}
|
|
493
|
+
/** Get change history for an app (ordered by version desc) */
|
|
494
|
+
async getHistory(uid, appId) {
|
|
495
|
+
try {
|
|
496
|
+
const db2 = getFirestore();
|
|
497
|
+
const query = await db2.collection(this.getCollectionPath(uid, appId)).orderBy("version", "desc").get();
|
|
498
|
+
return query.docs.map((doc) => doc.data());
|
|
499
|
+
} catch (error) {
|
|
500
|
+
console.error("[ChangeSetStore] Error getting change history:", error);
|
|
501
|
+
return [];
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/** Get a specific changeset by ID */
|
|
505
|
+
async get(uid, appId, changeSetId) {
|
|
506
|
+
const db2 = getFirestore();
|
|
507
|
+
const doc = await db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`).get();
|
|
508
|
+
if (!doc.exists) return null;
|
|
509
|
+
return doc.data();
|
|
510
|
+
}
|
|
511
|
+
/** Update a changeset's status */
|
|
512
|
+
async updateStatus(uid, appId, changeSetId, status) {
|
|
513
|
+
const db2 = getFirestore();
|
|
514
|
+
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
|
|
515
|
+
const doc = await ref.get();
|
|
516
|
+
if (!doc.exists) return;
|
|
517
|
+
await ref.update({ status });
|
|
518
|
+
}
|
|
519
|
+
/** Delete a changeset */
|
|
520
|
+
async delete(uid, appId, changeSetId) {
|
|
521
|
+
const db2 = getFirestore();
|
|
522
|
+
const ref = db2.doc(`${this.getCollectionPath(uid, appId)}/${changeSetId}`);
|
|
523
|
+
const doc = await ref.get();
|
|
524
|
+
if (!doc.exists) return false;
|
|
525
|
+
await ref.delete();
|
|
526
|
+
const appDocRef = db2.doc(this.getAppDocPath(uid, appId));
|
|
527
|
+
const appDoc = await appDocRef.get();
|
|
528
|
+
const currentMeta = appDoc.data()?._historyMeta;
|
|
529
|
+
if (currentMeta) {
|
|
530
|
+
const updatedMeta = {
|
|
531
|
+
...currentMeta,
|
|
532
|
+
changeSetCount: Math.max(0, (currentMeta.changeSetCount || 1) - 1),
|
|
533
|
+
latestChangeSetId: currentMeta.latestChangeSetId === changeSetId ? void 0 : currentMeta.latestChangeSetId
|
|
534
|
+
};
|
|
535
|
+
await appDocRef.set({ _historyMeta: updatedMeta }, { merge: true });
|
|
536
|
+
}
|
|
537
|
+
return true;
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// src/stores/ValidationStore.ts
|
|
542
|
+
var VALIDATION_COLLECTION = "validation";
|
|
543
|
+
var VALIDATION_DOC_ID = "current";
|
|
544
|
+
var ValidationStore = class {
|
|
545
|
+
appsCollection;
|
|
546
|
+
constructor(appsCollection = "apps") {
|
|
547
|
+
this.appsCollection = appsCollection;
|
|
548
|
+
}
|
|
549
|
+
getDocPath(uid, appId) {
|
|
550
|
+
return `users/${uid}/${this.appsCollection}/${appId}/${VALIDATION_COLLECTION}/${VALIDATION_DOC_ID}`;
|
|
551
|
+
}
|
|
552
|
+
getAppDocPath(uid, appId) {
|
|
553
|
+
return `users/${uid}/${this.appsCollection}/${appId}`;
|
|
554
|
+
}
|
|
555
|
+
/** Save validation results */
|
|
556
|
+
async save(uid, appId, results) {
|
|
557
|
+
const db2 = getFirestore();
|
|
558
|
+
await db2.doc(this.getDocPath(uid, appId)).set(results);
|
|
559
|
+
const validationMeta = {
|
|
560
|
+
errorCount: results.errors?.length || 0,
|
|
561
|
+
warningCount: results.warnings?.length || 0,
|
|
562
|
+
validatedAt: results.validatedAt
|
|
563
|
+
};
|
|
564
|
+
await db2.doc(this.getAppDocPath(uid, appId)).set(
|
|
565
|
+
{ _operational: { validationMeta } },
|
|
566
|
+
{ merge: true }
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
/** Get validation results */
|
|
570
|
+
async get(uid, appId) {
|
|
571
|
+
try {
|
|
572
|
+
const db2 = getFirestore();
|
|
573
|
+
const doc = await db2.doc(this.getDocPath(uid, appId)).get();
|
|
574
|
+
if (!doc.exists) return null;
|
|
575
|
+
return doc.data();
|
|
576
|
+
} catch (error) {
|
|
577
|
+
console.error("[ValidationStore] Error getting validation results:", error);
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
/** Clear validation results */
|
|
582
|
+
async clear(uid, appId) {
|
|
583
|
+
const db2 = getFirestore();
|
|
584
|
+
const { FieldValue } = await import('firebase-admin/firestore');
|
|
585
|
+
await db2.doc(this.getDocPath(uid, appId)).delete();
|
|
586
|
+
await db2.doc(this.getAppDocPath(uid, appId)).update({
|
|
587
|
+
"_operational.validationMeta": FieldValue.delete()
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
export { ChangeSetStore, SchemaProtectionService, SchemaStore, SnapshotStore, ValidationStore, fromFirestoreFormat, toFirestoreFormat };
|
|
593
|
+
//# sourceMappingURL=index.js.map
|
|
594
|
+
//# sourceMappingURL=index.js.map
|