react-achievements 4.4.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import React from 'react';
2
2
  import * as achievements_engine from 'achievements-engine';
3
- import { AchievementSnapshot, ImportOptions, ImportResult, AchievementEngine, AchievementStorage as AchievementStorage$1, AsyncAchievementStorage as AsyncAchievementStorage$1, StorageType, RestApiStorageConfig, EventMapping, AchievementError } from 'achievements-engine';
3
+ import { AchievementUpdateResult, ImportOptions, ImportResult, AchievementEngine, AchievementStorage as AchievementStorage$1, AsyncAchievementStorage as AsyncAchievementStorage$1, StorageType, RestApiStorageConfig, EventMapping, AchievementError } from 'achievements-engine';
4
4
  export { AchievementBuilder, AchievementEngine, AchievementEngineApi, AchievementError, AchievementSnapshot, AchievementUnlockedEvent, AchievementUpdateResult, AsyncStorageAdapter, AwardDetails, ConfigurationError, EngineConfig, EngineEvent, ErrorEvent, EventMapping, ExportedData, ImportOptions, ImportResult, ImportValidationError, IndexedDBStorage, LocalStorage, MemoryStorage, MetricUpdatedEvent, MetricUpdater, OfflineQueueStorage, RestApiStorage, RestApiStorageConfig, StateChangedEvent, StorageError, StorageQuotaError, StorageType, SyncError, UnsubscribeFn, createConfigHash, exportAchievementData, importAchievementData, isAchievementError, isRecoverableError, isSimpleConfig, normalizeAchievements } from 'achievements-engine';
5
5
 
6
6
  type ConfettiShape = 'square' | 'circle' | 'star';
@@ -34,6 +34,13 @@ interface AchievementDetails {
34
34
  }
35
35
  interface AchievementWithStatus extends AchievementDetails {
36
36
  isUnlocked: boolean;
37
+ unlockedAt?: string | null;
38
+ progress?: {
39
+ current: number;
40
+ target: number;
41
+ percent: number;
42
+ };
43
+ metadata?: Record<string, unknown>;
37
44
  }
38
45
  type AchievementConfetti = false | ConfettiOptions;
