@usions/sdk 2.32.0 → 2.34.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.
@@ -1,3 +1,5 @@
1
+ import { applyGameSyncedState } from './game-synced-state.js';
2
+
1
3
  /**
2
4
  * Usion SDK Game Reliability — the reconnection-lifecycle surface promised in
3
5
  * v2.16: sequence getters, the unified connection-state machine, and
@@ -105,174 +107,5 @@ export function applyGameReliability(game, Usion) {
105
107
  game.on('joined', trackHost);
106
108
  game.on('playerJoined', trackHost);
107
109
 
108
- // ── syncedState ───────────────────────────────────────────────────────────
109
-
110
- /**
111
- * Reconnect-safe authoritative shared state. Commits are sequenced actions
112
- * applied through `reduce` on every client in the same order (deduped by
113
- * sequence); the authority (player_ids[0] by default) auto-checkpoints via
114
- * setState, and (re)joining clients recover automatically (checkpoint +
115
- * un-checkpointed tail). Degrades to local-apply in direct mode.
116
- * Full contract: SyncedStateOptions / SyncedState in types/index.d.ts.
117
- */
118
- game.syncedState = function (initial, opts) {
119
- opts = opts || {};
120
- var self = this;
121
- var reduce = typeof opts.reduce === 'function'
122
- ? opts.reduce
123
- : function (state, action) { return Object.assign({}, state, action.data); };
124
- var checkpointEvery = opts.checkpointEvery != null ? opts.checkpointEvery : 1;
125
- var authorityMode = opts.authority === 'all' ? 'all' : 'host';
126
- var defaultType = opts.type || 'update';
127
-
128
- var state = initial === undefined ? {} : initial;
129
- var appliedSeq = 0;
130
- var sinceCheckpoint = 0;
131
- var lastGapRequest = -1;
132
- var changeCbs = [];
133
- var offs = [];
134
-
135
- function notify(reason) {
136
- var copy = changeCbs.slice();
137
- for (var i = 0; i < copy.length; i++) {
138
- try { copy[i](state, reason); } catch (e) { Usion.log('syncedState onChange error: ' + e.message); }
139
- }
140
- }
141
-
142
- function isAuthority() {
143
- if (authorityMode === 'all') return true;
144
- var me = self.playerId || (Usion.user && Usion.user.getId && Usion.user.getId());
145
- return !!(me && self._hostId && me === self._hostId);
146
- }
147
-
148
- function doCheckpoint() {
149
- if (self.directMode) {
150
- return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode' });
151
- }
152
- // The wrapper carries the sequence the checkpoint reflects, so recovery
153
- // knows exactly where the un-checkpointed tail starts.
154
- return self.setState({ __usionSyncedState: 1, seq: appliedSeq, state: state });
155
- }
156
-
157
- function maybeAutoCheckpoint() {
158
- if (!(checkpointEvery > 0) || !isAuthority()) return;
159
- sinceCheckpoint += 1;
160
- if (sinceCheckpoint >= checkpointEvery) {
161
- sinceCheckpoint = 0;
162
- doCheckpoint();
163
- }
164
- }
165
-
166
- function applyOne(playerId, type, data, sequence) {
167
- if (sequence !== undefined && sequence <= appliedSeq) return false; // dedupe
168
- var next;
169
- try {
170
- next = reduce(state, { playerId: playerId, type: type, data: data, sequence: sequence });
171
- } catch (e) {
172
- Usion.log('syncedState reduce error: ' + e.message);
173
- return false;
174
- }
175
- if (next !== undefined) state = next;
176
- if (sequence !== undefined) appliedSeq = sequence;
177
- return true;
178
- }
179
-
180
- function onAction(d) {
181
- if (!d) return;
182
- if (applyOne(d.player_id, d.action_type, d.action_data, d.sequence)) {
183
- notify('action');
184
- maybeAutoCheckpoint();
185
- }
186
- }
187
-
188
- // Recover from a join ack or sync payload: load the checkpoint (if it is
189
- // ours and newer), replay the action tail in order, and if the server's
190
- // sequence is still ahead of us, ask once for the missing range.
191
- function recover(d) {
192
- if (!d) return;
193
- var changed = false;
194
-
195
- var gs = d.game_state;
196
- if (gs && gs.__usionSyncedState && typeof gs.seq === 'number'
197
- && gs.seq >= appliedSeq && gs.state !== undefined) {
198
- state = gs.state;
199
- appliedSeq = gs.seq;
200
- changed = true;
201
- }
202
-
203
- var actions = d.actions;
204
- if (actions && actions.length) {
205
- var sorted = actions.slice().sort(function (a, b) {
206
- return (a.sequence || 0) - (b.sequence || 0);
207
- });
208
- for (var i = 0; i < sorted.length; i++) {
209
- var item = sorted[i];
210
- if (item && applyOne(item.player_id, item.action_type, item.action_data, item.sequence)) {
211
- changed = true;
212
- }
213
- }
214
- }
215
-
216
- if (changed) notify('recover');
217
-
218
- // Gap fill: the checkpoint may lag the room sequence (checkpointEvery>1).
219
- // Request the tail from OUR applied sequence — once per position, so a
220
- // trimmed history can't loop us.
221
- if (d.sequence !== undefined && d.sequence > appliedSeq && lastGapRequest !== appliedSeq) {
222
- lastGapRequest = appliedSeq;
223
- try { self.requestSync(appliedSeq); } catch (e) { /* non-fatal */ }
224
- }
225
- }
226
-
227
- offs.push(self.on('action', onAction));
228
- offs.push(self.on('sync', recover));
229
- offs.push(self.on('joined', recover));
230
-
231
- return {
232
- /** Current state value. */
233
- get: function () { return state; },
234
-
235
- /**
236
- * Commit a change: commit(data) with the default action type, or
237
- * commit(type, data, opts) to name it (opts forwarded to game.action,
238
- * e.g. nextTurn / queueOffline). Applied exactly once via the echo.
239
- */
240
- commit: function (typeOrData, data, actionOpts) {
241
- var t, payload, o;
242
- if (typeof typeOrData === 'string') { t = typeOrData; payload = data; o = actionOpts; }
243
- else { t = defaultType; payload = typeOrData; o = data; }
244
- if (self.directMode) {
245
- // No platform echo in direct mode — apply locally, then send.
246
- if (applyOne(self.playerId, t, payload, undefined)) notify('action');
247
- return self.action(t, payload, o);
248
- }
249
- return self.action(t, payload, o);
250
- },
251
-
252
- /** Subscribe to changes: cb(state, reason). Returns an unsubscribe fn. */
253
- onChange: function (cb) {
254
- changeCbs.push(cb);
255
- return function () {
256
- var i = changeCbs.indexOf(cb);
257
- if (i >= 0) changeCbs.splice(i, 1);
258
- };
259
- },
260
-
261
- /** Whether this client is the checkpointing authority. */
262
- isAuthority: isAuthority,
263
-
264
- /** Force a server checkpoint now (no-op result in direct mode). */
265
- checkpoint: function () { return doCheckpoint(); },
266
-
267
- /** Sequence of the last action applied into this state. */
268
- getSequence: function () { return appliedSeq; },
269
-
270
- /** Detach all listeners; the instance stops receiving updates. */
271
- destroy: function () {
272
- for (var i = 0; i < offs.length; i++) { try { offs[i](); } catch (e) { /* noop */ } }
273
- offs.length = 0;
274
- changeCbs.length = 0;
275
- },
276
- };
277
- };
110
+ applyGameSyncedState(game, Usion);
278
111
  }
