@usions/sdk 2.32.0 → 2.33.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,256 @@
1
+ /**
2
+ * Usion SDK App links — post to the News Feed with a link back into the app,
3
+ * and open an app at an in-app path (SDK >= 2.33).
4
+ *
5
+ * An app link is just two strings: a service id + a relative in-app path
6
+ * (the same `path` Usion.notify uses, read back via getLaunchParams().path or
7
+ * Usion.onHostNavigate). Plain host postMessages, not the backend channel.
8
+ */
9
+
10
+ import { UsionError, ERROR_CODES } from './errors.js';
11
+
12
+ // Same rule as the backend's validate_path (services/service_notifications.py)
13
+ // and the hosts' sanitizeAppPath: a relative in-app path, one leading '/'.
14
+ var APP_PATH_MAX = 512;
15
+ var APP_PATH_ILLEGAL = /[\x00-\x1f\x7f\s\\]/;
16
+
17
+ /**
18
+ * @param {*} path
19
+ * @returns {string|null} An error message, or null when the path is valid.
20
+ */
21
+ function appPathError(path) {
22
+ if (typeof path !== 'string') return 'path must be a string';
23
+ if (path.length > APP_PATH_MAX) return 'path too long (max ' + APP_PATH_MAX + ')';
24
+ if (path.charAt(0) !== '/' || path.charAt(1) === '/') {
25
+ return "path must be a relative in-app path starting with a single '/'";
26
+ }
27
+ if (path.indexOf('://') !== -1 || APP_PATH_ILLEGAL.test(path)) {
28
+ return 'path contains illegal characters';
29
+ }
30
+ return null;
31
+ }
32
+
33
+ var CARD_TITLE_MAX = 200;
34
+ var CARD_SUBTITLE_MAX = 60;
35
+
36
+ /** Length in Unicode code points (an emoji counts once, like the backend). */
37
+ function codePoints(str) {
38
+ return Array.from(str).length;
39
+ }
40
+
41
+ /**
42
+ * @param {*} card
43
+ * @returns {{error: string}|{card: {title: string, subtitle?: string}}}
44
+ */
45
+ function normalizeCard(card) {
46
+ if (!card || typeof card !== 'object' || Array.isArray(card)) {
47
+ return { error: 'card must be an object' };
48
+ }
49
+ var title = typeof card.title === 'string' ? card.title.trim() : '';
50
+ if (!title) return { error: 'card.title is required' };
51
+ if (codePoints(title) > CARD_TITLE_MAX) {
52
+ return { error: 'card.title too long (max ' + CARD_TITLE_MAX + ')' };
53
+ }
54
+ var out = { title: title };
55
+ if (card.subtitle != null) {
56
+ if (typeof card.subtitle !== 'string') return { error: 'card.subtitle must be a string' };
57
+ var subtitle = card.subtitle.trim();
58
+ if (codePoints(subtitle) > CARD_SUBTITLE_MAX) {
59
+ return { error: 'card.subtitle too long (max ' + CARD_SUBTITLE_MAX + ')' };
60
+ }
61
+ if (subtitle) out.subtitle = subtitle;
62
+ }
63
+ return { card: out };
64
+ }
65
+
66
+ var IMAGE_MAX_BYTES = 5 * 1024 * 1024;
67
+ var IMAGE_PREFIX = /^data:image\/(png|jpeg|webp);base64,/;
68
+ var BASE64_BODY = /^[A-Za-z0-9+/]+={0,2}$/;
69
+
70
+ /**
71
+ * Validate a feed image: a base64 data URL (png/jpeg/webp), decoded <= 5 MB.
72
+ * @param {*} image
73
+ * @returns {string|null} An error message, or null when valid.
74
+ */
75
+ function imageError(image) {
76
+ var prefix = typeof image === 'string' && IMAGE_PREFIX.exec(image);
77
+ if (!prefix) return 'image must be a data:image/(png|jpeg|webp);base64 URL';
78
+ var body = image.slice(prefix[0].length);
79
+ // Size first (cheap) so an oversized string is never scanned.
80
+ var padding = body.slice(-2) === '==' ? 2 : body.slice(-1) === '=' ? 1 : 0;
81
+ if (Math.floor(body.length * 3 / 4) - padding > IMAGE_MAX_BYTES) return 'image too large (max 5 MB)';
82
+ if (body.length % 4 !== 0 || !BASE64_BODY.test(body)) return 'image is not valid base64';
83
+ return null;
84
+ }
85
+
86
+ /** RFC 4122 v4 id; crypto.randomUUID where available. */
87
+ function newRequestId() {
88
+ var c = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
89
+ if (c && typeof c.randomUUID === 'function') return c.randomUUID();
90
+ var bytes = new Array(16);
91
+ if (c && typeof c.getRandomValues === 'function') {
92
+ var buf = new Uint8Array(16);
93
+ c.getRandomValues(buf);
94
+ for (var i = 0; i < 16; i++) bytes[i] = buf[i];
95
+ } else {
96
+ for (var j = 0; j < 16; j++) bytes[j] = Math.floor(Math.random() * 256);
97
+ }
98
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
99
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
100
+ var hex = bytes.map(function(b) { return (b + 0x100).toString(16).slice(1); }).join('');
101
+ return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' +
102
+ hex.slice(16, 20) + '-' + hex.slice(20);
103
+ }
104
+
105
+ export const appLinkMethods = {
106
+ /**
107
+ * Whether this host can confirm and post `shareToFeed` (it declared
108
+ * `hostFeatures.feedShare` in INIT). False outside a host and on older app
109
+ * builds — show your "Share to feed" button only when this is true.
110
+ * `canShareToFeed('image')` additionally requires `hostFeatures.feedShareImage`;
111
+ * send `image` only when it is true (older hosts drop it). (SDK >= 2.33)
112
+ * @param {'image'|'video'|'videoUpload'} [feature]
113
+ * @returns {boolean}
114
+ */
115
+ canShareToFeed: function(feature) {
116
+ var features = this.config && this.config.hostFeatures;
117
+ if (!features || features.feedShare !== true) return false;
118
+ return feature === 'image' ? features.feedShareImage === true : feature === 'video' ? features.feedShareVideo === true : feature === 'videoUpload' ? features.feedShareVideoUpload === true : !feature;
119
+ },
120
+
121
+ /** Upload a video directly, without crossing the host bridge as base64.
122
+ * @param {Blob} file
123
+ * @returns {Promise<{receipt: string}>}
124
+ */
125
+ uploadFeedVideo: function(file) {
126
+ if (!this.canShareToFeed('videoUpload')) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Video uploads require a newer host'));
127
+ var allowed = ['video/mp4', 'video/quicktime', 'video/webm', 'video/x-matroska'];
128
+ if (!file || typeof file.size !== 'number' || file.size <= 0 || file.size > 100 * 1024 * 1024 || allowed.indexOf(file.type) < 0) {
129
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'Choose a supported video of at most 100 MB'));
130
+ }
131
+ var token = this.user && this.user.getToken(), config = this.config || {};
132
+ if (!token || !config.serviceId || !config.apiUrl) return Promise.reject(new UsionError(ERROR_CODES.NOT_AUTHENTICATED, 'Sign in to upload'));
133
+ var form = new FormData();
134
+ form.append('file', file, file.name || 'video');
135
+ return fetch(config.apiUrl.replace(/\/$/, '') + '/feed/video-uploads/' + encodeURIComponent(config.serviceId), {
136
+ method: 'POST', headers: { Authorization: 'Bearer ' + token }, body: form
137
+ }).then(function(response) {
138
+ if (!response.ok) throw new UsionError(response.status === 429 ? ERROR_CODES.RATE_LIMITED : response.status === 401 ? ERROR_CODES.NOT_AUTHENTICATED : response.status === 403 ? ERROR_CODES.PERMISSION_DENIED : response.status < 500 ? ERROR_CODES.INVALID_INPUT : ERROR_CODES.UNKNOWN, 'Video upload failed');
139
+ return response.json();
140
+ }).then(function(result) {
141
+ if (!result || typeof result.receipt !== 'string') throw new UsionError(ERROR_CODES.UNKNOWN, 'Invalid upload response');
142
+ return { receipt: result.receipt };
143
+ });
144
+ },
145
+
146
+ /**
147
+ * Post a short text to the signed-in user's Usions News Feed (and so their
148
+ * profile), stamped with this app and an optional in-app `path` that readers
149
+ * tap to open the app right there. The host asks the user to confirm EVERY
150
+ * time; nothing is posted silently. Public apps only. (SDK >= 2.33)
151
+ *
152
+ * One call = at most one post: a `requestId` is generated when missing, so a
153
+ * host/network retry of the same call never duplicates the post. Pass your own
154
+ * `requestId` to make a user-level retry (e.g. a "try again" button) safe too.
155
+ *
156
+ * Rejects with a UsionError: CANCELLED (the user said no), RATE_LIMITED
157
+ * (5/min, 30/day per user per app), NOT_AUTHENTICATED (guest), PERMISSION_DENIED
158
+ * (the app is private/unlisted), INVALID_INPUT (empty text, bad path, card or
159
+ * image), REQUEST_TIMEOUT, UNKNOWN.
160
+ *
161
+ * `card` is the thing being shared (e.g. the question): the feed shows it as a
162
+ * tappable card that opens `path`, and `text` is the user's caption. The post
163
+ * mentions your app automatically. `image` is that card as a picture (e.g. a
164
+ * rendered question card): a `data:image/(png|jpeg|webp);base64,…` URL,
165
+ * decoded <= 5 MB. Send it only when `canShareToFeed('image')` is true, and
166
+ * keep `card` alongside as its text/alt.
167
+ *
168
+ * @param {'text'|'video'} contentType - Use video for an MP4 post
169
+ * @param {{text: string, path?: string, requestId?: string,
170
+ * card?: {title: string, subtitle?: string}, image?: string, video?: string}} data - card.title 1..200 and
171
+ * card.subtitle <= 60 Unicode code points, both trimmed
172
+ * @returns {Promise<{success: true, postId: string}>}
173
+ */
174
+ shareToFeed: function(contentType, data) {
175
+ data = data || {};
176
+ if (contentType === 'video' && data.video == null && data.videoReceipt == null) return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: video is required'));
177
+ var text = typeof data.text === 'string' ? data.text.trim() : '';
178
+ if (!text) {
179
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: text is required'));
180
+ }
181
+ var payload = {
182
+ contentType: contentType || 'text',
183
+ text: text,
184
+ requestId: typeof data.requestId === 'string' && data.requestId ? data.requestId : newRequestId(),
185
+ serviceId: this.config && this.config.serviceId,
186
+ serviceName: this.config && this.config.serviceName
187
+ };
188
+ if (data.path != null && data.path !== '') {
189
+ var pathError = appPathError(data.path);
190
+ if (pathError) {
191
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: ' + pathError));
192
+ }
193
+ payload.path = data.path;
194
+ }
195
+ if (data.card != null) {
196
+ var card = normalizeCard(data.card);
197
+ if ('error' in card) {
198
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: ' + card.error));
199
+ }
200
+ payload.card = card.card;
201
+ }
202
+ if (data.image != null) {
203
+ var imgError = imageError(data.image);
204
+ if (imgError) {
205
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: ' + imgError));
206
+ }
207
+ payload.image = data.image;
208
+ }
209
+ if (data.video != null) {
210
+ if (data.image != null || typeof data.video !== 'string' || !/^data:video\/mp4;base64,/.test(data.video)) {
211
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: video must be an MP4 data URL without an image'));
212
+ }
213
+ var videoBody = data.video.slice('data:video/mp4;base64,'.length);
214
+ var videoPadding = videoBody.slice(-2) === '==' ? 2 : videoBody.slice(-1) === '=' ? 1 : 0;
215
+ if (!videoBody || videoBody.length % 4 !== 0 || videoBody.length * 3 / 4 - videoPadding > IMAGE_MAX_BYTES || !BASE64_BODY.test(videoBody)) {
216
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'shareToFeed: invalid video or video exceeds 5 MB'));
217
+ }
218
+ if (!this.canShareToFeed('video')) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'shareToFeed: host does not support video'));
219
+ payload.video = data.video;
220
+ }
221
+ if (data.videoReceipt != null) {
222
+ if (data.video != null || data.image != null || typeof data.videoReceipt !== 'string' || !data.videoReceipt || data.videoReceipt.length > 8192) return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'Invalid video receipt'));
223
+ if (!this.canShareToFeed('videoUpload')) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Video uploads require a newer host'));
224
+ payload.videoReceipt = data.videoReceipt;
225
+ }
226
+ // The host waits on the user's confirm sheet (no host timeout), so allow
227
+ // 10 minutes rather than ever reporting REQUEST_TIMEOUT over an open sheet.
228
+ return this._request('SHARE_TO_FEED', payload, 600000).then(function(reply) {
229
+ return Object.assign({ success: true }, reply);
230
+ });
231
+ },
232
+
233
+ /**
234
+ * Open another Usion app (or this one) at an optional in-app path — the same
235
+ * address a notification or a feed post carries. The host checks the app
236
+ * exists and the user may open it; opening yourself just navigates in place
237
+ * (you receive HOST_NAVIGATE via Usion.onHostNavigate). Fire-and-forget; a
238
+ * no-op on hosts that predate it. (SDK >= 2.33)
239
+ *
240
+ * @param {string} serviceId - The target app's service id
241
+ * @param {string} [path] - Relative in-app path starting with a single '/'
242
+ * @throws {UsionError} INVALID_INPUT for an empty serviceId or a bad path
243
+ */
244
+ openApp: function(serviceId, path) {
245
+ if (typeof serviceId !== 'string' || !serviceId.trim()) {
246
+ throw new UsionError(ERROR_CODES.INVALID_INPUT, 'openApp: serviceId is required');
247
+ }
248
+ var msg = { type: 'OPEN_SERVICE', serviceId: serviceId.trim() };
249
+ if (path != null && path !== '') {
250
+ var pathError = appPathError(path);
251
+ if (pathError) throw new UsionError(ERROR_CODES.INVALID_INPUT, 'openApp: ' + pathError);
252
+ msg.path = path;
253
+ }
254
+ this._post(msg);
255
+ }
256
+ };
@@ -0,0 +1,46 @@
1
+ /** Permission-gated, local call signals. Streams and device handles never cross this API. */
2
+ /**
3
+ * @param {{ _request: (type: string, data: object, timeout: number) => Promise<any>, on: (type: string, callback: (event: any) => void) => (() => void) }} Usion
4
+ * @returns {import('../../types/index').CallModule}
5
+ */
6
+ export function createCallModule(Usion) {
7
+ return {
8
+ capabilities: function () {
9
+ return Usion._request('CALL_CAPABILITIES', {}, 5000);
10
+ },
11
+
12
+ /** @param {Parameters<import('../../types/index').CallModule['startAnalysis']>[0]} options */
13
+ startAnalysis: async function (options) {
14
+ if (!options || !Array.isArray(options.capabilities) || typeof options.onSample !== 'function') {
15
+ throw new Error('capabilities and onSample are required');
16
+ }
17
+ /** @type {number | null} */
18
+ var subscriptionId = null;
19
+ var stopped = false;
20
+ var offSample = Usion.on('CALL_ANALYSIS_EVENT', function (event) {
21
+ if (!stopped && subscriptionId !== null && event.subscriptionId === subscriptionId) options.onSample(event.sample);
22
+ });
23
+ var offStopped = Usion.on('CALL_ANALYSIS_STOPPED', function (event) {
24
+ if (event.subscriptionId === subscriptionId) cleanup();
25
+ });
26
+ function cleanup() {
27
+ if (stopped) return;
28
+ stopped = true;
29
+ offSample(); offStopped();
30
+ if (typeof options.onStopped === 'function') options.onStopped();
31
+ }
32
+ try {
33
+ var result = await Usion._request('CALL_ANALYSIS_START', { capabilities: options.capabilities }, 120000);
34
+ if (!result.started || !Number.isInteger(result.subscriptionId)) throw new Error('Invalid call analysis response');
35
+ subscriptionId = result.subscriptionId;
36
+ return {
37
+ stop: async function () {
38
+ if (stopped) return;
39
+ cleanup();
40
+ await Usion._request('CALL_ANALYSIS_STOP', {}, 5000);
41
+ },
42
+ };
43
+ } catch (error) { cleanup(); throw error; }
44
+ },
45
+ };
46
+ }
@@ -17,6 +17,12 @@
17
17
  * await Usion.cloud.shared.set('motd', 'hello');
