keeperboard 1.0.4 → 2.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.
- package/README.md +198 -294
- package/dist/index.d.mts +344 -109
- package/dist/index.d.ts +344 -109
- package/dist/index.js +475 -47
- package/dist/index.mjs +470 -46
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -14,51 +14,87 @@ var _KeeperBoardClient = class _KeeperBoardClient {
|
|
|
14
14
|
const url = config.apiUrl ?? _KeeperBoardClient.DEFAULT_API_URL;
|
|
15
15
|
this.apiUrl = url.replace(/\/$/, "");
|
|
16
16
|
this.apiKey = config.apiKey;
|
|
17
|
+
this.defaultLeaderboard = config.defaultLeaderboard;
|
|
17
18
|
}
|
|
18
|
-
|
|
19
|
+
// ============================================
|
|
20
|
+
// SCORE SUBMISSION
|
|
21
|
+
// ============================================
|
|
22
|
+
/**
|
|
23
|
+
* Submit a score. Only updates if the new score is higher than the existing one.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* const result = await client.submitScore({
|
|
27
|
+
* playerGuid: 'abc-123',
|
|
28
|
+
* playerName: 'ACE',
|
|
29
|
+
* score: 1500,
|
|
30
|
+
* });
|
|
31
|
+
* console.log(result.rank, result.isNewHighScore);
|
|
32
|
+
*/
|
|
33
|
+
async submitScore(options) {
|
|
34
|
+
const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
|
|
19
35
|
const params = new URLSearchParams();
|
|
20
|
-
if (leaderboard)
|
|
21
|
-
params.set("leaderboard", leaderboard);
|
|
22
|
-
}
|
|
36
|
+
if (leaderboard) params.set("leaderboard", leaderboard);
|
|
23
37
|
const url = `${this.apiUrl}/api/v1/scores${params.toString() ? "?" + params.toString() : ""}`;
|
|
24
38
|
const body = {
|
|
25
|
-
player_guid: playerGuid,
|
|
26
|
-
player_name: playerName,
|
|
27
|
-
score,
|
|
28
|
-
...metadata && { metadata }
|
|
39
|
+
player_guid: options.playerGuid,
|
|
40
|
+
player_name: options.playerName,
|
|
41
|
+
score: options.score,
|
|
42
|
+
...options.metadata && { metadata: options.metadata }
|
|
29
43
|
};
|
|
30
|
-
|
|
44
|
+
const raw = await this.request(url, {
|
|
31
45
|
method: "POST",
|
|
32
46
|
body: JSON.stringify(body)
|
|
33
47
|
});
|
|
48
|
+
return this.mapScoreResponse(raw);
|
|
34
49
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
// ============================================
|
|
51
|
+
// LEADERBOARD
|
|
52
|
+
// ============================================
|
|
53
|
+
/**
|
|
54
|
+
* Get a leaderboard. Supports pagination and version-based lookups for
|
|
55
|
+
* time-based boards.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* // Top 10 on default board
|
|
59
|
+
* const lb = await client.getLeaderboard();
|
|
60
|
+
*
|
|
61
|
+
* // Top 25 on a specific board
|
|
62
|
+
* const lb = await client.getLeaderboard({ leaderboard: 'Weekly', limit: 25 });
|
|
63
|
+
*
|
|
64
|
+
* // Historical version
|
|
65
|
+
* const lb = await client.getLeaderboard({ leaderboard: 'Weekly', version: 3 });
|
|
66
|
+
*/
|
|
67
|
+
async getLeaderboard(options) {
|
|
68
|
+
const leaderboard = options?.leaderboard ?? this.defaultLeaderboard;
|
|
69
|
+
const limit = options?.limit ?? 10;
|
|
70
|
+
const offset = options?.offset ?? 0;
|
|
46
71
|
const params = new URLSearchParams();
|
|
47
|
-
params.set("leaderboard", name);
|
|
48
|
-
params.set("version", String(version));
|
|
49
72
|
params.set("limit", String(Math.min(limit, 100)));
|
|
50
73
|
params.set("offset", String(offset));
|
|
74
|
+
if (leaderboard) params.set("leaderboard", leaderboard);
|
|
75
|
+
if (options?.version !== void 0) params.set("version", String(options.version));
|
|
51
76
|
const url = `${this.apiUrl}/api/v1/leaderboard?${params.toString()}`;
|
|
52
|
-
|
|
77
|
+
const raw = await this.request(url, { method: "GET" });
|
|
78
|
+
return this.mapLeaderboardResponse(raw);
|
|
53
79
|
}
|
|
54
|
-
|
|
80
|
+
// ============================================
|
|
81
|
+
// PLAYER
|
|
82
|
+
// ============================================
|
|
83
|
+
/**
|
|
84
|
+
* Get a player's rank and score. Returns `null` if the player has no score.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* const player = await client.getPlayerRank({ playerGuid: 'abc-123' });
|
|
88
|
+
* if (player) console.log(`Rank #${player.rank}`);
|
|
89
|
+
*/
|
|
90
|
+
async getPlayerRank(options) {
|
|
91
|
+
const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
|
|
55
92
|
const params = new URLSearchParams();
|
|
56
|
-
if (leaderboard)
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
|
|
93
|
+
if (leaderboard) params.set("leaderboard", leaderboard);
|
|
94
|
+
const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(options.playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
|
|
60
95
|
try {
|
|
61
|
-
|
|
96
|
+
const raw = await this.request(url, { method: "GET" });
|
|
97
|
+
return this.mapPlayerResponse(raw);
|
|
62
98
|
} catch (error) {
|
|
63
99
|
if (error instanceof KeeperBoardError && error.code === "NOT_FOUND") {
|
|
64
100
|
return null;
|
|
@@ -66,37 +102,52 @@ var _KeeperBoardClient = class _KeeperBoardClient {
|
|
|
66
102
|
throw error;
|
|
67
103
|
}
|
|
68
104
|
}
|
|
69
|
-
|
|
105
|
+
/**
|
|
106
|
+
* Update a player's display name.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* const player = await client.updatePlayerName({
|
|
110
|
+
* playerGuid: 'abc-123',
|
|
111
|
+
* newName: 'MAVERICK',
|
|
112
|
+
* });
|
|
113
|
+
*/
|
|
114
|
+
async updatePlayerName(options) {
|
|
115
|
+
const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
|
|
70
116
|
const params = new URLSearchParams();
|
|
71
|
-
if (leaderboard)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
|
|
75
|
-
return this.request(url, {
|
|
117
|
+
if (leaderboard) params.set("leaderboard", leaderboard);
|
|
118
|
+
const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(options.playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
|
|
119
|
+
const raw = await this.request(url, {
|
|
76
120
|
method: "PUT",
|
|
77
|
-
body: JSON.stringify({ player_name: newName })
|
|
121
|
+
body: JSON.stringify({ player_name: options.newName })
|
|
78
122
|
});
|
|
123
|
+
return this.mapPlayerResponse(raw);
|
|
79
124
|
}
|
|
80
|
-
|
|
125
|
+
// ============================================
|
|
126
|
+
// CLAIM (for migrated scores)
|
|
127
|
+
// ============================================
|
|
128
|
+
/**
|
|
129
|
+
* Claim a migrated score by matching player name.
|
|
130
|
+
* Used when scores were imported without player GUIDs.
|
|
131
|
+
*/
|
|
132
|
+
async claimScore(options) {
|
|
133
|
+
const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
|
|
81
134
|
const params = new URLSearchParams();
|
|
82
|
-
if (leaderboard)
|
|
83
|
-
params.set("leaderboard", leaderboard);
|
|
84
|
-
}
|
|
135
|
+
if (leaderboard) params.set("leaderboard", leaderboard);
|
|
85
136
|
const url = `${this.apiUrl}/api/v1/claim${params.toString() ? "?" + params.toString() : ""}`;
|
|
86
|
-
|
|
137
|
+
const raw = await this.request(url, {
|
|
87
138
|
method: "POST",
|
|
88
139
|
body: JSON.stringify({
|
|
89
|
-
player_guid: playerGuid,
|
|
90
|
-
player_name: playerName
|
|
140
|
+
player_guid: options.playerGuid,
|
|
141
|
+
player_name: options.playerName
|
|
91
142
|
})
|
|
92
143
|
});
|
|
144
|
+
return this.mapClaimResponse(raw);
|
|
93
145
|
}
|
|
94
146
|
// ============================================
|
|
95
147
|
// HEALTH CHECK
|
|
96
148
|
// ============================================
|
|
97
149
|
/**
|
|
98
|
-
* Check if the API is healthy.
|
|
99
|
-
* This endpoint does not require an API key.
|
|
150
|
+
* Check if the API is healthy. Does not require an API key.
|
|
100
151
|
*/
|
|
101
152
|
async healthCheck() {
|
|
102
153
|
const url = `${this.apiUrl}/api/v1/health`;
|
|
@@ -111,6 +162,51 @@ var _KeeperBoardClient = class _KeeperBoardClient {
|
|
|
111
162
|
return json.data;
|
|
112
163
|
}
|
|
113
164
|
// ============================================
|
|
165
|
+
// RESPONSE MAPPERS (snake_case → camelCase)
|
|
166
|
+
// ============================================
|
|
167
|
+
mapScoreResponse(raw) {
|
|
168
|
+
return {
|
|
169
|
+
id: raw.id,
|
|
170
|
+
playerGuid: raw.player_guid,
|
|
171
|
+
playerName: raw.player_name,
|
|
172
|
+
score: raw.score,
|
|
173
|
+
rank: raw.rank,
|
|
174
|
+
isNewHighScore: raw.is_new_high_score
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
mapLeaderboardResponse(raw) {
|
|
178
|
+
return {
|
|
179
|
+
entries: raw.entries.map((e) => ({
|
|
180
|
+
rank: e.rank,
|
|
181
|
+
playerGuid: e.player_guid,
|
|
182
|
+
playerName: e.player_name,
|
|
183
|
+
score: e.score
|
|
184
|
+
})),
|
|
185
|
+
totalCount: raw.total_count,
|
|
186
|
+
resetSchedule: raw.reset_schedule,
|
|
187
|
+
version: raw.version,
|
|
188
|
+
oldestVersion: raw.oldest_version,
|
|
189
|
+
nextReset: raw.next_reset
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
mapPlayerResponse(raw) {
|
|
193
|
+
return {
|
|
194
|
+
id: raw.id,
|
|
195
|
+
playerGuid: raw.player_guid,
|
|
196
|
+
playerName: raw.player_name,
|
|
197
|
+
score: raw.score,
|
|
198
|
+
rank: raw.rank
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
mapClaimResponse(raw) {
|
|
202
|
+
return {
|
|
203
|
+
claimed: raw.claimed,
|
|
204
|
+
score: raw.score,
|
|
205
|
+
rank: raw.rank,
|
|
206
|
+
playerName: raw.player_name
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
// ============================================
|
|
114
210
|
// INTERNAL
|
|
115
211
|
// ============================================
|
|
116
212
|
async request(url, options) {
|
|
@@ -220,8 +316,336 @@ var PlayerIdentity = class {
|
|
|
220
316
|
});
|
|
221
317
|
}
|
|
222
318
|
};
|
|
319
|
+
|
|
320
|
+
// src/Cache.ts
|
|
321
|
+
var Cache = class {
|
|
322
|
+
constructor(ttlMs) {
|
|
323
|
+
this.fetchedAt = 0;
|
|
324
|
+
this.inflight = null;
|
|
325
|
+
this.pendingRefresh = null;
|
|
326
|
+
this.ttlMs = ttlMs;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Get cached value if fresh, otherwise fetch via the provided function.
|
|
330
|
+
* Deduplicates concurrent calls — only one fetch runs at a time.
|
|
331
|
+
*/
|
|
332
|
+
async getOrFetch(fetchFn) {
|
|
333
|
+
if (this.isFresh()) {
|
|
334
|
+
return this.data;
|
|
335
|
+
}
|
|
336
|
+
if (this.inflight) {
|
|
337
|
+
return this.inflight;
|
|
338
|
+
}
|
|
339
|
+
this.inflight = fetchFn().then((result) => {
|
|
340
|
+
this.data = result;
|
|
341
|
+
this.fetchedAt = Date.now();
|
|
342
|
+
this.inflight = null;
|
|
343
|
+
return result;
|
|
344
|
+
}).catch((err) => {
|
|
345
|
+
this.inflight = null;
|
|
346
|
+
throw err;
|
|
347
|
+
});
|
|
348
|
+
return this.inflight;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Trigger a background refresh without awaiting the result.
|
|
352
|
+
* Returns immediately. If a fetch is already in flight, schedules
|
|
353
|
+
* the refresh to run after the current one completes.
|
|
354
|
+
*/
|
|
355
|
+
refreshInBackground(fetchFn) {
|
|
356
|
+
if (this.inflight) {
|
|
357
|
+
this.pendingRefresh = fetchFn;
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
this.startBackgroundFetch(fetchFn);
|
|
361
|
+
}
|
|
362
|
+
startBackgroundFetch(fetchFn) {
|
|
363
|
+
this.inflight = fetchFn().then((result) => {
|
|
364
|
+
this.data = result;
|
|
365
|
+
this.fetchedAt = Date.now();
|
|
366
|
+
this.inflight = null;
|
|
367
|
+
if (this.pendingRefresh) {
|
|
368
|
+
const pending = this.pendingRefresh;
|
|
369
|
+
this.pendingRefresh = null;
|
|
370
|
+
this.startBackgroundFetch(pending);
|
|
371
|
+
}
|
|
372
|
+
return result;
|
|
373
|
+
}).catch((err) => {
|
|
374
|
+
this.inflight = null;
|
|
375
|
+
this.pendingRefresh = null;
|
|
376
|
+
throw err;
|
|
377
|
+
});
|
|
378
|
+
this.inflight.catch(() => {
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
/** Invalidate the cache, forcing the next getOrFetch to re-fetch. */
|
|
382
|
+
invalidate() {
|
|
383
|
+
this.fetchedAt = 0;
|
|
384
|
+
}
|
|
385
|
+
/** Get the cached value without fetching. Returns undefined if empty or stale. */
|
|
386
|
+
get() {
|
|
387
|
+
return this.isFresh() ? this.data : void 0;
|
|
388
|
+
}
|
|
389
|
+
/** Get the cached value even if stale. Returns undefined only if never fetched. */
|
|
390
|
+
getStale() {
|
|
391
|
+
return this.data;
|
|
392
|
+
}
|
|
393
|
+
/** Check if the cache has fresh (non-expired) data. */
|
|
394
|
+
isFresh() {
|
|
395
|
+
return this.data !== void 0 && Date.now() - this.fetchedAt < this.ttlMs;
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
// src/RetryQueue.ts
|
|
400
|
+
var DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
401
|
+
var RetryQueue = class {
|
|
402
|
+
constructor(storageKey, maxAgeMs = DEFAULT_MAX_AGE_MS) {
|
|
403
|
+
this.storageKey = storageKey;
|
|
404
|
+
this.maxAgeMs = maxAgeMs;
|
|
405
|
+
}
|
|
406
|
+
/** Save a failed score for later retry. */
|
|
407
|
+
save(score, metadata) {
|
|
408
|
+
try {
|
|
409
|
+
const pending = { score, metadata, timestamp: Date.now() };
|
|
410
|
+
localStorage.setItem(this.storageKey, JSON.stringify(pending));
|
|
411
|
+
} catch {
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Get the pending score, or null if none exists or it has expired.
|
|
416
|
+
* Automatically clears expired entries.
|
|
417
|
+
*/
|
|
418
|
+
get() {
|
|
419
|
+
try {
|
|
420
|
+
const raw = localStorage.getItem(this.storageKey);
|
|
421
|
+
if (!raw) return null;
|
|
422
|
+
const pending = JSON.parse(raw);
|
|
423
|
+
if (Date.now() - pending.timestamp > this.maxAgeMs) {
|
|
424
|
+
this.clear();
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
return { score: pending.score, metadata: pending.metadata };
|
|
428
|
+
} catch {
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** Check if there's a pending score. */
|
|
433
|
+
hasPending() {
|
|
434
|
+
return this.get() !== null;
|
|
435
|
+
}
|
|
436
|
+
/** Clear the pending score. */
|
|
437
|
+
clear() {
|
|
438
|
+
try {
|
|
439
|
+
localStorage.removeItem(this.storageKey);
|
|
440
|
+
} catch {
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
// src/validation.ts
|
|
446
|
+
var DEFAULTS = {
|
|
447
|
+
minLength: 2,
|
|
448
|
+
maxLength: 12,
|
|
449
|
+
uppercase: true,
|
|
450
|
+
allowedPattern: /[^A-Z0-9_]/g
|
|
451
|
+
};
|
|
452
|
+
function validateName(input, options) {
|
|
453
|
+
const opts = { ...DEFAULTS, ...options };
|
|
454
|
+
let name = input.trim();
|
|
455
|
+
if (opts.uppercase) {
|
|
456
|
+
name = name.toUpperCase();
|
|
457
|
+
}
|
|
458
|
+
const pattern = options?.allowedPattern ?? (opts.uppercase ? /[^A-Z0-9_]/g : /[^A-Za-z0-9_]/g);
|
|
459
|
+
name = name.replace(pattern, "");
|
|
460
|
+
name = name.substring(0, opts.maxLength);
|
|
461
|
+
if (name.length < opts.minLength) {
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
return name;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/KeeperBoardSession.ts
|
|
468
|
+
var KeeperBoardSession = class {
|
|
469
|
+
constructor(config) {
|
|
470
|
+
this.cachedLimit = 0;
|
|
471
|
+
// Track the limit used for cached data
|
|
472
|
+
this.isSubmitting = false;
|
|
473
|
+
this.client = new KeeperBoardClient({
|
|
474
|
+
apiKey: config.apiKey,
|
|
475
|
+
defaultLeaderboard: config.leaderboard,
|
|
476
|
+
apiUrl: config.apiUrl
|
|
477
|
+
});
|
|
478
|
+
this.identity = new PlayerIdentity(config.identity);
|
|
479
|
+
this.leaderboard = config.leaderboard;
|
|
480
|
+
this.defaultPlayerName = config.defaultPlayerName ?? "ANON";
|
|
481
|
+
this.cache = config.cache ? new Cache(config.cache.ttlMs) : null;
|
|
482
|
+
this.retryQueue = config.retry ? new RetryQueue(
|
|
483
|
+
`keeperboard_retry_${config.leaderboard}`,
|
|
484
|
+
config.retry.maxAgeMs
|
|
485
|
+
) : null;
|
|
486
|
+
}
|
|
487
|
+
// ============================================
|
|
488
|
+
// IDENTITY
|
|
489
|
+
// ============================================
|
|
490
|
+
/** Get or create a persistent player GUID. */
|
|
491
|
+
getPlayerGuid() {
|
|
492
|
+
return this.identity.getOrCreatePlayerGuid();
|
|
493
|
+
}
|
|
494
|
+
/** Get the stored player name, falling back to defaultPlayerName. */
|
|
495
|
+
getPlayerName() {
|
|
496
|
+
return this.identity.getPlayerName() ?? this.defaultPlayerName;
|
|
497
|
+
}
|
|
498
|
+
/** Store a player name locally. Does NOT update the server — call updatePlayerName() for that. */
|
|
499
|
+
setPlayerName(name) {
|
|
500
|
+
this.identity.setPlayerName(name);
|
|
501
|
+
}
|
|
502
|
+
/** Validate a name using configurable rules. Returns sanitized string or null. */
|
|
503
|
+
validateName(input, options) {
|
|
504
|
+
return validateName(input, options);
|
|
505
|
+
}
|
|
506
|
+
// ============================================
|
|
507
|
+
// CORE API
|
|
508
|
+
// ============================================
|
|
509
|
+
/**
|
|
510
|
+
* Submit a score. Identity and leaderboard are auto-injected.
|
|
511
|
+
* Returns a discriminated union: `{ success: true, rank, isNewHighScore }` or `{ success: false, error }`.
|
|
512
|
+
*
|
|
513
|
+
* If retry is enabled, failed submissions are saved to localStorage for later retry.
|
|
514
|
+
* Prevents concurrent double-submissions.
|
|
515
|
+
*/
|
|
516
|
+
async submitScore(score, metadata) {
|
|
517
|
+
if (this.isSubmitting) {
|
|
518
|
+
return { success: false, error: "Submission in progress" };
|
|
519
|
+
}
|
|
520
|
+
this.isSubmitting = true;
|
|
521
|
+
try {
|
|
522
|
+
const result = await this.client.submitScore({
|
|
523
|
+
playerGuid: this.getPlayerGuid(),
|
|
524
|
+
playerName: this.getPlayerName(),
|
|
525
|
+
score,
|
|
526
|
+
metadata
|
|
527
|
+
});
|
|
528
|
+
this.retryQueue?.clear();
|
|
529
|
+
if (this.cache) {
|
|
530
|
+
this.cache.invalidate();
|
|
531
|
+
this.cachedLimit = 0;
|
|
532
|
+
this.cache.refreshInBackground(() => this.fetchSnapshot());
|
|
533
|
+
}
|
|
534
|
+
return {
|
|
535
|
+
success: true,
|
|
536
|
+
rank: result.rank,
|
|
537
|
+
isNewHighScore: result.isNewHighScore
|
|
538
|
+
};
|
|
539
|
+
} catch (error) {
|
|
540
|
+
this.retryQueue?.save(score, metadata);
|
|
541
|
+
return {
|
|
542
|
+
success: false,
|
|
543
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
544
|
+
};
|
|
545
|
+
} finally {
|
|
546
|
+
this.isSubmitting = false;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Get a combined snapshot: leaderboard entries (with `isCurrentPlayer` flag)
|
|
551
|
+
* plus the current player's rank if they're outside the top N.
|
|
552
|
+
*
|
|
553
|
+
* Uses cache if enabled and fresh. If a larger limit is requested than
|
|
554
|
+
* what's cached, the cache is invalidated and fresh data is fetched.
|
|
555
|
+
*/
|
|
556
|
+
async getSnapshot(options) {
|
|
557
|
+
const limit = options?.limit ?? 10;
|
|
558
|
+
if (this.cache) {
|
|
559
|
+
if (limit > this.cachedLimit) {
|
|
560
|
+
this.cache.invalidate();
|
|
561
|
+
}
|
|
562
|
+
const result = await this.cache.getOrFetch(() => this.fetchSnapshot(limit));
|
|
563
|
+
this.cachedLimit = limit;
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
566
|
+
return this.fetchSnapshot(limit);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Update the player's name on the server and locally.
|
|
570
|
+
* Returns true on success, false on failure.
|
|
571
|
+
*/
|
|
572
|
+
async updatePlayerName(newName) {
|
|
573
|
+
try {
|
|
574
|
+
await this.client.updatePlayerName({
|
|
575
|
+
playerGuid: this.getPlayerGuid(),
|
|
576
|
+
newName
|
|
577
|
+
});
|
|
578
|
+
this.identity.setPlayerName(newName);
|
|
579
|
+
if (this.cache) {
|
|
580
|
+
this.cache.invalidate();
|
|
581
|
+
this.cachedLimit = 0;
|
|
582
|
+
}
|
|
583
|
+
return true;
|
|
584
|
+
} catch {
|
|
585
|
+
return false;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Retry submitting a pending score (from a previous failed submission).
|
|
590
|
+
* Call this on app startup.
|
|
591
|
+
*/
|
|
592
|
+
async retryPendingScore() {
|
|
593
|
+
const pending = this.retryQueue?.get();
|
|
594
|
+
if (!pending) return null;
|
|
595
|
+
const result = await this.submitScore(pending.score, pending.metadata);
|
|
596
|
+
if (result.success) {
|
|
597
|
+
this.retryQueue?.clear();
|
|
598
|
+
}
|
|
599
|
+
return result;
|
|
600
|
+
}
|
|
601
|
+
/** Check if there's a pending score in the retry queue. */
|
|
602
|
+
hasPendingScore() {
|
|
603
|
+
return this.retryQueue?.hasPending() ?? false;
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Pre-fetch snapshot data in the background for instant display later.
|
|
607
|
+
* No-op if cache is disabled or already fresh.
|
|
608
|
+
*/
|
|
609
|
+
prefetch() {
|
|
610
|
+
if (!this.cache) return;
|
|
611
|
+
if (this.cache.isFresh()) return;
|
|
612
|
+
this.cache.refreshInBackground(() => this.fetchSnapshot());
|
|
613
|
+
}
|
|
614
|
+
/** Escape hatch: access the underlying KeeperBoardClient. */
|
|
615
|
+
getClient() {
|
|
616
|
+
return this.client;
|
|
617
|
+
}
|
|
618
|
+
// ============================================
|
|
619
|
+
// INTERNAL
|
|
620
|
+
// ============================================
|
|
621
|
+
async fetchSnapshot(limit = 10) {
|
|
622
|
+
const playerGuid = this.getPlayerGuid();
|
|
623
|
+
const [leaderboard, playerRank] = await Promise.all([
|
|
624
|
+
this.client.getLeaderboard({ limit }),
|
|
625
|
+
this.client.getPlayerRank({ playerGuid })
|
|
626
|
+
]);
|
|
627
|
+
const entries = leaderboard.entries.map((e) => ({
|
|
628
|
+
rank: e.rank,
|
|
629
|
+
playerGuid: e.playerGuid,
|
|
630
|
+
playerName: e.playerName,
|
|
631
|
+
score: e.score,
|
|
632
|
+
isCurrentPlayer: e.playerGuid === playerGuid
|
|
633
|
+
}));
|
|
634
|
+
const playerInEntries = entries.some((e) => e.isCurrentPlayer);
|
|
635
|
+
const effectivePlayerRank = playerRank && !playerInEntries ? playerRank : null;
|
|
636
|
+
return {
|
|
637
|
+
entries,
|
|
638
|
+
totalCount: leaderboard.totalCount,
|
|
639
|
+
playerRank: effectivePlayerRank
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
};
|
|
223
643
|
export {
|
|
644
|
+
Cache,
|
|
224
645
|
KeeperBoardClient,
|
|
225
646
|
KeeperBoardError,
|
|
226
|
-
|
|
647
|
+
KeeperBoardSession,
|
|
648
|
+
PlayerIdentity,
|
|
649
|
+
RetryQueue,
|
|
650
|
+
validateName
|
|
227
651
|
};
|
package/package.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keeperboard",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "TypeScript client SDK for KeeperBoard leaderboard-as-a-service",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
10
11
|
"import": "./dist/index.mjs",
|
|
11
|
-
"require": "./dist/index.js"
|
|
12
|
-
"types": "./dist/index.d.ts"
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
15
|
"files": [
|