@@ -0,0 +1,208 @@
1
+ export function applyGameSyncedState(game, Usion) {
2
+ // ── syncedState ───────────────────────────────────────────────────────────
3
+
4
+ /**
5
+ * Reconnect-safe authoritative shared state. Commits are sequenced actions
6
+ * applied through `reduce` on every client in the same order (deduped by
7
+ * sequence); the authority (player_ids[0] by default) auto-checkpoints via
8
+ * setState, and (re)joining clients recover automatically (checkpoint +
9
+ * un-checkpointed tail). Degrades to local-apply in direct mode.
10
+ * Full contract: SyncedStateOptions / SyncedState in types/index.d.ts.
11
+ */
12
+ game.syncedState = function (initial, opts) {
13
+ opts = opts || {};
14
+ var self = this;
15
+ var reduce = typeof opts.reduce === 'function'
16
+ ? opts.reduce
17
+ : function (state, action) { return Object.assign({}, state, action.data); };
18
+ var checkpointEvery = opts.checkpointEvery != null ? opts.checkpointEvery : 1;
19
+ var authorityMode = opts.authority === 'all' ? 'all' : 'host';
20
+ var defaultType = opts.type || 'update';
21
+
22
+ var state = initial === undefined ? {} : initial;
23
+ var appliedSeq = 0;
24
+ var sinceCheckpoint = 0;
25
+ var lastGapRequest = -1;
26
+ var highestSeen = 0;
27
+ var pending = new Map();
28
+ var changeCbs = [];
29
+ var offs = [];
30
+
31
+ function notify(reason) {
32
+ var copy = changeCbs.slice();
33
+ for (var i = 0; i < copy.length; i++) {
34
+ try { copy[i](state, reason); } catch (e) { Usion.log('syncedState onChange error: ' + e.message); }
35
+ }
36
+ }
37
+
38
+ function isAuthority() {
39
+ if (authorityMode === 'all') return true;
40
+ var me = self.playerId || (Usion.user && Usion.user.getId && Usion.user.getId());
41
+ return !!(me && self._hostId && me === self._hostId);
42
+ }
43
+
44
+ function doCheckpoint() {
45
+ if (self.directMode) {
46
+ return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode' });
47
+ }
48
+ // The wrapper carries the sequence the checkpoint reflects, so recovery
49
+ // knows exactly where the un-checkpointed tail starts.
50
+ return self.setState({ __usionSyncedState: 1, seq: appliedSeq, state: state });
51
+ }
52
+
53
+ function maybeAutoCheckpoint(count) {
54
+ if (!(checkpointEvery > 0) || !isAuthority()) return;
55
+ sinceCheckpoint += count;
56
+ if (sinceCheckpoint >= checkpointEvery) {
57
+ sinceCheckpoint = 0;
58
+ doCheckpoint();
59
+ }
60
+ }
61
+
62
+ function applyOne(playerId, type, data, sequence) {
63
+ if (sequence !== undefined) {
64
+ if (!Number.isSafeInteger(sequence) || sequence <= appliedSeq) return false;
65
+ highestSeen = Math.max(highestSeen, sequence);
66
+ if (sequence !== appliedSeq + 1) {
67
+ // Concurrent relay handlers can broadcast N+1 before N. Never treat
68
+ // the newer echo as a complete prefix or checkpoint over the hole.
69
+ // Bound the buffer to the server's action-history limit; sync remains
70
+ // authoritative if a very long gap requires a newer checkpoint.
71
+ if (pending.size < 1000) pending.set(sequence, {playerId, type, data, sequence});
72
+ return false;
73
+ }
74
+ }
75
+ var next;
76
+ try {
77
+ next = reduce(state, { playerId: playerId, type: type, data: data, sequence: sequence });
78
+ } catch (e) {
79
+ Usion.log('syncedState reduce error: ' + e.message);
80
+ return false;
81
+ }
82
+ if (next !== undefined) state = next;
83
+ if (sequence !== undefined) appliedSeq = sequence;
84
+ return true;
85
+ }
86
+
87
+ function drainPending() {
88
+ var count = 0;
89
+ pending.forEach(function (_, seq) { if (seq <= appliedSeq) pending.delete(seq); });
90
+ while (pending.has(appliedSeq + 1)) {
91
+ var item = pending.get(appliedSeq + 1);
92
+ if (!applyOne(item.playerId, item.type, item.data, item.sequence)) break;
93
+ pending.delete(item.sequence);
94
+ count += 1;
95
+ }
96
+ return count;
97
+ }
98
+
99
+ function requestGap() {
100
+ if (highestSeen <= appliedSeq || lastGapRequest === appliedSeq) return;
101
+ lastGapRequest = appliedSeq;
102
+ // Use the reducer's contiguous cursor, NOT the transport's high-water
103
+ // mark. Socket/proxy duplicate filtering may already have seen N+1.
104
+ try { self.requestSync(appliedSeq); } catch (e) { lastGapRequest = -1; }
105
+ }
106
+
107
+ function onAction(d) {
108
+ if (!d) return;
109
+ var count = applyOne(d.player_id, d.action_type, d.action_data, d.sequence) ? 1 : 0;
110
+ count += drainPending();
111
+ if (count) {
112
+ notify('action');
113
+ maybeAutoCheckpoint(count);
114
+ }
115
+ requestGap();
116
+ }
117
+
118
+ // Recover from a join ack or sync payload: load the checkpoint (if it is
119
+ // ours and newer), replay the action tail in order, and if the server's
120
+ // sequence is still ahead of us, ask once for the missing range.
121
+ function recover(d) {
122
+ if (!d) return;
123
+ var changed = false;
124
+ if (Number.isSafeInteger(d.sequence)) highestSeen = Math.max(highestSeen, d.sequence);
125
+
126
+ var gs = d.game_state;
127
+ if (gs && gs.__usionSyncedState && typeof gs.seq === 'number'
128
+ && gs.seq >= appliedSeq && gs.state !== undefined) {
129
+ state = gs.state;
130
+ appliedSeq = gs.seq;
131
+ changed = true;
132
+ }
133
+
134
+ var actions = d.actions;
135
+ if (actions && actions.length) {
136
+ var sorted = actions.slice().sort(function (a, b) {
137
+ return (a.sequence || 0) - (b.sequence || 0);
138
+ });
139
+ for (var i = 0; i < sorted.length; i++) {
140
+ var item = sorted[i];
141
+ if (item && applyOne(item.player_id, item.action_type, item.action_data, item.sequence)) {
142
+ changed = true;
143
+ }
144
+ }
145
+ }
146
+
147
+ if (drainPending()) changed = true;
148
+ if (changed) notify('recover');
149
+
150
+ // Gap fill: the checkpoint may lag the room sequence (checkpointEvery>1).
151
+ // Request the tail from OUR applied sequence — once per position, so a
152
+ // trimmed history can't loop us.
153
+ requestGap();
154
+ }
155
+
156
+ offs.push(self.on('action', onAction));
157
+ offs.push(self.on('sync', recover));
158
+ offs.push(self.on('joined', recover));
159
+
160
+ return {
161
+ /** Current state value. */
162
+ get: function () { return state; },
163
+
164
+ /**
165
+ * Commit a change: commit(data) with the default action type, or
166
+ * commit(type, data, opts) to name it (opts forwarded to game.action,
167
+ * e.g. nextTurn / queueOffline). Applied exactly once via the echo.
168
+ */
169
+ commit: function (typeOrData, data, actionOpts) {
170
+ var t, payload, o;
171
+ if (typeof typeOrData === 'string') { t = typeOrData; payload = data; o = actionOpts; }
172
+ else { t = defaultType; payload = typeOrData; o = data; }
173
+ if (self.directMode) {
174
+ // No platform echo in direct mode — apply locally, then send.
175
+ if (applyOne(self.playerId, t, payload, undefined)) notify('action');
176
+ return self.action(t, payload, o);
177
+ }
178
+ return self.action(t, payload, o);
179
+ },
180
+
181
+ /** Subscribe to changes: cb(state, reason). Returns an unsubscribe fn. */
182
+ onChange: function (cb) {
183
+ changeCbs.push(cb);
184
+ return function () {
185
+ var i = changeCbs.indexOf(cb);
186
+ if (i >= 0) changeCbs.splice(i, 1);
187
+ };
188
+ },
189
+
190
+ /** Whether this client is the checkpointing authority. */
191
+ isAuthority: isAuthority,
192
+
193
+ /** Force a server checkpoint now (no-op result in direct mode). */
194
+ checkpoint: function () { return doCheckpoint(); },
195
+
196
+ /** Sequence of the last action applied into this state. */
197
+ getSequence: function () { return appliedSeq; },
198
+
199
+ /** Detach all listeners; the instance stops receiving updates. */
200
+ destroy: function () {
201
+ for (var i = 0; i < offs.length; i++) { try { offs[i](); } catch (e) { /* noop */ } }
202
+ offs.length = 0;
203
+ changeCbs.length = 0;
204
+ pending.clear();
205
+ },
206
+ };
207
+ };
208
+ }
@@ -12,6 +12,7 @@
12
12
  * - Real-time game support via Socket.IO
