@almadar/server 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,632 @@
1
+ import { faker } from '@faker-js/faker';
2
+ import { z } from 'zod';
3
+ import dotenv from 'dotenv';
4
+ import admin from 'firebase-admin';
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
+ dotenv.config();
13
+ var envSchema = z.object({
14
+ NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
15
+ PORT: z.string().default("3030").transform((val) => parseInt(val, 10)),
16
+ CORS_ORIGIN: z.string().default("http://localhost:5173").transform((val) => val.includes(",") ? val.split(",").map((s) => s.trim()) : val),
17
+ // Database (Prisma/SQL) - optional
18
+ DATABASE_URL: z.string().optional(),
19
+ // Firebase/Firestore configuration
20
+ FIREBASE_PROJECT_ID: z.string().optional(),
21
+ FIREBASE_CLIENT_EMAIL: z.string().optional(),
22
+ FIREBASE_PRIVATE_KEY: z.string().optional(),
23
+ FIREBASE_SERVICE_ACCOUNT_PATH: z.string().optional(),
24
+ FIRESTORE_EMULATOR_HOST: z.string().optional(),
25
+ FIREBASE_AUTH_EMULATOR_HOST: z.string().optional(),
26
+ // API configuration
27
+ API_PREFIX: z.string().default("/api"),
28
+ // Mock data configuration
29
+ USE_MOCK_DATA: z.string().default("true").transform((v) => v === "true"),
30
+ MOCK_SEED: z.string().optional().transform((v) => v ? parseInt(v, 10) : void 0)
31
+ });
32
+ var parsed = envSchema.safeParse(process.env);
33
+ if (!parsed.success) {
34
+ console.error("\u274C Invalid environment variables:", parsed.error.flatten().fieldErrors);
35
+ throw new Error("Invalid environment variables");
36
+ }
37
+ var env = parsed.data;
38
+
39
+ // src/lib/logger.ts
40
+ var colors = {
41
+ debug: "\x1B[36m",
42
+ // Cyan
43
+ info: "\x1B[32m",
44
+ // Green
45
+ warn: "\x1B[33m",
46
+ // Yellow
47
+ error: "\x1B[31m",
48
+ // Red
49
+ reset: "\x1B[0m"
50
+ };
51
+ var shouldLog = (level) => {
52
+ const levels = ["debug", "info", "warn", "error"];
53
+ const minLevel = env.NODE_ENV === "production" ? "info" : "debug";
54
+ return levels.indexOf(level) >= levels.indexOf(minLevel);
55
+ };
56
+ var formatMessage = (level, message, meta) => {
57
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
58
+ const color = colors[level];
59
+ const prefix = `${color}[${level.toUpperCase()}]${colors.reset}`;
60
+ const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
61
+ return `${timestamp} ${prefix} ${message}${metaStr}`;
62
+ };
63
+ var logger = {
64
+ debug: (message, meta) => {
65
+ if (shouldLog("debug")) {
66
+ console.log(formatMessage("debug", message, meta));
67
+ }
68
+ },
69
+ info: (message, meta) => {
70
+ if (shouldLog("info")) {
71
+ console.log(formatMessage("info", message, meta));
72
+ }
73
+ },
74
+ warn: (message, meta) => {
75
+ if (shouldLog("warn")) {
76
+ console.warn(formatMessage("warn", message, meta));
77
+ }
78
+ },
79
+ error: (message, meta) => {
80
+ if (shouldLog("error")) {
81
+ console.error(formatMessage("error", message, meta));
82
+ }
83
+ }
84
+ };
85
+
86
+ // src/services/MockDataService.ts
87
+ var MockDataService = class {
88
+ stores = /* @__PURE__ */ new Map();
89
+ schemas = /* @__PURE__ */ new Map();
90
+ idCounters = /* @__PURE__ */ new Map();
91
+ constructor() {
92
+ if (env.MOCK_SEED !== void 0) {
93
+ faker.seed(env.MOCK_SEED);
94
+ logger.info(`[Mock] Using seed: ${env.MOCK_SEED}`);
95
+ }
96
+ }
97
+ // ============================================================================
98
+ // Store Management
99
+ // ============================================================================
100
+ /**
101
+ * Initialize store for an entity.
102
+ */
103
+ getStore(entityName) {
104
+ const normalized = entityName.toLowerCase();
105
+ if (!this.stores.has(normalized)) {
106
+ this.stores.set(normalized, /* @__PURE__ */ new Map());
107
+ this.idCounters.set(normalized, 0);
108
+ }
109
+ return this.stores.get(normalized);
110
+ }
111
+ /**
112
+ * Generate next ID for an entity.
113
+ */
114
+ nextId(entityName) {
115
+ const normalized = entityName.toLowerCase();
116
+ const counter = (this.idCounters.get(normalized) ?? 0) + 1;
117
+ this.idCounters.set(normalized, counter);
118
+ return `mock-${normalized}-${counter}`;
119
+ }
120
+ // ============================================================================
121
+ // Schema & Seeding
122
+ // ============================================================================
123
+ /**
124
+ * Register an entity schema.
125
+ */
126
+ registerSchema(entityName, schema) {
127
+ this.schemas.set(entityName.toLowerCase(), schema);
128
+ }
129
+ /**
130
+ * Seed an entity with mock data.
131
+ */
132
+ seed(entityName, fields, count = 10) {
133
+ const store = this.getStore(entityName);
134
+ const normalized = entityName.toLowerCase();
135
+ logger.info(`[Mock] Seeding ${count} ${entityName}...`);
136
+ for (let i = 0; i < count; i++) {
137
+ const item = this.generateMockItem(normalized, fields, i + 1);
138
+ store.set(item.id, item);
139
+ }
140
+ }
141
+ /**
142
+ * Generate a single mock item based on field schemas.
143
+ */
144
+ generateMockItem(entityName, fields, index) {
145
+ const id = this.nextId(entityName);
146
+ const now = /* @__PURE__ */ new Date();
147
+ const item = {
148
+ id,
149
+ createdAt: faker.date.past({ years: 1 }),
150
+ updatedAt: now
151
+ };
152
+ for (const field of fields) {
153
+ if (field.name === "id" || field.name === "createdAt" || field.name === "updatedAt") {
154
+ continue;
155
+ }
156
+ item[field.name] = this.generateFieldValue(entityName, field, index);
157
+ }
158
+ return item;
159
+ }
160
+ /**
161
+ * Generate a mock value for a field based on its schema.
162
+ */
163
+ generateFieldValue(entityName, field, index) {
164
+ if (!field.required && Math.random() > 0.8) {
165
+ return void 0;
166
+ }
167
+ switch (field.type) {
168
+ case "string":
169
+ return this.generateStringValue(entityName, field, index);
170
+ case "number":
171
+ return faker.number.int({
172
+ min: field.min ?? 0,
173
+ max: field.max ?? 1e3
174
+ });
175
+ case "boolean":
176
+ return faker.datatype.boolean();
177
+ case "date":
178
+ return this.generateDateValue(field);
179
+ case "enum":
180
+ if (field.enumValues && field.enumValues.length > 0) {
181
+ return faker.helpers.arrayElement(field.enumValues);
182
+ }
183
+ return null;
184
+ case "relation":
185
+ if (field.relatedEntity) {
186
+ const relatedStore = this.stores.get(field.relatedEntity.toLowerCase());
187
+ if (relatedStore && relatedStore.size > 0) {
188
+ const ids = Array.from(relatedStore.keys());
189
+ return faker.helpers.arrayElement(ids);
190
+ }
191
+ }
192
+ return null;
193
+ case "array":
194
+ return [];
195
+ default:
196
+ return null;
197
+ }
198
+ }
199
+ /**
200
+ * Generate a string value based on field name heuristics.
201
+ * Generic name/title fields use entity-aware format (e.g., "Project Name 1").
202
+ * Specific fields (email, phone, etc.) use faker.
203
+ */
204
+ generateStringValue(entityName, field, index) {
205
+ const name = field.name.toLowerCase();
206
+ if (field.enumValues && field.enumValues.length > 0) {
207
+ return faker.helpers.arrayElement(field.enumValues);
208
+ }
209
+ if (name.includes("email")) return faker.internet.email();
210
+ if (name.includes("phone")) return faker.phone.number();
211
+ if (name.includes("address")) return faker.location.streetAddress();
212
+ if (name.includes("city")) return faker.location.city();
213
+ if (name.includes("country")) return faker.location.country();
214
+ if (name.includes("url") || name.includes("website")) return faker.internet.url();
215
+ if (name.includes("avatar") || name.includes("image")) return faker.image.avatar();
216
+ if (name.includes("color")) return faker.color.human();
217
+ if (name.includes("uuid")) return faker.string.uuid();
218
+ const entityLabel = this.capitalizeFirst(entityName);
219
+ const fieldLabel = this.capitalizeFirst(field.name);
220
+ return `${entityLabel} ${fieldLabel} ${index}`;
221
+ }
222
+ /**
223
+ * Capitalize first letter of a string.
224
+ */
225
+ capitalizeFirst(str) {
226
+ return str.charAt(0).toUpperCase() + str.slice(1);
227
+ }
228
+ /**
229
+ * Generate a date value based on field name heuristics.
230
+ */
231
+ generateDateValue(field) {
232
+ const name = field.name.toLowerCase();
233
+ if (name.includes("created") || name.includes("start") || name.includes("birth")) {
234
+ return faker.date.past({ years: 2 });
235
+ }
236
+ if (name.includes("updated") || name.includes("modified")) {
237
+ return faker.date.recent({ days: 30 });
238
+ }
239
+ if (name.includes("deadline") || name.includes("due") || name.includes("end") || name.includes("expires")) {
240
+ return faker.date.future({ years: 1 });
241
+ }
242
+ return faker.date.anytime();
243
+ }
244
+ // ============================================================================
245
+ // CRUD Operations
246
+ // ============================================================================
247
+ /**
248
+ * List all items of an entity.
249
+ */
250
+ list(entityName) {
251
+ const store = this.getStore(entityName);
252
+ return Array.from(store.values());
253
+ }
254
+ /**
255
+ * Get a single item by ID.
256
+ */
257
+ getById(entityName, id) {
258
+ const store = this.getStore(entityName);
259
+ const item = store.get(id);
260
+ return item ?? null;
261
+ }
262
+ /**
263
+ * Create a new item.
264
+ */
265
+ create(entityName, data) {
266
+ const store = this.getStore(entityName);
267
+ const id = this.nextId(entityName);
268
+ const now = /* @__PURE__ */ new Date();
269
+ const item = {
270
+ ...data,
271
+ id,
272
+ createdAt: now,
273
+ updatedAt: now
274
+ };
275
+ store.set(id, item);
276
+ return item;
277
+ }
278
+ /**
279
+ * Update an existing item.
280
+ */
281
+ update(entityName, id, data) {
282
+ const store = this.getStore(entityName);
283
+ const existing = store.get(id);
284
+ if (!existing) {
285
+ return null;
286
+ }
287
+ const updated = {
288
+ ...existing,
289
+ ...data,
290
+ id,
291
+ // Preserve original ID
292
+ updatedAt: /* @__PURE__ */ new Date()
293
+ };
294
+ store.set(id, updated);
295
+ return updated;
296
+ }
297
+ /**
298
+ * Delete an item.
299
+ */
300
+ delete(entityName, id) {
301
+ const store = this.getStore(entityName);
302
+ if (!store.has(id)) {
303
+ return false;
304
+ }
305
+ store.delete(id);
306
+ return true;
307
+ }
308
+ // ============================================================================
309
+ // Utilities
310
+ // ============================================================================
311
+ /**
312
+ * Clear all data for an entity.
313
+ */
314
+ clear(entityName) {
315
+ const normalized = entityName.toLowerCase();
316
+ this.stores.delete(normalized);
317
+ this.idCounters.delete(normalized);
318
+ }
319
+ /**
320
+ * Clear all data.
321
+ */
322
+ clearAll() {
323
+ this.stores.clear();
324
+ this.idCounters.clear();
325
+ }
326
+ /**
327
+ * Get count of items for an entity.
328
+ */
329
+ count(entityName) {
330
+ const store = this.getStore(entityName);
331
+ return store.size;
332
+ }
333
+ };
334
+ var mockDataService = new MockDataService();
335
+ var firebaseApp = null;
336
+ function initializeFirebase() {
337
+ if (firebaseApp) {
338
+ return firebaseApp;
339
+ }
340
+ if (admin.apps.length > 0) {
341
+ firebaseApp = admin.apps[0];
342
+ return firebaseApp;
343
+ }
344
+ if (env.FIRESTORE_EMULATOR_HOST) {
345
+ firebaseApp = admin.initializeApp({
346
+ projectId: env.FIREBASE_PROJECT_ID || "demo-project"
347
+ });
348
+ console.log(`\u{1F527} Firebase Admin initialized for emulator: ${env.FIRESTORE_EMULATOR_HOST}`);
349
+ return firebaseApp;
350
+ }
351
+ const serviceAccountPath = env.FIREBASE_SERVICE_ACCOUNT_PATH;
352
+ if (serviceAccountPath) {
353
+ const serviceAccount = __require(serviceAccountPath);
354
+ firebaseApp = admin.initializeApp({
355
+ credential: admin.credential.cert(serviceAccount),
356
+ projectId: env.FIREBASE_PROJECT_ID
357
+ });
358
+ } else if (env.FIREBASE_PROJECT_ID && env.FIREBASE_CLIENT_EMAIL && env.FIREBASE_PRIVATE_KEY) {
359
+ firebaseApp = admin.initializeApp({
360
+ credential: admin.credential.cert({
361
+ projectId: env.FIREBASE_PROJECT_ID,
362
+ clientEmail: env.FIREBASE_CLIENT_EMAIL,
363
+ privateKey: env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n")
364
+ }),
365
+ projectId: env.FIREBASE_PROJECT_ID
366
+ });
367
+ } else if (env.FIREBASE_PROJECT_ID) {
368
+ firebaseApp = admin.initializeApp({
369
+ credential: admin.credential.applicationDefault(),
370
+ projectId: env.FIREBASE_PROJECT_ID
371
+ });
372
+ } else {
373
+ firebaseApp = admin.initializeApp({
374
+ projectId: "demo-project"
375
+ });
376
+ }
377
+ return firebaseApp;
378
+ }
379
+ function getFirestore() {
380
+ const app = initializeFirebase();
381
+ const db2 = app.firestore();
382
+ if (env.FIRESTORE_EMULATOR_HOST) {
383
+ db2.settings({
384
+ host: env.FIRESTORE_EMULATOR_HOST,
385
+ ssl: false
386
+ });
387
+ }
388
+ return db2;
389
+ }
390
+ var db = getFirestore();
391
+
392
+ // src/utils/queryFilters.ts
393
+ function applyFiltersToQuery(collection, filters) {
394
+ let query = collection;
395
+ for (const filter of filters) {
396
+ query = query.where(
397
+ filter.field,
398
+ filter.operator,
399
+ filter.value
400
+ );
401
+ }
402
+ return query;
403
+ }
404
+
405
+ // src/services/DataService.ts
406
+ function applyFilterCondition(value, operator, filterValue) {
407
+ if (value === null || value === void 0) {
408
+ return operator === "!=" ? filterValue !== null : false;
409
+ }
410
+ switch (operator) {
411
+ case "==":
412
+ return value === filterValue;
413
+ case "!=":
414
+ return value !== filterValue;
415
+ case ">":
416
+ return value > filterValue;
417
+ case ">=":
418
+ return value >= filterValue;
419
+ case "<":
420
+ return value < filterValue;
421
+ case "<=":
422
+ return value <= filterValue;
423
+ case "array-contains":
424
+ return Array.isArray(value) && value.includes(filterValue);
425
+ case "array-contains-any":
426
+ return Array.isArray(value) && Array.isArray(filterValue) && filterValue.some((v) => value.includes(v));
427
+ case "in":
428
+ return Array.isArray(filterValue) && filterValue.includes(value);
429
+ case "not-in":
430
+ return Array.isArray(filterValue) && !filterValue.includes(value);
431
+ default:
432
+ return true;
433
+ }
434
+ }
435
+ var MockDataServiceAdapter = class {
436
+ async list(collection) {
437
+ return mockDataService.list(collection);
438
+ }
439
+ async listPaginated(collection, options = {}) {
440
+ const {
441
+ page = 1,
442
+ pageSize = 20,
443
+ search,
444
+ searchFields,
445
+ sortBy,
446
+ sortOrder = "asc",
447
+ filters
448
+ } = options;
449
+ let items = mockDataService.list(collection);
450
+ if (filters && filters.length > 0) {
451
+ items = items.filter((item) => {
452
+ const record = item;
453
+ return filters.every((filter) => {
454
+ const value = record[filter.field];
455
+ return applyFilterCondition(value, filter.operator, filter.value);
456
+ });
457
+ });
458
+ }
459
+ if (search && search.trim()) {
460
+ const searchLower = search.toLowerCase();
461
+ items = items.filter((item) => {
462
+ const record = item;
463
+ const fieldsToSearch = searchFields || Object.keys(record);
464
+ return fieldsToSearch.some((field) => {
465
+ const value = record[field];
466
+ if (value === null || value === void 0) return false;
467
+ return String(value).toLowerCase().includes(searchLower);
468
+ });
469
+ });
470
+ }
471
+ if (sortBy) {
472
+ items = [...items].sort((a, b) => {
473
+ const aVal = a[sortBy];
474
+ const bVal = b[sortBy];
475
+ if (aVal === bVal) return 0;
476
+ if (aVal === null || aVal === void 0) return 1;
477
+ if (bVal === null || bVal === void 0) return -1;
478
+ const comparison = aVal < bVal ? -1 : 1;
479
+ return sortOrder === "asc" ? comparison : -comparison;
480
+ });
481
+ }
482
+ const total = items.length;
483
+ const totalPages = Math.ceil(total / pageSize);
484
+ const startIndex = (page - 1) * pageSize;
485
+ const data = items.slice(startIndex, startIndex + pageSize);
486
+ return { data, total, page, pageSize, totalPages };
487
+ }
488
+ async getById(collection, id) {
489
+ return mockDataService.getById(collection, id);
490
+ }
491
+ async create(collection, data) {
492
+ return mockDataService.create(collection, data);
493
+ }
494
+ async update(collection, id, data) {
495
+ return mockDataService.update(collection, id, data);
496
+ }
497
+ async delete(collection, id) {
498
+ return mockDataService.delete(collection, id);
499
+ }
500
+ };
501
+ var FirebaseDataService = class {
502
+ async list(collection) {
503
+ const snapshot = await db.collection(collection).get();
504
+ return snapshot.docs.map((doc) => ({
505
+ id: doc.id,
506
+ ...doc.data()
507
+ }));
508
+ }
509
+ async listPaginated(collection, options = {}) {
510
+ const {
511
+ page = 1,
512
+ pageSize = 20,
513
+ search,
514
+ searchFields,
515
+ sortBy,
516
+ sortOrder = "asc",
517
+ filters
518
+ } = options;
519
+ let query = db.collection(collection);
520
+ if (filters && filters.length > 0) {
521
+ query = applyFiltersToQuery(query, filters);
522
+ }
523
+ if (sortBy && !search) {
524
+ query = query.orderBy(sortBy, sortOrder);
525
+ }
526
+ const snapshot = await query.get();
527
+ let items = snapshot.docs.map((doc) => ({
528
+ id: doc.id,
529
+ ...doc.data()
530
+ }));
531
+ if (search && search.trim()) {
532
+ const searchLower = search.toLowerCase();
533
+ items = items.filter((item) => {
534
+ const record = item;
535
+ const fieldsToSearch = searchFields || Object.keys(record);
536
+ return fieldsToSearch.some((field) => {
537
+ const value = record[field];
538
+ if (value === null || value === void 0) return false;
539
+ return String(value).toLowerCase().includes(searchLower);
540
+ });
541
+ });
542
+ }
543
+ if (sortBy && search) {
544
+ items = [...items].sort((a, b) => {
545
+ const aVal = a[sortBy];
546
+ const bVal = b[sortBy];
547
+ if (aVal === bVal) return 0;
548
+ if (aVal === null || aVal === void 0) return 1;
549
+ if (bVal === null || bVal === void 0) return -1;
550
+ const comparison = aVal < bVal ? -1 : 1;
551
+ return sortOrder === "asc" ? comparison : -comparison;
552
+ });
553
+ }
554
+ const total = items.length;
555
+ const totalPages = Math.ceil(total / pageSize);
556
+ const startIndex = (page - 1) * pageSize;
557
+ const data = items.slice(startIndex, startIndex + pageSize);
558
+ return { data, total, page, pageSize, totalPages };
559
+ }
560
+ async getById(collection, id) {
561
+ const doc = await db.collection(collection).doc(id).get();
562
+ if (!doc.exists) {
563
+ return null;
564
+ }
565
+ return { id: doc.id, ...doc.data() };
566
+ }
567
+ async create(collection, data) {
568
+ const now = /* @__PURE__ */ new Date();
569
+ const docRef = await db.collection(collection).add({
570
+ ...data,
571
+ createdAt: now,
572
+ updatedAt: now
573
+ });
574
+ return {
575
+ ...data,
576
+ id: docRef.id,
577
+ createdAt: now,
578
+ updatedAt: now
579
+ };
580
+ }
581
+ async update(collection, id, data) {
582
+ const docRef = db.collection(collection).doc(id);
583
+ const doc = await docRef.get();
584
+ if (!doc.exists) {
585
+ return null;
586
+ }
587
+ const now = /* @__PURE__ */ new Date();
588
+ await docRef.update({
589
+ ...data,
590
+ updatedAt: now
591
+ });
592
+ return {
593
+ ...doc.data(),
594
+ ...data,
595
+ id,
596
+ updatedAt: now
597
+ };
598
+ }
599
+ async delete(collection, id) {
600
+ const docRef = db.collection(collection).doc(id);
601
+ const doc = await docRef.get();
602
+ if (!doc.exists) {
603
+ return false;
604
+ }
605
+ await docRef.delete();
606
+ return true;
607
+ }
608
+ };
609
+ function createDataService() {
610
+ if (env.USE_MOCK_DATA) {
611
+ logger.info("[DataService] Using MockDataService");
612
+ return new MockDataServiceAdapter();
613
+ }
614
+ logger.info("[DataService] Using FirebaseDataService");
615
+ return new FirebaseDataService();
616
+ }
617
+ var dataService = createDataService();
618
+ function seedMockData(entities) {
619
+ if (!env.USE_MOCK_DATA) {
620
+ logger.info("[DataService] Mock mode disabled, skipping seed");
621
+ return;
622
+ }
623
+ logger.info("[DataService] Seeding mock data...");
624
+ for (const entity of entities) {
625
+ mockDataService.seed(entity.name, entity.fields, entity.seedCount);
626
+ }
627
+ logger.info("[DataService] Mock data seeding complete");
628
+ }
629
+
630
+ export { dataService, mockDataService, seedMockData };
631
+ //# sourceMappingURL=index.js.map
632
+ //# sourceMappingURL=index.js.map