@tesana/sdk 1.0.3 → 1.1.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.
@@ -2,7 +2,7 @@
2
2
  * Tesana play-time SDK. Vanilla JS, no npm in games.
3
3
  * Host injects window.__TESANA__ or postMessage { type: "tesana-bootstrap", ... }.
4
4
  * v1 is player identity, per-game saves, optional open-lobby multiplayer,
5
- * cloud saves, and the in-game coin economy.
5
+ * cloud saves, the in-game coin economy, and gameplay analytics.
6
6
  *
7
7
  * THIS FILE IS THE ONE COPY. It is the source of truth for `window.Tesana`:
8
8
  * the engine injects the built artifact into every game and the CDN serves it
@@ -37,7 +37,11 @@
37
37
  // 1.0.0 ships six services together: saves, shop, leaderboards, achievements,
38
38
  // a vanity address (`tesana.vanity`) and in-game ads (`tesana.ads`). These are
39
39
  // the first release, so there is no earlier number to stay compatible with.
40
- const VERSION = "1.0.3";
40
+ //
41
+ // 1.1.0 adds gameplay analytics, `tesana.track` and `tesana.gameplay.*`. The
42
+ // engine's analytics skill already taught them, so a game following it threw a
43
+ // TypeError on its first death; this is the release that makes those calls real.
44
+ const VERSION = "1.1.0";
41
45
 
42
46
  const LOCAL_CACHE = "tesana.play.v1";
43
47
 
@@ -53,6 +57,21 @@ const LOCAL_CACHE = "tesana.play.v1";
53
57
  const MP_RECONNECT_BASE_MS = 1000;
54
58
  const MP_RECONNECT_MAX_MS = 30000;
55
59
  const MP_RECONNECT_MAX_ATTEMPTS = 8;
60
+ //: How long to wait for the host to answer a bootstrap request before giving
61
+ //: up on that attempt. The answer is a token mint; a host that is slow must not
62
+ //: hold a request open indefinitely.
63
+ const MP_HOST_ASK_TIMEOUT_MS = 5000;
64
+ //: How long `create`/`quickJoin` will wait for a room that is being placed.
65
+ //:
66
+ //: Room creation on GameLift is asynchronous, so the service answers 202 with
67
+ //: no `wsUrl` and a `retryAfterMs` instead of holding the request open. The
68
+ //: client polls until the room is ready or this budget runs out. It is longer
69
+ //: than the service's own placement poll (90s) only in the sense that it gives
70
+ //: up first: a client should decide for itself how long it will wait, and a
71
+ //: game can watch `onStatus` rather than being blocked.
72
+ const MP_PLACING_TIMEOUT_MS = 45000;
73
+ //: Default gap between placement polls, used when the service does not say.
74
+ const MP_PLACING_RETRY_MS = 1500;
56
75
 
57
76
  /**
58
77
  * A polite, dns-safe label: lowercase letters, digits and internal hyphens,
@@ -126,6 +145,18 @@ const bootstrapWaiters = [];
126
145
  // can re-point them in place. A game holds a reference to its client, so it
127
146
  // must not be rebuilt — only upgraded.
128
147
  const upgradeHandlers = [];
148
+ // Whether a bootstrap the client asked for is in flight. It is what makes a
149
+ // late answer an update rather than an unsolicited message that re-points a
150
+ // live session.
151
+ let bootstrapRequestPending = false;
152
+ // The in-flight ask, so a burst of refused calls mints once rather than once
153
+ // per caller. The host does its own rate-limiting; this only removes the
154
+ // duplicate round-trips a simultaneous burst would otherwise make.
155
+ let bootstrapAskPromise = null;
156
+ //: Bumped every time a host answer replaces the live bootstrap. A caller that
157
+ //: asked for a fresh token can tell whether it actually arrived by watching
158
+ //: this, without having to hold a listener of its own.
159
+ let bootstrapGeneration = 0;
129
160
 
130
161
  /**
131
162
  * Diagnostics that should say their piece once per session, not once per call.
@@ -150,17 +181,34 @@ function isGuestBootstrap(data) {
150
181
  }
151
182
 
152
183
  /** Fold a host's answer into the live config, upgrading a provisional one. */
