@usions/sdk 2.24.2 → 3.0.0-next.7
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 +45 -277
- package/dist/browser.global.js +1972 -0
- package/dist/browser.global.js.map +1 -0
- package/dist/index.d.ts +337 -0
- package/dist/index.js +1955 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.d.ts +23 -0
- package/dist/testing.js +63 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-G075L8Nl.d.ts +83 -0
- package/package.json +25 -46
- package/src/browser.js +0 -6725
- package/src/index.js +0 -10
- package/src/modules/back-button.js +0 -26
- package/src/modules/backend-channel.js +0 -109
- package/src/modules/bot.js +0 -52
- package/src/modules/chat.js +0 -35
- package/src/modules/cloud.js +0 -67
- package/src/modules/core.js +0 -424
- package/src/modules/errors.js +0 -120
- package/src/modules/file-storage.js +0 -46
- package/src/modules/game-ack.js +0 -32
- package/src/modules/game-core.js +0 -278
- package/src/modules/game-direct.js +0 -267
- package/src/modules/game-methods.js +0 -782
- package/src/modules/game-netcode.js +0 -349
- package/src/modules/game-proxy.js +0 -184
- package/src/modules/game-reliability.js +0 -278
- package/src/modules/game-resilience.js +0 -245
- package/src/modules/game-socket.js +0 -214
- package/src/modules/index.js +0 -78
- package/src/modules/leaderboard.js +0 -46
- package/src/modules/lobby.js +0 -103
- package/src/modules/matchmaking.js +0 -140
- package/src/modules/misc.js +0 -152
- package/src/modules/netcode/binary.js +0 -113
- package/src/modules/netcode/delta.js +0 -236
- package/src/modules/netcode/index.js +0 -43
- package/src/modules/netcode/interest-grid.js +0 -227
- package/src/modules/netcode/interpolation.js +0 -235
- package/src/modules/netcode/lagcomp.js +0 -104
- package/src/modules/netcode/lockstep.js +0 -103
- package/src/modules/netcode/mesh-network.js +0 -103
- package/src/modules/netcode/mesh.js +0 -188
- package/src/modules/netcode/netsim.js +0 -77
- package/src/modules/netcode/ping.js +0 -69
- package/src/modules/netcode/prediction.js +0 -113
- package/src/modules/netcode/sender.js +0 -102
- package/src/modules/netcode/webtransport.js +0 -195
- package/src/modules/notify.js +0 -70
- package/src/modules/permissions.js +0 -157
- package/src/modules/results.js +0 -34
- package/src/modules/session.js +0 -62
- package/src/modules/storage.js +0 -64
- package/src/modules/ui.js +0 -111
- package/src/modules/user.js +0 -61
- package/src/modules/wallet.js +0 -253
- package/types/browser.d.ts +0 -5
- package/types/index.d.ts +0 -1308
package/src/modules/core.js
DELETED
|
@@ -1,424 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Core — init, _post, _request, message handling
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
6
|
-
|
|
7
|
-
// Request ID counter for tracking async responses
|
|
8
|
-
let _requestId = 0;
|
|
9
|
-
export const _pendingRequests = {};
|
|
10
|
-
|
|
11
|
-
export function getNextRequestId() {
|
|
12
|
-
return ++_requestId;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
// Trusted origin of the host shell that embedded us (web iframe only).
|
|
16
|
-
// Resolved lazily from the real embedder, never from message contents.
|
|
17
|
-
let _parentOrigin = null;
|
|
18
|
-
|
|
19
|
-
function _resolveParentOrigin() {
|
|
20
|
-
try {
|
|
21
|
-
if (window.location.ancestorOrigins && window.location.ancestorOrigins.length) {
|
|
22
|
-
return window.location.ancestorOrigins[0];
|
|
23
|
-
}
|
|
24
|
-
} catch (e) { /* not supported */ }
|
|
25
|
-
try {
|
|
26
|
-
if (typeof document !== 'undefined' && document.referrer) {
|
|
27
|
-
return new URL(document.referrer).origin;
|
|
28
|
-
}
|
|
29
|
-
} catch (e) { /* malformed referrer */ }
|
|
30
|
-
return null;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Decide whether an incoming postMessage may be trusted.
|
|
35
|
-
*
|
|
36
|
-
* The host shell is the only legitimate sender. A sibling iframe or any other
|
|
37
|
-
* script on the page must NOT be able to forge messages (e.g. a fake
|
|
38
|
-
* PAYMENT_SUCCESS that unlocks paid value for free).
|
|
39
|
-
*
|
|
40
|
-
* - React Native WebView: messages are delivered in-process and carry no
|
|
41
|
-
* usable origin/source, so they are trusted.
|
|
42
|
-
* - Web iframe: the only window that equals `window.parent` is the real
|
|
43
|
-
* embedder. `event.source` is set by the browser and cannot be spoofed, so
|
|
44
|
-
* `event.source === window.parent` rejects siblings and self-posts. We then
|
|
45
|
-
* cross-check `event.origin` against the embedder's origin as defense-in-depth.
|
|
46
|
-
* - Not embedded (standalone / tests): nothing to protect against; allowed.
|
|
47
|
-
*
|
|
48
|
-
* @param {MessageEvent} event
|
|
49
|
-
* @returns {boolean}
|
|
50
|
-
*/
|
|
51
|
-
export function isTrustedMessageSource(event) {
|
|
52
|
-
if (typeof window === 'undefined') return true;
|
|
53
|
-
if (window.ReactNativeWebView) return true;
|
|
54
|
-
if (window.parent === window) return true;
|
|
55
|
-
|
|
56
|
-
if (event && event.source && event.source !== window.parent) return false;
|
|
57
|
-
|
|
58
|
-
if (_parentOrigin === null) {
|
|
59
|
-
_parentOrigin = _resolveParentOrigin();
|
|
60
|
-
}
|
|
61
|
-
if (_parentOrigin && event && event.origin && event.origin !== _parentOrigin) {
|
|
62
|
-
return false;
|
|
63
|
-
}
|
|
64
|
-
return true;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Core Usion object with init, _post, _request
|
|
69
|
-
*/
|
|
70
|
-
export const core = {
|
|
71
|
-
version: '2.24.2', // synced from package.json by scripts/sync-version.mjs
|
|
72
|
-
config: {},
|
|
73
|
-
_initialized: false,
|
|
74
|
-
_initCallback: null,
|
|
75
|
-
_messageHandlerRegistered: false,
|
|
76
|
-
_results: [],
|
|
77
|
-
_backButtonCallback: null,
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Initialize the SDK with config from parent app.
|
|
81
|
-
*
|
|
82
|
-
* Callback form (unchanged): `Usion.init(cb)` — cb(config) fires when the
|
|
83
|
-
* host's INIT arrives. Promise form: every call ALSO returns a
|
|
84
|
-
* Promise<config>, so `const config = await Usion.init()` works.
|
|
85
|
-
*
|
|
86
|
-
* `opts.timeout` (ms, optional) rejects the promise with
|
|
87
|
-
* UsionError(INIT_TIMEOUT) if no INIT arrives in time — the "embedded but
|
|
88
|
-
* host silent" case that otherwise hangs forever. The callback still fires
|
|
89
|
-
* if INIT arrives late. Both `init(cb, opts)` and `init(opts)` are accepted.
|
|
90
|
-
*
|
|
91
|
-
* @param {function|{timeout?: number}} [callback] - Called with config when ready
|
|
92
|
-
* @param {{timeout?: number}} [opts]
|
|
93
|
-
* @returns {Promise<object>} Resolves with config
|
|
94
|
-
*/
|
|
95
|
-
init: function(callback, opts) {
|
|
96
|
-
const self = this;
|
|
97
|
-
if (callback && typeof callback === 'object') {
|
|
98
|
-
opts = callback;
|
|
99
|
-
callback = null;
|
|
100
|
-
}
|
|
101
|
-
opts = opts || {};
|
|
102
|
-
|
|
103
|
-
// Prevent double initialization - just update callback
|
|
104
|
-
if (self._initialized) {
|
|
105
|
-
if (callback) callback(self.config);
|
|
106
|
-
return Promise.resolve(self.config);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Store callback for when config arrives
|
|
110
|
-
if (callback) self._initCallback = callback;
|
|
111
|
-
|
|
112
|
-
// One shared promise for every init() call before INIT arrives.
|
|
113
|
-
if (!self._initPromise) {
|
|
114
|
-
self._initPromise = new Promise(function(resolve, reject) {
|
|
115
|
-
self._initResolve = resolve;
|
|
116
|
-
self._initReject = reject;
|
|
117
|
-
});
|
|
118
|
-
// Callback-style users never touch the promise — don't let an
|
|
119
|
-
// INIT_TIMEOUT rejection surface as an unhandled-rejection error.
|
|
120
|
-
self._initPromise.catch(function() {});
|
|
121
|
-
}
|
|
122
|
-
if (opts.timeout > 0 && !self._initTimer) {
|
|
123
|
-
self._initTimer = setTimeout(function() {
|
|
124
|
-
self._initTimer = null;
|
|
125
|
-
if (self._initialized || !self._initReject) return;
|
|
126
|
-
self._initReject(new UsionError(ERROR_CODES.INIT_TIMEOUT,
|
|
127
|
-
'No INIT from host within ' + opts.timeout + 'ms — host silent or running standalone'));
|
|
128
|
-
}, opts.timeout);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Only register message handler once
|
|
132
|
-
if (self._messageHandlerRegistered) {
|
|
133
|
-
return self._initPromise;
|
|
134
|
-
}
|
|
135
|
-
self._messageHandlerRegistered = true;
|
|
136
|
-
|
|
137
|
-
// Setup global message handler
|
|
138
|
-
window.addEventListener('message', function(event) {
|
|
139
|
-
// Reject messages from anything other than the host shell.
|
|
140
|
-
if (!isTrustedMessageSource(event)) return;
|
|
141
|
-
|
|
142
|
-
let data;
|
|
143
|
-
try {
|
|
144
|
-
data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
|
|
145
|
-
} catch (e) {
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Handle INIT message
|
|
150
|
-
if (data.type === 'INIT' && data.config) {
|
|
151
|
-
// Re-INIT = credential/state refresh, not a re-boot. Hosts re-mint the
|
|
152
|
-
// scoped iframe token and re-INIT before it expires (and retry failed
|
|
153
|
-
// mints with backoff) — dropping these left long-lived iframes 401ing
|
|
154
|
-
// forever once their first token raced the mint or hit the 60-min TTL.
|
|
155
|
-
// Merge the refreshed fields; never re-fire the init callback.
|
|
156
|
-
if (self._initialized) {
|
|
157
|
-
if (data.config.authToken) {
|
|
158
|
-
self.config.authToken = data.config.authToken;
|
|
159
|
-
if (self.user) self.user._token = data.config.authToken;
|
|
160
|
-
}
|
|
161
|
-
if (data.config.balance !== undefined && self.wallet) {
|
|
162
|
-
self.wallet._balance = data.config.balance;
|
|
163
|
-
}
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
self.config = data.config;
|
|
168
|
-
self._initialized = true;
|
|
169
|
-
// We received INIT from a parent -> we are embedded (iframe or WebView)
|
|
170
|
-
self._isEmbedded = true;
|
|
171
|
-
|
|
172
|
-
// Initialize user module with config data
|
|
173
|
-
if (data.config.userId) {
|
|
174
|
-
self.user._id = data.config.userId;
|
|
175
|
-
self.user._name = data.config.userName;
|
|
176
|
-
self.user._avatar = data.config.userAvatar;
|
|
177
|
-
self.user._token = data.config.authToken;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// Initialize session module
|
|
181
|
-
if (data.config.sessionId) {
|
|
182
|
-
self.session._id = data.config.sessionId;
|
|
183
|
-
self.session._data = data.config.sessionData || {};
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Initialize wallet with balance if provided
|
|
187
|
-
if (data.config.balance !== undefined) {
|
|
188
|
-
self.wallet._balance = data.config.balance;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// Initialize results from server
|
|
192
|
-
if (data.config.results) {
|
|
193
|
-
self._results = data.config.results;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Call the stored init callback
|
|
197
|
-
if (self._initCallback) {
|
|
198
|
-
self._initCallback(data.config);
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// Settle the promise form
|
|
202
|
-
if (self._initTimer) {
|
|
203
|
-
clearTimeout(self._initTimer);
|
|
204
|
-
self._initTimer = null;
|
|
205
|
-
}
|
|
206
|
-
if (self._initResolve) {
|
|
207
|
-
self._initResolve(data.config);
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// Handle response messages for async requests
|
|
212
|
-
if (data._requestId && _pendingRequests[data._requestId]) {
|
|
213
|
-
const { resolve, reject } = _pendingRequests[data._requestId];
|
|
214
|
-
delete _pendingRequests[data._requestId];
|
|
215
|
-
|
|
216
|
-
if (data.error) {
|
|
217
|
-
// Preserve the backend's stable code/retry_after when the host
|
|
218
|
-
// relayed them (see errors.js).
|
|
219
|
-
reject(toUsionError(data));
|
|
220
|
-
} else {
|
|
221
|
-
resolve(data);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Handle balance updates
|
|
226
|
-
if (data.type === 'BALANCE_UPDATE') {
|
|
227
|
-
self.wallet._balance = data.balance;
|
|
228
|
-
if (self.wallet._balanceChangeHandler) {
|
|
229
|
-
self.wallet._balanceChangeHandler(data.balance);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Handle back button pressed (one-time claim)
|
|
234
|
-
if (data.type === 'BACK_BUTTON_PRESSED' && self._backButtonCallback) {
|
|
235
|
-
var cb = self._backButtonCallback;
|
|
236
|
-
self._backButtonCallback = null; // one-time use
|
|
237
|
-
cb();
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// Handle bot messages forwarded from host app
|
|
241
|
-
if (data.type === 'BOT_MESSAGE' && self.bot && self.bot._messageHandler) {
|
|
242
|
-
self.bot._messageHandler(data.message);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Handle backend server-push events relayed by the host (embedded mode).
|
|
246
|
-
if (data.type === 'BACKEND_EVENT' && data.event && self._backendHandlers) {
|
|
247
|
-
const h = self._backendHandlers[data.event];
|
|
248
|
-
if (h) h(data.data);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Handle a room assigned by the host AFTER launch — the solo→host
|
|
252
|
-
// promotion path. The user opened the game solo from Explore (launch
|
|
253
|
-
// mode 'single'), then shared it; the host created a room and tells us
|
|
254
|
-
// to adopt it so invitees connect to the SAME room and the host starts
|
|
255
|
-
// receiving onPlayerJoined. No-op when there is no game module.
|
|
256
|
-
if (data.type === 'GAME_ROOM_ASSIGNED' && data.roomId && self.game) {
|
|
257
|
-
var _assignedRoom = data.roomId;
|
|
258
|
-
// Reflect the new room in launch config so getLaunchParams().roomId,
|
|
259
|
-
// .mode and game.isMultiplayer() all report multiplayer from here on.
|
|
260
|
-
self.config.roomId = _assignedRoom;
|
|
261
|
-
self.config.mode = 'multiplayer';
|
|
262
|
-
// Let a solo game flip to its multiplayer UI before peers arrive.
|
|
263
|
-
self.game._dispatch('roomAssigned', { roomId: _assignedRoom });
|
|
264
|
-
// Connect + join so the host is actually in the room. Idempotent when
|
|
265
|
-
// already connected/joined; non-fatal on failure (the game can retry).
|
|
266
|
-
Promise.resolve()
|
|
267
|
-
.then(function() { return self.game.connect(); })
|
|
268
|
-
.then(function() { return self.game.join(_assignedRoom); })
|
|
269
|
-
.catch(function() { /* non-fatal */ });
|
|
270
|
-
}
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
// Report the user's first real interaction to the host (see below).
|
|
274
|
-
this._setupInteractionBeacon();
|
|
275
|
-
|
|
276
|
-
// Signal ready to parent
|
|
277
|
-
this._post({ type: 'READY' });
|
|
278
|
-
|
|
279
|
-
return self._initPromise;
|
|
280
|
-
},
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Tell the host the moment the user FIRST genuinely interacts with the
|
|
284
|
-
* mini-app — a tap, click, key press, or touch — and only once.
|
|
285
|
-
*
|
|
286
|
-
* The host uses this as the SOLE signal to surface the mini-app in the user's
|
|
287
|
-
* chat list — only after real engagement (opening alone, and automatic
|
|
288
|
-
* load-time SDK calls, never count). It works for a fully self-contained
|
|
289
|
-
* app/game that never calls any other SDK method: no `Usion.*` call is
|
|
290
|
-
* required for the host to know the user is engaged.
|
|
291
|
-
*
|
|
292
|
-
* Standalone (non-embedded) apps are unaffected — `_post` no-ops when there
|
|
293
|
-
* is no host. Note: input that produces no DOM gesture (pure device-motion,
|
|
294
|
-
* gamepad) won't trigger this until the first tap/click/key.
|
|
295
|
-
* @private
|
|
296
|
-
*/
|
|
297
|
-
_setupInteractionBeacon: function() {
|
|
298
|
-
const self = this;
|
|
299
|
-
if (self._interactionBeaconSetup) return;
|
|
300
|
-
self._interactionBeaconSetup = true;
|
|
301
|
-
if (typeof window === 'undefined' || !window.addEventListener) return;
|
|
302
|
-
|
|
303
|
-
const events = ['pointerdown', 'mousedown', 'touchstart', 'keydown'];
|
|
304
|
-
function fire(event) {
|
|
305
|
-
// Only count real user gestures, never programmatically dispatched ones.
|
|
306
|
-
if (event && event.isTrusted === false) return;
|
|
307
|
-
if (self._interactionReported) return;
|
|
308
|
-
self._interactionReported = true;
|
|
309
|
-
for (let i = 0; i < events.length; i++) {
|
|
310
|
-
try { window.removeEventListener(events[i], fire, true); } catch (e) { /* noop */ }
|
|
311
|
-
}
|
|
312
|
-
self._post({ type: 'USER_INTERACTION' });
|
|
313
|
-
}
|
|
314
|
-
for (let i = 0; i < events.length; i++) {
|
|
315
|
-
// Capture phase + passive so we observe the gesture without interfering
|
|
316
|
-
// with the app's own handlers or scroll performance.
|
|
317
|
-
try {
|
|
318
|
-
window.addEventListener(events[i], fire, { capture: true, passive: true });
|
|
319
|
-
} catch (e) {
|
|
320
|
-
try { window.addEventListener(events[i], fire, true); } catch (e2) { /* noop */ }
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
},
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Get the current theme ('light' or 'dark')
|
|
327
|
-
* @returns {string}
|
|
328
|
-
*/
|
|
329
|
-
getTheme: function() {
|
|
330
|
-
return this.config.theme || 'light';
|
|
331
|
-
},
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* Get the current language/locale (e.g. 'en', 'mn')
|
|
335
|
-
* @returns {string}
|
|
336
|
-
*/
|
|
337
|
-
getLanguage: function() {
|
|
338
|
-
return this.config.language || 'en';
|
|
339
|
-
},
|
|
340
|
-
|
|
341
|
-
/**
|
|
342
|
-
* Launch parameters the host opened this app with. Use `path` to deep-link
|
|
343
|
-
* to a specific screen — e.g. when the user taps a notification sent via
|
|
344
|
-
* `Usion.notify.send({ path })`, the app reopens and `getLaunchParams().path`
|
|
345
|
-
* returns that same path so the app can route to it.
|
|
346
|
-
*
|
|
347
|
-
* `mode` is how the app was launched: `'single'` (opened from Explore / the
|
|
348
|
-
* Game hub, played solo) or `'multiplayer'` (opened from a game invite in a
|
|
349
|
-
* chat, played with another person). The host declares it authoritatively;
|
|
350
|
-
* branch on it to skip lobby/matchmaking UI in single-player or wire up
|
|
351
|
-
* netcode in multiplayer. When the host doesn't declare a mode (legacy hosts
|
|
352
|
-
* or a standalone URL), it falls back to "a room means multiplayer".
|
|
353
|
-
* @returns {{ path: string|null, ref: string|null, roomId: string|null, mode: 'single'|'multiplayer' }}
|
|
354
|
-
*/
|
|
355
|
-
getLaunchParams: function() {
|
|
356
|
-
var c = this.config || {};
|
|
357
|
-
var mode = (c.mode === 'single' || c.mode === 'multiplayer')
|
|
358
|
-
? c.mode
|
|
359
|
-
: (c.roomId ? 'multiplayer' : 'single');
|
|
360
|
-
return {
|
|
361
|
-
path: c.launchPath || null,
|
|
362
|
-
ref: c.ref || c.launchRef || null,
|
|
363
|
-
roomId: c.roomId || null,
|
|
364
|
-
mode: mode,
|
|
365
|
-
};
|
|
366
|
-
},
|
|
367
|
-
|
|
368
|
-
/**
|
|
369
|
-
* Send message to parent app
|
|
370
|
-
* @private
|
|
371
|
-
*/
|
|
372
|
-
_post: function(message) {
|
|
373
|
-
const msg = JSON.stringify(message);
|
|
374
|
-
|
|
375
|
-
// React Native WebView
|
|
376
|
-
if (window.ReactNativeWebView) {
|
|
377
|
-
window.ReactNativeWebView.postMessage(msg);
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// Web iframe
|
|
382
|
-
if (window.parent !== window) {
|
|
383
|
-
window.parent.postMessage(message, '*');
|
|
384
|
-
}
|
|
385
|
-
},
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* Send async request to parent and wait for response
|
|
389
|
-
* @private
|
|
390
|
-
*/
|
|
391
|
-
_request: function(type, data, timeout) {
|
|
392
|
-
const self = this;
|
|
393
|
-
timeout = timeout || 5000;
|
|
394
|
-
|
|
395
|
-
return new Promise(function(resolve, reject) {
|
|
396
|
-
const requestId = getNextRequestId();
|
|
397
|
-
|
|
398
|
-
// Setup timeout
|
|
399
|
-
const timer = setTimeout(function() {
|
|
400
|
-
delete _pendingRequests[requestId];
|
|
401
|
-
reject(new UsionError(ERROR_CODES.REQUEST_TIMEOUT, 'Request timeout'));
|
|
402
|
-
}, timeout);
|
|
403
|
-
|
|
404
|
-
// Store pending request
|
|
405
|
-
_pendingRequests[requestId] = {
|
|
406
|
-
resolve: function(result) {
|
|
407
|
-
clearTimeout(timer);
|
|
408
|
-
resolve(result);
|
|
409
|
-
},
|
|
410
|
-
reject: function(error) {
|
|
411
|
-
clearTimeout(timer);
|
|
412
|
-
reject(error);
|
|
413
|
-
}
|
|
414
|
-
};
|
|
415
|
-
|
|
416
|
-
// Send request
|
|
417
|
-
self._post({
|
|
418
|
-
type: type,
|
|
419
|
-
_requestId: requestId,
|
|
420
|
-
...data
|
|
421
|
-
});
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
};
|
package/src/modules/errors.js
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Errors — stable, machine-readable error codes.
|
|
3
|
-
*
|
|
4
|
-
* Developers should branch on `err.code`, never on message text. Messages
|
|
5
|
-
* are human-readable and may change; codes are part of the public API and
|
|
6
|
-
* follow the deprecation policy (never removed within a major version).
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/** @type {Record<string, string>} */
|
|
10
|
-
export const ERROR_CODES = {
|
|
11
|
-
NOT_CONNECTED: 'NOT_CONNECTED', // No live connection for this call
|
|
12
|
-
NO_ROOM: 'NO_ROOM', // No room id provided/known
|
|
13
|
-
ROOM_NOT_FOUND: 'ROOM_NOT_FOUND', // Room does not exist server-side
|
|
14
|
-
NOT_PARTICIPANT: 'NOT_PARTICIPANT', // Caller is not a player in the room
|
|
15
|
-
NOT_IN_ROOM: 'NOT_IN_ROOM', // Socket not in the room — rejoin required
|
|
16
|
-
NOT_AUTHORITY: 'NOT_AUTHORITY', // Authority-only call (e.g. lobby start)
|
|
17
|
-
NOT_AUTHENTICATED: 'NOT_AUTHENTICATED', // Missing/invalid auth server-side
|
|
18
|
-
JOIN_TIMEOUT: 'JOIN_TIMEOUT', // Join did not complete in time
|
|
19
|
-
CONNECT_TIMEOUT: 'CONNECT_TIMEOUT', // Connect did not complete in time
|
|
20
|
-
INIT_TIMEOUT: 'INIT_TIMEOUT', // init() got no INIT from the host in time
|
|
21
|
-
MATCH_TIMEOUT: 'MATCH_TIMEOUT', // matchmaking.find() opts.timeout elapsed
|
|
22
|
-
STATE_TOO_LARGE: 'STATE_TOO_LARGE', // setState payload over the quota
|
|
23
|
-
INVALID_STATE: 'INVALID_STATE', // setState payload not a JSON object
|
|
24
|
-
STALE_STATE: 'STALE_STATE', // setState older than the stored checkpoint
|
|
25
|
-
INVALID_NEXT_TURN: 'INVALID_NEXT_TURN', // nextTurn is not a player in the room
|
|
26
|
-
INVALID_INPUT: 'INVALID_INPUT', // Missing/malformed argument server-side
|
|
27
|
-
NOT_FOUND: 'NOT_FOUND', // Referenced entity (service, lobby, …) missing
|
|
28
|
-
QUOTA_EXCEEDED: 'QUOTA_EXCEEDED', // Bucket key/size quota reached (cloud KV)
|
|
29
|
-
VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
|
|
30
|
-
LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
|
|
31
|
-
LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
|
|
32
|
-
WORLD_FULL: 'WORLD_FULL', // World room at max_players
|
|
33
|
-
CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
|
|
34
|
-
RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
|
|
35
|
-
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
|
|
36
|
-
QUEUE_FULL: 'QUEUE_FULL', // Offline action queue at capacity
|
|
37
|
-
CANCELLED: 'CANCELLED', // Cancelled by a local cancel() call
|
|
38
|
-
SUPERSEDED: 'SUPERSEDED', // Replaced by a newer identical request
|
|
39
|
-
UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
|
|
40
|
-
UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export class UsionError extends Error {
|
|
44
|
-
/**
|
|
45
|
-
* @param {string} code - One of ERROR_CODES
|
|
46
|
-
* @param {string} [message] - Human-readable detail (may change between versions)
|
|
47
|
-
*/
|
|
48
|
-
constructor(code, message) {
|
|
49
|
-
super(message || code);
|
|
50
|
-
this.name = 'UsionError';
|
|
51
|
-
this.code = ERROR_CODES[code] ? code : ERROR_CODES.UNKNOWN;
|
|
52
|
-
/** @type {number|undefined} Seconds until a RATE_LIMITED call may retry. */
|
|
53
|
-
this.retryAfter = undefined;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Backend error strings → stable codes. Order matters: first match wins.
|
|
58
|
-
// Fallback path only: the backend now sends a structured `code` on every
|
|
59
|
-
// error ack, which toUsionError prefers. These patterns cover old backends
|
|
60
|
-
// and hosts that strip the code.
|
|
61
|
-
/** @type {Array<[RegExp, string]>} */
|
|
62
|
-
const BACKEND_PATTERNS = [
|
|
63
|
-
[/not authenticated/i, ERROR_CODES.NOT_AUTHENTICATED],
|
|
64
|
-
[/room_id required|no room id/i, ERROR_CODES.NO_ROOM],
|
|
65
|
-
[/room not found/i, ERROR_CODES.ROOM_NOT_FOUND],
|
|
66
|
-
[/not in room/i, ERROR_CODES.NOT_IN_ROOM],
|
|
67
|
-
[/not a participant/i, ERROR_CODES.NOT_PARTICIPANT],
|
|
68
|
-
[/room authority/i, ERROR_CODES.NOT_AUTHORITY],
|
|
69
|
-
[/exceeds .*limit/i, ERROR_CODES.STATE_TOO_LARGE],
|
|
70
|
-
[/stale checkpoint|stale state/i, ERROR_CODES.STALE_STATE],
|
|
71
|
-
[/state must be/i, ERROR_CODES.INVALID_STATE],
|
|
72
|
-
[/next_turn must be/i, ERROR_CODES.INVALID_NEXT_TURN],
|
|
73
|
-
[/rate limit|too many/i, ERROR_CODES.RATE_LIMITED],
|
|
74
|
-
[/join timeout/i, ERROR_CODES.JOIN_TIMEOUT],
|
|
75
|
-
[/connection timeout|connect timeout/i, ERROR_CODES.CONNECT_TIMEOUT],
|
|
76
|
-
[/request timeout/i, ERROR_CODES.REQUEST_TIMEOUT],
|
|
77
|
-
[/not connected/i, ERROR_CODES.NOT_CONNECTED],
|
|
78
|
-
[/quota exceeded/i, ERROR_CODES.QUOTA_EXCEEDED],
|
|
79
|
-
[/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
|
|
80
|
-
[/lobby is full/i, ERROR_CODES.LOBBY_FULL],
|
|
81
|
-
[/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
|
|
82
|
-
[/world room is full/i, ERROR_CODES.WORLD_FULL],
|
|
83
|
-
[/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
|
|
84
|
-
[/conflict/i, ERROR_CODES.CONFLICT],
|
|
85
|
-
[/cancelled/i, ERROR_CODES.CANCELLED],
|
|
86
|
-
[/superseded/i, ERROR_CODES.SUPERSEDED],
|
|
87
|
-
];
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Normalize anything — a structured backend ack ({ error, code?, retry_after? }),
|
|
91
|
-
* an Error, or a raw string — into a UsionError with the best stable code.
|
|
92
|
-
* A machine-readable `code` on the input always wins over message matching.
|
|
93
|
-
* @param {*} err
|
|
94
|
-
* @param {string} [fallbackCode] - Code to use when nothing matches
|
|
95
|
-
* @returns {UsionError}
|
|
96
|
-
*/
|
|
97
|
-
export function toUsionError(err, fallbackCode) {
|
|
98
|
-
if (err instanceof UsionError) return err;
|
|
99
|
-
|
|
100
|
-
// Structured input (backend ack object or an Error carrying a code).
|
|
101
|
-
if (err && typeof err === 'object') {
|
|
102
|
-
const code = typeof err.code === 'string' && ERROR_CODES[err.code] ? err.code : null;
|
|
103
|
-
const message = err.message || err.error;
|
|
104
|
-
if (code) {
|
|
105
|
-
const ue = new UsionError(code, typeof message === 'string' ? message : code);
|
|
106
|
-
const retryAfter = err.retry_after != null ? err.retry_after : err.retryAfter;
|
|
107
|
-
if (typeof retryAfter === 'number' && isFinite(retryAfter)) ue.retryAfter = retryAfter;
|
|
108
|
-
return ue;
|
|
109
|
-
}
|
|
110
|
-
if (!(err instanceof Error) && typeof message === 'string') err = message;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const message = err && err.message ? err.message : String(err || 'Unknown error');
|
|
114
|
-
for (let i = 0; i < BACKEND_PATTERNS.length; i++) {
|
|
115
|
-
if (BACKEND_PATTERNS[i][0].test(message)) {
|
|
116
|
-
return new UsionError(BACKEND_PATTERNS[i][1], message);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
return new UsionError(fallbackCode || ERROR_CODES.UNKNOWN, message);
|
|
120
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK File Storage — large binary data (IndexedDB / filesystem)
|
|
3
|
-
*
|
|
4
|
-
* Scoped per-user, per-service like regular storage.
|
|
5
|
-
* Uses IndexedDB (web) or filesystem (mobile) — no localStorage size limits.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
export function createFileStorageModule(sdk) {
|
|
9
|
-
return {
|
|
10
|
-
/**
|
|
11
|
-
* Store a file (base64 encoded)
|
|
12
|
-
* @param {string} key - Storage key
|
|
13
|
-
* @param {string} base64Data - Base64-encoded file content (no data: prefix)
|
|
14
|
-
* @param {string} mimeType - MIME type (e.g. 'image/png')
|
|
15
|
-
* @returns {Promise<void>}
|
|
16
|
-
*/
|
|
17
|
-
set: function(key, base64Data, mimeType) {
|
|
18
|
-
return sdk._request('FILE_STORAGE_SET', {
|
|
19
|
-
key: key,
|
|
20
|
-
base64Data: base64Data,
|
|
21
|
-
mimeType: mimeType || 'application/octet-stream'
|
|
22
|
-
}, 30000).then(function() { return; });
|
|
23
|
-
},
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Get a stored file
|
|
27
|
-
* @param {string} key - Storage key
|
|
28
|
-
* @returns {Promise<{base64Data: string, mimeType: string} | null>}
|
|
29
|
-
*/
|
|
30
|
-
get: function(key) {
|
|
31
|
-
return sdk._request('FILE_STORAGE_GET', { key: key }, 30000).then(function(response) {
|
|
32
|
-
if (!response || !response.base64Data) return null;
|
|
33
|
-
return { base64Data: response.base64Data, mimeType: response.mimeType };
|
|
34
|
-
});
|
|
35
|
-
},
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Remove a stored file
|
|
39
|
-
* @param {string} key - Storage key
|
|
40
|
-
* @returns {Promise<void>}
|
|
41
|
-
*/
|
|
42
|
-
remove: function(key) {
|
|
43
|
-
return sdk._request('FILE_STORAGE_REMOVE', { key: key }).then(function() { return; });
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
}
|
package/src/modules/game-ack.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { UsionError, ERROR_CODES } from './errors.js';
|
|
2
|
-
|
|
3
|
-
export const GAME_ACK_TIMEOUT_MS = 10000;
|
|
4
|
-
export const GAME_JOIN_TIMEOUT_MS = 15000;
|
|
5
|
-
|
|
6
|
-
export function emitGameWithAck(socket, event, payload, timeoutMs, timeoutCode) {
|
|
7
|
-
timeoutMs = timeoutMs || GAME_ACK_TIMEOUT_MS;
|
|
8
|
-
timeoutCode = timeoutCode || ERROR_CODES.REQUEST_TIMEOUT;
|
|
9
|
-
return new Promise(function(resolve, reject) {
|
|
10
|
-
let settled = false;
|
|
11
|
-
const timer = setTimeout(function() {
|
|
12
|
-
if (settled) return;
|
|
13
|
-
settled = true;
|
|
14
|
-
reject(new UsionError(timeoutCode,
|
|
15
|
-
timeoutCode === ERROR_CODES.JOIN_TIMEOUT ? 'Join timeout' : 'Game request timeout'));
|
|
16
|
-
}, timeoutMs);
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
socket.emit(event, payload, function(response) {
|
|
20
|
-
if (settled) return;
|
|
21
|
-
settled = true;
|
|
22
|
-
clearTimeout(timer);
|
|
23
|
-
resolve(response || {});
|
|
24
|
-
});
|
|
25
|
-
} catch (err) {
|
|
26
|
-
if (settled) return;
|
|
27
|
-
settled = true;
|
|
28
|
-
clearTimeout(timer);
|
|
29
|
-
reject(err);
|
|
30
|
-
}
|
|
31
|
-
});
|
|
32
|
-
}
|