@usions/sdk 2.25.0 → 2.27.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,8 +1,9 @@
1
1
  /**
2
2
  * Usion SDK Cloud — server-persisted KV storage for mini-apps.
3
3
  *
4
- * Unlike `Usion.storage` (device-local), cloud values live on the backend and
5
- * survive reinstall / device switch. Enabled for every service, bounded by
4
+ * `Usion.storage` has its own durable per-user database scope; `Usion.cloud`
5
+ * exposes explicit per-user and shared app data. Cloud values survive
6
+ * reinstall / device switch. Enabled for every service, bounded by
6
7
  * quotas (64 KB per value, 200 keys / 1 MB per bucket, 60 ops/min).
7
8
  * Rides the unified backend channel, so it works standalone AND embedded.
8
9
  *
@@ -68,7 +68,7 @@ export function isTrustedMessageSource(event) {
68
68
  * Core Usion object with init, _post, _request
69
69
  */
70
70
  export const core = {
71
- version: '2.25.0', // synced from package.json by scripts/sync-version.mjs
71
+ version: '2.27.1', // synced from package.json by scripts/sync-version.mjs
72
72
  config: {},
73
73
  _initialized: false,
74
74
  _initCallback: null,
@@ -530,6 +530,70 @@ export function applyGameMethods(game, Usion) {
530
530
  });
531
531
  };
532
532
 
533
+ /**
534
+ * Report a finished 2–8 player match to Game Center. Call ONCE from the host
535
+ * (config.playerIds[0]) at match end; pass an EXPLICIT winnerId (never
536
+ * inferred from scores).
537
+ *
538
+ * WHERE the result lands follows where the game was launched from:
539
+ * • started in a GROUP CHAT → one ranked standings card in that group
540
+ * (1-on-1 included — the group sees who beat who);
541
+ * • anywhere else (GameTok / invite / matchmaking) → cards in the DMs:
542
+ * "You beat Bob — 3 : 1" / "Bob beat you — 1 : 3" for 1-on-1, and a
543
+ * standings card across the host↔guest DMs for 3–8 players.
544
+ *
545
+ * `standings` is how a 3+ player game declares the finishing ORDER (best
546
+ * first). Pass it whenever there IS a ranking: it cannot be derived from
547
+ * `scores`, because a high score wins in some games and a low one wins in
548
+ * others. Accepts ids or {userId} objects. Omit for 1-on-1.
549
+ *
550
+ * result: { winnerId | draw, standings?, scores?, displayScore?, metric?,
551
+ * matchId?, roomId? }. Returns Promise<{ ok, notified? }>. See
552
+ * types/index.d.ts + the usion-app skill for the full contract.
553
+ */
554
+ game.reportResult = function(result, opts) {
555
+ const self = this;
556
+ result = result || {};
557
+ opts = opts || {};
558
+
559
+ if (!result.draw && (typeof result.winnerId !== 'string' || !result.winnerId)) {
560
+ return Promise.reject(new UsionError(
561
+ ERROR_CODES.INVALID_INPUT,
562
+ 'reportResult needs a winnerId (or draw: true)'));
563
+ }
564
+
565
+ const roomId = result.roomId || self.roomId || (Usion.config && Usion.config.roomId) || null;
566
+ if (!roomId) {
567
+ return Promise.reject(new UsionError(
568
+ ERROR_CODES.NO_ROOM, 'reportResult needs a room — join a game first'));
569
+ }
570
+
571
+ // Normalize standings to a plain id array. The server drops anything that
572
+ // isn't actually in the room, so a stray entry can't fabricate a player.
573
+ let standings = null;
574
+ if (Array.isArray(result.standings)) {
575
+ standings = result.standings
576
+ .map(function(e) {
577
+ if (typeof e === 'string') return e;
578
+ return (e && (e.userId || e.user_id)) || null;
579
+ })
580
+ .filter(function(id) { return typeof id === 'string' && id; });
581
+ if (!standings.length) standings = null;
582
+ }
583
+
584
+ return Usion._backendEmit('gc:match_result', {
585
+ service_id: opts.serviceId || (Usion.config && Usion.config.serviceId),
586
+ room_id: roomId,
587
+ winner_id: result.draw ? null : result.winnerId,
588
+ draw: !!result.draw,
589
+ standings: standings,
590
+ scores: (result.scores && typeof result.scores === 'object') ? result.scores : null,
591
+ display_score: result.displayScore != null ? String(result.displayScore) : null,
592
+ metric: result.metric != null ? String(result.metric) : null,
593
+ match_id: result.matchId != null ? String(result.matchId) : null,
594
+ });
595
+ };
596
+
533
597
  /**
534
598
  * Invite friends to play in your room — like asking for money, but for players.
535
599
  *
@@ -1,64 +1,157 @@
1
1
  /**
2
- * Usion SDK Storage Module — persistent storage (per-user, per-service)
2
+ * Usion SDK Storage Module — durable storage (per-user, per-service).
3
+ *
4
+ * The database `storage` scope is authoritative. Host-provided local storage
5
+ * remains a best-effort offline cache and a one-time migration source for
6
+ * values written by SDKs before 2.27.
3
7
  */