39
46
  interface AchievementCondition {
@@ -102,14 +109,63 @@ interface AchievementContextValue {
102
109
  resetStorage: () => void;
103
110
  }
104
111
 
112
+ interface AchievementProgress {
113
+ current: number;
114
+ target: number;
115
+ percent: number;
116
+ }
117
+ interface AchievementDto {
118
+ id: string;
119
+ title: string;
120
+ description?: string;
121
+ icon?: string;
122
+ iconKey?: string;
123
+ isUnlocked: boolean;
124
+ unlockedAt?: string | null;
125
+ progress?: AchievementProgress;
126
+ metadata?: Record<string, unknown>;
127
+ confetti?: AchievementConfetti;
128
+ }
129
+ interface AchievementClientSnapshot {
130
+ achievements: AchievementDto[];
131
+ unlockedIds: string[];
132
+ unlockedAchievements: AchievementDto[];
133
+ unlockedCount: number;
134
+ totalCount: number;
135
+ metrics?: Record<string, unknown>;
136
+ }
137
+ interface AchievementClientMutationResult {
138
+ snapshot: AchievementClientSnapshot;
139
+ newlyUnlocked: AchievementDto[];
140
+ }
141
+ interface AchievementClient {
142
+ getSnapshot(): Promise<AchievementClientSnapshot>;
143
+ track(metric: string, value: unknown): Promise<AchievementClientMutationResult>;
144
+ trackMany?(metrics: Record<string, unknown>): Promise<AchievementClientMutationResult>;
145
+ increment(metric: string, amount?: number): Promise<AchievementClientMutationResult>;
146
+ event(name: string, payload?: unknown): Promise<AchievementClientMutationResult>;
147
+ reset?(): Promise<AchievementClientSnapshot>;
148
+ }
149
+
150
+ interface AchievementSnapshot {
151
+ metrics: Record<string, any>;
152
+ unlockedIds: string[];
153
+ unlockedAchievements: AchievementWithStatus[];
154
+ allAchievements: AchievementWithStatus[];
155
+ unlockedCount: number;
156
+ totalCount: number;
157
+ }
105
158
  interface AchievementContextType {
106
- update: (metrics: Record<string, any>) => void;
159
+ update: (metrics: Record<string, any>) => void | AchievementUpdateResult | Promise<AchievementClientMutationResult | void>;
160
+ increment: (metric: string, amount?: number) => AchievementUpdateResult | Promise<AchievementClientMutationResult | void> | void;
161
+ event: (name: string, payload?: unknown) => Promise<AchievementClientMutationResult | void> | void;
162
+ refresh: () => Promise<AchievementSnapshot>;
107
163
  achievements: {
108
164
  unlocked: string[];
109
165
  all: Record<string, AchievementWithStatus>;
110
166
  };
111
167
  snapshot: AchievementSnapshot;
112
- reset: () => void;
168
+ reset: () => void | Promise<void>;
113
169
  getState: () => {
114
170
  metrics: Record<string, any>;
115
171
  unlocked: string[];
@@ -117,8 +173,12 @@ interface AchievementContextType {
117
173
  exportData: () => string;
118
174
  importData: (jsonString: string, options?: ImportOptions) => ImportResult;
119
175
  getAllAchievements: () => AchievementWithStatus[];
120
- engine: AchievementEngine;
176
+ engine?: AchievementEngine;
177
+ client?: AchievementClient;
121
178
  icons: Record<string, string>;
179
+ recentlyUnlocked: AchievementWithStatus[];
180
+ isLoading: boolean;
181
+ error: Error | null;
122
182
  /**
123
183
  * @deprecated Use provider props or the presence of an injected engine directly.
124
184
  * This compatibility flag will be removed in 5.0.
@@ -127,6 +187,7 @@ interface AchievementContextType {
127
187
  }
128
188
  declare const AchievementContext: React.Context<AchievementContextType | undefined>;
129
189
  interface AchievementProviderProps {
190
+ client?: AchievementClient;
130
191
  achievements?: AchievementConfigurationType;
131
192
  storage?: AchievementStorage$1 | AsyncAchievementStorage$1 | StorageType;
132
193
  restApiConfig?: RestApiStorageConfig;
@@ -150,23 +211,28 @@ declare const useAchievements: () => AchievementContextType;
150
211
  * Provides the v4 happy path for direct metric updates plus explicit state names.
151
212
  */
152
213
  declare const useSimpleAchievements: () => {
153
- track: (metric: string, value: any) => void;
154
- increment: (metric: string, amount?: number) => achievements_engine.AchievementUpdateResult;
155
- trackMultiple: (metrics: Record<string, any>) => void;
214
+ track: (metric: string, value: any) => void | achievements_engine.AchievementUpdateResult | Promise<void | AchievementClientMutationResult>;
215
+ increment: (metric: string, amount?: number) => void | achievements_engine.AchievementUpdateResult | Promise<void | AchievementClientMutationResult>;
216
+ trackMultiple: (metrics: Record<string, any>) => void | achievements_engine.AchievementUpdateResult | Promise<void | AchievementClientMutationResult>;
156
217
  unlockedIds: string[];
157
- unlockedAchievements: achievements_engine.AchievementWithStatus[];
158
- allAchievements: achievements_engine.AchievementWithStatus[];
218
+ unlockedAchievements: AchievementWithStatus[];
219
+ allAchievements: AchievementWithStatus[];
159
220
  unlockedCount: number;
160
221
  totalCount: number;
161
- metrics: achievements_engine.AchievementMetrics;
162
- reset: () => void;
222
+ metrics: Record<string, any>;
223
+ isLoading: boolean;
224
+ error: Error | null;
225
+ event: (name: string, payload?: unknown) => Promise<AchievementClientMutationResult | void> | void;
226
+ emit: (name: string, payload?: unknown) => Promise<AchievementClientMutationResult | void> | void;
227
+ refresh: () => Promise<AchievementSnapshot>;
228
+ reset: () => void | Promise<void>;
163
229
  getState: () => {
164
230
  metrics: Record<string, any>;
165
231
  unlocked: string[];
166
232
  };
167
233
  exportData: () => string;
168
234
  importData: (jsonString: string, options?: achievements_engine.ImportOptions) => achievements_engine.ImportResult;
169
- getAllAchievements: () => achievements_engine.AchievementWithStatus[];
235
+ getAllAchievements: () => AchievementWithStatus[];
170
236
  /**
171
237
  * @deprecated Use `unlockedIds` instead. This alias will be removed in 5.0.
172
238
  */
@@ -174,16 +240,16 @@ declare const useSimpleAchievements: () => {
174
240
  /**
175
241
  * @deprecated Use `allAchievements` instead. This alias will be removed in 5.0.
176
242
  */
177
- all: achievements_engine.AchievementWithStatus[];
243
+ all: AchievementWithStatus[];
178
244
  };
179
245
 
180
246
  declare const useAchievementState: () => {
181
247
  unlockedIds: string[];
182
- unlockedAchievements: achievements_engine.AchievementWithStatus[];
183
- allAchievements: achievements_engine.AchievementWithStatus[];
248
+ unlockedAchievements: AchievementWithStatus[];
249
+ allAchievements: AchievementWithStatus[];
184
250
  unlockedCount: number;
185
251
  totalCount: number;
186
- metrics: achievements_engine.AchievementMetrics;
252
+ metrics: Record<string, any>;
187
253
  };
188
254
 
189
255
  /**
@@ -194,4 +260,30 @@ declare const useAchievementState: () => {
194
260
  */
195
261
  declare const useAchievementEngine: () => AchievementEngine;
196
262
 
197
- export { AchievementCondition, AchievementConfetti, AchievementConfiguration, AchievementConfigurationType, AchievementContext, AchievementContextType, AchievementContextValue, AchievementDetails, AchievementMetricArrayValue, AchievementMetricValue, AchievementMetrics, AchievementProvider, AchievementProviderProps, AchievementState, AchievementStorage, AchievementWithStatus, AnyAchievementStorage, AsyncAchievementStorage, CustomAchievementDetails, InitialAchievementMetrics, SimpleAchievementConfig, SimpleAchievementDetails, isAsyncStorage, useAchievementEngine, useAchievementState, useAchievements, useSimpleAchievements };
263
+ type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
264
+ interface RestAchievementClientConfig {
265
+ baseUrl: string;
266
+ fetcher?: Fetcher;
267
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
268
+ credentials?: RequestCredentials;
269
+ timeout?: number;
270
+ }
271
+ declare class RestAchievementClient implements AchievementClient {
272
+ private baseUrl;
273
+ private fetcher;
274
+ private headers?;
275
+ private credentials?;
276
+ private timeout?;
277
+ constructor(config: RestAchievementClientConfig);
278
+ getSnapshot(): Promise<AchievementClientSnapshot>;
279
+ track(metric: string, value: unknown): Promise<AchievementClientMutationResult>;
280
+ trackMany(metrics: Record<string, unknown>): Promise<AchievementClientMutationResult>;
281
+ increment(metric: string, amount?: number): Promise<AchievementClientMutationResult>;
282
+ event(name: string, payload?: unknown): Promise<AchievementClientMutationResult>;
283
+ reset(): Promise<AchievementClientSnapshot>;
284
+ private request;
285
+ private resolveHeaders;
286
+ }
287
+ declare const createRestAchievementClient: (config: RestAchievementClientConfig) => AchievementClient;
288
+
289
+ export { AchievementClient, AchievementClientMutationResult, AchievementClientSnapshot, AchievementCondition, AchievementConfetti, AchievementConfiguration, AchievementConfigurationType, AchievementContext, AchievementContextType, AchievementContextValue, AchievementDetails, AchievementDto, AchievementMetricArrayValue, AchievementMetricValue, AchievementMetrics, AchievementProgress, AchievementProvider, AchievementProviderProps, AchievementState, AchievementStorage, AchievementWithStatus, AnyAchievementStorage, AsyncAchievementStorage, CustomAchievementDetails, InitialAchievementMetrics, RestAchievementClient, RestAchievementClientConfig, SimpleAchievementConfig, SimpleAchievementDetails, createRestAchievementClient, isAsyncStorage, useAchievementEngine, useAchievementState, useAchievements, useSimpleAchievements };
@@ -16,6 +16,38 @@ var StorageType;
16
16
  StorageType["RestAPI"] = "restapi"; // Asynchronous REST API storage
17
17
  })(StorageType || (StorageType = {}));
18
18
 
19
+ /******************************************************************************
20
+ Copyright (c) Microsoft Corporation.
21
+
22
+ Permission to use, copy, modify, and/or distribute this software for any
23
+ purpose with or without fee is hereby granted.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
26
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
27
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
28
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
29
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
30
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
31
+ PERFORMANCE OF THIS SOFTWARE.
32
+ ***************************************************************************** */
33
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
34
+
35
+
36
+ function __awaiter(thisArg, _arguments, P, generator) {
37
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
+ return new (P || (P = Promise))(function (resolve, reject) {
39
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ }
45
+
46
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
47
+ var e = new Error(message);
48
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
49
+ };
50
+
19
51
  const warnedMessages = new Set();
20
52
  function warnDeprecation(message) {
21
53
  var _a, _b;
@@ -32,18 +64,74 @@ const AchievementContext = createContext(undefined);
32
64
  const getAllAchievementRecord = (achievements) => {
33
65
  return Object.fromEntries(achievements.map((achievement) => [achievement.achievementId, achievement]));
34
66
  };
35
- const AchievementProvider = ({ achievements: achievementsConfig, storage = 'local', children, onError, useBuiltInUI, restApiConfig, engine: externalEngine, eventMapping, icons = {}, }) => {
67
+ const emptySnapshot = () => ({
68
+ metrics: {},
69
+ unlockedIds: [],
70
+ unlockedAchievements: [],
71
+ allAchievements: [],
72
+ unlockedCount: 0,
73
+ totalCount: 0,
74
+ });
75
+ const normalizeAchievementDto = (achievement) => {
76
+ const source = achievement;
77
+ const achievementId = source.id || source.achievementId || '';
78
+ const achievementTitle = source.title || source.achievementTitle || achievementId;
79
+ const achievementDescription = source.description || source.achievementDescription || '';
80
+ const achievementIconKey = source.iconKey || source.icon || source.achievementIconKey;
81
+ return {
82
+ achievementId,
83
+ achievementTitle,
84
+ achievementDescription,
85
+ achievementIconKey,
86
+ confetti: source.confetti,
87
+ isUnlocked: Boolean(source.isUnlocked),
88
+ unlockedAt: source.unlockedAt,
89
+ progress: source.progress,
90
+ metadata: source.metadata,
91
+ };
92
+ };
93
+ const normalizeClientSnapshot = (snapshot) => {
94
+ var _a, _b, _c;
95
+ const allAchievements = (snapshot.achievements || []).map(normalizeAchievementDto);
96
+ const unlockedIds = snapshot.unlockedIds ||
97
+ allAchievements
98
+ .filter((achievement) => achievement.isUnlocked)
99
+ .map((achievement) => achievement.achievementId);
100
+ const unlockedIdSet = new Set(unlockedIds);
101
+ const unlockedAchievements = ((_a = snapshot.unlockedAchievements) === null || _a === void 0 ? void 0 : _a.length)
102
+ ? snapshot.unlockedAchievements.map(normalizeAchievementDto)
103
+ : allAchievements.filter((achievement) => unlockedIdSet.has(achievement.achievementId));
104
+ return {
105
+ metrics: Object.assign({}, (snapshot.metrics || {})),
106
+ unlockedIds,
107
+ unlockedAchievements,
108
+ allAchievements,
109
+ unlockedCount: (_b = snapshot.unlockedCount) !== null && _b !== void 0 ? _b : unlockedAchievements.length,
110
+ totalCount: (_c = snapshot.totalCount) !== null && _c !== void 0 ? _c : allAchievements.length,
111
+ };
112
+ };
113
+ const toError = (unknownError, fallbackMessage) => (unknownError instanceof Error ? unknownError : new Error(fallbackMessage));
114
+ const AchievementProvider = ({ client, achievements: achievementsConfig, storage = 'local', children, onError, useBuiltInUI, restApiConfig, engine: externalEngine, eventMapping, icons = {}, }) => {
36
115
  if (useBuiltInUI !== undefined) {
37
116
  warnDeprecation('`useBuiltInUI` is deprecated and is now a no-op because built-in UI is the default. It will be removed in 5.0.');
38
117
  }
118
+ if (client && (achievementsConfig || externalEngine)) {
119
+ throw new Error('Cannot provide "client" with "achievements" or "engine" props to AchievementProvider.\n\n' +
120
+ 'Use one pattern:\n' +
121
+ '1. Server-backed display: <AchievementProvider client={achievementClient}>\n' +
122
+ '2. Legacy in-browser engine: <AchievementProvider achievements={config}>');
123
+ }
39
124
  if (achievementsConfig && externalEngine) {
40
125
  throw new Error('Cannot provide both "achievements" and "engine" props to AchievementProvider.\n\n' +
41
126
  'Choose one pattern:\n' +
42
127
  '1. Direct metric tracking: <AchievementProvider achievements={config}>\n' +
43
128
  '2. Event-based tracking: <AchievementProvider engine={myEngine}>');
44
129
  }
45
- const isProviderCreatedEngine = Boolean(achievementsConfig);
130
+ const isProviderCreatedEngine = Boolean(achievementsConfig) && !client;
46
131
  const [engine] = useState(() => {
132
+ if (client) {
133
+ return undefined;
134
+ }
47
135
  if (externalEngine) {
48
136
  return externalEngine;
49
137
  }
@@ -60,18 +148,63 @@ const AchievementProvider = ({ achievements: achievementsConfig, storage = 'loca
60
148
  eventMapping,
61
149
  });
62
150
  });
63
- const [achievementSnapshot, setAchievementSnapshot] = useState(() => engine.getSnapshot());
151
+ const [achievementSnapshot, setAchievementSnapshot] = useState(() => engine ? engine.getSnapshot() : emptySnapshot());
152
+ const [recentlyUnlocked, setRecentlyUnlocked] = useState([]);
153
+ const [isLoading, setIsLoading] = useState(Boolean(client));
154
+ const [error, setError] = useState(null);
64
155
  const syncAchievementState = useCallback((snapshot) => {
65
- setAchievementSnapshot(snapshot || engine.getSnapshot());
156
+ if (snapshot) {
157
+ setAchievementSnapshot(snapshot);
158
+ return;
159
+ }
160
+ if (engine) {
161
+ setAchievementSnapshot(engine.getSnapshot());
162
+ }
66
163
  }, [engine]);
164
+ const applyClientMutationResult = useCallback((result) => {
165
+ setRecentlyUnlocked((result.newlyUnlocked || []).map(normalizeAchievementDto));
166
+ const normalizedSnapshot = normalizeClientSnapshot(result.snapshot);
167
+ setAchievementSnapshot(normalizedSnapshot);
168
+ return result;
169
+ }, []);
170
+ const refresh = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
171
+ if (!client) {
172
+ const snapshot = engine ? engine.getSnapshot() : emptySnapshot();
173
+ setAchievementSnapshot(snapshot);
174
+ return snapshot;
175
+ }
176
+ setIsLoading(true);
177
+ setError(null);
178
+ try {
179
+ const snapshot = normalizeClientSnapshot(yield client.getSnapshot());
180
+ setAchievementSnapshot(snapshot);
181
+ return snapshot;
182
+ }
183
+ catch (unknownError) {
184
+ const nextError = toError(unknownError, 'Failed to load achievements');
185
+ setError(nextError);
186
+ throw nextError;
187
+ }
188
+ finally {
189
+ setIsLoading(false);
190
+ }
191
+ }), [client, engine]);
192
+ const handleClientMutationFailure = useCallback((unknownError) => {
193
+ const nextError = toError(unknownError, 'Failed to update achievements');
194
+ setError(nextError);
195
+ throw nextError;
196
+ }, []);
67
197
  useEffect(() => {
68
198
  return () => {
69
- if (!externalEngine) {
199
+ if (engine && !externalEngine) {
70
200
  engine.destroy();
71
201
  }
72
202
  };
73
203
  }, [engine, externalEngine]);
74
204
  useEffect(() => {
205
+ if (!engine) {
206
+ return;
207
+ }
75
208
  let isMounted = true;
76
209
  const unsubscribeStateChanged = engine.on('state:changed', (event) => {
77
210
  syncAchievementState(event);
@@ -86,29 +219,84 @@ const AchievementProvider = ({ achievements: achievementsConfig, storage = 'loca
86
219
  unsubscribeStateChanged();
87
220
  };
88
221
  }, [engine, syncAchievementState]);
222
+ useEffect(() => {
223
+ if (!client) {
224
+ return;
225
+ }
226
+ refresh().catch(() => {
227
+ });
228
+ return () => {
229
+ };
230
+ }, [client, refresh]);
89
231
  const update = (newMetrics) => {
90
- engine.update(newMetrics);
232
+ if (client) {
233
+ setError(null);
234
+ const mutation = client.trackMany
235
+ ? client.trackMany(newMetrics)
236
+ : Promise.all(Object.entries(newMetrics).map(([metric, value]) => client.track(metric, value))).then((results) => results[results.length - 1]);
237
+ return mutation.then((result) => {
238
+ if (result) {
239
+ applyClientMutationResult(result);
240
+ }
241
+ return result;
242
+ }).catch(handleClientMutationFailure);
243
+ }
244
+ return engine === null || engine === void 0 ? void 0 : engine.update(newMetrics);
245
+ };
246
+ const increment = (metric, amount = 1) => {
247
+ if (client) {
248
+ setError(null);
249
+ return client.increment(metric, amount)
250
+ .then(applyClientMutationResult)
251
+ .catch(handleClientMutationFailure);
252
+ }
253
+ return engine === null || engine === void 0 ? void 0 : engine.increment(metric, amount);
254
+ };
255
+ const event = (name, payload) => {
256
+ if (client) {
257
+ setError(null);
258
+ return client.event(name, payload)
259
+ .then(applyClientMutationResult)
260
+ .catch(handleClientMutationFailure);
261
+ }
262
+ engine === null || engine === void 0 ? void 0 : engine.emit(name, payload);
91
263
  };
92
264
  const reset = () => {
93
- engine.reset();
265
+ if (client === null || client === void 0 ? void 0 : client.reset) {
266
+ setError(null);
267
+ return client.reset().then((snapshot) => {
268
+ setRecentlyUnlocked([]);
269
+ setAchievementSnapshot(normalizeClientSnapshot(snapshot));
270
+ }).catch(handleClientMutationFailure);
271
+ }
272
+ if (client) {
273
+ return refresh().then(() => undefined);
274
+ }
275
+ engine === null || engine === void 0 ? void 0 : engine.reset();
94
276
  };
95
277
  const getState = () => {
96
- const snapshot = engine.getSnapshot();
278
+ const snapshot = engine ? engine.getSnapshot() : achievementSnapshot;
97
279
  return {
98
280
  metrics: snapshot.metrics,
99
281
  unlocked: snapshot.unlockedIds,
100
282
  };
101
283
  };
102
284
  const exportData = () => {
103
- return engine.export();
285
+ return engine ? engine.export() : JSON.stringify(achievementSnapshot);
104
286
  };
105
287
  const importData = (jsonString, options) => {
288
+ if (!engine) {
289
+ return {
290
+ success: false,
291
+ errors: ['importData is not supported by remote achievement clients. Import on the server instead.'],
292
+ };
293
+ }
106
294
  const result = engine.import(jsonString, options);
107
295
  syncAchievementState();
108
296
  return result;
109
297
  };
110
298
  const getAllAchievements = () => {
111
- return engine.getSnapshot().allAchievements;
299
+ return engine ? engine.getSnapshot().allAchievements : achievementSnapshot.allAchievements;
112
300
  };
113
301
  const achievements = {
114
302
  unlocked: achievementSnapshot.unlockedIds,
@@ -116,6 +304,9 @@ const AchievementProvider = ({ achievements: achievementsConfig, storage = 'loca
116
304
  };
117
305
  return (React.createElement(AchievementContext.Provider, { value: {
118
306
  update,
307
+ increment,
308
+ event,
309
+ refresh,
119
310
  achievements,
120
311
  snapshot: achievementSnapshot,
121
312
  reset,
@@ -124,7 +315,11 @@ const AchievementProvider = ({ achievements: achievementsConfig, storage = 'loca
124
315
  importData,
125
316
  getAllAchievements,
126
317
  engine,
318
+ client,
127
319
  icons,
320
+ recentlyUnlocked,
321
+ isLoading,
322
+ error,
128
323
  _isLegacyPattern: isProviderCreatedEngine,
129
324
  } }, children));
130
325
  };
@@ -154,11 +349,11 @@ const useAchievementState = () => {
154
349
  * Provides the v4 happy path for direct metric updates plus explicit state names.
155
350
  */
156
351
  const useSimpleAchievements = () => {
157
- const { update, reset, getState, exportData, importData, engine } = useAchievements();
352
+ const { update, increment: incrementMetric, event, refresh, reset, getState, exportData, importData, isLoading, error, } = useAchievements();
158
353
  const achievementState = useAchievementState();
159
354
  const track = (metric, value) => update({ [metric]: value });
160
355
  const increment = (metric, amount = 1) => {
161
- return engine.increment(metric, amount);
356
+ return incrementMetric(metric, amount);
162
357
  };
163
358
  const trackMultiple = (metrics) => update(metrics);
164
359
  return {
@@ -171,6 +366,11 @@ const useSimpleAchievements = () => {
171
366
  unlockedCount: achievementState.unlockedCount,
172
367
  totalCount: achievementState.totalCount,
173
368
  metrics: achievementState.metrics,
369
+ isLoading,
370
+ error,
371
+ event,
372
+ emit: event,
373
+ refresh,
174
374
  reset,
175
375
  getState,
176
376
  exportData,
@@ -202,8 +402,94 @@ const useAchievementEngine = () => {
202
402
  ' <YourComponent />\n' +
203
403
  '</AchievementProvider>');
204
404
  }
405
+ if (!context.engine) {
406
+ throw new Error('useAchievementEngine is only available when AchievementProvider is using the legacy in-browser engine. ' +
407
+ 'For server-backed achievements, use useSimpleAchievements().event(), track(), or increment().');
408
+ }
205
409
  return context.engine;
206
410
  };
207
411
 
208
- export { AchievementContext, AchievementProvider, isAsyncStorage, useAchievementEngine, useAchievementState, useAchievements, useSimpleAchievements };
412
+ const trimTrailingSlash = (value) => value.replace(/\/$/, '');
413
+ class RestAchievementClient {
414
+ constructor(config) {
415
+ this.baseUrl = trimTrailingSlash(config.baseUrl);
416
+ this.fetcher = config.fetcher || fetch.bind(globalThis);
417
+ this.headers = config.headers;
418
+ this.credentials = config.credentials;
419
+ this.timeout = config.timeout;
420
+ }
421
+ getSnapshot() {
422
+ return __awaiter(this, void 0, void 0, function* () {
423
+ return this.request('', { method: 'GET' });
424
+ });
425
+ }
426
+ track(metric, value) {
427
+ return __awaiter(this, void 0, void 0, function* () {
428
+ return this.request('/track', {
429
+ method: 'POST',
430
+ body: JSON.stringify({ metric, value }),
431
+ });
432
+ });
433
+ }
434
+ trackMany(metrics) {
435
+ return __awaiter(this, void 0, void 0, function* () {
436
+ return this.request('/track', {
437
+ method: 'POST',
438
+ body: JSON.stringify({ metrics }),
439
+ });
440
+ });
441
+ }
442
+ increment(metric_1) {
443
+ return __awaiter(this, arguments, void 0, function* (metric, amount = 1) {
444
+ return this.request('/increment', {
445
+ method: 'POST',
446
+ body: JSON.stringify({ metric, amount }),
447
+ });
448
+ });
449
+ }
450
+ event(name, payload) {
451
+ return __awaiter(this, void 0, void 0, function* () {
452
+ return this.request('/event', {
453
+ method: 'POST',
454
+ body: JSON.stringify({ name, payload }),
455
+ });
456
+ });
457
+ }
458
+ reset() {
459
+ return __awaiter(this, void 0, void 0, function* () {
460
+ return this.request('/reset', { method: 'POST' });
461
+ });
462
+ }
463
+ request(path, init) {
464
+ return __awaiter(this, void 0, void 0, function* () {
465
+ const controller = this.timeout ? new AbortController() : undefined;
466
+ const timeoutId = controller
467
+ ? setTimeout(() => controller.abort(), this.timeout)
468
+ : undefined;
469
+ try {
470
+ const response = yield this.fetcher(`${this.baseUrl}${path}`, Object.assign(Object.assign({}, init), { credentials: this.credentials, headers: Object.assign(Object.assign({ 'Content-Type': 'application/json' }, (yield this.resolveHeaders())), init.headers), signal: controller === null || controller === void 0 ? void 0 : controller.signal }));
471
+ if (!response.ok) {
472
+ throw new Error(`Achievement request failed: HTTP ${response.status}`);
473
+ }
474
+ return yield response.json();
475
+ }
476
+ finally {
477
+ if (timeoutId) {
478
+ clearTimeout(timeoutId);
479
+ }
480
+ }
481
+ });
482
+ }
483
+ resolveHeaders() {
484
+ return __awaiter(this, void 0, void 0, function* () {
485
+ if (!this.headers) {
486
+ return {};
487
+ }
488
+ return typeof this.headers === 'function' ? this.headers() : this.headers;
489
+ });
490
+ }
491
+ }
492
+ const createRestAchievementClient = (config) => new RestAchievementClient(config);
493
+
494
+ export { AchievementContext, AchievementProvider, RestAchievementClient, createRestAchievementClient, isAsyncStorage, useAchievementEngine, useAchievementState, useAchievements, useSimpleAchievements };
209
495
  //# sourceMappingURL=headless.esm.js.map