153
- function applyBootstrap(data) {
184
+ function applyBootstrap(data, opts = {}) {
154
185
  const next = data && typeof data === "object" ? data : {};
186
+ // Whether the client asked for this answer. A bootstrap it asked for is a
187
+ // refresh — its token aged out and the host minted another — and may update a
188
+ // live session. One it did not ask for may not, or anything able to post into
189
+ // the frame could re-point a running game's credential and identity.
190
+ const asked = opts.force || bootstrapRequestPending;
191
+ bootstrapRequestPending = false;
155
192
  if (bootstrap) {
156
193
  // A real host has already answered — unless that answer was a guest and
157
194
  // this one is the account they just signed in to.
158
- if (!bootstrap.offline && !(isGuestBootstrap(bootstrap) && !next.offline && !isGuestBootstrap(next))) return;
195
+ if (!bootstrap.offline && !(isGuestBootstrap(bootstrap) && !next.offline && !isGuestBootstrap(next))) {
196
+ if (asked) {
197
+ // A forced update may refresh credentials (token, save token, room
198
+ // token) but never the player's identity: the player is who the
199
+ // signing-in page said they are, and a stale or mismatched answer must
200
+ // not silently become them.
201
+ if (bootstrap.player && next.player !== undefined) delete next.player;
202
+ } else {
203
+ return;
204
+ }
205
+ }
159
206
  // Still offline, unless it now carries a room token: a signed-out
160
207
  // visitor's multiplayer arrives after the site has already said "offline".
161
- if (next.offline && !(next.roomToken && !bootstrap.roomToken)) return;
208
+ if (next.offline && !(next.roomToken && !bootstrap.roomToken) && !asked) return;
162
209
  }
163
210
  bootstrap = next;
211
+ bootstrapGeneration += 1;
164
212
  window.__TESANA__ = { ...(window.__TESANA__ || {}), ...next };
165
213
  const waiting = bootstrapWaiters.splice(0);
166
214
  for (const resolve of waiting) resolve(bootstrap);
@@ -197,6 +245,60 @@ function onBootstrapUpgrade(fn) {
197
245
  */
198
246
  let adClient = null;
199
247
 
248
+ /**
249
+ * The live localization capability, kept module-scoped for the same reason as
250
+ * the ad client: the host can change the language at any moment, and the game
251
+ * holds a reference to `tesana.l10n` that must not be replaced underneath it.
252
+ * The listener calls `applyLocale`, which re-points this object in place.
253
+ */
254
+ let l10nClient = null;
255
+
256
+ /**
257
+ * The languages the platform can translate into, in display order.
258
+ *
259
+ * Mirrors the service's own list, which is the authority; this copy exists so a
260
+ * language picker can be drawn before the service has answered — and so a page
261
+ * with no host at all, where nothing will ever answer, still has an honest
262
+ * list rather than an empty one.
263
+ */
264
+ const L10N_TARGETS = ["en", "es", "fr", "de", "it", "pt-BR", "ru", "zh", "ja", "ko"];
265
+
266
+ /**
267
+ * Fold whatever a host calls a language onto one of ours.
268
+ *
269
+ * `navigator.language` reports `en-US` and `pt-PT`; a site may store `pt` or
270
+ * `zh`; a player may be handed `de-AT`. None of those are in the list above and
271
+ * all of them mean a language we do translate into, so the base tag is what
272
+ * gets matched and the region is dropped — a game in `pt-BR` is more useful to
273
+ * a `pt-PT` player than one left in English. An unknown tag stays as it is and
274
+ * simply falls back to the source language at the call site.
275
+ */
276
+ function normalizeLocale(tag) {
277
+ const value = String(tag || "").trim().replace(/_/g, "-");
278
+ if (!value) return "";
279
+ const exact = L10N_TARGETS.find((t) => t.toLowerCase() === value.toLowerCase());
280
+ if (exact) return exact;
281
+ const base = value.split("-")[0].toLowerCase();
282
+ return L10N_TARGETS.find((t) => t.split("-")[0].toLowerCase() === base) || value;
283
+ }
284
+
285
+ /** `{name}` in `text`, filled from `values`. The one interpolation rule the SDK and the service share. */
286
+ function fillPlaceholders(text, values) {
287
+ const source = String(text == null ? "" : text);
288
+ if (!values || typeof values !== "object") return source;
289
+ return source.replace(/\{(\w+)\}/g, (whole, key) =>
290
+ Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : whole,
291
+ );
292
+ }
293
+
294
+ /** Fold a locale message from the host into the live client, if it is listening. */
295
+ function resyncLocale(data) {
296
+ if (!l10nClient) return;
297
+ const payload = data && typeof data.payload === "object" ? data.payload : data;
298
+ const next = payload && (payload.locale || payload.lang || payload.language);
299
+ if (next) l10nClient.applyLocale(next);
300
+ }
301
+
200
302
  /** A policy message from the host, or `null` when none is in force. */
201
303
  function adPolicyFrom(data) {
202
304
  if (!data || typeof data !== "object") return null;
@@ -348,6 +450,8 @@ function startListening() {
348
450
  // The site posts `{ type, payload }`; a baked or spliced bootstrap is the
349
451
  // payload itself. Accept both, so one SDK reads either host.
350
452
  if (data.type === "tesana-bootstrap") {
453
+ // `applyBootstrap` decides whether this answer may update a live session:
454
+ // one the client asked for may, one it did not may not.
351
455
  applyBootstrap(data.payload && typeof data.payload === "object" ? data.payload : data);
352
456
  return;
353
457
  }
@@ -366,6 +470,19 @@ function startListening() {
366
470
  }
367
471
  return;
368
472
  }
473
+ // The player changed the site's language. The host is the authority — it
474
+ // resolved which language the player wants, and it owns the setting — so
475
+ // this only carries it down. The game's own text re-renders when it draws
476
+ // again, which is why the skill tells games to redraw from `t()` rather
477
+ // than cache translated strings at startup.
478
+ if (data.type === "tesana-locale") {
479
+ try {
480
+ resyncLocale(data);
481
+ } catch {
482
+ /* a bad locale must never break the listener */
483
+ }
484
+ return;
485
+ }
369
486
  if (data.type === "tesana-ad-show") {
370
487
  try {
371
488
  const requestId = data.requestId || data.request_id;
@@ -397,16 +514,73 @@ function waitBootstrap(timeoutMs = 1500) {
397
514
  if (bootstrap) return Promise.resolve(bootstrap);
398
515
 
399
516
  startListening();
400
- // Ask, rather than wait to be told. The frame can finish loading before the
401
- // site has minted the session, and a request is what makes the site post the
402
- // second time — without it a signed-in player's real bootstrap never arrives.
403
- post({ type: "tesana-bootstrap-request" });
404
517
  return new Promise((resolve) => {
518
+ // The waiter is registered before the ask goes out. A host that answers
519
+ // from the same tick — a test double, or a same-document frame — would
520
+ // otherwise be answered into an empty list and the game would fall to
521
+ // "offline" a second and a half later for no reason.
405
522
  bootstrapWaiters.push(resolve);
406
523
  setTimeout(() => applyBootstrap({ offline: true }), timeoutMs);
524
+ // Ask, rather than wait to be told. The frame can finish loading before the
525
+ // site has minted the session, and a request is what makes the site post the
526
+ // second time — without it a signed-in player's real bootstrap never arrives.
527
+ askHostForBootstrap();
407
528
  });
408
529
  }
409
530
 
531
+ /** Ask the host to post a bootstrap. Shared by boot and refresh, so the flag
532
+ * that makes an answer an update is set in exactly one place. The message name
533
+ * is what tells the host whether to re-mint or merely re-post. */
534
+ function askHostForBootstrap(type = "tesana-bootstrap-request") {
535
+ bootstrapRequestPending = true;
536
+ post({ type });
537
+ }
538
+
539
+ /**
540
+ * Ask the host for a fresh bootstrap after a credential was refused.
541
+ *
542
+ * This is the SDK half of token expiry. A player token lives two hours and
543
+ * used to be re-minted only on a page load, so after two hours a blip was
544
+ * permanent until the player reloaded. Asking the host re-mints through it, and
545
+ * the answer flows back through the same upgrade path identity and ads already
546
+ * use, so a live game is re-pointed in place.
547
+ *
548
+ * Resolves with the new bootstrap, or `null` when there is no host or the host
549
+ * did not answer in time. Concurrent callers share one ask: a game that has
550
+ * been open for hours hits a burst of refusals at once, and one mint is what
551
+ * all of them needed. The host rate-limits the mints themselves.
552
+ *
553
+ * @returns {Promise<object|null>}
554
+ */
555
+ function requestHostBootstrap() {
556
+ if (typeof window === "undefined") return Promise.resolve(null);
557
+ if (bootstrapAskPromise) return bootstrapAskPromise;
558
+ startListening();
559
+ const askedAt = bootstrapGeneration;
560
+ // A refresh, named as one. The host re-mints on this and merely re-posts on a
561
+ // boot request, so the two are never confused.
562
+ askHostForBootstrap("tesana-bootstrap-refresh");
563
+ bootstrapAskPromise = new Promise((resolve) => {
564
+ let done = false;
565
+ const finish = (value) => {
566
+ if (done) return;
567
+ done = true;
568
+ clearInterval(poll);
569
+ clearTimeout(expiry);
570
+ bootstrapAskPromise = null;
571
+ resolve(value);
572
+ };
573
+ // The bootstrap is delivered by the module-level listener, so watch the
574
+ // generation rather than registering a second listener — the token the host
575
+ // mints is scoped to this frame and is not ours to consume only here.
576
+ const poll = setInterval(() => {
577
+ if (bootstrapGeneration !== askedAt) finish(bootstrap);
578
+ }, 25);
579
+ const expiry = setTimeout(() => finish(null), MP_HOST_ASK_TIMEOUT_MS);
580
+ });
581
+ return bootstrapAskPromise;
582
+ }
583
+
410
584
  function deviceId() {
411
585
  const cache = readCache();
412
586
  if (cache.deviceId) return cache.deviceId;
@@ -451,6 +625,308 @@ function post(message) {
451
625
  }
452
626
  }
453
627
 
628
+ // ---------------------------------------------------------------------------
629
+ // Gameplay analytics: `tesana.track` and `tesana.gameplay`
630
+ // ---------------------------------------------------------------------------
631
+ //
632
+ // A game reports what happened in it (a level started, the player died, a run
633
+ // ended with a score) so its creator can see where players get stuck and where
634
+ // they quit. The pipe already exists end to end: the runtime shell injected
635
+ // into every web build exposes `window.__TESANA_EVENT__`, the Tesana page above
636
+ // the game buffers `tesana-gameplay-event` messages and files them against the
637
+ // play session with a token only it holds, and the ingest endpoint stores them.
638
+ // These functions are the game's end of that pipe.
639
+ //
640
+ // Three rules shape everything below:
641
+ //
642
+ // - **Never throw.** The engine tells the AI to call these inline, at the
643
+ // moment a player dies, with no guard. A TypeError here would turn a death
644
+ // into a crash, so every entry point is wrapped and answers `false` when it
645
+ // drops something.
646
+ // - **Match the ingest endpoint's caps.** The server keeps at most 20 payload
647
+ // keys, 40-character keys, 64-character strings and 2,000 characters in all,
648
+ // and throws away the whole payload when it is over. Trimming here means a
649
+ // slightly-too-big event loses a key rather than all of its context.
650
+ // - **Discrete moments, not frames.** A game that reports on every frame
651
+ // would fill the table and answer nothing, so events are rate limited per
652
+ // second and capped per page load.
653
+ //
654
+ // They are synchronous and need no `init()`: they never touch the play service,
655
+ // only the page, so a game can report a level start on its first frame.
656
+
657
+ //: The message the host's play tracking listens for. Mirrored by the web host
658
+ //: (`PLAY_MESSAGES.gameplayEvent`) and the runtime shell.
659
+ const GAMEPLAY_MESSAGE = "tesana-gameplay-event";
660
+
661
+ //: The event types the ingest endpoint understands, minus the two the shell
662
+ //: owns (`session_end`, `error`). `track()` with one of these names files the
663
+ //: event under that type; any other name is a `custom` event.
664
+ const GAMEPLAY_EVENT_TYPES = new Set(["level_start", "level_complete", "death", "checkpoint", "score"]);
665
+ const GAMEPLAY_TYPE_ALIASES = { levelStart: "level_start", levelComplete: "level_complete" };
666
+
667
+ //: The ingest endpoint's own limits (`games/api/play_events.py`).
668
+ const GAMEPLAY_NAME_MAX = 64;
669
+ const GAMEPLAY_STRING_MAX = 64;
670
+ const GAMEPLAY_KEY_MAX = 40;
671
+ const GAMEPLAY_PROPS_MAX_KEYS = 20;
672
+ const GAMEPLAY_PROPS_MAX_CHARS = 2000;
673
+
674
+ //: At most this many events in any one second. Ten a second is exactly what
675
+ //: one host flush can carry (100 events every 10 seconds), and far above what a
676
+ //: game reporting real moments ever needs.
677
+ const GAMEPLAY_RATE_PER_SECOND = 10;
678
+ //: At most this many events per page load. An honest session sends tens; a
679
+ //: game stuck reporting at the rate limit for an hour would send 36,000.
680
+ const GAMEPLAY_SESSION_MAX = 1000;
681
+
682
+ //: Props promoted to the event's own columns rather than kept as context.
683
+ const GAMEPLAY_LEVEL_ID_KEYS = ["levelId", "level_id", "level"];
684
+ const GAMEPLAY_LEVEL_INDEX_KEYS = ["levelIndex", "level_index"];
685
+ const GAMEPLAY_NUMBER_KEYS = ["x", "y", "z", "value"];
686
+ const GAMEPLAY_PROMOTED = new Set([
687
+ ...GAMEPLAY_LEVEL_ID_KEYS,
688
+ ...GAMEPLAY_LEVEL_INDEX_KEYS,
689
+ ...GAMEPLAY_NUMBER_KEYS,
690
+ "name",
691
+ ]);
692
+
693
+ let gameplaySecond = -1;
694
+ let gameplayInSecond = 0;
695
+ let gameplaySent = 0;
696
+
697
+ /** A finite number, or `undefined`. Numeric strings count; NaN never does. */
698
+ function gameplayNumber(value) {
699
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
700
+ if (typeof value === "string" && value.trim() !== "") {
701
+ const parsed = Number(value);
702
+ return Number.isFinite(parsed) ? parsed : undefined;
703
+ }
704
+ return undefined;
705
+ }
706
+
707
+ /** A trimmed, capped string id from a string or a number, or `undefined`. */
708
+ function gameplayId(value, limit) {
709
+ if (typeof value === "number") {
710
+ if (!Number.isFinite(value)) return undefined;
711
+ return String(value).slice(0, limit);
712
+ }
713
+ if (typeof value !== "string") return undefined;
714
+ const text = value.trim().slice(0, limit);
715
+ return text || undefined;
716
+ }
717
+
718
+ /** The first of `keys` that `props` holds a value for. */
719
+ function gameplayFirst(props, keys) {
720
+ for (const key of keys) {
721
+ if (props[key] !== undefined && props[key] !== null) return props[key];
722
+ }
723
+ return undefined;
724
+ }
725
+
726
+ /**
727
+ * Roughly how long the server's `repr()` of this payload will be.
728
+ *
729
+ * The endpoint measures Python's `repr`, not JSON: it writes `1.0` for `1` and
730
+ * puts a space after each colon and comma. Four characters per key is a safe
731
+ * margin over both differences, so a payload that passes here passes there.
732
+ */
733
+ function gameplayPayloadSize(payload, keys) {
734
+ return JSON.stringify(payload).length + 4 * keys;
735
+ }
736
+
737
+ /**
738
+ * Keep the scalar context a game passed, within the endpoint's caps.
739
+ *
740
+ * @param {object} props
741
+ * @param {boolean} keepName keep a `name` prop as context (a custom event, whose
742
+ * own name is the event's name) rather than treating it as the name column
743
+ */
744
+ function gameplayPayload(props, keepName) {
745
+ const payload = {};
746
+ let kept = 0;
747
+ for (const rawKey of Object.keys(props)) {
748
+ if (kept >= GAMEPLAY_PROPS_MAX_KEYS) break;
749
+ if (GAMEPLAY_PROMOTED.has(rawKey) && !(keepName && rawKey === "name")) continue;
750
+ const key = String(rawKey).trim().slice(0, GAMEPLAY_KEY_MAX);
751
+ if (!key || Object.prototype.hasOwnProperty.call(payload, key)) continue;
752
+ let value;
753
+ try {
754
+ value = props[rawKey];
755
+ } catch {
756
+ continue;
757
+ }
758
+ if (typeof value === "string") {
759
+ value = value.slice(0, GAMEPLAY_STRING_MAX);
760
+ } else if (typeof value === "number") {
761
+ if (!Number.isFinite(value)) continue;
762
+ } else if (typeof value !== "boolean" && value !== null) {
763
+ // Objects, arrays, functions, undefined, symbols and bigints are not
764
+ // stored: the analytics layer queries flat keys, and a nested shape it
765
+ // did not expect is a foot-gun rather than a feature.
766
+ continue;
767
+ }
768
+ payload[key] = value;
769
+ if (gameplayPayloadSize(payload, kept + 1) > GAMEPLAY_PROPS_MAX_CHARS) {
770
+ delete payload[key];
771
+ continue;
772
+ }
773
+ kept += 1;
774
+ }
775
+ return kept ? payload : null;
776
+ }
777
+
778
+ /**
779
+ * Build the event the host files, in the shape `POST /play/events` accepts.
780
+ *
781
+ * @param {string} type one of the ingest endpoint's event types
782
+ * @param {string|undefined} name the event's own name (a custom event, a death's cause)
783
+ * @param {object} props what the game passed
784
+ */
785
+ function gameplayEvent(type, name, props) {
786
+ const event = { type };
787
+ const named = name !== undefined ? name : gameplayId(props.name, GAMEPLAY_NAME_MAX);
788
+ if (named) event.name = named;
789
+ const levelId = gameplayId(gameplayFirst(props, GAMEPLAY_LEVEL_ID_KEYS), GAMEPLAY_STRING_MAX);
790
+ if (levelId) event.level_id = levelId;
791
+ const levelIndex = gameplayNumber(gameplayFirst(props, GAMEPLAY_LEVEL_INDEX_KEYS));
792
+ if (levelIndex !== undefined) event.level_index = Math.max(0, Math.floor(levelIndex));
793
+ for (const key of GAMEPLAY_NUMBER_KEYS) {
794
+ const number = gameplayNumber(props[key]);
795
+ if (number !== undefined) event[key] = number;
796
+ }
797
+ // A custom event's own name is already its name, so a `name` prop is kept as
798
+ // context like any other key instead of overwriting it.
799
+ const payload = gameplayPayload(props, type === "custom");
800
+ if (payload) event.payload = payload;
801
+ event.ts = Date.now();
802
+ return event;
803
+ }
804
+
805
+ /** Whether one more event fits this second and this page load. */
806
+ function gameplayAllowed() {
807
+ if (gameplaySent >= GAMEPLAY_SESSION_MAX) {
808
+ warnOnce(
809
+ "gameplay-session-max",
810
+ `tesana.track: ${GAMEPLAY_SESSION_MAX} events this session; further events are dropped. Report discrete moments (a level, a death, a run's end), never every frame.`,
811
+ );
812
+ return false;
813
+ }
814
+ const second = Math.floor(Date.now() / 1000);
815
+ if (second !== gameplaySecond) {
816
+ gameplaySecond = second;
817
+ gameplayInSecond = 0;
818
+ }
819
+ if (gameplayInSecond >= GAMEPLAY_RATE_PER_SECOND) {
820
+ warnOnce(
821
+ "gameplay-rate",
822
+ `tesana.track: more than ${GAMEPLAY_RATE_PER_SECOND} events in one second; the extra ones are dropped. Report discrete moments, never every frame.`,
823
+ );
824
+ return false;
825
+ }
826
+ gameplayInSecond += 1;
827
+ gameplaySent += 1;
828
+ return true;
829
+ }
830
+
831
+ /**
832
+ * Hand an event to whoever files it. `true` when it was handed on.
833
+ *
834
+ * The shell's `__TESANA_EVENT__` comes first: it posts the same message, and
835
+ * going through it lets the shell name the last level in its `session_end`.
836
+ * Without the shell, the message goes straight to the Tesana page above. With
837
+ * neither there is nobody to tell, and the event is dropped.
838
+ */
839
+ function gameplayDeliver(event) {
840
+ if (typeof window === "undefined") return false;
841
+ const bridge = window.__TESANA_EVENT__;
842
+ if (typeof bridge === "function") {
843
+ bridge(event);
844
+ return true;
845
+ }
846
+ if (!hasHost()) return false;
847
+ post({ type: GAMEPLAY_MESSAGE, event });
848
+ return true;
849
+ }
850
+
851
+ /** The game's props as a plain object, whatever it actually passed. */
852
+ function gameplayProps(props) {
853
+ return props && typeof props === "object" && !Array.isArray(props) ? props : {};
854
+ }
855
+
856
+ /**
857
+ * Report something that happened in the game.
858
+ *
859
+ * `name` is the game's own name for it (`"powerup_picked"`). A name that is one
860
+ * of the platform's types (`"death"`, `"level_start"`, `"level_complete"`,
861
+ * `"checkpoint"`, `"score"`) is filed as that type. `props` is a small object of
862
+ * scalars; `levelId`, `levelIndex`, `x`, `y`, `z` and `value` become columns and
863
+ * anything else rides along as context.
864
+ *
865
+ * Synchronous, never throws, and never returns a promise: `true` when the event
866
+ * was handed on, `false` when it was dropped (a bad name, too many events, or
867
+ * nothing above the game to hand it to).
868
+ *
869
+ * @param {string} name
870
+ * @param {Record<string, string|number|boolean|null>} [props]
871
+ * @returns {boolean}
872
+ */
873
+ function track(name, props) {
874
+ try {
875
+ const label = gameplayId(name, GAMEPLAY_NAME_MAX);
876
+ if (!label) {
877
+ warnOnce("gameplay-name", "tesana.track: the first argument must be a non-empty event name.");
878
+ return false;
879
+ }
880
+ if (!gameplayAllowed()) return false;
881
+ const builtIn = GAMEPLAY_TYPE_ALIASES[label] || label;
882
+ const event = GAMEPLAY_EVENT_TYPES.has(builtIn)
883
+ ? gameplayEvent(builtIn, undefined, gameplayProps(props))
884
+ : gameplayEvent("custom", label, gameplayProps(props));
885
+ return gameplayDeliver(event);
886
+ } catch {
887
+ return false;
888
+ }
889
+ }
890
+
891
+ /**
892
+ * One gameplay helper. `props` may also be a bare level id (`levelStart(3)`), or
893
+ * for `score` a bare value (`score(1200)`).
894
+ *
895
+ * @param {string} type
896
+ * @param {"levelId"|"value"} shorthand
897
+ */
898
+ function gameplayHelper(type, shorthand) {
899
+ return function report(props) {
900
+ try {
901
+ if (!gameplayAllowed()) return false;
902
+ const given = typeof props === "string" || typeof props === "number"
903
+ ? { [shorthand]: props }
904
+ : gameplayProps(props);
905
+ return gameplayDeliver(gameplayEvent(type, undefined, given));
906
+ } catch {
907
+ return false;
908
+ }
909
+ };
910
+ }
911
+
912
+ /**
913
+ * The progression events every game with levels, waves, runs or deaths should
914
+ * send. `levelId` is the join key: give it the same stable value in each call
915
+ * for one level, so a funnel can line them up.
916
+ */
917
+ const gameplay = Object.freeze({
918
+ /** A level, stage, wave or area begins: `{ levelId, levelIndex? }`. */
919
+ levelStart: gameplayHelper("level_start", "levelId"),
920
+ /** A level is cleared: `{ levelId }`. */
921
+ levelComplete: gameplayHelper("level_complete", "levelId"),
922
+ /** The player died: `{ levelId, x?, y?, z?, name? }` (`name` is the cause). */
923
+ death: gameplayHelper("death", "levelId"),
924
+ /** A checkpoint is reached: `{ levelId, name? }`. */
925
+ checkpoint: gameplayHelper("checkpoint", "levelId"),
926
+ /** A run ended: `{ value, levelId? }`. */
927
+ score: gameplayHelper("score", "value"),
928
+ });
929
+
454
930
  /**
455
931
  * @param {TesanaConfig} [config]
456
932
  */
@@ -489,6 +965,16 @@ export async function init(config = {}) {
489
965
  } catch (err) {
490
966
  client.goOffline(err);
491
967
  }
968
+ // Localization comes after identity, not before: the bundle is fetched with
969
+ // the player's token, so a game that just minted one would otherwise load it
970
+ // unauthenticated and stay in its source language all session. Awaited here
971
+ // so `await __TESANA_READY__` is genuinely enough — the first frame a game
972
+ // draws can already be translated.
973
+ try {
974
+ await client.l10n.reload();
975
+ } catch {
976
+ /* localization must never block the game's start */
977
+ }
492
978
  window.__TESANA_PLAYER__ = client.player.me();
493
979
  // A provisional "offline" answer can upgrade later. Re-point this client in
494
980
  // place — the game holds a reference to it — and re-run the identity step,
@@ -496,7 +982,7 @@ export async function init(config = {}) {
496
982
  // player with a balance frozen at zero.
497
983
  const finishUpgrade = () => {
498
984
  client.configure(buildConfig(mergedConfig()));
499
- client.ensureSession();
985
+ client.ensureSession().then(() => client.l10n.reload());
500
986
  window.__TESANA_PLAYER__ = client.player.me();
501
987
  };
502
988
  onBootstrapUpgrade(finishUpgrade);
@@ -559,6 +1045,18 @@ function buildConfig(merged) {
559
1045
  adsEnabled: merged.adsEnabled,
560
1046
  adFormats: merged.adFormats || merged.ad_formats || [],
561
1047
  adMinIntervalMs: merged.adMinIntervalMs ?? merged.ad_min_interval_ms,
1048
+ // The player's language, as the host resolved it. The host owns the
1049
+ // setting (the site has a language picker and the game does not), so this
1050
+ // is read from the bootstrap rather than sniffed here — a game that
1051
+ // guessed from `navigator.language` would disagree with the site the
1052
+ // player is reading. Absent means an older host: localization then falls
1053
+ // back to the source language and the game renders exactly as it did.
1054
+ locale: normalizeLocale(
1055
+ merged.locale || merged.language || merged.lang || (typeof navigator !== "undefined" && navigator.language) || "",
1056
+ ),
1057
+ // How a dropped room socket is retried. A game can shrink the waits (a
1058
+ // test, or a game with unusual tolerance); the defaults are the fleet's.
1059
+ multiplayerReconnect: merged.multiplayerReconnect || undefined,
562
1060
  };
563
1061
  }
564
1062
 
@@ -570,7 +1068,7 @@ function defaultEndpoint() {
570
1068
 
571
1069
  class TesanaClient {
572
1070
  /**
573
- * @param {{ endpoint: string, gameId: string, token: string, rail: string, deviceId: string, multiplayer?: boolean, saveEndpoint?: string, saveToken?: string, offline?: boolean, roomEndpoint?: string, roomToken?: string, player?: object|null, vanityAddress?: string, adsEnabled?: boolean }} opts
1071
+ * @param {{ endpoint: string, gameId: string, token: string, rail: string, deviceId: string, multiplayer?: boolean, saveEndpoint?: string, saveToken?: string, offline?: boolean, roomEndpoint?: string, roomToken?: string, player?: object|null, vanityAddress?: string, adsEnabled?: boolean, locale?: string }} opts
574
1072
  */
575
1073
  constructor(opts) {
576
1074
  this.endpoint = opts.endpoint;
@@ -613,12 +1111,18 @@ class TesanaClient {
613
1111
  ws: null,
614
1112
  handlers: [],
615
1113
  roomId: null,
1114
+ // The current room's share code, or null for a public room.
1115
+ code: null,
616
1116
  // Reconnect state. `wsUrl` is kept so a dropped socket can re-enter the
617
1117
  // same room; `leaving` stops a deliberate leave from being retried.
618
1118
  wsUrl: null,
619
1119
  leaving: false,
620
1120
  reconnectTimer: null,
621
1121
  reconnectAttempts: 0,
1122
+ // The code of the last close we saw. 4401 means the grant was refused —
1123
+ // expired, most likely — and a fresh one has to be minted before the next
1124
+ // reconnect can succeed. Cleared once a reconnect has used it.
1125
+ lastCloseCode: null,
622
1126
  reconnectExhausted: false,
623
1127
  statusHandlers: [],
624
1128
  // Overridable so a test (or a game with unusual tolerance) can shorten
@@ -825,6 +1329,22 @@ class TesanaClient {
825
1329
  // same object in place, rather than the game holding a stale policy.
826
1330
  adClient = this.ads;
827
1331
 
1332
+ // Localization. A generated game draws its text onto a canvas, so the
1333
+ // platform cannot translate the running game the way it translates the
1334
+ // site's own pages — the game has to ask, and this is the surface it asks
1335
+ // through. The same one rule as the shop: an unreachable service costs a
1336
+ // translation and never the game. Every method here has a source-language
1337
+ // answer, and `t()` is synchronous, so a menu never waits on a network to
1338
+ // draw itself in the player's language.
1339
+ this.l10n = this._makeL10n(opts);
1340
+ l10nClient = this.l10n;
1341
+
1342
+ // Gameplay analytics. The same functions as `Tesana.track` and
1343
+ // `Tesana.gameplay` on the global, so a game can call them before its
1344
+ // `await __TESANA_READY__` resolves; none of them depends on this client.
1345
+ this.track = track;
1346
+ this.gameplay = gameplay;
1347
+
828
1348
  this.multiplayer = {
829
1349
  // Read this before drawing a lobby: when it is false the game is not
830
1350
  // allowed rooms yet and the calls below refuse.
@@ -841,14 +1361,42 @@ class TesanaClient {
841
1361
  .then((r) => r.rooms)
842
1362
  .catch(() => [])
843
1363
  : Promise.resolve([]),
1364
+ // Open a room. It is public and always joinable unless you pass a `code`,
1365
+ // which is the only way entry is restricted: the room is then unlisted and
1366
+ // only someone with the code can reach it. The resolved code is on
1367
+ // `room.code` in the result (the service generates one if you pass
1368
+ // `code: true`), so show it to the room.
844
1369
  create: (opts) =>
845
1370
  this._mpEnabled
846
1371
  ? this._mpEnter(this._mpRequest("POST", "/v1/mp/rooms", opts || {}))
847
1372
  : this._mpRefuse(),
848
- join: (roomId) =>
849
- this._mpEnabled
850
- ? this._mpEnter(this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`))
851
- : this._mpRefuse(),
1373
+ // Accept the room a game got from list() as well as from a session. Both
1374
+ // read as "the room to join": `list()` rows are keyed `id`, a
1375
+ // create/quickJoin/join result carries `roomId`. Taking an object here is
1376
+ // what stops a lobby that calls `join(room)` from having to know which.
1377
+ join: (room) => {
1378
+ if (!this._mpEnabled) return this._mpRefuse();
1379
+ const roomId =
1380
+ room && typeof room === "object" ? room.id || room.roomId : room;
1381
+ // The bug this guards: a game read `room.roomId` off a list() row,
1382
+ // where it is undefined, and we asked the service for the room named
1383
+ // "undefined" — a 404 indistinguishable from a deleted room. Fail
1384
+ // here, by name, so the mistake is legible.
1385
+ if (roomId == null || roomId === "") {
1386
+ const err = new Error(
1387
+ "join() needs a room id — pass a room from list() (its `id`) or a create/join result",
1388
+ );
1389
+ err.code = "mp_room_id_required";
1390
+ return Promise.reject(err);
1391
+ }
1392
+ return this._mpEnter(
1393
+ this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`),
1394
+ );
1395
+ },
1396
+ // Join the fullest public room with a free seat, creating one if there is
1397
+ // none. Pass `code` to enter a private room instead: the first player to
1398
+ // use a code opens that room and the rest join it, and a full one refuses
1399
+ // rather than opening a second room under the same code.
852
1400
  quickJoin: (opts) =>
853
1401
  this._mpEnabled
854
1402
  ? this._mpEnter(this._mpRequest("POST", "/v1/mp/quick-join", opts || {}))
@@ -1025,17 +1573,83 @@ class TesanaClient {
1025
1573
  * @param {Promise<{ wsUrl: string, roomId?: string, room?: object, playerId?: string }>} session
1026
1574
  */
1027
1575
  async _mpEnter(session) {
1028
- const joined = await session;
1029
- await this._mpOpen(joined.wsUrl);
1576
+ const joined = await this._mpAwaitPlacement(await session);
1577
+ // A room that was opened and then could not be entered is reported as what
1578
+ // it is: the room exists. The SDK cannot seat the player — that is the
1579
+ // host's job — but it can name the room so a game retries `join(roomId)`
1580
+ // instead of opening a second one and stranding the first.
1581
+ try {
1582
+ await this._mpOpen(joined.wsUrl);
1583
+ } catch (err) {
1584
+ const roomId = joined.roomId || joined.room?.id || null;
1585
+ const wrapped = new Error(
1586
+ roomId ? `${err?.message || "multiplayer unavailable"} (room ${roomId})` : err?.message || "multiplayer unavailable",
1587
+ );
1588
+ wrapped.code = err?.code || "mp_enter_failed";
1589
+ wrapped.roomId = roomId;
1590
+ throw wrapped;
1591
+ }
1030
1592
  this._mp.roomId = joined.roomId || joined.room?.id || null;
1593
+ this._mp.code = joined.room?.code || null;
1031
1594
  return {
1032
1595
  wsUrl: joined.wsUrl,
1033
1596
  roomId: this._mp.roomId,
1597
+ code: this._mp.code,
1034
1598
  playerId: joined.playerId || this._player?.id,
1035
1599
  room: joined.room,
1036
1600
  };
1037
1601
  }
1038
1602
 
1603
+ /**
1604
+ * Wait out a room that is still being placed, then hand back its session.
1605
+ *
1606
+ * Room creation on GameLift outlives a single HTTP request — a cold fleet can
1607
+ * take minutes — so the service answers 202 with the room's identity, the
1608
+ * caller's seat, and `retryAfterMs`, and no `wsUrl`. Treating that as a failed
1609
+ * create is what used to leave a ghost: the room existed, its creator was
1610
+ * seated, and the client believed nothing had happened. So the client polls
1611
+ * the same room it was handed (`join` re-issues the seat, it does not take a
1612
+ * second) until the address exists or the wait budget runs out.
1613
+ *
1614
+ * The budget is the client's own. A game that would rather show a spinner and
1615
+ * decide for itself calls `join(roomId)` after `create` rejects with
1616
+ * `mp_room_placing`, and this consumes the same code path.
1617
+ *
1618
+ * @param {{ wsUrl?: string, roomId?: string, state?: string, retryAfterMs?: number, room?: object }} session
1619
+ */
1620
+ async _mpAwaitPlacement(session) {
1621
+ if (!session || session.wsUrl || session.state !== "placing") return session;
1622
+ const roomId = session.roomId || session.room?.id;
1623
+ if (!roomId) return session;
1624
+ this._mpEmitStatus({ status: "placing", roomId });
1625
+ // Instance-overridable so a game (or a test) can decide how long it will
1626
+ // wait for placement without reaching into module scope.
1627
+ const budget = Number(this._mpPlacingTimeoutMs) || MP_PLACING_TIMEOUT_MS;
1628
+ const deadline = Date.now() + budget;
1629
+ let current = session;
1630
+ while (!current?.wsUrl && Date.now() < deadline) {
1631
+ const gap = Math.max(250, Number(current.retryAfterMs) || MP_PLACING_RETRY_MS);
1632
+ await new Promise((resolve) => setTimeout(resolve, Math.min(gap, Math.max(0, deadline - Date.now()))));
1633
+ if (Date.now() >= deadline) break;
1634
+ try {
1635
+ current = await this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`, {});
1636
+ } catch (err) {
1637
+ // A 404 here is a room that ended between polls, which is a real
1638
+ // failure; anything else is worth another try until the budget is gone.
1639
+ if (err?.status === 404) throw err;
1640
+ }
1641
+ }
1642
+ if (!current?.wsUrl) {
1643
+ // The room is still real, so the code names it and says so — a game can
1644
+ // choose to keep waiting with `join(roomId)` rather than start over.
1645
+ const err = new Error("Room is still starting");
1646
+ err.code = "mp_room_placing";
1647
+ err.roomId = roomId;
1648
+ throw err;
1649
+ }
1650
+ return current;
1651
+ }
1652
+
1039
1653
  /**
1040
1654
  * @param {string} wsUrl
1041
1655
  */
@@ -1094,13 +1708,22 @@ class TesanaClient {
1094
1708
  if (this._mp.ws === ws) this._mp.ws = null;
1095
1709
  if (!opened) {
1096
1710
  clearTimeout(timer);
1097
- reject(new Error(event.reason || "multiplayer closed"));
1711
+ const err = new Error(event.reason || "multiplayer closed");
1712
+ // The code is carried, not just the reason: 4401 is an expired or
1713
+ // rejected grant, which a re-mint can fix, while 4403 is the game
1714
+ // being denied rooms, which it cannot. Recovery keys off this.
1715
+ err.code = event.code || 1006;
1716
+ // Recorded for the same reason: a reconnect whose fresh grant is
1717
+ // *also* refused must mint again rather than retry a dead URL.
1718
+ if (this._mp.wsUrl) this._mp.lastCloseCode = event.code || null;
1719
+ reject(err);
1098
1720
  return;
1099
1721
  }
1100
1722
  // The socket dropped after we were in the room. That is a scale-in,
1101
1723
  // a deploy, or a network blip — none of which the player caused, and
1102
1724
  // all of which used to leave them silently alone in a match. Retry
1103
1725
  // unless they actually meant to leave.
1726
+ this._mp.lastCloseCode = event.code || null;
1104
1727
  this._mpScheduleReconnect();
1105
1728
  };
1106
1729
  });
@@ -1132,7 +1755,7 @@ class TesanaClient {
1132
1755
  mp.reconnectTimer = setTimeout(() => {
1133
1756
  mp.reconnectTimer = null;
1134
1757
  if (mp.leaving) return;
1135
- this._mpOpen(mp.wsUrl).catch(() => {
1758
+ this._mpReconnectAttempt().catch(() => {
1136
1759
  // Still not up — schedule the next attempt, which is where the
1137
1760
  // attempt count grows and the backoff widens.
1138
1761
  this._mpScheduleReconnect();
@@ -1140,6 +1763,56 @@ class TesanaClient {
1140
1763
  }, delay);
1141
1764
  }
1142
1765
 
1766
+ /**
1767
+ * One reconnect: get a current grant if the last one was refused, then try the
1768
+ * room again.
1769
+ *
1770
+ * The grant the client holds is embedded in `wsUrl` and was minted when it
1771
+ * first joined. A game open longer than the token's life therefore cannot
1772
+ * re-enter on a reconnect, and the backoff above only retries the same dead
1773
+ * URL — the player sits in "reconnecting" until they reload. Re-requesting the
1774
+ * room session mints a fresh URL, and `mpJoin` is idempotent, so asking as an
1775
+ * already-seated player re-issues the same seat rather than a second one.
1776
+ *
1777
+ * The fresh grant itself comes from the ordinary 401 path in `_send`: the join
1778
+ * goes out with the token the client already has, comes back refused, and is
1779
+ * retried once with one minted token. That is deliberate — it keeps the mint in
1780
+ * the one place that knows how to do it, so a stale socket and a stale HTTP
1781
+ * call recover identically and only ever ask the host once between them.
1782
+ */
1783
+ async _mpReconnectAttempt() {
1784
+ const mp = this._mp;
1785
+ let wsUrl = mp.wsUrl;
1786
+ // 4401 — the grant was refused, so the URL itself is dead and a fresh one is
1787
+ // required. 4409 — the room is being re-placed and has no address yet, so
1788
+ // the URL the client holds is not usable either. Both are fixed by asking
1789
+ // for the room again; 4403 (the game is denied rooms) and 4404 (the room is
1790
+ // gone) are not, and fall through to the URL we have so the attempt is still
1791
+ // counted and the backoff still applies.
1792
+ if ((mp.lastCloseCode === 4401 || mp.lastCloseCode === 4409) && mp.roomId) {
1793
+ try {
1794
+ // `_mpAwaitPlacement` is harmless when the room is already up (it
1795
+ // returns the session untouched) and necessary when a reconnect lands
1796
+ // during a re-placement — a 4409 close, or a room swept and reopened,
1797
+ // answers with no `wsUrl`, and retrying the old URL would never work.
1798
+ const session = await this._mpAwaitPlacement(
1799
+ await this._mpRequest("POST", `/v1/mp/rooms/${enc(mp.roomId)}/join`),
1800
+ );
1801
+ if (session && session.wsUrl) {
1802
+ wsUrl = session.wsUrl;
1803
+ mp.wsUrl = wsUrl;
1804
+ mp.code = session.room?.code ?? mp.code;
1805
+ }
1806
+ } catch {
1807
+ // The room is gone, or the fresh grant was refused too. Fall through to
1808
+ // the URL we have: the room may have been replaced under the same id,
1809
+ // and if it has not, the next attempt retries this same path.
1810
+ }
1811
+ }
1812
+ mp.lastCloseCode = null;
1813
+ return this._mpOpen(wsUrl);
1814
+ }
1815
+
1143
1816
  _mpEmitStatus(status) {
1144
1817
  for (const fn of this._mp.statusHandlers) {
1145
1818
  try {
@@ -1173,7 +1846,14 @@ class TesanaClient {
1173
1846
  */
1174
1847
  _mpSend(data) {
1175
1848
  const ws = this._mp.ws;
1176
- if (!ws || ws.readyState !== 1) throw new Error("Not in a room");
1849
+ if (!ws || ws.readyState !== 1) {
1850
+ // Not a room failure — a socket that is between attempts. Tagged so a
1851
+ // game can tell it from a real refusal, and so a caller that has an
1852
+ // outbox can wait for the reconnect rather than drop the message.
1853
+ const err = new Error("Not in a room");
1854
+ err.code = "mp_not_connected";
1855
+ throw err;
1856
+ }
1177
1857
  ws.send(JSON.stringify(data && typeof data === "object" ? data : { value: data }));
1178
1858
  }
1179
1859
 
@@ -1207,9 +1887,11 @@ class TesanaClient {
1207
1887
  this._mp.leaving = true;
1208
1888
  this._mpClose();
1209
1889
  this._mp.roomId = null;
1890
+ this._mp.code = null;
1210
1891
  this._mp.wsUrl = null;
1211
1892
  this._mp.reconnectAttempts = 0;
1212
1893
  this._mp.reconnectExhausted = false;
1894
+ this._mp.lastCloseCode = null;
1213
1895
  try {
1214
1896
  if (!roomId) return { ok: true, room: null };
1215
1897
  try {
@@ -1231,24 +1913,13 @@ class TesanaClient {
1231
1913
  return this._send(this._baseFor(), this._authFor(), method, path, body);
1232
1914
  }
1233
1915
 
1234
- /** Whether multiplayer rides a rooms-only token while everything else is offline. */
1235
- _roomsOnly() {
1236
- return Boolean(this.offline && this.roomEndpoint && this.roomToken);
1237
- }
1238
-
1239
- _mpRequest(method, path, body) {
1240
- return this._roomsOnly()
1241
- ? this._send(this.roomEndpoint, this.roomToken, method, path, body)
1242
- : this.request(method, path, body);
1243
- }
1244
-
1245
- async _send(base, authToken, method, path, body) {
1916
+ /** One transport attempt, with no retry and no body parsing. */
1917
+ async _fetchSend(base, authToken, method, path, body) {
1246
1918
  const headers = { "content-type": "application/json" };
1247
1919
  if (authToken) headers.authorization = `Bearer ${authToken}`;
1248
1920
  if (this.deviceId) headers["x-tesana-device"] = this.deviceId;
1249
- let res;
1250
1921
  try {
1251
- res = await fetch(`${base}${path}`, {
1922
+ return await fetch(`${base}${path}`, {
1252
1923
  method,
1253
1924
  headers,
1254
1925
  body: body == null || method === "GET" ? undefined : JSON.stringify(body),
@@ -1261,6 +1932,34 @@ class TesanaClient {
1261
1932
  // still has, reported as missing.
1262
1933
  throw err;
1263
1934
  }
1935
+ }
1936
+
1937
+ /** Whether multiplayer rides a rooms-only token while everything else is offline. */
1938
+ _roomsOnly() {
1939
+ return Boolean(this.offline && this.roomEndpoint && this.roomToken);
1940
+ }
1941
+
1942
+ _mpRequest(method, path, body) {
1943
+ return this._roomsOnly()
1944
+ ? this._send(this.roomEndpoint, this.roomToken, method, path, body)
1945
+ : this.request(method, path, body);
1946
+ }
1947
+
1948
+ async _send(base, authToken, method, path, body) {
1949
+ let res = await this._fetchSend(base, authToken, method, path, body);
1950
+ // A refused credential is usually age, not refusal: the player token lives
1951
+ // two hours. Ask the host to re-mint and retry once with the new one. The
1952
+ // retry is guarded on the token actually changing, so a genuinely
1953
+ // unauthorized player fails exactly as they did before rather than looping.
1954
+ if (res.status === 401) {
1955
+ // The ask may land on a host we cannot reach, so `asked` is null and the
1956
+ // retry is skipped — the 401 below is thrown exactly as it always was.
1957
+ const asked = await requestHostBootstrap();
1958
+ const next = base === this.roomEndpoint ? this.roomToken : this._authFor();
1959
+ if (asked && next && next !== authToken) {
1960
+ res = await this._fetchSend(base, next, method, path, body);
1961
+ }
1962
+ }
1264
1963
  const data = await res.json().catch(() => ({}));
1265
1964
  if (!res.ok) {
1266
1965
  const error = new Error(data.message || res.statusText);
@@ -1305,6 +2004,13 @@ class TesanaClient {
1305
2004
  minIntervalMs: config.adMinIntervalMs,
1306
2005
  });
1307
2006
  }
2007
+ // A later bootstrap may carry the player's language — a provisionally
2008
+ // "offline" answer has none, and the real one arrives a moment later. The
2009
+ // capability is re-pointed in place, exactly as the ad policy is.
2010
+ if (config.locale && this.l10n) {
2011
+ const next = normalizeLocale(config.locale);
2012
+ if (next && next !== this.l10n.locale()) this.l10n.applyLocale(next);
2013
+ }
1308
2014
  this._mpEnabled = config.multiplayer !== false;
1309
2015
  this.multiplayer.enabled = this._mpEnabled;
1310
2016
  return this;
@@ -1538,6 +2244,300 @@ class TesanaClient {
1538
2244
  };
1539
2245
  }
1540
2246
 
2247
+ // -------------------------------------------------------------------- l10n
2248
+ //
2249
+ // Localization, from the game's side. The service owns the dictionary and the
2250
+ // translation; this owns one promise: a game that asks for its text in the
2251
+ // player's language gets something renderable, always.
2252
+ //
2253
+ // Deliberately synchronous where the game needs it to be. `t()` reads a map
2254
+ // that was filled before the first frame, so drawing a localized menu costs no
2255
+ // await and no round trip; only text the game discovers at runtime — a
2256
+ // procedurally generated item name, something the player typed — goes through
2257
+ // the async path. A game that never awaits anything still localizes.
2258
+ _makeL10n(opts) {
2259
+ const state = {
2260
+ locale: normalizeLocale(opts.locale || ""),
2261
+ // The language the game's own strings are written in. Declared by the
2262
+ // build; the service is told the same value, so the two agree rather
2263
+ // than one guessing what the other meant.
2264
+ source: "en",
2265
+ // The platform's list, refined by the service's answer when it arrives.
2266
+ languages: L10N_TARGETS.slice(),
2267
+ // Source text -> translated text, filled before `ready` resolves.
2268
+ bundle: {},
2269
+ // The game's own key -> source text, for `t("ui.play")`.
2270
+ index: {},
2271
+ handlers: [],
2272
+ // `requested`: what the game's source language resolved to (en, de, …)
2273
+ // vs `target`: what is actually being served — the difference is a
2274
+ // language the game did not declare, where the source is the answer.
2275
+ target: "",
2276
+ loaded: false,
2277
+ // The bundle is asked for from three places on a normal boot — `ready`,
2278
+ // `init`'s await, and the post-session reload — and all three want the
2279
+ // same one. `inflight` is the shared request; `loadedFor` is the target
2280
+ // that has already been answered, so a repeat is a no-op rather than a
2281
+ // second round trip for an object we already hold.
2282
+ inflight: null,
2283
+ inflightTarget: "",
2284
+ loadedFor: null,
2285
+ };
2286
+
2287
+ const self = this;
2288
+
2289
+ /** Emit a locale change to every listener, without letting one break the rest. */
2290
+ function emit() {
2291
+ const event = { locale: state.locale, target: state.target, languages: state.languages.slice() };
2292
+ for (const fn of [...state.handlers]) {
2293
+ try {
2294
+ fn(event);
2295
+ } catch {
2296
+ /* a game handler */
2297
+ }
2298
+ }
2299
+ }
2300
+
2301
+ /**
2302
+ * Resolve `key` against the bundle.
2303
+ *
2304
+ * Three shapes, because a game reaches for all three: a key it declared
2305
+ * (`"ui.play"`), the source sentence itself (`"Play"`), and a key with a
2306
+ * fallback for the source text that was never declared. Whatever is not
2307
+ * found comes back as the fallback or the key, which is what makes an
2308
+ * unreachable service a non-event.
2309
+ */
2310
+ function lookup(key, fallback) {
2311
+ const name = String(key == null ? "" : key);
2312
+ const source = state.index[name] || name;
2313
+ const hit = state.bundle[source];
2314
+ if (typeof hit === "string" && hit) return hit;
2315
+ if (typeof fallback === "string" && fallback) return fallback;
2316
+ return source;
2317
+ }
2318
+
2319
+ /**
2320
+ * Load the bundle, at most once per (language, reachability) combination.
2321
+ *
2322
+ * A boot calls this from several independent places — the `ready` promise,
2323
+ * `init`'s await, and the post-session `reload` — and they all want the
2324
+ * same bundle. Coalescing them is not an optimization for its own sake:
2325
+ * every extra request is the player's bundle fetched twice, and a game
2326
+ * that redraws on `onChange` should not be able to multiply it.
2327
+ */
2328
+ function load() {
2329
+ const target = self._canReach() && state.locale && state.locale !== state.source ? state.locale : "";
2330
+ if (state.inflight && state.inflightTarget === target) return state.inflight;
2331
+ if (state.loadedFor === target && state.loaded) return Promise.resolve(state);
2332
+ state.inflightTarget = target;
2333
+ state.inflight = fetchBundle(target).finally(() => {
2334
+ state.inflight = null;
2335
+ });
2336
+ return state.inflight;
2337
+ }
2338
+
2339
+ async function fetchBundle(target) {
2340
+ if (!self._canReach()) {
2341
+ // No address, or no game id: nothing will ever answer, and asking
2342
+ // anyway would throw a relative-URL fetch. The source language is the
2343
+ // honest answer and the game renders exactly as it always did.
2344
+ state.loaded = true;
2345
+ state.loadedFor = target;
2346
+ return state;
2347
+ }
2348
+ try {
2349
+ if (!target) {
2350
+ // Nothing to fetch — and no request at all, either. A source-language
2351
+ // boot needs no bundle (nothing is translated) and no language list
2352
+ // (the platform's known set is already in memory), so a game with no
2353
+ // localization in force makes zero localization requests. That
2354
+ // matters beyond tidiness: it is the same rule as the rest of the
2355
+ // SDK, that a capability nobody asked for must not put bytes on the
2356
+ // wire, and it is what a game running entirely offline relies on.
2357
+ state.target = "";
2358
+ state.loaded = true;
2359
+ state.loadedFor = target;
2360
+ return state;
2361
+ }
2362
+ const data = await self.request(
2363
+ "GET",
2364
+ `/v1/l10n/bundle?target=${enc(target)}`,
2365
+ );
2366
+ if (data && typeof data.translations === "object" && data.translations) {
2367
+ state.bundle = data.translations;
2368
+ }
2369
+ if (data && typeof data.index === "object" && data.index) {
2370
+ state.index = data.index;
2371
+ }
2372
+ if (typeof data?.source === "string" && data.source) state.source = data.source;
2373
+ // `target` is the service's answer about what it actually served.
2374
+ // It is `""` for a language this game has not declared, which is the
2375
+ // signal that the source text IS the answer.
2376
+ state.target = typeof data?.target === "string" && data.target ? data.target : "";
2377
+ // The declared language set arrives with the bundle's own response
2378
+ // rather than a second route. It is one fact about one game, and two
2379
+ // requests to learn it is one more chance for a boot to be slower than
2380
+ // the first frame.
2381
+ if (Array.isArray(data?.languages) && data.languages.length) {
2382
+ // The game's own declared set, in the order it chose — which is how
2383
+ // a game that lists French first gets French first in its picker.
2384
+ state.languages = data.languages.slice();
2385
+ }
2386
+ } catch (err) {
2387
+ // An outage costs the translation, not the game. One deduped line is
2388
+ // enough to make it findable without spamming the console on retry.
2389
+ warnOnce(
2390
+ "l10n-unreachable",
2391
+ `Tesana localization: could not reach the translation service (${(err && err.message) || "request failed"}).`
2392
+ + " The game keeps playing in its source language.",
2393
+ );
2394
+ }
2395
+ state.loaded = true;
2396
+ state.loadedFor = target;
2397
+ return state;
2398
+ }
2399
+
2400
+ return {
2401
+ /**
2402
+ * The player's language, synchronously, as the host resolved it.
2403
+ *
2404
+ * Follows the same tag vocabulary the site uses (`pt-BR`, `zh`), not
2405
+ * AWS's, so a game can pass it straight to `Intl`/`toLocaleString`.
2406
+ */
2407
+ locale: () => state.locale,
2408
+ /** The languages this game offers, the host's order preserved. */
2409
+ languages: () => state.languages.slice(),
2410
+ /** The language text is actually being served in, or `""` when it is the source. */
2411
+ target: () => state.target,
2412
+ /** The language the game's own strings are written in. */
2413
+ source: () => state.source,
2414
+ /** Whether the initial bundle has landed. `t()` works before it does. */
2415
+ get loaded() {
2416
+ return state.loaded;
2417
+ },
2418
+
2419
+ /**
2420
+ * The translated text for `key`, synchronously.
2421
+ *
2422
+ * Prefer this. It is filled before the first frame, so a game never has
2423
+ * to await anything to draw a localized menu — and when the bundle is
2424
+ * empty (a service outage, a language the game never declared) it returns
2425
+ * the source text, which is a rendered game rather than a blank one.
2426
+ *
2427
+ * @param {string} key a declared key, or the source sentence itself
2428
+ * @param {object|string} [vars] `{name}` values, or a fallback string
2429
+ */
2430
+ t: (key, vars) => {
2431
+ // The second argument is both of the things a caller wants to pass:
2432
+ // placeholder values, and a fallback for an undeclared key. A string is
2433
+ // unambiguously a fallback; an object is unambiguously values.
2434
+ const values = vars && typeof vars === "object" ? vars : null;
2435
+ const fallback = typeof vars === "string" ? vars : "";
2436
+ return fillPlaceholders(lookup(key, fallback), values);
2437
+ },
2438
+
2439
+ /**
2440
+ * Translate text the game discovered while running.
2441
+ *
2442
+ * The one path that costs a round trip, so it is the one to keep off the
2443
+ * hot path: ask once, at the moment the text is created (a generated
2444
+ * name, a line of dialogue just chosen), never per frame. Resolves the
2445
+ * source text on any failure, so a `.then` never sees a rejection.
2446
+ *
2447
+ * @param {string} text
2448
+ * @param {{ id?: string, values?: Record<string, unknown>, target?: string }} [opts]
2449
+ */
2450
+ translate: async (text, opts = {}) => {
2451
+ const values = opts.values && typeof opts.values === "object" ? opts.values : null;
2452
+ const target = opts.target || state.target || (state.locale !== state.source ? state.locale : "");
2453
+ // A named string is routed through the id-keyed path, which is what
2454
+ // lets the service remember it under the game's own name and serve it
2455
+ // from cache next time without even a hash lookup.
2456
+ if (opts.id && self._canReach() && target) {
2457
+ try {
2458
+ const data = await self.request("POST", "/v1/l10n/string", {
2459
+ id: String(opts.id),
2460
+ text: String(text == null ? "" : text),
2461
+ values: values || undefined,
2462
+ target,
2463
+ source: state.source,
2464
+ });
2465
+ if (data && typeof data.value === "string" && data.value) return data.value;
2466
+ } catch {
2467
+ /* falls through to the source text below */
2468
+ }
2469
+ }
2470
+ // The anonymous path requires a target to be worth a call. With no
2471
+ // target this *is* the source language, and asking the server to hand
2472
+ // back what it was given is the most expensive no-op available.
2473
+ if (self._canReach() && target) {
2474
+ try {
2475
+ const data = await self.request("POST", "/v1/l10n/translate", {
2476
+ strings: [String(text == null ? "" : text)],
2477
+ target,
2478
+ source: state.source,
2479
+ });
2480
+ const hit = data?.translations?.[String(text)];
2481
+ if (typeof hit === "string" && hit) return fillPlaceholders(hit, values);
2482
+ } catch {
2483
+ /* ditto */
2484
+ }
2485
+ }
2486
+ return fillPlaceholders(String(text == null ? "" : text), values);
2487
+ },
2488
+
2489
+ /**
2490
+ * Subscribe to a language change. Returns an unsubscribe function.
2491
+ *
2492
+ * A game should redraw its text (or call `t()` again) on this rather than
2493
+ * caching translated strings at startup, because the player can change
2494
+ * the site's language without reloading the frame.
2495
+ *
2496
+ * @param {(event: { locale: string, target: string, languages: string[] }) => void} fn
2497
+ */
2498
+ onChange: (fn) => {
2499
+ if (typeof fn !== "function") return () => {};
2500
+ state.handlers.push(fn);
2501
+ return () => {
2502
+ state.handlers = state.handlers.filter((handler) => handler !== fn);
2503
+ };
2504
+ },
2505
+
2506
+ /** Resolves after the initial bundle. A game may await it with `__TESANA_READY__`. */
2507
+ ready: load(),
2508
+
2509
+ /**
2510
+ * Reload the bundle, after an identity or language change.
2511
+ *
2512
+ * The constructor loads immediately from whatever the page already
2513
+ * carries. A game that minted its own token — or a host whose real
2514
+ * bootstrap replaced a provisional "offline" one — has no credential that
2515
+ * first time, so the bundle would be empty and the game would stay in its
2516
+ * source language for the whole session. `init` awaits this after the
2517
+ * identity step, which is what makes the documented
2518
+ * `await window.__TESANA_READY__` sufficient for a localized first frame.
2519
+ */
2520
+ reload: () => load(),
2521
+
2522
+ // ---- internal wiring (used by the bootstrap listener) ----
2523
+ /** A new language from the host. Resolves the same promise the game already holds. */
2524
+ applyLocale(next) {
2525
+ const locale = normalizeLocale(next);
2526
+ if (!locale || locale === state.locale) return state;
2527
+ state.locale = locale;
2528
+ // The old bundle is the *previous* language's, so it is cleared rather
2529
+ // than left to serve: showing a menu in a language the player just
2530
+ // switched away from is worse than showing the source text for the
2531
+ // moment the refill takes. `t()` falls back to source in between.
2532
+ state.bundle = {};
2533
+ state.target = "";
2534
+ emit();
2535
+ load().catch(() => {});
2536
+ return state;
2537
+ },
2538
+ };
2539
+ }
2540
+
1541
2541
  // ------------------------------------------------------------------ saves
1542
2542
  //
1543
2543
  // Writes go to the local cache first, always, so a failed upload is a save
@@ -1678,5 +2678,5 @@ function enc(value) {
1678
2678
  return encodeURIComponent(String(value));
1679
2679
  }
1680
2680
 
1681
- export const Tesana = { init, TesanaClient, version: VERSION };
2681
+ export const Tesana = { init, TesanaClient, version: VERSION, track, gameplay };
1682
2682
  export default Tesana;