4
8
 
9
+ var DATA_PREFIX = '_d:';
10
+ var MIGRATION_KEY = '_migrated_v2';
11
+
12
+ function dbKey(key) {
13
+ return DATA_PREFIX + key;
14
+ }
15
+
16
+ function emit(Usion, event, extra) {
17
+ return Usion._backendEmit(event, Object.assign({
18
+ service_id: Usion.config && Usion.config.serviceId,
19
+ scope: 'storage',
20
+ }, extra));
21
+ }
22
+
23
+ function localGet(Usion, key) {
24
+ return Usion._request('STORAGE_GET', { key: key }).then(function (response) {
25
+ return response ? response.value : null;
26
+ });
27
+ }
28
+
29
+ function localSet(Usion, key, value) {
30
+ return Usion._request('STORAGE_SET', { key: key, value: value });
31
+ }
32
+
33
+ function localRemove(Usion, key) {
34
+ return Usion._request('STORAGE_REMOVE', { key: key });
35
+ }
36
+
37
+ function localKeys(Usion) {
38
+ return Usion._request('STORAGE_KEYS', {}).then(function (response) {
39
+ return (response && response.keys) || [];
40
+ });
41
+ }
42
+
43
+ function bestEffort(promise) {
44
+ return promise.catch(function () { return; });
45
+ }
46
+
5
47
  /**
6
48
  * @param {object} Usion - Reference to the main Usion object
7
49
  */