13
13
  */
14
14
 
15
+ import { createCallModule } from './call.js';
15
16
  import { core } from './core.js';
16
17
  import { createUserModule } from './user.js';
17
18
  import { createStorageModule } from './storage.js';
@@ -24,6 +25,7 @@ import { createBackButtonMethods } from './back-button.js';
24
25
  import { createHostTabsMethods } from './host-tabs.js';
25
26
  import { uiMethods } from './ui.js';
26
27
  import { miscMethods } from './misc.js';
28
+ import { appLinkMethods } from './app-links.js';
27
29
  import { createFileStorageModule } from './file-storage.js';
28
30
  import { createGameModule } from './game-core.js';
29
31
  import { createLobbyModule } from './lobby.js';
@@ -33,6 +35,7 @@ import { createMatchmakingModule } from './matchmaking.js';
33
35
  import { createNotifyModule } from './notify.js';
34
36
  import { createPermissionsModule } from './permissions.js';
35
37
  import { createScreenModule } from './screen.js';
38
+ import { createProfileModule } from './profile.js';
36
39
  import { applyBackendChannel } from './backend-channel.js';
37
40
  import { netcode } from './netcode/index.js';
38
41
  import { UsionError, ERROR_CODES } from './errors.js';
@@ -63,6 +66,8 @@ Usion.notify = createNotifyModule(Usion);
63
66
  Usion.permissions = createPermissionsModule(Usion);
