@usions/sdk 2.34.0 → 2.36.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.
- package/README.md +58 -0
- package/package.json +1 -1
- package/src/browser.js +2 -2
- package/src/modules/call-voice.js +165 -0
- package/src/modules/call.js +4 -2
- package/src/modules/core.js +25 -15
- package/src/modules/errors.js +12 -0
- package/src/modules/host-tabs.js +43 -0
- package/src/modules/index.js +2 -1
- package/src/modules/user.js +70 -0
- package/types/index.d.ts +96 -5
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usion.call voice — a game's own mic button.
|
|
3
|
+
*
|
|
4
|
+
* `micOn({ channel })` joins a named voice channel of this game with the mic
|
|
5
|
+
* on; everyone in the same channel talks. The host app does the audio, the mic
|
|
6
|
+
* permission, safety (mute, block, report) and limits — the game only ever
|
|
7
|
+
* sees state and events, never streams or tokens.
|
|
8
|
+
*/
|
|
9
|
+
import { UsionError, ERROR_CODES } from './errors.js';
|
|
10
|
+
|
|
11
|
+
const CHANNEL_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
|
|
12
|
+
|
|
13
|
+
/** @returns {import('../../types/index').VoiceState} */
|
|
14
|
+
function idleState() {
|
|
15
|
+
return { on: false, channel: null, scope: null, status: 'idle', micOn: false, peers: [] };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {any} raw
|
|
20
|
+
* @returns {import('../../types/index').VoiceState}
|
|
21
|
+
*/
|
|
22
|
+
function normalizeState(raw) {
|
|
23
|
+
if (!raw || typeof raw !== 'object') return idleState();
|
|
24
|
+
const peers = Array.isArray(raw.peers) ? raw.peers : [];
|
|
25
|
+
return {
|
|
26
|
+
on: !!raw.on,
|
|
27
|
+
channel: typeof raw.channel === 'string' ? raw.channel : null,
|
|
28
|
+
scope: raw.scope === 'room' || raw.scope === 'game' ? raw.scope : null,
|
|
29
|
+
status: ['idle', 'connecting', 'connected', 'reconnecting'].indexOf(raw.status) >= 0 ? raw.status : 'idle',
|
|
30
|
+
micOn: !!raw.micOn,
|
|
31
|
+
peers: peers
|
|
32
|
+
.filter(/** @param {any} p */ function (p) { return p && typeof p.userId === 'string'; })
|
|
33
|
+
.map(/** @param {any} p */ function (p) {
|
|
34
|
+
return {
|
|
35
|
+
userId: p.userId,
|
|
36
|
+
name: typeof p.name === 'string' ? p.name : '',
|
|
37
|
+
isMe: !!p.isMe,
|
|
38
|
+
micOn: !!p.micOn,
|
|
39
|
+
speaking: !!p.speaking,
|
|
40
|
+
};
|
|
41
|
+
}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {(...args: any[]) => void} cb @param {any} value */
|
|
46
|
+
function safeCall(cb, value) {
|
|
47
|
+
try { cb(value); } catch (e) { console.error('[Usion] call voice listener error:', e); }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {{ _request: (type: string, data: object, timeout: number) => Promise<any>, on: (type: string, cb: (e: any) => void) => (() => void), config?: any }} Usion
|
|
52
|
+
*/
|
|
53
|
+
export function createVoiceApi(Usion) {
|
|
54
|
+
let last = idleState();
|
|
55
|
+
/** @type {Set<(s: import('../../types/index').VoiceState) => void>} */
|
|
56
|
+
const changeListeners = new Set();
|
|
57
|
+
/** @type {Set<(ids: string[]) => void>} */
|
|
58
|
+
const speakingListeners = new Set();
|
|
59
|
+
let wired = false;
|
|
60
|
+
|
|
61
|
+
function isAvailable() {
|
|
62
|
+
const features = Usion.config && Usion.config.hostFeatures;
|
|
63
|
+
return !!(features && features.voice);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function wire() {
|
|
67
|
+
if (wired) return;
|
|
68
|
+
wired = true;
|
|
69
|
+
Usion.on('CALL_VOICE_CHANGED', function (event) {
|
|
70
|
+
if (event && event.state) setState(event.state);
|
|
71
|
+
});
|
|
72
|
+
Usion.on('CALL_VOICE_SPEAKING', function (event) {
|
|
73
|
+
const ids = event && Array.isArray(event.userIds)
|
|
74
|
+
? event.userIds.filter(/** @param {any} id */ function (id) { return typeof id === 'string'; })
|
|
75
|
+
: [];
|
|
76
|
+
speakingListeners.forEach(function (cb) { safeCall(cb, ids); });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @param {any} raw */
|
|
81
|
+
function setState(raw) {
|
|
82
|
+
last = normalizeState(raw);
|
|
83
|
+
changeListeners.forEach(function (cb) { safeCall(cb, last); });
|
|
84
|
+
return last;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {string} type @param {object} data @param {number} timeout
|
|
89
|
+
* @returns {Promise<import('../../types/index').VoiceState>}
|
|
90
|
+
*/
|
|
91
|
+
function request(type, data, timeout) {
|
|
92
|
+
if (!isAvailable()) {
|
|
93
|
+
return Promise.reject(new UsionError(ERROR_CODES.VOICE_UNSUPPORTED,
|
|
94
|
+
'Voice needs a newer version of the Usion app'));
|
|
95
|
+
}
|
|
96
|
+
wire();
|
|
97
|
+
return Usion._request(type, data, timeout).then(function (result) {
|
|
98
|
+
return result && result.state ? setState(result.state) : last;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
isAvailable: isAvailable,
|
|
104
|
+
|
|
105
|
+
/** @param {{ channel?: string, scope?: 'room'|'game', listen?: boolean }} [opts] */
|
|
106
|
+
micOn: function (opts) {
|
|
107
|
+
const o = opts || {};
|
|
108
|
+
const channel = o.channel == null ? 'main' : o.channel;
|
|
109
|
+
const scope = o.scope == null ? 'room' : o.scope;
|
|
110
|
+
if (typeof channel !== 'string' || !CHANNEL_RE.test(channel)) {
|
|
111
|
+
return Promise.reject(new UsionError(ERROR_CODES.VOICE_BAD_CHANNEL,
|
|
112
|
+
"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit"));
|
|
113
|
+
}
|
|
114
|
+
if (scope !== 'room' && scope !== 'game') {
|
|
115
|
+
return Promise.reject(new UsionError(ERROR_CODES.VOICE_BAD_CHANNEL, "scope must be 'room' or 'game'"));
|
|
116
|
+
}
|
|
117
|
+
// 60s: the first time this covers the host's permission prompts.
|
|
118
|
+
return request('CALL_VOICE_ON', { channel: channel, scope: scope, listen: !!o.listen }, 60000);
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
micOff: function () {
|
|
122
|
+
return request('CALL_VOICE_OFF', {}, 5000).then(function () { return undefined; });
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
/** @param {boolean} on */
|
|
126
|
+
setMic: function (on) {
|
|
127
|
+
return request('CALL_VOICE_SET_MIC', { on: !!on }, 5000);
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
/** @param {string} userId @param {boolean} [muted] */
|
|
131
|
+
mutePeer: function (userId, muted) {
|
|
132
|
+
if (typeof userId !== 'string' || !userId) {
|
|
133
|
+
return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'userId required'));
|
|
134
|
+
}
|
|
135
|
+
return request('CALL_VOICE_MUTE_PEER', { userId: userId, muted: muted !== false }, 5000)
|
|
136
|
+
.then(function () { return undefined; });
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
state: function () {
|
|
140
|
+
if (!isAvailable()) return Promise.resolve(idleState());
|
|
141
|
+
return request('CALL_VOICE_STATE', {}, 5000);
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
/** @param {(s: import('../../types/index').VoiceState) => void} callback */
|
|
145
|
+
onChange: function (callback) {
|
|
146
|
+
wire();
|
|
147
|
+
changeListeners.add(callback);
|
|
148
|
+
// A listener added mid-call learns the current state once.
|
|
149
|
+
if (last.on) {
|
|
150
|
+
const current = last;
|
|
151
|
+
Promise.resolve().then(function () {
|
|
152
|
+
if (changeListeners.has(callback) && last === current) safeCall(callback, current);
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return function () { changeListeners.delete(callback); };
|
|
156
|
+
},
|
|
157
|
+
|
|
158
|
+
/** @param {(userIds: string[]) => void} callback */
|
|
159
|
+
onSpeaking: function (callback) {
|
|
160
|
+
wire();
|
|
161
|
+
speakingListeners.add(callback);
|
|
162
|
+
return function () { speakingListeners.delete(callback); };
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
package/src/modules/call.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/** Permission-gated, local call signals. Streams and device handles never cross this API. */
|
|
2
|
+
import { createVoiceApi } from './call-voice.js';
|
|
3
|
+
|
|
2
4
|
/**
|
|
3
5
|
* @param {{ _request: (type: string, data: object, timeout: number) => Promise<any>, on: (type: string, callback: (event: any) => void) => (() => void) }} Usion
|
|
4
6
|
* @returns {import('../../types/index').CallModule}
|
|
5
7
|
*/
|
|
6
8
|
export function createCallModule(Usion) {
|
|
7
|
-
return {
|
|
9
|
+
return Object.assign(createVoiceApi(Usion), {
|
|
8
10
|
capabilities: function () {
|
|
9
11
|
return Usion._request('CALL_CAPABILITIES', {}, 5000);
|
|
10
12
|
},
|
|
@@ -42,5 +44,5 @@ export function createCallModule(Usion) {
|
|
|
42
44
|
};
|
|
43
45
|
} catch (error) { cleanup(); throw error; }
|
|
44
46
|
},
|
|
45
|
-
};
|
|
47
|
+
});
|
|
46
48
|
}
|
package/src/modules/core.js
CHANGED
|
@@ -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.
|
|
71
|
+
version: '2.36.0', // synced from package.json by scripts/sync-version.mjs
|
|
72
72
|
config: {},
|
|
73
73
|
_initialized: false,
|
|
74
74
|
_initCallback: null,
|
|
@@ -154,10 +154,12 @@ export const core = {
|
|
|
154
154
|
// forever once their first token raced the mint or hit the 60-min TTL.
|
|
155
155
|
// Merge the refreshed fields; never re-fire the init callback.
|
|
156
156
|
if (self._initialized) {
|
|
157
|
-
if (data.config
|
|
158
|
-
|
|
159
|
-
|
|
157
|
+
if (self.user) self.user._applyAuth(data.config, false);
|
|
158
|
+
if (data.config.sessionId !== undefined && self.session) {
|
|
159
|
+
self.config.sessionId = self.session._id = data.config.sessionId || null;
|
|
160
|
+
self.config.sessionData = self.session._data = data.config.sessionData || {};
|
|
160
161
|
}
|
|
162
|
+
if (Array.isArray(data.config.results)) self._results = self.config.results = data.config.results;
|
|
161
163
|
if (data.config.balance !== undefined && self.wallet) {
|
|
162
164
|
self.wallet._balance = data.config.balance;
|
|
163
165
|
}
|
|
@@ -180,17 +182,8 @@ export const core = {
|
|
|
180
182
|
// We received INIT from a parent -> we are embedded (iframe or WebView)
|
|
181
183
|
self._isEmbedded = true;
|
|
182
184
|
|
|
183
|
-
//
|
|
184
|
-
if (data.config
|
|
185
|
-
self.user._id = data.config.userId;
|
|
186
|
-
self.user._name = data.config.userName;
|
|
187
|
-
self.user._avatar = data.config.userAvatar;
|
|
188
|
-
self.user._token = data.config.authToken;
|
|
189
|
-
self.user._isAdult =
|
|
190
|
-
(data.config.userIsAdult === true || data.config.userIsAdult === false)
|
|
191
|
-
? data.config.userIsAdult
|
|
192
|
-
: null;
|
|
193
|
-
}
|
|
185
|
+
// Identity changes (including explicit guest/null) clear cached credentials.
|
|
186
|
+
if (self.user) self.user._applyAuth(data.config, false);
|
|
194
187
|
|
|
195
188
|
// Initialize session module
|
|
196
189
|
if (data.config.sessionId) {
|
|
@@ -224,6 +217,13 @@ export const core = {
|
|
|
224
217
|
}
|
|
225
218
|
|
|
226
219
|
// Handle response messages for async requests
|
|
220
|
+
if (data.type === 'AUTH_CHANGED' && self.user) {
|
|
221
|
+
self.user._applyAuth(data, true);
|
|
222
|
+
}
|
|
223
|
+
if (data.type === 'HOST_TAB_BLOCKED' && self.tabs) {
|
|
224
|
+
self.tabs._dispatchBlocked(data);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
227
|
if (data._requestId && _pendingRequests[data._requestId]) {
|
|
228
228
|
const { resolve, reject } = _pendingRequests[data._requestId];
|
|
229
229
|
delete _pendingRequests[data._requestId];
|
|
@@ -412,6 +412,15 @@ export const core = {
|
|
|
412
412
|
* Send async request to parent and wait for response
|
|
413
413
|
* @private
|
|
414
414
|
*/
|
|
415
|
+
_invalidateAuthRequests: function() {
|
|
416
|
+
Object.keys(_pendingRequests).forEach(function(id) {
|
|
417
|
+
const request = _pendingRequests[id];
|
|
418
|
+
if (!request.identityBound) return;
|
|
419
|
+
delete _pendingRequests[id];
|
|
420
|
+
request.reject(new UsionError(ERROR_CODES.AUTH_CHANGED, 'Account changed while request was pending'));
|
|
421
|
+
});
|
|
422
|
+
},
|
|
423
|
+
|
|
415
424
|
_request: function(type, data, timeout) {
|
|
416
425
|
const self = this;
|
|
417
426
|
timeout = timeout || 5000;
|
|
@@ -427,6 +436,7 @@ export const core = {
|
|
|
427
436
|
|
|
428
437
|
// Store pending request
|
|
429
438
|
_pendingRequests[requestId] = {
|
|
439
|
+
identityBound: ['CONFIGURE_HOST_TABS', 'OPEN_HOST_TAB', 'REQUEST_LOGIN', 'CALL_CAPABILITIES'].indexOf(type) === -1,
|
|
430
440
|
resolve: function(result) {
|
|
431
441
|
clearTimeout(timer);
|
|
432
442
|
resolve(result);
|
package/src/modules/errors.js
CHANGED
|
@@ -35,9 +35,21 @@ export const ERROR_CODES = {
|
|
|
35
35
|
RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
|
|
36
36
|
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
|
|
37
37
|
QUEUE_FULL: 'QUEUE_FULL', // Offline action queue at capacity
|
|
38
|
+
AUTH_CHANGED: 'AUTH_CHANGED', // Pending account request invalidated by login/logout/account switch
|
|
38
39
|
CANCELLED: 'CANCELLED', // Cancelled by a local cancel() call
|
|
39
40
|
SUPERSEDED: 'SUPERSEDED', // Replaced by a newer identical request
|
|
40
41
|
UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
|
|
42
|
+
VOICE_UNSUPPORTED: 'VOICE_UNSUPPORTED', // Host app too old for Usion.call voice
|
|
43
|
+
VOICE_DISABLED: 'VOICE_DISABLED', // Voice turned off for this game / platform
|
|
44
|
+
VOICE_UNAVAILABLE: 'VOICE_UNAVAILABLE', // Voice can't run here (private game, no channel)
|
|
45
|
+
VOICE_NO_ROOM: 'VOICE_NO_ROOM', // scope 'room' channel but no game room
|
|
46
|
+
VOICE_NOT_IN_ROOM: 'VOICE_NOT_IN_ROOM', // Not seated in the game room
|
|
47
|
+
VOICE_BAD_CHANNEL: 'VOICE_BAD_CHANNEL', // Invalid channel name or scope
|
|
48
|
+
VOICE_FULL: 'VOICE_FULL', // Channel at its participant cap
|
|
49
|
+
VOICE_DECLINED: 'VOICE_DECLINED', // User said no to the mic / to leaving a call
|
|
50
|
+
VOICE_MIC_DENIED: 'VOICE_MIC_DENIED', // OS microphone permission denied
|
|
51
|
+
VOICE_GUEST: 'VOICE_GUEST', // Web guest: log in to talk
|
|
52
|
+
VOICE_FAILED: 'VOICE_FAILED', // Couldn't connect (network)
|
|
41
53
|
UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
|
|
42
54
|
};
|
|
43
55
|
|
package/src/modules/host-tabs.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { UsionError, ERROR_CODES } from './errors.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Usion SDK Host Tabs — hybrid tabbed services (SDK ≥ 2.25)
|
|
3
5
|
*
|
|
@@ -64,3 +66,44 @@ export function createHostTabsMethods(Usion) {
|
|
|
64
66
|
}
|
|
65
67
|
};
|
|
66
68
|
}
|
|
69
|
+
|
|
70
|
+
/** Host-controlled tabs. Policy is a UI gate; protect data on your server. */
|
|
71
|
+
export function createTabsModule(Usion) {
|
|
72
|
+
const listeners = new Set();
|
|
73
|
+
function request(type, payload) {
|
|
74
|
+
if (!Usion.config.hostFeatures?.tabControl) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Tab control requires a newer Usion host'));
|
|
75
|
+
return Usion._request(type, payload);
|
|
76
|
+
}
|
|
77
|
+
function safePath(path) {
|
|
78
|
+
return typeof path === 'string' && path.startsWith('/') && !path.startsWith('//')
|
|
79
|
+
&& !/[\\\s\x00-\x1f]/.test(path) && path.length <= 2048;
|
|
80
|
+
}
|
|
81
|
+
function key(value) { return typeof value === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(value); }
|
|
82
|
+
function invalid() { return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'Invalid tab navigation options')); }
|
|
83
|
+
return {
|
|
84
|
+
configure: function(options) {
|
|
85
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) return invalid();
|
|
86
|
+
const allowed = ['landingTab', 'landingPath', 'lockedTabs', 'fallbackTab', 'fallbackPath'];
|
|
87
|
+
if (Object.keys(options).some(name => allowed.indexOf(name) === -1)) return invalid();
|
|
88
|
+
if (['landingTab', 'fallbackTab'].some(name => options[name] !== undefined && !key(options[name]))) return invalid();
|
|
89
|
+
if (['landingPath', 'fallbackPath'].some(name => options[name] !== undefined && !safePath(options[name]))) return invalid();
|
|
90
|
+
if (options.lockedTabs !== undefined && (!Array.isArray(options.lockedTabs) || options.lockedTabs.length > 32 || options.lockedTabs.some(value => !key(value)))) return invalid();
|
|
91
|
+
return request('CONFIGURE_HOST_TABS', { ...options });
|
|
92
|
+
},
|
|
93
|
+
open: function(tab, options) {
|
|
94
|
+
options = options || {};
|
|
95
|
+
if (!key(tab) || Object.keys(options).some(name => name !== 'path') || (options.path !== undefined && !safePath(options.path))) return invalid();
|
|
96
|
+
return request('OPEN_HOST_TAB', { tab, ...(options.path === undefined ? {} : { path: options.path }) });
|
|
97
|
+
},
|
|
98
|
+
onBlocked: function(callback) {
|
|
99
|
+
if (typeof callback !== 'function') return function() {};
|
|
100
|
+
listeners.add(callback);
|
|
101
|
+
return function() { listeners.delete(callback); };
|
|
102
|
+
},
|
|
103
|
+
_dispatchBlocked: function(data) {
|
|
104
|
+
if (!key(data.tab)) return;
|
|
105
|
+
const event = { tab: data.tab, ...(safePath(data.path) ? { path: data.path } : {}) };
|
|
106
|
+
listeners.forEach(function(callback) { try { callback(event); } catch (error) { console.error('[Usion] tab listener error:', error); } });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
package/src/modules/index.js
CHANGED
|
@@ -22,7 +22,7 @@ import { createChatModule } from './chat.js';
|
|
|
22
22
|
import { createBotModule } from './bot.js';
|
|
23
23
|
import { createResultsMethods } from './results.js';
|
|
24
24
|
import { createBackButtonMethods } from './back-button.js';
|
|
25
|
-
import { createHostTabsMethods } from './host-tabs.js';
|
|
25
|
+
import { createHostTabsMethods, createTabsModule } from './host-tabs.js';
|
|
26
26
|
import { uiMethods } from './ui.js';
|
|
27
27
|
import { miscMethods } from './misc.js';
|
|
28
28
|
import { appLinkMethods } from './app-links.js';
|
|
@@ -68,6 +68,7 @@ Usion.permissions = createPermissionsModule(Usion);
|
|
|
68
68
|
Usion.screen = createScreenModule(Usion);
|
|
69
69
|
Usion.profile = createProfileModule(Usion);
|
|
70
70
|
Usion.call = createCallModule(Usion);
|
|
71
|
+
Usion.tabs = createTabsModule(Usion);
|
|
71
72
|
|
|
72
73
|
// Netcode toolkit (transport-agnostic, zero-dependency).
|
|
73
74
|
Usion.netcode = netcode;
|
package/src/modules/user.js
CHANGED
|
@@ -2,11 +2,81 @@
|
|
|
2
2
|
* Usion SDK User Module — user info and authentication
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { UsionError, ERROR_CODES } from './errors.js';
|
|
6
|
+
|
|
5
7
|
/**
|
|
6
8
|
* @param {object} Usion - Reference to the main Usion object
|
|
7
9
|
*/
|
|
8
10
|
export function createUserModule(Usion) {
|
|
11
|
+
const listeners = new Set();
|
|
12
|
+
let authState = { status: 'loading', userId: null };
|
|
13
|
+
function emitAuth() {
|
|
14
|
+
listeners.forEach(function(callback) {
|
|
15
|
+
try { callback({ ...authState }); } catch (error) { console.error('[Usion] auth listener error:', error); }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
9
18
|
return {
|
|
19
|
+
/** Internal: apply only host-authenticated state, including explicit logout. */
|
|
20
|
+
_applyAuth: function(config, clearToken) {
|
|
21
|
+
config = { ...config };
|
|
22
|
+
const previous = authState;
|
|
23
|
+
const has = key => Object.prototype.hasOwnProperty.call(config, key);
|
|
24
|
+
const declared = config.authState;
|
|
25
|
+
const hasIdentity = has('userId') || !!declared;
|
|
26
|
+
const identity = has('userId') ? config.userId : declared ? declared.userId : this.getId();
|
|
27
|
+
const realId = typeof identity === 'string' && identity && identity.indexOf('guest_') !== 0 ? identity : null;
|
|
28
|
+
if (hasIdentity) {
|
|
29
|
+
const status = declared && declared.status === 'loading' ? 'loading'
|
|
30
|
+
: declared && declared.status === 'guest' ? 'guest' : realId ? 'authenticated' : 'guest';
|
|
31
|
+
authState = { status, userId: status === 'authenticated' ? realId : null };
|
|
32
|
+
const changed = previous.status !== authState.status || previous.userId !== authState.userId;
|
|
33
|
+
if (changed && previous.status !== 'loading') {
|
|
34
|
+
this._name = this._avatar = this._token = this._isAdult = null;
|
|
35
|
+
Usion.config.userName = Usion.config.userAvatar = Usion.config.authToken = Usion.config.userIsAdult = null;
|
|
36
|
+
}
|
|
37
|
+
this._id = typeof identity === 'string' ? identity : null;
|
|
38
|
+
Usion.config.userId = this._id;
|
|
39
|
+
}
|
|
40
|
+
if (has('userName')) this._name = Usion.config.userName = config.userName || null;
|
|
41
|
+
if (has('userAvatar')) this._avatar = Usion.config.userAvatar = config.userAvatar || null;
|
|
42
|
+
if (has('userIsAdult')) this._isAdult = Usion.config.userIsAdult = typeof config.userIsAdult === 'boolean' ? config.userIsAdult : null;
|
|
43
|
+
if (clearToken || has('authToken') || (hasIdentity && authState.status !== 'authenticated')) {
|
|
44
|
+
// Guest games receive fresh scoped guest tokens too. Accept one only
|
|
45
|
+
// with an explicit guest identity, never inherit an old account token.
|
|
46
|
+
const freshGuest = has('userId') && typeof config.userId === 'string' && config.userId.indexOf('guest_') === 0;
|
|
47
|
+
this._token = Usion.config.authToken = (authState.status === 'authenticated' || freshGuest) && typeof config.authToken === 'string' ? config.authToken : null;
|
|
48
|
+
}
|
|
49
|
+
Usion.config.authState = { ...authState };
|
|
50
|
+
if (previous.status !== authState.status || previous.userId !== authState.userId) {
|
|
51
|
+
// Account-scoped snapshots must never survive identity changes.
|
|
52
|
+
if (previous.status !== 'loading') {
|
|
53
|
+
if (Usion._invalidateAuthRequests) Usion._invalidateAuthRequests();
|
|
54
|
+
Usion._results = [];
|
|
55
|
+
Usion.config.sessionId = null; Usion.config.sessionData = {};
|
|
56
|
+
Usion.config.results = []; Usion.config.balance = null;
|
|
57
|
+
if (Usion.session) { Usion.session._id = null; Usion.session._data = {}; }
|
|
58
|
+
if (Usion.wallet) Usion.wallet._balance = null;
|
|
59
|
+
}
|
|
60
|
+
emitAuth();
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
/** Current host login state. This is UI state, not server authorization. */
|
|
64
|
+
getAuthState: function() { return { ...authState }; },
|
|
65
|
+
/** Subscribe to login/logout/account changes; returns an unsubscribe. */
|
|
66
|
+
onAuthChange: function(callback) {
|
|
67
|
+
if (typeof callback !== 'function') return function() {};
|
|
68
|
+
listeners.add(callback);
|
|
69
|
+
return function() { listeners.delete(callback); };
|
|
70
|
+
},
|
|
71
|
+
/** Open the host login flow from a user action; resolves when launched. */
|
|
72
|
+
requestLogin: function(options) {
|
|
73
|
+
if (!Usion.config.hostFeatures?.auth) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Login requires a newer Usion host'));
|
|
74
|
+
const returnPath = options && options.returnPath;
|
|
75
|
+
if (returnPath != null && (typeof returnPath !== 'string' || !returnPath.startsWith('/') || returnPath.startsWith('//') || /[\\\s\x00-\x1f]/.test(returnPath) || returnPath.length > 2048)) {
|
|
76
|
+
return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'returnPath must be a safe relative app path'));
|
|
77
|
+
}
|
|
78
|
+
return Usion._request('REQUEST_LOGIN', returnPath == null ? {} : { returnPath });
|
|
79
|
+
},
|
|
10
80
|
_id: null,
|
|
11
81
|
_name: null,
|
|
12
82
|
_avatar: null,
|
package/types/index.d.ts
CHANGED
|
@@ -5,10 +5,12 @@
|
|
|
5
5
|
// ─── Config & Init ───────────────────────────────────────────────
|
|
6
6
|
|
|
7
7
|
export interface UsionConfig {
|
|
8
|
-
userId?: string;
|
|
9
|
-
userName?: string;
|
|
10
|
-
userAvatar?: string;
|
|
11
|
-
authToken?: string;
|
|
8
|
+
userId?: string | null;
|
|
9
|
+
userName?: string | null;
|
|
10
|
+
userAvatar?: string | null;
|
|
11
|
+
authToken?: string | null;
|
|
12
|
+
authState?: AuthState;
|
|
13
|
+
hostTabs?: boolean;
|
|
12
14
|
sessionId?: string;
|
|
13
15
|
sessionData?: Record<string, any>;
|
|
14
16
|
balance?: number;
|
|
@@ -47,7 +49,7 @@ export interface UsionConfig {
|
|
|
47
49
|
* Host capabilities declared in INIT. Absent on older app builds — read
|
|
48
50
|
* `feedShare` via `Usion.canShareToFeed()`. (SDK ≥ 2.33)
|
|
49
51
|
*/
|
|
50
|
-
hostFeatures?: { feedShare?: boolean; feedShareImage?: boolean; feedShareVideo?: boolean; [feature: string]: boolean | undefined };
|
|
52
|
+
hostFeatures?: { feedShare?: boolean; feedShareImage?: boolean; feedShareVideo?: boolean; voice?: boolean; [feature: string]: boolean | undefined };
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
// ─── Payment ─────────────────────────────────────────────────────
|
|
@@ -81,7 +83,39 @@ export interface UserProfile {
|
|
|
81
83
|
isAdult?: boolean | null;
|
|
82
84
|
}
|
|
83
85
|
|
|
86
|
+
export interface AuthState {
|
|
87
|
+
status: 'loading' | 'authenticated' | 'guest';
|
|
88
|
+
userId: string | null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface HostActionResult {
|
|
92
|
+
ok: true;
|
|
93
|
+
alreadyAuthenticated?: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface HostTabsConfiguration {
|
|
97
|
+
/** Initial tab choice; a valid explicit deep link takes precedence. */
|
|
98
|
+
landingTab?: string;
|
|
99
|
+
landingPath?: string;
|
|
100
|
+
/** Replaces existing locks. UI controls, not authorization. */
|
|
101
|
+
lockedTabs?: string[];
|
|
102
|
+
/** Allowed destination when the current/deep-linked tab is locked. */
|
|
103
|
+
fallbackTab?: string;
|
|
104
|
+
fallbackPath?: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface TabsModule {
|
|
108
|
+
configure(options: HostTabsConfiguration): Promise<HostActionResult>;
|
|
109
|
+
open(tab: string, options?: { path?: string }): Promise<HostActionResult>;
|
|
110
|
+
onBlocked(callback: (event: { tab: string; path?: string }) => void): () => void;
|
|
111
|
+
}
|
|
112
|
+
|
|
84
113
|
export interface UserModule {
|
|
114
|
+
/** Host login state for routing only; verify authorization on your server. */
|
|
115
|
+
getAuthState(): AuthState;
|
|
116
|
+
onAuthChange(callback: (state: AuthState) => void): () => void;
|
|
117
|
+
/** Launch host login from a user action. ACK means opened, not signed in. */
|
|
118
|
+
requestLogin(options?: { returnPath?: string }): Promise<HostActionResult>;
|
|
85
119
|
getId(): string | null;
|
|
86
120
|
getName(): string | null;
|
|
87
121
|
getAvatar(): string | null;
|
|
@@ -1227,7 +1261,51 @@ export type CallAnalysisCapability = 'headPosition' | 'voiceActivity';
|
|
|
1227
1261
|
export type CallAnalysisSample =
|
|
1228
1262
|
| { kind: 'face'; detected: boolean; x: number; y: number }
|
|
1229
1263
|
| { kind: 'voice'; speaking: boolean };
|
|
1264
|
+
/** Where a voice channel lives: one game room (seated players only) or the whole game. */
|
|
1265
|
+
export type VoiceScope = 'room' | 'game';
|
|
1266
|
+
export interface VoicePeer {
|
|
1267
|
+
userId: string;
|
|
1268
|
+
name: string;
|
|
1269
|
+
isMe: boolean;
|
|
1270
|
+
micOn: boolean;
|
|
1271
|
+
speaking: boolean;
|
|
1272
|
+
}
|
|
1273
|
+
export interface VoiceState {
|
|
1274
|
+
/** I'm in a voice channel. */
|
|
1275
|
+
on: boolean;
|
|
1276
|
+
channel: string | null;
|
|
1277
|
+
scope: VoiceScope | null;
|
|
1278
|
+
status: 'idle' | 'connecting' | 'connected' | 'reconnecting';
|
|
1279
|
+
/** My mic is live. */
|
|
1280
|
+
micOn: boolean;
|
|
1281
|
+
/** Everyone in my channel, me included. */
|
|
1282
|
+
peers: VoicePeer[];
|
|
1283
|
+
}
|
|
1284
|
+
export interface MicOnOptions {
|
|
1285
|
+
/** Channel name the game picks: 1-48 of a-z, 0-9, '-', '_'. Default 'main'. */
|
|
1286
|
+
channel?: string;
|
|
1287
|
+
/** 'room' (default): only players seated in the current game room. 'game': everyone in this game using the same name. */
|
|
1288
|
+
scope?: VoiceScope;
|
|
1289
|
+
/** Join hearing others with the mic still off (spectators). Default false. */
|
|
1290
|
+
listen?: boolean;
|
|
1291
|
+
}
|
|
1230
1292
|
export interface CallModule {
|
|
1293
|
+
/** True when the host app supports voice (SDK 2.35+ host). */
|
|
1294
|
+
isAvailable(): boolean;
|
|
1295
|
+
/** Join a voice channel with the mic on. Call it from a user tap — the host asks for the mic the first time. */
|
|
1296
|
+
micOn(options?: MicOnOptions): Promise<VoiceState>;
|
|
1297
|
+
/** Leave the voice channel. */
|
|
1298
|
+
micOff(): Promise<void>;
|
|
1299
|
+
/** Stay in the channel, stop or start talking. */
|
|
1300
|
+
setMic(on: boolean): Promise<VoiceState>;
|
|
1301
|
+
/** Only I stop (or start again) hearing this person. */
|
|
1302
|
+
mutePeer(userId: string, muted?: boolean): Promise<void>;
|
|
1303
|
+
/** Current state; idle when the host has no voice support. */
|
|
1304
|
+
state(): Promise<VoiceState>;
|
|
1305
|
+
/** Joins, leaves, mic and connection changes. */
|
|
1306
|
+
onChange(callback: (state: VoiceState) => void): UnsubscribeFn;
|
|
1307
|
+
/** Who is talking right now (at most 4 updates a second). */
|
|
1308
|
+
onSpeaking(callback: (userIds: string[]) => void): UnsubscribeFn;
|
|
1231
1309
|
capabilities(): Promise<{ capabilities: CallAnalysisCapability[]; connected: boolean }>;
|
|
1232
1310
|
startAnalysis(options: {
|
|
1233
1311
|
capabilities: CallAnalysisCapability[];
|
|
@@ -1404,6 +1482,7 @@ export interface UsionSDK {
|
|
|
1404
1482
|
|
|
1405
1483
|
// Modules
|
|
1406
1484
|
user: UserModule;
|
|
1485
|
+
tabs: TabsModule;
|
|
1407
1486
|
storage: StorageModule;
|
|
1408
1487
|
fileStorage: FileStorageModule;
|
|
1409
1488
|
wallet: WalletModule;
|
|
@@ -1677,9 +1756,21 @@ export declare const ERROR_CODES: {
|
|
|
1677
1756
|
readonly RATE_LIMITED: 'RATE_LIMITED';
|
|
1678
1757
|
readonly REQUEST_TIMEOUT: 'REQUEST_TIMEOUT';
|
|
1679
1758
|
readonly QUEUE_FULL: 'QUEUE_FULL';
|
|
1759
|
+
readonly AUTH_CHANGED: 'AUTH_CHANGED';
|
|
1680
1760
|
readonly CANCELLED: 'CANCELLED';
|
|
1681
1761
|
readonly SUPERSEDED: 'SUPERSEDED';
|
|
1682
1762
|
readonly UNSUPPORTED: 'UNSUPPORTED';
|
|
1763
|
+
readonly VOICE_UNSUPPORTED: 'VOICE_UNSUPPORTED';
|
|
1764
|
+
readonly VOICE_DISABLED: 'VOICE_DISABLED';
|
|
1765
|
+
readonly VOICE_UNAVAILABLE: 'VOICE_UNAVAILABLE';
|
|
1766
|
+
readonly VOICE_NO_ROOM: 'VOICE_NO_ROOM';
|
|
1767
|
+
readonly VOICE_NOT_IN_ROOM: 'VOICE_NOT_IN_ROOM';
|
|
1768
|
+
readonly VOICE_BAD_CHANNEL: 'VOICE_BAD_CHANNEL';
|
|
1769
|
+
readonly VOICE_FULL: 'VOICE_FULL';
|
|
1770
|
+
readonly VOICE_DECLINED: 'VOICE_DECLINED';
|
|
1771
|
+
readonly VOICE_MIC_DENIED: 'VOICE_MIC_DENIED';
|
|
1772
|
+
readonly VOICE_GUEST: 'VOICE_GUEST';
|
|
1773
|
+
readonly VOICE_FAILED: 'VOICE_FAILED';
|
|
1683
1774
|
readonly UNKNOWN: 'UNKNOWN';
|
|
1684
1775
|
};
|
|
1685
1776
|
|