achievements-engine 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,1677 @@
1
+ /**
2
+ * Lightweight, type-safe event emitter for the achievements engine
3
+ * Zero dependencies, memory-leak safe implementation
4
+ */
5
+ class EventEmitter {
6
+ constructor() {
7
+ this.listeners = new Map();
8
+ this.onceListeners = new Map();
9
+ }
10
+ /**
11
+ * Subscribe to an event
12
+ * @param event - Event name
13
+ * @param handler - Event handler function
14
+ * @returns Unsubscribe function
15
+ */
16
+ on(event, handler) {
17
+ if (!this.listeners.has(event)) {
18
+ this.listeners.set(event, new Set());
19
+ }
20
+ this.listeners.get(event).add(handler);
21
+ // Return unsubscribe function
22
+ return () => this.off(event, handler);
23
+ }
24
+ /**
25
+ * Subscribe to an event once (auto-unsubscribes after first emission)
26
+ * @param event - Event name
27
+ * @param handler - Event handler function
28
+ * @returns Unsubscribe function
29
+ */
30
+ once(event, handler) {
31
+ if (!this.onceListeners.has(event)) {
32
+ this.onceListeners.set(event, new Set());
33
+ }
34
+ this.onceListeners.get(event).add(handler);
35
+ // Return unsubscribe function
36
+ return () => {
37
+ const onceSet = this.onceListeners.get(event);
38
+ if (onceSet) {
39
+ onceSet.delete(handler);
40
+ }
41
+ };
42
+ }
43
+ /**
44
+ * Unsubscribe from an event
45
+ * @param event - Event name
46
+ * @param handler - Event handler function to remove
47
+ */
48
+ off(event, handler) {
49
+ const regularListeners = this.listeners.get(event);
50
+ if (regularListeners) {
51
+ regularListeners.delete(handler);
52
+ // Clean up empty sets to prevent memory leaks
53
+ if (regularListeners.size === 0) {
54
+ this.listeners.delete(event);
55
+ }
56
+ }
57
+ const onceSet = this.onceListeners.get(event);
58
+ if (onceSet) {
59
+ onceSet.delete(handler);
60
+ // Clean up empty sets
61
+ if (onceSet.size === 0) {
62
+ this.onceListeners.delete(event);
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * Emit an event to all subscribers
68
+ * @param event - Event name
69
+ * @param data - Event payload
70
+ */
71
+ emit(event, data) {
72
+ // Call regular listeners
73
+ const regularListeners = this.listeners.get(event);
74
+ if (regularListeners) {
75
+ // Create a copy to avoid issues if listeners modify the set during iteration
76
+ const listenersCopy = Array.from(regularListeners);
77
+ listenersCopy.forEach(handler => {
78
+ try {
79
+ handler(data);
80
+ }
81
+ catch (error) {
82
+ // Prevent one handler's error from stopping other handlers
83
+ console.error(`Error in event handler for "${event}":`, error);
84
+ }
85
+ });
86
+ }
87
+ // Call once listeners and remove them
88
+ const onceSet = this.onceListeners.get(event);
89
+ if (onceSet) {
90
+ const onceListenersCopy = Array.from(onceSet);
91
+ // Clear the set before calling handlers to prevent re-entry issues
92
+ this.onceListeners.delete(event);
93
+ onceListenersCopy.forEach(handler => {
94
+ try {
95
+ handler(data);
96
+ }
97
+ catch (error) {
98
+ console.error(`Error in once event handler for "${event}":`, error);
99
+ }
100
+ });
101
+ }
102
+ }
103
+ /**
104
+ * Remove all listeners for a specific event, or all events if no event specified
105
+ * @param event - Optional event name. If not provided, removes all listeners.
106
+ */
107
+ removeAllListeners(event) {
108
+ if (event) {
109
+ this.listeners.delete(event);
110
+ this.onceListeners.delete(event);
111
+ }
112
+ else {
113
+ this.listeners.clear();
114
+ this.onceListeners.clear();
115
+ }
116
+ }
117
+ /**
118
+ * Get the number of listeners for an event
119
+ * @param event - Event name
120
+ * @returns Number of listeners
121
+ */
122
+ listenerCount(event) {
123
+ var _a, _b;
124
+ const regularCount = ((_a = this.listeners.get(event)) === null || _a === void 0 ? void 0 : _a.size) || 0;
125
+ const onceCount = ((_b = this.onceListeners.get(event)) === null || _b === void 0 ? void 0 : _b.size) || 0;
126
+ return regularCount + onceCount;
127
+ }
128
+ /**
129
+ * Get all event names that have listeners
130
+ * @returns Array of event names
131
+ */
132
+ eventNames() {
133
+ const regularEvents = Array.from(this.listeners.keys());
134
+ const onceEvents = Array.from(this.onceListeners.keys());
135
+ // Combine and deduplicate
136
+ return Array.from(new Set([...regularEvents, ...onceEvents]));
137
+ }
138
+ }
139
+
140
+ // Type guard to check if config is simple format
141
+ function isSimpleConfig(config) {
142
+ if (!config || typeof config !== 'object')
143
+ return false;
144
+ const firstKey = Object.keys(config)[0];
145
+ if (!firstKey)
146
+ return true; // Empty config is considered simple
147
+ const firstValue = config[firstKey];
148
+ // Check if it's the current complex format (array of AchievementCondition)
149
+ if (Array.isArray(firstValue))
150
+ return false;
151
+ // Check if it's the simple format (object with string keys)
152
+ return typeof firstValue === 'object' && !Array.isArray(firstValue);
153
+ }
154
+ // Generate a unique ID for achievements
155
+ function generateId() {
156
+ return Math.random().toString(36).substr(2, 9);
157
+ }
158
+ // Check if achievement details has a custom condition
159
+ function hasCustomCondition(details) {
160
+ return 'condition' in details && typeof details.condition === 'function';
161
+ }
162
+ // Convert simple config to complex config format
163
+ function normalizeAchievements(config) {
164
+ if (!isSimpleConfig(config)) {
165
+ // Already in complex format, return as-is
166
+ return config;
167
+ }
168
+ const normalized = {};
169
+ Object.entries(config).forEach(([metric, achievements]) => {
170
+ normalized[metric] = Object.entries(achievements).map(([key, achievement]) => {
171
+ if (hasCustomCondition(achievement)) {
172
+ // Custom condition function
173
+ return {
174
+ isConditionMet: (_value, _state) => {
175
+ // Convert internal metrics format (arrays) to simple format for custom conditions
176
+ const simpleMetrics = {};
177
+ Object.entries(_state.metrics).forEach(([key, val]) => {
178
+ simpleMetrics[key] = Array.isArray(val) ? val[0] : val;
179
+ });
180
+ return achievement.condition(simpleMetrics);
181
+ },
182
+ achievementDetails: {
183
+ achievementId: `${metric}_custom_${generateId()}`,
184
+ achievementTitle: achievement.title,
185
+ achievementDescription: achievement.description || '',
186
+ achievementIconKey: achievement.icon || 'default'
187
+ }
188
+ };
189
+ }
190
+ else {
191
+ // Threshold-based achievement
192
+ const threshold = parseFloat(key);
193
+ const isValidThreshold = !isNaN(threshold);
194
+ let conditionMet;
195
+ if (isValidThreshold) {
196
+ // Numeric threshold
197
+ conditionMet = (value) => {
198
+ const numValue = Array.isArray(value) ? value[0] : value;
199
+ return typeof numValue === 'number' && numValue >= threshold;
200
+ };
201
+ }
202
+ else {
203
+ // String or boolean threshold
204
+ conditionMet = (value) => {
205
+ const actualValue = Array.isArray(value) ? value[0] : value;
206
+ // Handle boolean thresholds
207
+ if (key === 'true')
208
+ return actualValue === true;
209
+ if (key === 'false')
210
+ return actualValue === false;
211
+ // Handle string thresholds
212
+ return actualValue === key;
213
+ };
214
+ }
215
+ return {
216
+ isConditionMet: conditionMet,
217
+ achievementDetails: {
218
+ achievementId: `${metric}_${key}`,
219
+ achievementTitle: achievement.title,
220
+ achievementDescription: achievement.description || (isValidThreshold ? `Reach ${threshold} ${metric}` : `Achieve ${key} for ${metric}`),
221
+ achievementIconKey: achievement.icon || 'default'
222
+ }
223
+ };
224
+ }
225
+ });
226
+ });
227
+ return normalized;
228
+ }
229
+
230
+ /**
231
+ * Exports achievement data to a JSON string
232
+ *
233
+ * @param metrics - Current achievement metrics
234
+ * @param unlocked - Array of unlocked achievement IDs
235
+ * @param configHash - Optional hash of achievement configuration for validation
236
+ * @returns JSON string containing all achievement data
237
+ *
238
+ * @example
239
+ * ```typescript
240
+ * const json = exportAchievementData(_metrics, ['score_100', 'level_5']);
241
+ * // Save json to file or send to server
242
+ * ```
243
+ */
244
+ function exportAchievementData(metrics, unlocked, configHash) {
245
+ const data = Object.assign({ version: '3.3.0', timestamp: Date.now(), metrics, unlockedAchievements: unlocked }, (configHash && { configHash }));
246
+ return JSON.stringify(data, null, 2);
247
+ }
248
+ /**
249
+ * Creates a simple hash of the achievement configuration
250
+ * Used to validate that imported data matches the current configuration
251
+ *
252
+ * @param config - Achievement configuration object
253
+ * @returns Simple hash string
254
+ */
255
+ function createConfigHash(config) {
256
+ // Simple hash based on stringified config
257
+ // In production, you might want to use a more robust hashing algorithm
258
+ const str = JSON.stringify(config);
259
+ let hash = 0;
260
+ for (let i = 0; i < str.length; i++) {
261
+ const char = str.charCodeAt(i);
262
+ hash = ((hash << 5) - hash) + char;
263
+ hash = hash & hash; // Convert to 32bit integer
264
+ }
265
+ return hash.toString(36);
266
+ }
267
+
268
+ /**
269
+ * Imports achievement data from a JSON string
270
+ *
271
+ * @param jsonString - JSON string containing exported achievement data
272
+ * @param currentMetrics - Current metrics state
273
+ * @param currentUnlocked - Current unlocked achievements
274
+ * @param options - Import options
275
+ * @returns Import result with success status and any errors
276
+ *
277
+ * @example
278
+ * ```typescript
279
+ * const result = importAchievementData(
280
+ * jsonString,
281
+ * currentMetrics,
282
+ * currentUnlocked,
283
+ * { mergeStrategy: 'merge', validate: true }
284
+ * );
285
+ *
286
+ * if (result.success) {
287
+ * console.log(`Imported ${result.imported.achievements} achievements`);
288
+ * } else {
289
+ * console.error('Import failed:', result.errors);
290
+ * }
291
+ * ```
292
+ */
293
+ function importAchievementData(jsonString, currentMetrics, currentUnlocked, options = {}) {
294
+ const { mergeStrategy = 'replace', validate = true, expectedConfigHash } = options;
295
+ const warnings = [];
296
+ // Parse JSON
297
+ let data;
298
+ try {
299
+ data = JSON.parse(jsonString);
300
+ }
301
+ catch (_a) {
302
+ return {
303
+ success: false,
304
+ imported: { metrics: 0, achievements: 0 },
305
+ errors: ['Invalid JSON format']
306
+ };
307
+ }
308
+ // Validate structure
309
+ if (validate) {
310
+ const validationErrors = validateExportedData(data, expectedConfigHash);
311
+ if (validationErrors.length > 0) {
312
+ return {
313
+ success: false,
314
+ imported: { metrics: 0, achievements: 0 },
315
+ errors: validationErrors
316
+ };
317
+ }
318
+ }
319
+ // Version compatibility check
320
+ if (data.version && data.version !== '3.3.0') {
321
+ warnings.push(`Data exported from version ${data.version}, current version is 3.3.0`);
322
+ }
323
+ // Merge metrics based on strategy
324
+ let mergedMetrics;
325
+ let mergedUnlocked;
326
+ switch (mergeStrategy) {
327
+ case 'replace':
328
+ // Replace all existing data
329
+ mergedMetrics = data.metrics;
330
+ mergedUnlocked = data.unlockedAchievements;
331
+ break;
332
+ case 'merge':
333
+ // Union of both datasets, keeping higher metric values
334
+ mergedMetrics = mergeMetrics(currentMetrics, data.metrics);
335
+ mergedUnlocked = Array.from(new Set([...currentUnlocked, ...data.unlockedAchievements]));
336
+ break;
337
+ case 'preserve':
338
+ // Keep existing values, only add new ones
339
+ mergedMetrics = preserveMetrics(currentMetrics, data.metrics);
340
+ mergedUnlocked = Array.from(new Set([...currentUnlocked, ...data.unlockedAchievements]));
341
+ break;
342
+ default:
343
+ return {
344
+ success: false,
345
+ imported: { metrics: 0, achievements: 0 },
346
+ errors: [`Invalid merge strategy: ${mergeStrategy}`]
347
+ };
348
+ }
349
+ return Object.assign(Object.assign({ success: true, imported: {
350
+ metrics: Object.keys(mergedMetrics).length,
351
+ achievements: mergedUnlocked.length
352
+ } }, (warnings.length > 0 && { warnings })), { mergedMetrics,
353
+ mergedUnlocked });
354
+ }
355
+ /**
356
+ * Validates the structure and content of exported data
357
+ */
358
+ function validateExportedData(data, expectedConfigHash) {
359
+ const errors = [];
360
+ // Check required fields
361
+ if (!data.version) {
362
+ errors.push('Missing version field');
363
+ }
364
+ if (!data.timestamp) {
365
+ errors.push('Missing timestamp field');
366
+ }
367
+ if (!data.metrics || typeof data.metrics !== 'object') {
368
+ errors.push('Missing or invalid metrics field');
369
+ }
370
+ if (!Array.isArray(data.unlockedAchievements)) {
371
+ errors.push('Missing or invalid unlockedAchievements field');
372
+ }
373
+ // Validate config hash if provided
374
+ if (expectedConfigHash && data.configHash && data.configHash !== expectedConfigHash) {
375
+ errors.push('Configuration mismatch: imported data may not be compatible with current achievement configuration');
376
+ }
377
+ // Validate metrics structure
378
+ if (data.metrics && typeof data.metrics === 'object') {
379
+ for (const [key, value] of Object.entries(data.metrics)) {
380
+ if (!Array.isArray(value)) {
381
+ errors.push(`Invalid metric format for "${key}": expected array, got ${typeof value}`);
382
+ }
383
+ }
384
+ }
385
+ // Validate achievement IDs are strings
386
+ if (Array.isArray(data.unlockedAchievements)) {
387
+ const invalidIds = data.unlockedAchievements.filter((id) => typeof id !== 'string');
388
+ if (invalidIds.length > 0) {
389
+ errors.push('All achievement IDs must be strings');
390
+ }
391
+ }
392
+ return errors;
393
+ }
394
+ /**
395
+ * Merges two metrics objects, keeping higher values for overlapping keys
396
+ */
397
+ function mergeMetrics(current, imported) {
398
+ const merged = Object.assign({}, current);
399
+ for (const [key, importedValues] of Object.entries(imported)) {
400
+ if (!merged[key]) {
401
+ // New metric, add it
402
+ merged[key] = importedValues;
403
+ }
404
+ else {
405
+ // Existing metric, merge values
406
+ merged[key] = mergeMetricValues(merged[key], importedValues);
407
+ }
408
+ }
409
+ return merged;
410
+ }
411
+ /**
412
+ * Merges two metric value arrays, keeping higher numeric values
413
+ */
414
+ function mergeMetricValues(current, imported) {
415
+ // For simplicity, we'll use the imported values if they're "higher"
416
+ // This works for numeric values; for other types, we prefer imported
417
+ const currentValue = current[0];
418
+ const importedValue = imported[0];
419
+ // If both are numbers, keep the higher one
420
+ if (typeof currentValue === 'number' && typeof importedValue === 'number') {
421
+ return currentValue >= importedValue ? current : imported;
422
+ }
423
+ // For non-numeric values, prefer imported (assume it's newer)
424
+ return imported;
425
+ }
426
+ /**
427
+ * Preserves existing metrics, only adding new ones from imported data
428
+ */
429
+ function preserveMetrics(current, imported) {
430
+ const preserved = Object.assign({}, current);
431
+ for (const [key, value] of Object.entries(imported)) {
432
+ if (!preserved[key]) {
433
+ // Only add if it doesn't exist
434
+ preserved[key] = value;
435
+ }
436
+ // If it exists, keep current value (preserve strategy)
437
+ }
438
+ return preserved;
439
+ }
440
+
441
+ /**
442
+ * Type definitions for the achievements engine
443
+ * Framework-agnostic achievement system types
444
+ */
445
+ const isDate = (value) => {
446
+ return value instanceof Date;
447
+ };
448
+ // Type guard to detect async storage
449
+ function isAsyncStorage(storage) {
450
+ // Check if methods return Promises
451
+ const testResult = storage.getMetrics();
452
+ return testResult && typeof testResult.then === 'function';
453
+ }
454
+ var StorageType;
455
+ (function (StorageType) {
456
+ StorageType["Local"] = "local";
457
+ StorageType["Memory"] = "memory";
458
+ StorageType["IndexedDB"] = "indexeddb";
459
+ StorageType["RestAPI"] = "restapi"; // Asynchronous REST API storage
460
+ })(StorageType || (StorageType = {}));
461
+
462
+ /**
463
+ * Base error class for all achievement-related errors
464
+ */
465
+ class AchievementError extends Error {
466
+ constructor(message, code, recoverable, remedy) {
467
+ super(message);
468
+ this.code = code;
469
+ this.recoverable = recoverable;
470
+ this.remedy = remedy;
471
+ this.name = 'AchievementError';
472
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
473
+ if (Error.captureStackTrace) {
474
+ Error.captureStackTrace(this, AchievementError);
475
+ }
476
+ }
477
+ }
478
+ /**
479
+ * Error thrown when browser storage quota is exceeded
480
+ */
481
+ class StorageQuotaError extends AchievementError {
482
+ constructor(bytesNeeded) {
483
+ super('Browser storage quota exceeded. Achievement data could not be saved.', 'STORAGE_QUOTA_EXCEEDED', true, 'Clear browser storage, reduce the number of achievements, or use an external database backend. You can export your current data using exportData() before clearing storage.');
484
+ this.bytesNeeded = bytesNeeded;
485
+ this.name = 'StorageQuotaError';
486
+ }
487
+ }
488
+ /**
489
+ * Error thrown when imported data fails validation
490
+ */
491
+ class ImportValidationError extends AchievementError {
492
+ constructor(validationErrors) {
493
+ super(`Imported data failed validation: ${validationErrors.join(', ')}`, 'IMPORT_VALIDATION_ERROR', true, 'Check that the imported data was exported from a compatible version and matches your current achievement configuration.');
494
+ this.validationErrors = validationErrors;
495
+ this.name = 'ImportValidationError';
496
+ }
497
+ }
498
+ /**
499
+ * Error thrown when storage operations fail
500
+ */
501
+ class StorageError extends AchievementError {
502
+ constructor(message, originalError) {
503
+ super(message, 'STORAGE_ERROR', true, 'Check browser storage permissions and available space. If using custom storage, verify the implementation is correct.');
504
+ this.originalError = originalError;
505
+ this.name = 'StorageError';
506
+ }
507
+ }
508
+ /**
509
+ * Error thrown when configuration is invalid
510
+ */
511
+ class ConfigurationError extends AchievementError {
512
+ constructor(message) {
513
+ super(message, 'CONFIGURATION_ERROR', false, 'Review your achievement configuration and ensure it follows the correct format.');
514
+ this.name = 'ConfigurationError';
515
+ }
516
+ }
517
+ /**
518
+ * Error thrown when network sync operations fail
519
+ */
520
+ class SyncError extends AchievementError {
521
+ constructor(message, details) {
522
+ super(message, 'SYNC_ERROR', true, // recoverable (can retry)
523
+ 'Check your network connection and try again. If the problem persists, achievements will sync when connection is restored.');
524
+ this.name = 'SyncError';
525
+ this.statusCode = details === null || details === void 0 ? void 0 : details.statusCode;
526
+ this.timeout = details === null || details === void 0 ? void 0 : details.timeout;
527
+ }
528
+ }
529
+ /**
530
+ * Type guard to check if an error is an AchievementError
531
+ */
532
+ function isAchievementError(error) {
533
+ return error instanceof AchievementError;
534
+ }
535
+ /**
536
+ * Type guard to check if an error is recoverable
537
+ */
538
+ function isRecoverableError(error) {
539
+ return isAchievementError(error) && error.recoverable;
540
+ }
541
+
542
+ class LocalStorage {
543
+ constructor(storageKey) {
544
+ this.storageKey = storageKey;
545
+ }
546
+ serializeValue(value) {
547
+ if (isDate(value)) {
548
+ return { __type: 'Date', value: value.toISOString() };
549
+ }
550
+ return value;
551
+ }
552
+ deserializeValue(value) {
553
+ if (value && typeof value === 'object' && value.__type === 'Date') {
554
+ return new Date(value.value);
555
+ }
556
+ return value;
557
+ }
558
+ serializeMetrics(metrics) {
559
+ const serialized = {};
560
+ for (const [key, values] of Object.entries(metrics)) {
561
+ serialized[key] = values.map(this.serializeValue);
562
+ }
563
+ return serialized;
564
+ }
565
+ deserializeMetrics(metrics) {
566
+ if (!metrics)
567
+ return {};
568
+ const deserialized = {};
569
+ for (const [key, values] of Object.entries(metrics)) {
570
+ deserialized[key] = values.map(this.deserializeValue);
571
+ }
572
+ return deserialized;
573
+ }
574
+ getStorageData() {
575
+ const data = localStorage.getItem(this.storageKey);
576
+ if (!data)
577
+ return { metrics: {}, unlockedAchievements: [] };
578
+ try {
579
+ const parsed = JSON.parse(data);
580
+ return {
581
+ metrics: this.deserializeMetrics(parsed.metrics || {}),
582
+ unlockedAchievements: parsed.unlockedAchievements || []
583
+ };
584
+ }
585
+ catch (_a) {
586
+ return { metrics: {}, unlockedAchievements: [] };
587
+ }
588
+ }
589
+ setStorageData(data) {
590
+ try {
591
+ const serialized = {
592
+ metrics: this.serializeMetrics(data.metrics),
593
+ unlockedAchievements: data.unlockedAchievements
594
+ };
595
+ const jsonString = JSON.stringify(serialized);
596
+ localStorage.setItem(this.storageKey, jsonString);
597
+ }
598
+ catch (error) {
599
+ // Throw proper error instead of silently failing
600
+ if (error instanceof DOMException &&
601
+ (error.name === 'QuotaExceededError' ||
602
+ error.name === 'NS_ERROR_DOM_QUOTA_REACHED')) {
603
+ const serialized = {
604
+ metrics: this.serializeMetrics(data.metrics),
605
+ unlockedAchievements: data.unlockedAchievements
606
+ };
607
+ const bytesNeeded = JSON.stringify(serialized).length;
608
+ throw new StorageQuotaError(bytesNeeded);
609
+ }
610
+ if (error instanceof Error) {
611
+ if (error.message && error.message.includes('QuotaExceeded')) {
612
+ const serialized = {
613
+ metrics: this.serializeMetrics(data.metrics),
614
+ unlockedAchievements: data.unlockedAchievements
615
+ };
616
+ const bytesNeeded = JSON.stringify(serialized).length;
617
+ throw new StorageQuotaError(bytesNeeded);
618
+ }
619
+ throw new StorageError(`Failed to save achievement data: ${error.message}`, error);
620
+ }
621
+ throw new StorageError('Failed to save achievement data');
622
+ }
623
+ }
624
+ getMetrics() {
625
+ return this.getStorageData().metrics;
626
+ }
627
+ setMetrics(metrics) {
628
+ const data = this.getStorageData();
629
+ this.setStorageData(Object.assign(Object.assign({}, data), { metrics }));
630
+ }
631
+ getUnlockedAchievements() {
632
+ return this.getStorageData().unlockedAchievements;
633
+ }
634
+ setUnlockedAchievements(achievements) {
635
+ const data = this.getStorageData();
636
+ this.setStorageData(Object.assign(Object.assign({}, data), { unlockedAchievements: achievements }));
637
+ }
638
+ clear() {
639
+ localStorage.removeItem(this.storageKey);
640
+ }
641
+ }
642
+
643
+ class MemoryStorage {
644
+ constructor() {
645
+ this.metrics = {};
646
+ this.unlockedAchievements = [];
647
+ }
648
+ getMetrics() {
649
+ return this.metrics;
650
+ }
651
+ setMetrics(metrics) {
652
+ this.metrics = metrics;
653
+ }
654
+ getUnlockedAchievements() {
655
+ return this.unlockedAchievements;
656
+ }
657
+ setUnlockedAchievements(achievements) {
658
+ this.unlockedAchievements = achievements;
659
+ }
660
+ clear() {
661
+ this.metrics = {};
662
+ this.unlockedAchievements = [];
663
+ }
664
+ }
665
+
666
+ /******************************************************************************
667
+ Copyright (c) Microsoft Corporation.
668
+
669
+ Permission to use, copy, modify, and/or distribute this software for any
670
+ purpose with or without fee is hereby granted.
671
+
672
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
673
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
674
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
675
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
676
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
677
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
678
+ PERFORMANCE OF THIS SOFTWARE.
679
+ ***************************************************************************** */
680
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
681
+
682
+
683
+ function __awaiter(thisArg, _arguments, P, generator) {
684
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
685
+ return new (P || (P = Promise))(function (resolve, reject) {
686
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
687
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
688
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
689
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
690
+ });
691
+ }
692
+
693
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
694
+ var e = new Error(message);
695
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
696
+ };
697
+
698
+ class IndexedDBStorage {
699
+ constructor(dbName = 'react-achievements') {
700
+ this.storeName = 'achievements';
701
+ this.db = null;
702
+ this.dbName = dbName;
703
+ this.initPromise = this.initDB();
704
+ }
705
+ /**
706
+ * Initialize IndexedDB database and object store
707
+ */
708
+ initDB() {
709
+ return __awaiter(this, void 0, void 0, function* () {
710
+ return new Promise((resolve, reject) => {
711
+ const request = indexedDB.open(this.dbName, 1);
712
+ request.onerror = () => {
713
+ reject(new StorageError('Failed to open IndexedDB'));
714
+ };
715
+ request.onsuccess = () => {
716
+ this.db = request.result;
717
+ resolve();
718
+ };
719
+ request.onupgradeneeded = (event) => {
720
+ const db = event.target.result;
721
+ // Create object store if it doesn't exist
722
+ if (!db.objectStoreNames.contains(this.storeName)) {
723
+ db.createObjectStore(this.storeName);
724
+ }
725
+ };
726
+ });
727
+ });
728
+ }
729
+ /**
730
+ * Generic get operation from IndexedDB
731
+ */
732
+ get(key) {
733
+ return __awaiter(this, void 0, void 0, function* () {
734
+ yield this.initPromise;
735
+ if (!this.db)
736
+ throw new StorageError('Database not initialized');
737
+ return new Promise((resolve, reject) => {
738
+ const transaction = this.db.transaction([this.storeName], 'readonly');
739
+ const store = transaction.objectStore(this.storeName);
740
+ const request = store.get(key);
741
+ request.onsuccess = () => {
742
+ resolve(request.result || null);
743
+ };
744
+ request.onerror = () => {
745
+ reject(new StorageError(`Failed to read from IndexedDB: ${key}`));
746
+ };
747
+ transaction.onerror = () => {
748
+ reject(new StorageError(`Transaction failed for key: ${key}`));
749
+ };
750
+ });
751
+ });
752
+ }
753
+ /**
754
+ * Generic set operation to IndexedDB
755
+ */
756
+ set(key, value) {
757
+ return __awaiter(this, void 0, void 0, function* () {
758
+ yield this.initPromise;
759
+ if (!this.db)
760
+ throw new StorageError('Database not initialized');
761
+ return new Promise((resolve, reject) => {
762
+ const transaction = this.db.transaction([this.storeName], 'readwrite');
763
+ const store = transaction.objectStore(this.storeName);
764
+ const request = store.put(value, key);
765
+ request.onsuccess = () => {
766
+ resolve();
767
+ };
768
+ request.onerror = () => {
769
+ reject(new StorageError(`Failed to write to IndexedDB: ${key}`));
770
+ };
771
+ transaction.onerror = () => {
772
+ reject(new StorageError(`Transaction failed for key: ${key}`));
773
+ };
774
+ });
775
+ });
776
+ }
777
+ /**
778
+ * Delete operation from IndexedDB
779
+ */
780
+ delete(key) {
781
+ return __awaiter(this, void 0, void 0, function* () {
782
+ yield this.initPromise;
783
+ if (!this.db)
784
+ throw new StorageError('Database not initialized');
785
+ return new Promise((resolve, reject) => {
786
+ const transaction = this.db.transaction([this.storeName], 'readwrite');
787
+ const store = transaction.objectStore(this.storeName);
788
+ const request = store.delete(key);
789
+ request.onsuccess = () => {
790
+ resolve();
791
+ };
792
+ request.onerror = () => {
793
+ reject(new StorageError(`Failed to delete from IndexedDB: ${key}`));
794
+ };
795
+ transaction.onerror = () => {
796
+ reject(new StorageError(`Transaction failed while deleting key: ${key}`));
797
+ };
798
+ });
799
+ });
800
+ }
801
+ getMetrics() {
802
+ return __awaiter(this, void 0, void 0, function* () {
803
+ const metrics = yield this.get('metrics');
804
+ return metrics || {};
805
+ });
806
+ }
807
+ setMetrics(metrics) {
808
+ return __awaiter(this, void 0, void 0, function* () {
809
+ yield this.set('metrics', metrics);
810
+ });
811
+ }
812
+ getUnlockedAchievements() {
813
+ return __awaiter(this, void 0, void 0, function* () {
814
+ const unlocked = yield this.get('unlocked');
815
+ return unlocked || [];
816
+ });
817
+ }
818
+ setUnlockedAchievements(achievements) {
819
+ return __awaiter(this, void 0, void 0, function* () {
820
+ yield this.set('unlocked', achievements);
821
+ });
822
+ }
823
+ clear() {
824
+ return __awaiter(this, void 0, void 0, function* () {
825
+ yield Promise.all([
826
+ this.delete('metrics'),
827
+ this.delete('unlocked')
828
+ ]);
829
+ });
830
+ }
831
+ /**
832
+ * Close the database connection
833
+ */
834
+ close() {
835
+ if (this.db) {
836
+ this.db.close();
837
+ this.db = null;
838
+ }
839
+ }
840
+ }
841
+
842
+ class RestApiStorage {
843
+ constructor(config) {
844
+ this.config = Object.assign({ timeout: 10000, headers: {} }, config);
845
+ }
846
+ /**
847
+ * Generic fetch wrapper with timeout and error handling
848
+ */
849
+ fetchWithTimeout(url, options) {
850
+ return __awaiter(this, void 0, void 0, function* () {
851
+ const controller = new AbortController();
852
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
853
+ try {
854
+ const response = yield fetch(url, Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({ 'Content-Type': 'application/json' }, this.config.headers), options.headers), signal: controller.signal }));
855
+ clearTimeout(timeoutId);
856
+ if (!response.ok) {
857
+ throw new SyncError(`HTTP ${response.status}: ${response.statusText}`, { statusCode: response.status });
858
+ }
859
+ return response;
860
+ }
861
+ catch (error) {
862
+ clearTimeout(timeoutId);
863
+ if (error instanceof Error && error.name === 'AbortError') {
864
+ throw new SyncError('Request timeout', { timeout: this.config.timeout });
865
+ }
866
+ throw error;
867
+ }
868
+ });
869
+ }
870
+ getMetrics() {
871
+ return __awaiter(this, void 0, void 0, function* () {
872
+ var _a;
873
+ try {
874
+ const url = `${this.config.baseUrl}/users/${this.config.userId}/achievements/metrics`;
875
+ const response = yield this.fetchWithTimeout(url, { method: 'GET' });
876
+ const data = yield response.json();
877
+ return data.metrics || {};
878
+ }
879
+ catch (error) {
880
+ // Re-throw SyncError and other AchievementErrors (but not StorageError)
881
+ // Multiple checks for Jest compatibility
882
+ const err = error;
883
+ if (((_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'SyncError' || (err === null || err === void 0 ? void 0 : err.name) === 'SyncError') {
884
+ throw error;
885
+ }
886
+ // Also check instanceof for normal cases
887
+ if (error instanceof AchievementError && !(error instanceof StorageError)) {
888
+ throw error;
889
+ }
890
+ throw new StorageError('Failed to fetch metrics from API', error);
891
+ }
892
+ });
893
+ }
894
+ setMetrics(metrics) {
895
+ return __awaiter(this, void 0, void 0, function* () {
896
+ var _a;
897
+ try {
898
+ const url = `${this.config.baseUrl}/users/${this.config.userId}/achievements/metrics`;
899
+ yield this.fetchWithTimeout(url, {
900
+ method: 'PUT',
901
+ body: JSON.stringify({ metrics })
902
+ });
903
+ }
904
+ catch (error) {
905
+ const err = error;
906
+ if (((_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'SyncError' || (err === null || err === void 0 ? void 0 : err.name) === 'SyncError')
907
+ throw error;
908
+ if (error instanceof AchievementError && !(error instanceof StorageError))
909
+ throw error;
910
+ throw new StorageError('Failed to save metrics to API', error);
911
+ }
912
+ });
913
+ }
914
+ getUnlockedAchievements() {
915
+ return __awaiter(this, void 0, void 0, function* () {
916
+ var _a;
917
+ try {
918
+ const url = `${this.config.baseUrl}/users/${this.config.userId}/achievements/unlocked`;
919
+ const response = yield this.fetchWithTimeout(url, { method: 'GET' });
920
+ const data = yield response.json();
921
+ return data.unlocked || [];
922
+ }
923
+ catch (error) {
924
+ const err = error;
925
+ if (((_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'SyncError' || (err === null || err === void 0 ? void 0 : err.name) === 'SyncError')
926
+ throw error;
927
+ if (error instanceof AchievementError && !(error instanceof StorageError))
928
+ throw error;
929
+ throw new StorageError('Failed to fetch unlocked achievements from API', error);
930
+ }
931
+ });
932
+ }
933
+ setUnlockedAchievements(achievements) {
934
+ return __awaiter(this, void 0, void 0, function* () {
935
+ var _a;
936
+ try {
937
+ const url = `${this.config.baseUrl}/users/${this.config.userId}/achievements/unlocked`;
938
+ yield this.fetchWithTimeout(url, {
939
+ method: 'PUT',
940
+ body: JSON.stringify({ unlocked: achievements })
941
+ });
942
+ }
943
+ catch (error) {
944
+ const err = error;
945
+ if (((_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'SyncError' || (err === null || err === void 0 ? void 0 : err.name) === 'SyncError')
946
+ throw error;
947
+ if (error instanceof AchievementError && !(error instanceof StorageError))
948
+ throw error;
949
+ throw new StorageError('Failed to save unlocked achievements to API', error);
950
+ }
951
+ });
952
+ }
953
+ clear() {
954
+ return __awaiter(this, void 0, void 0, function* () {
955
+ var _a;
956
+ try {
957
+ const url = `${this.config.baseUrl}/users/${this.config.userId}/achievements`;
958
+ yield this.fetchWithTimeout(url, { method: 'DELETE' });
959
+ }
960
+ catch (error) {
961
+ const err = error;
962
+ if (((_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'SyncError' || (err === null || err === void 0 ? void 0 : err.name) === 'SyncError')
963
+ throw error;
964
+ if (error instanceof AchievementError && !(error instanceof StorageError))
965
+ throw error;
966
+ throw new StorageError('Failed to clear achievements via API', error);
967
+ }
968
+ });
969
+ }
970
+ }
971
+
972
+ class AsyncStorageAdapter {
973
+ constructor(asyncStorage, options) {
974
+ this.pendingWrites = [];
975
+ this.asyncStorage = asyncStorage;
976
+ this.onError = options === null || options === void 0 ? void 0 : options.onError;
977
+ this.cache = {
978
+ metrics: {},
979
+ unlocked: [],
980
+ loaded: false
981
+ };
982
+ // Eagerly load data from async storage (non-blocking)
983
+ this.initializeCache();
984
+ }
985
+ /**
986
+ * Initialize cache by loading from async storage
987
+ * This happens in the background during construction
988
+ */
989
+ initializeCache() {
990
+ return __awaiter(this, void 0, void 0, function* () {
991
+ try {
992
+ const [metrics, unlocked] = yield Promise.all([
993
+ this.asyncStorage.getMetrics(),
994
+ this.asyncStorage.getUnlockedAchievements()
995
+ ]);
996
+ this.cache.metrics = metrics;
997
+ this.cache.unlocked = unlocked;
998
+ this.cache.loaded = true;
999
+ }
1000
+ catch (error) {
1001
+ // Handle initialization errors
1002
+ console.error('Failed to initialize async storage:', error);
1003
+ if (this.onError) {
1004
+ const storageError = error instanceof AchievementError
1005
+ ? error
1006
+ : new StorageError('Failed to initialize storage', error);
1007
+ this.onError(storageError);
1008
+ }
1009
+ // Set to empty state on error
1010
+ this.cache.loaded = true; // Mark as loaded even on error to prevent blocking
1011
+ }
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Wait for cache to be loaded (used internally)
1016
+ * Returns immediately if already loaded, otherwise waits
1017
+ */
1018
+ ensureCacheLoaded() {
1019
+ return __awaiter(this, void 0, void 0, function* () {
1020
+ while (!this.cache.loaded) {
1021
+ yield new Promise(resolve => setTimeout(resolve, 10));
1022
+ }
1023
+ });
1024
+ }
1025
+ /**
1026
+ * SYNC READ: Returns cached metrics immediately
1027
+ * Cache is loaded eagerly during construction
1028
+ */
1029
+ getMetrics() {
1030
+ return this.cache.metrics;
1031
+ }
1032
+ /**
1033
+ * SYNC WRITE: Updates cache immediately, writes to storage in background
1034
+ * Uses optimistic updates - assumes write will succeed
1035
+ */
1036
+ setMetrics(metrics) {
1037
+ // Update cache immediately (optimistic update)
1038
+ this.cache.metrics = metrics;
1039
+ // Write to async storage in background
1040
+ const writePromise = this.asyncStorage.setMetrics(metrics).catch(error => {
1041
+ console.error('Failed to write metrics to async storage:', error);
1042
+ if (this.onError) {
1043
+ const storageError = error instanceof AchievementError
1044
+ ? error
1045
+ : new StorageError('Failed to write metrics', error);
1046
+ this.onError(storageError);
1047
+ }
1048
+ });
1049
+ // Track pending write for cleanup/testing
1050
+ this.pendingWrites.push(writePromise);
1051
+ }
1052
+ /**
1053
+ * SYNC READ: Returns cached unlocked achievements immediately
1054
+ */
1055
+ getUnlockedAchievements() {
1056
+ return this.cache.unlocked;
1057
+ }
1058
+ /**
1059
+ * SYNC WRITE: Updates cache immediately, writes to storage in background
1060
+ */
1061
+ setUnlockedAchievements(achievements) {
1062
+ // Update cache immediately (optimistic update)
1063
+ this.cache.unlocked = achievements;
1064
+ // Write to async storage in background
1065
+ const writePromise = this.asyncStorage.setUnlockedAchievements(achievements).catch(error => {
1066
+ console.error('Failed to write unlocked achievements to async storage:', error);
1067
+ if (this.onError) {
1068
+ const storageError = error instanceof AchievementError
1069
+ ? error
1070
+ : new StorageError('Failed to write achievements', error);
1071
+ this.onError(storageError);
1072
+ }
1073
+ });
1074
+ // Track pending write
1075
+ this.pendingWrites.push(writePromise);
1076
+ }
1077
+ /**
1078
+ * SYNC CLEAR: Clears cache immediately, clears storage in background
1079
+ */
1080
+ clear() {
1081
+ // Clear cache immediately
1082
+ this.cache.metrics = {};
1083
+ this.cache.unlocked = [];
1084
+ // Clear async storage in background
1085
+ const clearPromise = this.asyncStorage.clear().catch(error => {
1086
+ console.error('Failed to clear async storage:', error);
1087
+ if (this.onError) {
1088
+ const storageError = error instanceof AchievementError
1089
+ ? error
1090
+ : new StorageError('Failed to clear storage', error);
1091
+ this.onError(storageError);
1092
+ }
1093
+ });
1094
+ // Track pending write
1095
+ this.pendingWrites.push(clearPromise);
1096
+ }
1097
+ /**
1098
+ * Wait for all pending writes to complete (useful for testing/cleanup)
1099
+ * NOT part of AchievementStorage interface - utility method
1100
+ */
1101
+ flush() {
1102
+ return __awaiter(this, void 0, void 0, function* () {
1103
+ yield Promise.all(this.pendingWrites);
1104
+ this.pendingWrites = [];
1105
+ });
1106
+ }
1107
+ }
1108
+
1109
+ /**
1110
+ * AchievementEngine - Framework-agnostic achievement system
1111
+ * Event-based core with support for multiple storage backends
1112
+ */
1113
+ class AchievementEngine extends EventEmitter {
1114
+ constructor(config) {
1115
+ super();
1116
+ this.metrics = {};
1117
+ this.unlockedAchievements = [];
1118
+ this.config = config;
1119
+ // Normalize achievements configuration
1120
+ this.achievements = normalizeAchievements(config.achievements);
1121
+ // Create config hash for export/import validation
1122
+ this.configHash = createConfigHash(config.achievements);
1123
+ // Initialize storage
1124
+ this.storage = this.initializeStorage(config);
1125
+ // Load initial state from storage
1126
+ this.loadFromStorage();
1127
+ }
1128
+ /**
1129
+ * Initialize storage based on configuration
1130
+ */
1131
+ initializeStorage(config) {
1132
+ const { storage, onError, restApiConfig } = config;
1133
+ // If no storage specified, use memory storage
1134
+ if (!storage) {
1135
+ return new MemoryStorage();
1136
+ }
1137
+ // Handle string storage types
1138
+ if (typeof storage === 'string') {
1139
+ switch (storage) {
1140
+ case 'local':
1141
+ return new LocalStorage('achievements');
1142
+ case 'memory':
1143
+ return new MemoryStorage();
1144
+ case 'indexeddb': {
1145
+ const indexedDB = new IndexedDBStorage('achievements-engine');
1146
+ return new AsyncStorageAdapter(indexedDB, { onError });
1147
+ }
1148
+ case 'restapi': {
1149
+ if (!restApiConfig) {
1150
+ throw new Error('restApiConfig is required when using StorageType.RestAPI');
1151
+ }
1152
+ const restApi = new RestApiStorage(restApiConfig);
1153
+ return new AsyncStorageAdapter(restApi, { onError });
1154
+ }
1155
+ default:
1156
+ throw new Error(`Unsupported storage type: ${storage}`);
1157
+ }
1158
+ }
1159
+ // Handle custom storage instances
1160
+ const storageInstance = storage;
1161
+ if (typeof storageInstance.getMetrics === 'function') {
1162
+ // Check if async storage
1163
+ const testResult = storageInstance.getMetrics();
1164
+ if (testResult && typeof testResult.then === 'function') {
1165
+ return new AsyncStorageAdapter(storageInstance, { onError });
1166
+ }
1167
+ return storageInstance;
1168
+ }
1169
+ throw new Error('Invalid storage configuration');
1170
+ }
1171
+ /**
1172
+ * Load state from storage
1173
+ */
1174
+ loadFromStorage() {
1175
+ try {
1176
+ const savedMetrics = this.storage.getMetrics() || {};
1177
+ const savedUnlocked = this.storage.getUnlockedAchievements() || [];
1178
+ // Convert metrics from array format to simple format
1179
+ Object.entries(savedMetrics).forEach(([key, value]) => {
1180
+ this.metrics[key] = Array.isArray(value) ? value[0] : value;
1181
+ });
1182
+ this.unlockedAchievements = savedUnlocked;
1183
+ }
1184
+ catch (error) {
1185
+ this.handleError(error, 'loadFromStorage');
1186
+ }
1187
+ }
1188
+ /**
1189
+ * Save state to storage
1190
+ */
1191
+ saveToStorage() {
1192
+ try {
1193
+ // Convert metrics to array format for storage
1194
+ const metricsForStorage = {};
1195
+ Object.entries(this.metrics).forEach(([key, value]) => {
1196
+ metricsForStorage[key] = Array.isArray(value) ? value : [value];
1197
+ });
1198
+ this.storage.setMetrics(metricsForStorage);
1199
+ this.storage.setUnlockedAchievements(this.unlockedAchievements);
1200
+ }
1201
+ catch (error) {
1202
+ this.handleError(error, 'saveToStorage');
1203
+ }
1204
+ }
1205
+ /**
1206
+ * Handle errors with optional callback
1207
+ */
1208
+ handleError(error, context) {
1209
+ const errorEvent = {
1210
+ error,
1211
+ context,
1212
+ timestamp: Date.now()
1213
+ };
1214
+ // Emit error event
1215
+ this.emit('error', errorEvent);
1216
+ // Call config error handler if provided
1217
+ if (this.config.onError) {
1218
+ this.config.onError(error);
1219
+ }
1220
+ else {
1221
+ // Fallback to console.error if no error handler provided
1222
+ console.error('[AchievementEngine]', context ? `${context}:` : '', error);
1223
+ }
1224
+ }
1225
+ /**
1226
+ * Emit a custom event and optionally update metrics based on event mapping
1227
+ * @param eventName - Name of the event
1228
+ * @param data - Event data
1229
+ */
1230
+ emit(eventName, data) {
1231
+ // If this is a mapped event, update metrics
1232
+ if (this.config.eventMapping && eventName in this.config.eventMapping) {
1233
+ const mapping = this.config.eventMapping[eventName];
1234
+ if (typeof mapping === 'string') {
1235
+ // Direct mapping: event name -> metric name
1236
+ this.update({ [mapping]: data });
1237
+ }
1238
+ else if (typeof mapping === 'function') {
1239
+ // Custom transformer function
1240
+ const metricsUpdate = mapping(data, Object.assign({}, this.metrics));
1241
+ this.update(metricsUpdate);
1242
+ }
1243
+ }
1244
+ // Emit the event to listeners
1245
+ super.emit(eventName, data);
1246
+ }
1247
+ /**
1248
+ * Update metrics and evaluate achievements
1249
+ * @param newMetrics - Metrics to update
1250
+ */
1251
+ update(newMetrics) {
1252
+ Object.assign({}, this.metrics);
1253
+ // Update metrics
1254
+ Object.entries(newMetrics).forEach(([key, value]) => {
1255
+ const oldValue = this.metrics[key];
1256
+ this.metrics[key] = value;
1257
+ // Emit metric updated event
1258
+ if (oldValue !== value) {
1259
+ const metricEvent = {
1260
+ metric: key,
1261
+ oldValue,
1262
+ newValue: value,
1263
+ timestamp: Date.now()
1264
+ };
1265
+ super.emit('metric:updated', metricEvent);
1266
+ }
1267
+ });
1268
+ // Evaluate achievements
1269
+ this.evaluateAchievements();
1270
+ // Save to storage
1271
+ this.saveToStorage();
1272
+ // Emit state changed event
1273
+ const stateEvent = {
1274
+ metrics: this.getMetricsAsArray(),
1275
+ unlocked: [...this.unlockedAchievements],
1276
+ timestamp: Date.now()
1277
+ };
1278
+ super.emit('state:changed', stateEvent);
1279
+ }
1280
+ /**
1281
+ * Evaluate all achievements and unlock any newly met conditions
1282
+ * This is the core evaluation logic extracted from AchievementProvider
1283
+ */
1284
+ evaluateAchievements() {
1285
+ const newlyUnlockedAchievements = [];
1286
+ // Convert metrics to array format for condition checking
1287
+ const metricsInArrayFormat = this.getMetricsAsArray();
1288
+ // Iterate through all achievements
1289
+ Object.entries(this.achievements).forEach(([metricName, metricAchievements]) => {
1290
+ metricAchievements.forEach((achievement) => {
1291
+ const state = {
1292
+ metrics: metricsInArrayFormat,
1293
+ unlockedAchievements: this.unlockedAchievements
1294
+ };
1295
+ const achievementId = achievement.achievementDetails.achievementId;
1296
+ // Check if already unlocked
1297
+ if (this.unlockedAchievements.includes(achievementId)) {
1298
+ return;
1299
+ }
1300
+ // Get current value for this metric
1301
+ const currentValue = this.metrics[metricName];
1302
+ // For custom conditions, we always check against all metrics
1303
+ // For threshold-based conditions, we check against the specific metric
1304
+ const shouldCheckAchievement = currentValue !== undefined ||
1305
+ achievementId.includes('_custom_');
1306
+ if (shouldCheckAchievement) {
1307
+ const valueToCheck = currentValue;
1308
+ if (achievement.isConditionMet(valueToCheck, state)) {
1309
+ newlyUnlockedAchievements.push(achievementId);
1310
+ // Emit achievement unlocked event
1311
+ const unlockEvent = {
1312
+ achievementId,
1313
+ achievementTitle: achievement.achievementDetails.achievementTitle || 'Achievement Unlocked!',
1314
+ achievementDescription: achievement.achievementDetails.achievementDescription || '',
1315
+ achievementIconKey: achievement.achievementDetails.achievementIconKey,
1316
+ timestamp: Date.now()
1317
+ };
1318
+ super.emit('achievement:unlocked', unlockEvent);
1319
+ }
1320
+ }
1321
+ });
1322
+ });
1323
+ // Add newly unlocked achievements to the list
1324
+ if (newlyUnlockedAchievements.length > 0) {
1325
+ this.unlockedAchievements = [...this.unlockedAchievements, ...newlyUnlockedAchievements];
1326
+ }
1327
+ }
1328
+ /**
1329
+ * Get metrics in array format (for backward compatibility with storage)
1330
+ */
1331
+ getMetricsAsArray() {
1332
+ const metricsInArrayFormat = {};
1333
+ Object.entries(this.metrics).forEach(([key, value]) => {
1334
+ metricsInArrayFormat[key] = Array.isArray(value) ? value : [value];
1335
+ });
1336
+ return metricsInArrayFormat;
1337
+ }
1338
+ /**
1339
+ * Get current metrics (readonly to prevent external modification)
1340
+ */
1341
+ getMetrics() {
1342
+ return Object.freeze(Object.assign({}, this.metrics));
1343
+ }
1344
+ /**
1345
+ * Get unlocked achievement IDs (readonly)
1346
+ */
1347
+ getUnlocked() {
1348
+ return Object.freeze([...this.unlockedAchievements]);
1349
+ }
1350
+ /**
1351
+ * Get all achievements with their unlock status
1352
+ */
1353
+ getAllAchievements() {
1354
+ const result = [];
1355
+ Object.entries(this.achievements).forEach(([_metricName, metricAchievements]) => {
1356
+ metricAchievements.forEach((achievement) => {
1357
+ const { achievementDetails } = achievement;
1358
+ const isUnlocked = this.unlockedAchievements.includes(achievementDetails.achievementId);
1359
+ result.push({
1360
+ achievementId: achievementDetails.achievementId,
1361
+ achievementTitle: achievementDetails.achievementTitle || '',
1362
+ achievementDescription: achievementDetails.achievementDescription || '',
1363
+ achievementIconKey: achievementDetails.achievementIconKey,
1364
+ isUnlocked
1365
+ });
1366
+ });
1367
+ });
1368
+ return result;
1369
+ }
1370
+ /**
1371
+ * Reset all achievement data
1372
+ */
1373
+ reset() {
1374
+ this.metrics = {};
1375
+ this.unlockedAchievements = [];
1376
+ try {
1377
+ this.storage.clear();
1378
+ }
1379
+ catch (error) {
1380
+ this.handleError(error, 'reset');
1381
+ }
1382
+ // Emit state changed event
1383
+ const stateEvent = {
1384
+ metrics: {},
1385
+ unlocked: [],
1386
+ timestamp: Date.now()
1387
+ };
1388
+ super.emit('state:changed', stateEvent);
1389
+ }
1390
+ /**
1391
+ * Clean up resources and event listeners
1392
+ */
1393
+ destroy() {
1394
+ this.removeAllListeners();
1395
+ }
1396
+ /**
1397
+ * Export achievement data as JSON string
1398
+ */
1399
+ export() {
1400
+ const metricsInArrayFormat = this.getMetricsAsArray();
1401
+ return exportAchievementData(metricsInArrayFormat, this.unlockedAchievements, this.configHash);
1402
+ }
1403
+ /**
1404
+ * Import achievement data from JSON string
1405
+ * @param jsonString - Exported achievement data
1406
+ * @param options - Import options
1407
+ */
1408
+ import(jsonString, options) {
1409
+ var _a;
1410
+ const metricsInArrayFormat = this.getMetricsAsArray();
1411
+ // Transform options from public API format to internal format
1412
+ const internalOptions = {
1413
+ mergeStrategy: (options === null || options === void 0 ? void 0 : options.merge) ? 'merge' :
1414
+ (options === null || options === void 0 ? void 0 : options.overwrite) ? 'replace' :
1415
+ 'replace',
1416
+ validate: (_a = options === null || options === void 0 ? void 0 : options.validateConfig) !== null && _a !== void 0 ? _a : true,
1417
+ expectedConfigHash: this.configHash
1418
+ };
1419
+ const result = importAchievementData(jsonString, metricsInArrayFormat, this.unlockedAchievements, internalOptions);
1420
+ if (result.success && 'mergedMetrics' in result && 'mergedUnlocked' in result) {
1421
+ // Convert metrics from array format to simple format
1422
+ const mergedMetrics = {};
1423
+ Object.entries(result.mergedMetrics).forEach(([key, value]) => {
1424
+ mergedMetrics[key] = Array.isArray(value) ? value[0] : value;
1425
+ });
1426
+ this.metrics = mergedMetrics;
1427
+ this.unlockedAchievements = result.mergedUnlocked || [];
1428
+ // Save to storage
1429
+ this.saveToStorage();
1430
+ // Emit state changed event
1431
+ const stateEvent = {
1432
+ metrics: this.getMetricsAsArray(),
1433
+ unlocked: [...this.unlockedAchievements],
1434
+ timestamp: Date.now()
1435
+ };
1436
+ super.emit('state:changed', stateEvent);
1437
+ }
1438
+ return result;
1439
+ }
1440
+ /**
1441
+ * Subscribe to engine events
1442
+ * @param event - Event name
1443
+ * @param handler - Event handler
1444
+ */
1445
+ on(event, handler) {
1446
+ return super.on(event, handler);
1447
+ }
1448
+ /**
1449
+ * Subscribe to an event once
1450
+ * @param event - Event name
1451
+ * @param handler - Event handler
1452
+ */
1453
+ once(event, handler) {
1454
+ return super.once(event, handler);
1455
+ }
1456
+ /**
1457
+ * Unsubscribe from an event
1458
+ * @param event - Event name
1459
+ * @param handler - Event handler
1460
+ */
1461
+ off(event, handler) {
1462
+ return super.off(event, handler);
1463
+ }
1464
+ }
1465
+
1466
+ class OfflineQueueStorage {
1467
+ constructor(innerStorage) {
1468
+ this.queue = [];
1469
+ this.isOnline = typeof navigator !== 'undefined' ? navigator.onLine : true;
1470
+ this.isSyncing = false;
1471
+ this.queueStorageKey = 'achievements_offline_queue';
1472
+ this.handleOnline = () => {
1473
+ this.isOnline = true;
1474
+ console.log('[OfflineQueue] Back online, processing queue...');
1475
+ this.processQueue();
1476
+ };
1477
+ this.handleOffline = () => {
1478
+ this.isOnline = false;
1479
+ console.log('[OfflineQueue] Offline mode activated');
1480
+ };
1481
+ this.innerStorage = innerStorage;
1482
+ // Load queued operations from localStorage
1483
+ this.loadQueue();
1484
+ // Listen for online/offline events (only in browser environment)
1485
+ if (typeof window !== 'undefined') {
1486
+ window.addEventListener('online', this.handleOnline);
1487
+ window.addEventListener('offline', this.handleOffline);
1488
+ }
1489
+ // Process queue if already online
1490
+ if (this.isOnline) {
1491
+ this.processQueue();
1492
+ }
1493
+ }
1494
+ loadQueue() {
1495
+ try {
1496
+ if (typeof localStorage !== 'undefined') {
1497
+ const queueData = localStorage.getItem(this.queueStorageKey);
1498
+ if (queueData) {
1499
+ this.queue = JSON.parse(queueData);
1500
+ }
1501
+ }
1502
+ }
1503
+ catch (error) {
1504
+ console.error('Failed to load offline queue:', error);
1505
+ this.queue = [];
1506
+ }
1507
+ }
1508
+ saveQueue() {
1509
+ try {
1510
+ if (typeof localStorage !== 'undefined') {
1511
+ localStorage.setItem(this.queueStorageKey, JSON.stringify(this.queue));
1512
+ }
1513
+ }
1514
+ catch (error) {
1515
+ console.error('Failed to save offline queue:', error);
1516
+ }
1517
+ }
1518
+ processQueue() {
1519
+ return __awaiter(this, void 0, void 0, function* () {
1520
+ if (this.isSyncing || this.queue.length === 0 || !this.isOnline) {
1521
+ return;
1522
+ }
1523
+ this.isSyncing = true;
1524
+ try {
1525
+ // Process operations in order
1526
+ while (this.queue.length > 0 && this.isOnline) {
1527
+ const operation = this.queue[0];
1528
+ try {
1529
+ switch (operation.type) {
1530
+ case 'setMetrics':
1531
+ yield this.innerStorage.setMetrics(operation.data);
1532
+ break;
1533
+ case 'setUnlockedAchievements':
1534
+ yield this.innerStorage.setUnlockedAchievements(operation.data);
1535
+ break;
1536
+ case 'clear':
1537
+ yield this.innerStorage.clear();
1538
+ break;
1539
+ }
1540
+ // Operation succeeded, remove from queue
1541
+ this.queue.shift();
1542
+ this.saveQueue();
1543
+ }
1544
+ catch (error) {
1545
+ console.error('Failed to sync queued operation:', error);
1546
+ // Stop processing on error, will retry later
1547
+ break;
1548
+ }
1549
+ }
1550
+ }
1551
+ finally {
1552
+ this.isSyncing = false;
1553
+ }
1554
+ });
1555
+ }
1556
+ queueOperation(type, data) {
1557
+ const operation = {
1558
+ id: `${Date.now()}_${Math.random()}`,
1559
+ type,
1560
+ data,
1561
+ timestamp: Date.now()
1562
+ };
1563
+ this.queue.push(operation);
1564
+ this.saveQueue();
1565
+ // Try to process queue if online
1566
+ if (this.isOnline) {
1567
+ this.processQueue();
1568
+ }
1569
+ }
1570
+ getMetrics() {
1571
+ return __awaiter(this, void 0, void 0, function* () {
1572
+ // Reads always try to hit the server first
1573
+ try {
1574
+ return yield this.innerStorage.getMetrics();
1575
+ }
1576
+ catch (error) {
1577
+ if (!this.isOnline) {
1578
+ throw new StorageError('Cannot read metrics while offline');
1579
+ }
1580
+ throw error;
1581
+ }
1582
+ });
1583
+ }
1584
+ setMetrics(metrics) {
1585
+ return __awaiter(this, void 0, void 0, function* () {
1586
+ if (this.isOnline) {
1587
+ try {
1588
+ yield this.innerStorage.setMetrics(metrics);
1589
+ return;
1590
+ }
1591
+ catch (error) {
1592
+ // Failed while online, queue it
1593
+ console.warn('Failed to set metrics, queuing for later:', error);
1594
+ }
1595
+ }
1596
+ // Queue operation if offline or if online operation failed
1597
+ this.queueOperation('setMetrics', metrics);
1598
+ });
1599
+ }
1600
+ getUnlockedAchievements() {
1601
+ return __awaiter(this, void 0, void 0, function* () {
1602
+ // Reads always try to hit the server first
1603
+ try {
1604
+ return yield this.innerStorage.getUnlockedAchievements();
1605
+ }
1606
+ catch (error) {
1607
+ if (!this.isOnline) {
1608
+ throw new StorageError('Cannot read achievements while offline');
1609
+ }
1610
+ throw error;
1611
+ }
1612
+ });
1613
+ }
1614
+ setUnlockedAchievements(achievements) {
1615
+ return __awaiter(this, void 0, void 0, function* () {
1616
+ if (this.isOnline) {
1617
+ try {
1618
+ yield this.innerStorage.setUnlockedAchievements(achievements);
1619
+ return;
1620
+ }
1621
+ catch (error) {
1622
+ // Failed while online, queue it
1623
+ console.warn('Failed to set unlocked achievements, queuing for later:', error);
1624
+ }
1625
+ }
1626
+ // Queue operation if offline or if online operation failed
1627
+ this.queueOperation('setUnlockedAchievements', achievements);
1628
+ });
1629
+ }
1630
+ clear() {
1631
+ return __awaiter(this, void 0, void 0, function* () {
1632
+ if (this.isOnline) {
1633
+ try {
1634
+ yield this.innerStorage.clear();
1635
+ // Also clear the queue
1636
+ this.queue = [];
1637
+ this.saveQueue();
1638
+ return;
1639
+ }
1640
+ catch (error) {
1641
+ console.warn('Failed to clear, queuing for later:', error);
1642
+ }
1643
+ }
1644
+ // Queue operation if offline or if online operation failed
1645
+ this.queueOperation('clear');
1646
+ });
1647
+ }
1648
+ /**
1649
+ * Manually trigger queue processing (useful for testing)
1650
+ */
1651
+ sync() {
1652
+ return __awaiter(this, void 0, void 0, function* () {
1653
+ yield this.processQueue();
1654
+ });
1655
+ }
1656
+ /**
1657
+ * Get current queue status (useful for debugging)
1658
+ */
1659
+ getQueueStatus() {
1660
+ return {
1661
+ pending: this.queue.length,
1662
+ operations: [...this.queue]
1663
+ };
1664
+ }
1665
+ /**
1666
+ * Cleanup listeners (call on unmount)
1667
+ */
1668
+ destroy() {
1669
+ if (typeof window !== 'undefined') {
1670
+ window.removeEventListener('online', this.handleOnline);
1671
+ window.removeEventListener('offline', this.handleOffline);
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ export { AchievementEngine, AchievementError, AsyncStorageAdapter, ConfigurationError, EventEmitter, ImportValidationError, IndexedDBStorage, LocalStorage, MemoryStorage, OfflineQueueStorage, RestApiStorage, StorageError, StorageQuotaError, StorageType, SyncError, createConfigHash, exportAchievementData, importAchievementData, isAchievementError, isAsyncStorage, isRecoverableError, normalizeAchievements };
1677
+ //# sourceMappingURL=index.esm.js.map