8
50
  export function createStorageModule(Usion) {
51
+ var migrationPromise = null;
52
+
53
+ /**
54
+ * Import the complete legacy cache once, then persist a database sentinel.
55
+ * The sentinel prevents a removed database key from being recreated later
56
+ * by a stale device cache.
57
+ */
58
+ function ensureMigrated() {
59
+ if (migrationPromise) return migrationPromise;
60
+ migrationPromise = emit(Usion, 'kv:get', { key: MIGRATION_KEY }).then(function (result) {
61
+ if (result && result.exists && result.value === true) return;
62
+ return Promise.all([
63
+ emit(Usion, 'kv:keys', {}),
64
+ localKeys(Usion),
65
+ ]).then(function (results) {
66
+ var durableKeys = new Set((results[0] && results[0].keys) || []);
67
+ return Promise.all(results[1].map(function (key) {
68
+ var target = dbKey(key);
69
+ if (durableKeys.has(target)) return;
70
+ return localGet(Usion, key).then(function (legacyValue) {
71
+ if (legacyValue == null) return;
72
+ return emit(Usion, 'kv:set', { key: target, value: legacyValue });
73
+ });
74
+ }));
75
+ }).then(function () {
76
+ return emit(Usion, 'kv:set', { key: MIGRATION_KEY, value: true });
77
+ });
78
+ }).catch(function (error) {
79
+ migrationPromise = null;
80
+ throw error;
81
+ });
82
+ return migrationPromise;
83
+ }
84
+
9
85
  return {
10
86
  /**
11
- * Get a stored value
12
- * @param {string} key - Storage key
13
- * @returns {Promise<any>} Stored value or null
87
+ * Read from the database, falling back to the device cache only when the
88
+ * database is unavailable.
14
89
  */
15
- get: function(key) {
16
- return Usion._request('STORAGE_GET', { key: key }).then(function(response) {
17
- return response.value;
90
+ get: function (key) {
91
+ return ensureMigrated().then(function () {
92
+ return emit(Usion, 'kv:get', { key: dbKey(key) });
93
+ }).then(function (result) {
94
+ if (result && result.exists) {
95
+ return bestEffort(localSet(Usion, key, result.value)).then(function () {
96
+ return result.value;
97
+ });
98
+ }
99
+ // Absence after the migration sentinel is authoritative.
100
+ return bestEffort(localRemove(Usion, key)).then(function () {
101
+ return null;
102
+ });
103
+ }).catch(function (databaseError) {
104
+ return localGet(Usion, key).then(function (cachedValue) {
105
+ if (cachedValue != null) return cachedValue;
106
+ throw databaseError;
107
+ }, function () {
108
+ throw databaseError;
109
+ });
18
110
  });
19
111
  },
20
112
 
21
- /**
22
- * Set a stored value
23
- * @param {string} key - Storage key
24
- * @param {any} value - Value to store (will be JSON serialized)
25
- * @returns {Promise<void>}
26
- */
27
- set: function(key, value) {
28
- return Usion._request('STORAGE_SET', { key: key, value: value }).then(function() {
29
- return;
113
+ /** Persist to the database before refreshing the local cache. */
114
+ set: function (key, value) {
115
+ return ensureMigrated().then(function () {
116
+ return emit(Usion, 'kv:set', { key: dbKey(key), value: value });
117
+ }).then(function () {
118
+ return bestEffort(localSet(Usion, key, value));
30
119
  });
31
120
  },
32
121
 
33
- /**
34
- * Remove a stored value
35
- * @param {string} key - Storage key
36
- * @returns {Promise<void>}
37
- */
38
- remove: function(key) {
39
- return Usion._request('STORAGE_REMOVE', { key: key }).then(function() {
40
- return;
122
+ /** Delete from the database before evicting the local cache. */
123
+ remove: function (key) {
124
+ return ensureMigrated().then(function () {
125
+ return emit(Usion, 'kv:remove', { key: dbKey(key) });
126
+ }).then(function () {
127
+ return bestEffort(localRemove(Usion, key));
41
128
  });
42
129
  },
43
130
 
44
- /**
45
- * Clear all stored values for this service
46
- * @returns {Promise<void>}
47
- */
48
- clear: function() {
49
- return Usion._request('STORAGE_CLEAR', {}).then(function() {
50
- return;
131
+ /** Clear only the storage data namespace, preserving the migration guard. */
132
+ clear: function () {
133
+ return ensureMigrated().then(function () {
134
+ return emit(Usion, 'kv:clear', { prefix: DATA_PREFIX });
135
+ }).then(function () {
136
+ return bestEffort(Usion._request('STORAGE_CLEAR', {}));
51
137
  });
52
138
  },
53
139
 
54
- /**
55
- * Get all keys
56
- * @returns {Promise<string[]>}
57
- */
58
- keys: function() {
59
- return Usion._request('STORAGE_KEYS', {}).then(function(response) {
60
- return response.keys || [];
140
+ /** List durable keys; internal metadata is never exposed. */
141
+ keys: function () {
142
+ return ensureMigrated().then(function () {
143
+ return emit(Usion, 'kv:keys', {});
144
+ }).then(function (result) {
145
+ return ((result && result.keys) || []).filter(function (key) {
146
+ return key.indexOf(DATA_PREFIX) === 0;
147
+ }).map(function (key) {
148
+ return key.slice(DATA_PREFIX.length);
149
+ });
150
+ }).catch(function (databaseError) {
151
+ return localKeys(Usion).catch(function () {
152
+ throw databaseError;
153
+ });
61
154
  });
62
- }
155
+ },
63
156
  };
64
157
  }
package/types/index.d.ts CHANGED
@@ -79,10 +79,15 @@ export interface UserModule {
79
79
  // ─── Storage ─────────────────────────────────────────────────────
80
80
 
81
81
  export interface StorageModule {
82
- get(key: string): Promise<any>;
82
+ /** Durable per-user/per-service read; device cache is an offline fallback. */
83
+ get(key: string): Promise<any | null>;
84
+ /** Resolves only after the database acknowledges the write. */
83
85
  set(key: string, value: any): Promise<void>;
86
+ /** Resolves only after the database acknowledges the delete. */
84
87
  remove(key: string): Promise<void>;
88
+ /** Clears only this service's durable storage scope for the current user. */
85
89
  clear(): Promise<void>;
90
+ /** Lists durable keys; SDK migration metadata is never returned. */
86
91
  keys(): Promise<string[]>;
87
92
  }
88
93
 
@@ -325,6 +330,39 @@ export interface GameInviteResult {
325
330
  invited: string[];
326
331
  }
327
332
 
333
+ /** Final result of a match, passed to game.reportResult(). */
334
+ export interface MatchResult {
335
+ /** userId of the winner. Required unless `draw` is true. */
336
+ winnerId?: string;
337
+ /** True when the match ended in a draw (no winner). */
338
+ draw?: boolean;
339
+ /** Final score per userId, e.g. `{ [alice]: 3, [bob]: 1 }`. Optional. */
340
+ scores?: Record<string, number>;
341
+ /** Game-authored score text for the card, e.g. "3 - 1". Optional. */
342
+ displayScore?: string;
343
+ /** Optional label for the score, e.g. "goals", "points", "time". */
344
+ metric?: string;
345
+ /**
346
+ * Finishing order for a 3+ player match, BEST FIRST — how the card ranks
347
+ * everyone. Pass it whenever there is a ranking: it cannot be derived from
348
+ * `scores`, since a high score wins in some games and a low one wins in
349
+ * others. Ids not in the room are ignored; anyone omitted is appended.
350
+ * Omit for 1-on-1. (SDK ≥ 2.27)
351
+ */
352
+ standings?: Array<string | { userId: string }>;
353
+ /** Optional idempotency key for this match (dedupes ack retries). */
354
+ matchId?: string;
355
+ /** Room to report for (defaults to the current room). */
356
+ roomId?: string;
357
+ }
358
+
359
+ /** Ack from game.reportResult(). */
360
+ export interface MatchResultAck {
361
+ ok: boolean;
362
+ /** How many participants were sent a Game Center card. */
363
+ notified?: number;
364
+ }
365
+
328
366
  /** Options for game.joinWorld(). */
329
367
  export interface JoinWorldOptions {
330
368
  /** Service to place into (defaults to the current service). */
@@ -439,6 +477,26 @@ export interface GameModule {
439
477
  requestRematch(): void;
440
478
  forfeit(): Promise<{ success: boolean; error?: string }>;
441
479
 
480
+ /**
481
+ * Report the final result of a finished 2–8 player match.
482
+ *
483
+ * WHERE the card lands follows where the game was launched from:
484
+ * - **Started in a group chat** → one ranked standings card posted into that
485
+ * group. Covers 1-on-1 too, so the group sees who beat who.
486
+ * - **Anywhere else** (GameTok / invite / matchmaking) → cards in the direct
487
+ * chats, written from each player's perspective ("You beat Bob — 3 : 1" /
488
+ * "Bob beat you — 1 : 3"). A 3–8 player match fans a standings card across
489
+ * the host↔guest DMs.
490
+ *
491
+ * Call ONCE, from the authoritative client only (your host,
492
+ * `config.playerIds[0]`), the moment the match ends. The backend re-checks
493
+ * that the players really shared this room, so a peer can't fabricate a
494
+ * result. Pass an EXPLICIT `winnerId` — Game Center never infers the winner
495
+ * from the scores, so lowest-wins and no-score games work identically, and
496
+ * pass `standings` for a 3+ player ranking. (SDK ≥ 2.26; `standings` ≥ 2.27)
497
+ */
498
+ reportResult(result: MatchResult, opts?: { serviceId?: string }): Promise<MatchResultAck>;
499
+
442
500
  /**
443
501
  * Invite friends to play in your room. Opens the host's friend/group picker
444
502
  * (recent chats + username search + your groups, multi-select); each pick gets