64
67
  // Screen-capture guard (host-mediated; honest per-platform capability).
65
68
  Usion.screen = createScreenModule(Usion);
69
+ Usion.profile = createProfileModule(Usion);
70
+ Usion.call = createCallModule(Usion);
66
71
 
67
72
  // Netcode toolkit (transport-agnostic, zero-dependency).
68
73
  Usion.netcode = netcode;
@@ -81,5 +86,6 @@ Object.assign(Usion, uiMethods);
81
86
 
82
87
  // Attach misc methods (submit, error, exit, share, log, on, requestPayment)
83
88
  Object.assign(Usion, miscMethods);
89
+ Object.assign(Usion, appLinkMethods);
84
90
 
85
91
  export default Usion;
@@ -3,7 +3,6 @@
3
3
  */
4
4
 
5
5
  import { isTrustedMessageSource } from './core.js';
6
-
7
6
  export const miscMethods = {
8
7
  /**
9
8
  * Request payment from user (legacy method)
@@ -150,21 +149,6 @@ export const miscMethods = {
150
149
  return this._request('SHARE_TO_STORY', payload, 120000);
151
150
  },
152
151
 
153
- /**
154
- * Publish content to the signed-in user's Usions feed with service attribution.
155
- * @param {'audio'|'image'|'video'|'text'|'mixed'} contentType
156
- * @param {object} data
157
- * @returns {Promise<{success: boolean, postId?: string, shareUrl?: string}>}
158
- */
159
- shareToFeed: function(contentType, data) {
160
- var payload = Object.assign({}, data, {
161
- contentType: contentType,
162
- serviceId: this.config.serviceId,
163
- serviceName: this.config.serviceName
164
- });
165
- return this._request('SHARE_TO_FEED', payload, 30000);
166
- },
167
-
168
152
  /**
169
153
  * Download a file to the device's storage / gallery. In auto mode images
170
154
  * and videos go to the gallery; other file types go to Files/Downloads.
@@ -0,0 +1,37 @@
1
+ import { UsionError, ERROR_CODES } from './errors.js';
2
+
3
+ /**
4
+ * Native cards in this app's category on the current user's profile.
5
+ * Request profile_content permission separately, following a user gesture.
6
+ * @param {{ _request: (type: string, data: object, timeout?: number) => Promise<any> }} Usion
7
+ */
8
+ export function createProfileModule(Usion) {
9
+ /** @param {string} type @param {object} data */
10
+ function request(type, data) {
11
+ const embedded = typeof window !== 'undefined'
12
+ && (('ReactNativeWebView' in window) || window.parent !== window);
13
+ if (!embedded) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Profile content requires the Usion host'));
14
+ return Usion._request(type, data, 30000);
15
+ }
16
+ return {
17
+ /** @returns {Promise<import('../../types/index.js').ProfileContent>} */
18
+ getContent() {
19
+ return request('PROFILE_CONTENT_GET', {}).then(response => response.content);
20
+ },
21
+ /**
22
+ * Replace this app's cards. An empty list hides the category.
23
+ * @param {import('../../types/index.js').ProfileContent} content
24
+ * @returns {Promise<import('../../types/index.js').ProfileContent>}
25
+ */
26
+ setContent(content) {
27
+ if (!content || !Array.isArray(content.items) || content.items.length > 50) {
28
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'Profile content requires at most 50 items'));
29
+ }
30
+ return request('PROFILE_CONTENT_SET', { content }).then(response => response.content);
31
+ },
32
+ /** Remove this app's content, including after permission is revoked. */
33
+ clearContent() {
34
+ return request('PROFILE_CONTENT_CLEAR', {}).then(() => undefined);
35
+ },
36
+ };
37
+ }
@@ -74,6 +74,18 @@ export function createUserModule(Usion) {
74
74
  isAdult: Usion.user.isAdult()
75
75
  };
76
76
  });
77
+ },
78
+
79
+ /**
80
+ * Open another player's Usion profile (SDK ≥ 2.33) — e.g. when a
81
+ * leaderboard row is tapped. The host shows the profile over the app and
82
+ * the app keeps running underneath; back returns to it. Fire-and-forget:
83
+ * a no-op outside the Usion host or for an id that isn't a real user.
84
+ * @param {string} userId - A player's id (leaderboard `user_id`, room `player_ids`)
85
+ */
86
+ openProfile: function(userId) {
87
+ if (typeof userId !== 'string' || !userId || userId.indexOf('guest_') === 0) return;
88
+ Usion._post({ type: 'OPEN_USER_PROFILE', userId: userId });
77
89
  }
78
90
  };
79
91
  }