18
18
  * const plays = await Usion.cloud.shared.incr('plays'); // atomic counter
19
19
  *
20
+ * Friends scope (you write yours; your accepted friends read it in this app):
21
+ * await Usion.cloud.friends.set('status', 'brb'); // max 4 KB/value, 200 keys
22
+ * const mine = await Usion.cloud.friends.get('status');
23
+ * const theirs = await Usion.cloud.friends.list('status');
24
+ * // → [{ userId, name, avatar, value, updatedAt }] — friends only, newest first
25
+ *
20
26
  * Keys: 1-128 chars of A-Za-z0-9_.-:/
21
27
  */
22
28
  export function createCloudModule(Usion) {
@@ -58,6 +64,28 @@ export function createCloudModule(Usion) {
58
64
  var cloud = scopeApi('user');
59
65
  cloud.shared = scopeApi('shared');
60
66
 
67
+ cloud.friends = scopeApi('friends');
68
+
69
+ /**
70
+ * Your accepted friends' values for `key` in this app, newest first (max
71
+ * 200). Strangers and blocked users are never included; neither are you.
72
+ * Resolves to [] for guests or when no friend has set the key.
73
+ */
74
+ cloud.friends.list = function (key, opts) {
75
+ return emit('kv:get', 'friends', { key: key, friends: true }, opts)
76
+ .then(function (r) {
77
+ return ((r && r.entries) || []).map(function (e) {
78
+ return {
79
+ userId: e.user_id,
80
+ name: e.name || null,
81
+ avatar: e.avatar || null,
82
+ value: e.value,
83
+ updatedAt: e.updated_at || null,
84
+ };
85
+ });
86
+ });
87
+ };
88
+
61
89
  /** Atomically increment a shared numeric value (default delta 1). Resolves to the new value. */
62
90
  cloud.shared.incr = function (key, delta, opts) {
63
91
  return emit('kv:incr', 'shared', { key: key, delta: delta == null ? 1 : delta }, opts)
@@ -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.32.0', // synced from package.json by scripts/sync-version.mjs
71
+ version: '2.33.0', // synced from package.json by scripts/sync-version.mjs
72
72
  config: {},
73
73
  _initialized: false,
74
74
  _initCallback: null,
@@ -168,6 +168,10 @@ export const core = {
168
168
  self.config.userIsAdult = data.config.userIsAdult;
169
169
  self.user._isAdult = data.config.userIsAdult;
170
170
  }
171
+ // Host capabilities (e.g. feedShare) — keep the latest the host declared.
172
+ if (data.config.hostFeatures && typeof data.config.hostFeatures === 'object') {
173
+ self.config.hostFeatures = data.config.hostFeatures;
174
+ }
171
175
  return;
172
176
  }
173
177
 
@@ -8,6 +8,7 @@
8
8
 
9
9
  /** @type {Record<string, string>} */
10
10
  export const ERROR_CODES = {
11
+ PERMISSION_DENIED: 'PERMISSION_DENIED', // User has not granted this app permission
11
12
  NOT_CONNECTED: 'NOT_CONNECTED', // No live connection for this call
12
13
  NO_ROOM: 'NO_ROOM', // No room id provided/known
13
14
  ROOM_NOT_FOUND: 'ROOM_NOT_FOUND', // Room does not exist server-side
@@ -9,6 +9,8 @@ import { applyGameProxy } from './game-proxy.js';
9
9
  import { applyGameMethods } from './game-methods.js';
10
10
  import { applyGameNetcode } from './game-netcode.js';
11
11
  import { applyGameReliability } from './game-reliability.js';
12
+ import { applyGameParticipants } from './game-participants.js';
13
+ import { applyGamePlayers } from './game-players.js';
12
14
 
13
15
  // Map any reasonable spelling of a game event onto the internal handler
14
16
  // name: 'game:player_joined' / 'player_joined' / 'playerJoined' → 'playerJoined'.
@@ -253,6 +255,8 @@ export function createGameModule(Usion) {
253
255
  applyGameProxy(game, Usion);
254
256
  applyGameMethods(game, Usion);
255
257
  applyGameNetcode(game, Usion);
258
+ applyGamePlayers(game, Usion);
259
+ applyGameParticipants(game, Usion);
256
260
  // Applied last: wraps connect/connectDirect and rides dispatched events.
257
261
  applyGameReliability(game, Usion);
258
262
 
@@ -130,6 +130,7 @@ export function applyGameMethods(game, Usion) {
130
130
  */
131
131
  game.leave = function() {
132
132
  const self = this;
133
+ if (self._playersConnection) self._playersConnection.close();
133
134
 
134
135
  if (self.directMode) {
135
136
  if (self.roomId) self._sendDirect('leave', {});
@@ -381,7 +382,13 @@ export function applyGameMethods(game, Usion) {
381
382
  // The checkpoint carries the action sequence this state reflects. The
382
383
  // server persists it and rejects OLDER checkpoints (STALE_STATE), so two
383
384
  // concurrent writers can't clobber newer state with older.
384
- const checkpointSeq = self._lastSequence || 0;
385
+ const observedSeq = self._lastSequence || 0;
386
+ // syncedState can lag the transport while a sequence gap is recovering.
387
+ // Persist only the prefix actually reflected in its wrapped snapshot, so
388
+ // the server keeps the missing tail available for the next sync.
389
+ const checkpointSeq = state && state.__usionSyncedState === 1
390
+ && Number.isSafeInteger(state.seq) && state.seq >= 0 && state.seq <= observedSeq
391
+ ? state.seq : observedSeq;
385
392
 
386
393
  if (self._useProxy) {
387
394
  return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {}, sequence: checkpointSeq })
@@ -546,6 +553,9 @@ export function applyGameMethods(game, Usion) {
546
553
  * first). Pass it whenever there IS a ranking: it cannot be derived from
547
554
  * `scores`, because a high score wins in some games and a low one wins in
548
555
  * others. Accepts ids or {userId} objects. Omit for 1-on-1.
556
+ * When scores or standings are supplied, include every actual participant
557
+ * in either field. Other room members do not receive match cards; without
558
+ * either field, the server falls back to the room roster.
549
559
  *
550
560
  * result: { winnerId | draw, standings?, scores?, displayScore?, metric?,
551
561
  * matchId?, roomId? }. Returns Promise<{ ok, notified? }>. See
@@ -665,6 +675,7 @@ export function applyGameMethods(game, Usion) {
665
675
  */
666
676
  game.disconnect = function() {
667
677
  const self = this;
678
+ if (self._playersConnection) self._playersConnection.close();
668
679
 
669
680
  // Always clear heartbeat
670
681
  if (self._heartbeatInterval) {
@@ -0,0 +1,28 @@
1
+ /** Read minimal identities scoped to the currently joined room. */
2
+ export function applyGameParticipants(game, Usion) {
3
+ game.getParticipants = async function() {
4
+ const roomId = this.roomId;
5
+ if (!roomId) throw new Error('Join a room before reading participants');
6
+ // Init may precede the host's scoped-token update. Read the current token
7
+ // per request, including retries, rather than retaining the init snapshot.
8
+ for (let attempt = 0; attempt < 5; attempt++) {
9
+ const token = Usion.user.getToken();
10
+ if (!token) {
11
+ if (attempt < 4) { await new Promise(r => setTimeout(r, 500)); continue; }
12
+ throw new Error('Participant access needs an authenticated Usions session');
13
+ }
14
+ const base = String(Usion.config.apiUrl || '').replace(/\/$/, '');
15
+ if (!base) throw new Error('No API URL provided');
16
+ const response = await fetch(base + '/games/rooms/' + encodeURIComponent(roomId) + '/participants', {
17
+ headers: { Authorization: 'Bearer ' + token }, cache: 'no-store',
18
+ });
19
+ if (response.status === 401 && attempt < 4) {
20
+ await new Promise(r => setTimeout(r, 500)); continue;
21
+ }
22
+ if (!response.ok) throw new Error('Participant access failed: HTTP ' + response.status);
23
+ const result = await response.json();
24
+ if (this.roomId !== roomId) throw new Error('Room changed while loading participants');
25
+ return result;
26
+ }
27
+ };
28
+ }