@playcademy/sdk 0.9.1-beta.1 → 0.9.1-beta.3

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/dist/index.js CHANGED
@@ -19,13 +19,11 @@ var MessageEvents;
19
19
  MessageEvents2["RESUME"] = "PLAYCADEMY_RESUME";
20
20
  MessageEvents2["FORCE_EXIT"] = "PLAYCADEMY_FORCE_EXIT";
21
21
  MessageEvents2["OVERLAY"] = "PLAYCADEMY_OVERLAY";
22
- MessageEvents2["CONNECTION_STATE"] = "PLAYCADEMY_CONNECTION_STATE";
23
22
  MessageEvents2["READY"] = "PLAYCADEMY_READY";
24
23
  MessageEvents2["INIT_ERROR"] = "PLAYCADEMY_INIT_ERROR";
25
24
  MessageEvents2["EXIT"] = "PLAYCADEMY_EXIT";
26
25
  MessageEvents2["TELEMETRY"] = "PLAYCADEMY_TELEMETRY";
27
26
  MessageEvents2["KEY_EVENT"] = "PLAYCADEMY_KEY_EVENT";
28
- MessageEvents2["DISPLAY_ALERT"] = "PLAYCADEMY_DISPLAY_ALERT";
29
27
  MessageEvents2["DEMO_END"] = "PLAYCADEMY_DEMO_END";
30
28
  MessageEvents2["AUTH_STATE_CHANGE"] = "PLAYCADEMY_AUTH_STATE_CHANGE";
31
29
  MessageEvents2["AUTH_CALLBACK"] = "PLAYCADEMY_AUTH_CALLBACK";
@@ -87,7 +85,6 @@ class PlaycademyMessaging {
87
85
  "PLAYCADEMY_EXIT" /* EXIT */,
88
86
  "PLAYCADEMY_TELEMETRY" /* TELEMETRY */,
89
87
  "PLAYCADEMY_KEY_EVENT" /* KEY_EVENT */,
90
- "PLAYCADEMY_DISPLAY_ALERT" /* DISPLAY_ALERT */,
91
88
  "PLAYCADEMY_DEMO_END" /* DEMO_END */
92
89
  ];
93
90
  const shouldUsePostMessage = isIframe && iframeToParentEvents.includes(eventType);
@@ -194,7 +191,6 @@ function createStandaloneConfig() {
194
191
  gameUrl: globalThis.location.origin,
195
192
  token: "mock-game-token-for-local-dev",
196
193
  gameId: "mock-game-id-from-template",
197
- realtimeUrl: undefined,
198
194
  mode: "standalone"
199
195
  };
200
196
  globalThis.PLAYCADEMY = mockConfig;
@@ -213,10 +209,7 @@ async function init(options) {
213
209
  gameUrl: config.gameUrl,
214
210
  token: config.token,
215
211
  gameId: config.gameId,
216
- mode: config.mode,
217
- autoStartSession: globalThis.self !== window.top,
218
- onDisconnect: options?.onDisconnect,
219
- enableConnectionMonitoring: options?.enableConnectionMonitoring
212
+ mode: config.mode
220
213
  });
221
214
  client["initPayload"] = config;
222
215
  messaging.listen("PLAYCADEMY_TOKEN_REFRESH" /* TOKEN_REFRESH */, ({ token }) => client.setToken(token));
@@ -637,6 +630,80 @@ function getOAuthConfig(provider) {
637
630
  var identity = {
638
631
  parseOAuthState
639
632
  };
633
+ // src/namespaces/game/backend.ts
634
+ function normalizePath(path) {
635
+ return path.startsWith("/") ? path : `/${path}`;
636
+ }
637
+ function createBackendNamespace(client) {
638
+ return {
639
+ async get(path, headers) {
640
+ return client["requestGameBackend"](normalizePath(path), "GET", undefined, headers);
641
+ },
642
+ async post(path, body, headers) {
643
+ return client["requestGameBackend"](normalizePath(path), "POST", body, headers);
644
+ },
645
+ async put(path, body, headers) {
646
+ return client["requestGameBackend"](normalizePath(path), "PUT", body, headers);
647
+ },
648
+ async patch(path, body, headers) {
649
+ return client["requestGameBackend"](normalizePath(path), "PATCH", body, headers);
650
+ },
651
+ async delete(path, headers) {
652
+ return client["requestGameBackend"](normalizePath(path), "DELETE", undefined, headers);
653
+ },
654
+ async request(path, method, body, headers) {
655
+ return client["requestGameBackend"](normalizePath(path), method, body, headers);
656
+ },
657
+ async download(path, method = "GET", body, headers) {
658
+ return client["requestGameBackend"](normalizePath(path), method, body, headers, { raw: true });
659
+ },
660
+ url(pathOrStrings, ...values) {
661
+ if (Array.isArray(pathOrStrings) && "raw" in pathOrStrings) {
662
+ const strings = pathOrStrings;
663
+ const path2 = strings.reduce((acc, str, i) => acc + str + (values[i] != null ? String(values[i]) : ""), "");
664
+ return `${client.gameUrl}/api${path2.startsWith("/") ? path2 : `/${path2}`}`;
665
+ }
666
+ const path = pathOrStrings;
667
+ return `${client.gameUrl}/api${path.startsWith("/") ? path : `/${path}`}`;
668
+ }
669
+ };
670
+ }
671
+ // src/core/assert.ts
672
+ function assertPlatformMode(client, operation) {
673
+ if (client.mode !== "platform") {
674
+ throw new PlaycademyError(`${operation} requires platform mode (current: ${client.mode}). Check client.mode before calling.`);
675
+ }
676
+ }
677
+ function assertDemoMode(client, operation) {
678
+ if (client.mode !== "demo") {
679
+ throw new PlaycademyError(`${operation} requires demo mode (current: ${client.mode}). Check client.mode before calling.`);
680
+ }
681
+ }
682
+
683
+ // src/namespaces/game/demo.ts
684
+ function createDemoNamespace(client) {
685
+ return {
686
+ profile: {
687
+ get: async () => {
688
+ assertDemoMode(client, "demo.profile.get()");
689
+ return client["request"]("/users/demo-profile", "GET");
690
+ },
691
+ update: async (updates) => {
692
+ assertDemoMode(client, "demo.profile.update()");
693
+ return client["request"]("/users/demo-profile", "PATCH", {
694
+ body: updates
695
+ });
696
+ }
697
+ },
698
+ end: (score, options) => {
699
+ assertDemoMode(client, "demo.end()");
700
+ messaging.send("PLAYCADEMY_DEMO_END" /* DEMO_END */, {
701
+ score,
702
+ ...options
703
+ });
704
+ }
705
+ };
706
+ }
640
707
  // src/core/auth/utils.ts
641
708
  function openPopupWindow(url, name = "auth-popup", width = 500, height = 600) {
642
709
  const left = window.screenX + (window.outerWidth - width) / 2;
@@ -941,17 +1008,7 @@ function createRuntimeNamespace(client) {
941
1008
  }
942
1009
  return res;
943
1010
  },
944
- exit: async () => {
945
- if (client["internalClientSessionId"] && client["gameId"]) {
946
- try {
947
- await client["_sessionManager"].endSession(client["internalClientSessionId"], client["gameId"]);
948
- } catch (error) {
949
- log.error("[Playcademy SDK] Failed to auto-end session:", {
950
- sessionId: client["internalClientSessionId"],
951
- error
952
- });
953
- }
954
- }
1011
+ exit: () => {
955
1012
  messaging.send("PLAYCADEMY_EXIT" /* EXIT */, undefined);
956
1013
  },
957
1014
  onInit: (handler) => {
@@ -1051,401 +1108,6 @@ function createAssetsNamespace(client) {
1051
1108
  }
1052
1109
  };
1053
1110
  }
1054
- // src/namespaces/game/backend.ts
1055
- function normalizePath(path) {
1056
- return path.startsWith("/") ? path : `/${path}`;
1057
- }
1058
- function createBackendNamespace(client) {
1059
- return {
1060
- async get(path, headers) {
1061
- return client["requestGameBackend"](normalizePath(path), "GET", undefined, headers);
1062
- },
1063
- async post(path, body, headers) {
1064
- return client["requestGameBackend"](normalizePath(path), "POST", body, headers);
1065
- },
1066
- async put(path, body, headers) {
1067
- return client["requestGameBackend"](normalizePath(path), "PUT", body, headers);
1068
- },
1069
- async patch(path, body, headers) {
1070
- return client["requestGameBackend"](normalizePath(path), "PATCH", body, headers);
1071
- },
1072
- async delete(path, headers) {
1073
- return client["requestGameBackend"](normalizePath(path), "DELETE", undefined, headers);
1074
- },
1075
- async request(path, method, body, headers) {
1076
- return client["requestGameBackend"](normalizePath(path), method, body, headers);
1077
- },
1078
- async download(path, method = "GET", body, headers) {
1079
- return client["requestGameBackend"](normalizePath(path), method, body, headers, { raw: true });
1080
- },
1081
- url(pathOrStrings, ...values) {
1082
- if (Array.isArray(pathOrStrings) && "raw" in pathOrStrings) {
1083
- const strings = pathOrStrings;
1084
- const path2 = strings.reduce((acc, str, i) => acc + str + (values[i] != null ? String(values[i]) : ""), "");
1085
- return `${client.gameUrl}/api${path2.startsWith("/") ? path2 : `/${path2}`}`;
1086
- }
1087
- const path = pathOrStrings;
1088
- return `${client.gameUrl}/api${path.startsWith("/") ? path : `/${path}`}`;
1089
- }
1090
- };
1091
- }
1092
- // src/namespaces/game/guard.ts
1093
- function assertPlatformMode(client, operation) {
1094
- if (client.mode !== "platform") {
1095
- throw new PlaycademyError(`${operation} requires platform mode (current: ${client.mode}). Check client.mode before calling.`);
1096
- }
1097
- }
1098
- function assertDemoMode(client, operation) {
1099
- if (client.mode !== "demo") {
1100
- throw new PlaycademyError(`${operation} requires demo mode (current: ${client.mode}). Check client.mode before calling.`);
1101
- }
1102
- }
1103
-
1104
- // src/namespaces/game/demo.ts
1105
- function createDemoNamespace(client) {
1106
- return {
1107
- profile: {
1108
- get: async () => {
1109
- assertDemoMode(client, "demo.profile.get()");
1110
- return client["request"]("/users/demo-profile", "GET");
1111
- },
1112
- update: async (updates) => {
1113
- assertDemoMode(client, "demo.profile.update()");
1114
- return client["request"]("/users/demo-profile", "PATCH", {
1115
- body: updates
1116
- });
1117
- }
1118
- },
1119
- end: (score, options) => {
1120
- assertDemoMode(client, "demo.end()");
1121
- messaging.send("PLAYCADEMY_DEMO_END" /* DEMO_END */, {
1122
- score,
1123
- ...options
1124
- });
1125
- }
1126
- };
1127
- }
1128
- // src/core/cache/permanent-cache.ts
1129
- function createPermanentCache(keyPrefix) {
1130
- const cache = new Map;
1131
- async function get(key, loader) {
1132
- const fullKey = keyPrefix ? `${keyPrefix}:${key}` : key;
1133
- const existing = cache.get(fullKey);
1134
- if (existing) {
1135
- return existing;
1136
- }
1137
- const promise = loader().catch((error) => {
1138
- cache.delete(fullKey);
1139
- throw error;
1140
- });
1141
- cache.set(fullKey, promise);
1142
- return promise;
1143
- }
1144
- function clear(key) {
1145
- if (key === undefined) {
1146
- cache.clear();
1147
- } else {
1148
- const fullKey = keyPrefix ? `${keyPrefix}:${key}` : key;
1149
- cache.delete(fullKey);
1150
- }
1151
- }
1152
- function has(key) {
1153
- const fullKey = keyPrefix ? `${keyPrefix}:${key}` : key;
1154
- return cache.has(fullKey);
1155
- }
1156
- function size() {
1157
- return cache.size;
1158
- }
1159
- function keys() {
1160
- const result = [];
1161
- const prefixLen = keyPrefix ? keyPrefix.length + 1 : 0;
1162
- for (const fullKey of cache.keys()) {
1163
- result.push(fullKey.substring(prefixLen));
1164
- }
1165
- return result;
1166
- }
1167
- return { get, clear, has, size, keys };
1168
- }
1169
-
1170
- // src/namespaces/game/users.ts
1171
- function createUsersNamespace(client) {
1172
- const itemIdCache = createPermanentCache("items");
1173
- const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1174
- async function resolveItemId(identifier) {
1175
- if (UUID_REGEX.test(identifier)) {
1176
- return identifier;
1177
- }
1178
- const gameId = client["gameId"];
1179
- const cacheKey = gameId ? `${identifier}:${gameId}` : identifier;
1180
- return itemIdCache.get(cacheKey, async () => {
1181
- const queryParams = new URLSearchParams({ slug: identifier });
1182
- if (gameId) {
1183
- queryParams.append("gameId", gameId);
1184
- }
1185
- const item = await client["request"](`/items/resolve?${queryParams.toString()}`, "GET");
1186
- return item.id;
1187
- });
1188
- }
1189
- return {
1190
- me: async () => {
1191
- assertPlatformMode(client, "users.me()");
1192
- return client["request"]("/users/me", "GET");
1193
- },
1194
- inventory: {
1195
- get: async () => {
1196
- assertPlatformMode(client, "users.inventory.get()");
1197
- return client["request"](`/inventory`, "GET");
1198
- },
1199
- add: async (identifier, qty) => {
1200
- assertPlatformMode(client, "users.inventory.add()");
1201
- const itemId = await resolveItemId(identifier);
1202
- const res = await client["request"](`/inventory/add`, "POST", { body: { itemId, qty } });
1203
- client["emit"]("inventoryChange", {
1204
- itemId,
1205
- delta: qty,
1206
- newTotal: res.newTotal
1207
- });
1208
- return res;
1209
- },
1210
- remove: async (identifier, qty) => {
1211
- assertPlatformMode(client, "users.inventory.remove()");
1212
- const itemId = await resolveItemId(identifier);
1213
- const res = await client["request"](`/inventory/remove`, "POST", { body: { itemId, qty } });
1214
- client["emit"]("inventoryChange", {
1215
- itemId,
1216
- delta: -qty,
1217
- newTotal: res.newTotal
1218
- });
1219
- return res;
1220
- },
1221
- quantity: async (identifier) => {
1222
- assertPlatformMode(client, "users.inventory.quantity()");
1223
- const itemId = await resolveItemId(identifier);
1224
- const inventory = await client["request"](`/inventory`, "GET");
1225
- const item = inventory.find((inv) => inv.item?.id === itemId);
1226
- return item?.quantity ?? 0;
1227
- },
1228
- has: async (identifier, minQuantity = 1) => {
1229
- assertPlatformMode(client, "users.inventory.has()");
1230
- const itemId = await resolveItemId(identifier);
1231
- const inventory = await client["request"](`/inventory`, "GET");
1232
- const item = inventory.find((inv) => inv.item?.id === itemId);
1233
- const qty = item?.quantity ?? 0;
1234
- return qty >= minQuantity;
1235
- }
1236
- }
1237
- };
1238
- }
1239
- // ../constants/src/achievements.ts
1240
- var ACHIEVEMENT_IDS = {
1241
- PLAY_ANY_GAME_DAILY: "play_any_game_daily",
1242
- DAILY_CHEST_OPEN: "daily_chest_open",
1243
- LEADERBOARD_TOP3_DAILY: "leaderboard_top3_daily",
1244
- LEADERBOARD_TOP3_WEEKLY: "leaderboard_top3_weekly",
1245
- FIRST_SCORE_ANY_GAME: "first_score_any_game",
1246
- PERSONAL_BEST_ANY_GAME: "personal_best_any_game"
1247
- };
1248
- var ACHIEVEMENT_DEFINITIONS = [
1249
- {
1250
- id: ACHIEVEMENT_IDS.PLAY_ANY_GAME_DAILY,
1251
- title: "Play any game",
1252
- description: "Play any arcade game for at least 60 seconds in a single session.",
1253
- scope: "daily",
1254
- rewardCredits: 10,
1255
- limit: 1,
1256
- completionType: "time_played_session",
1257
- completionConfig: { minSeconds: 60 },
1258
- target: { anyArcadeGame: true },
1259
- active: true
1260
- },
1261
- {
1262
- id: ACHIEVEMENT_IDS.DAILY_CHEST_OPEN,
1263
- title: "Opened the daily chest",
1264
- description: "Find the chest on the map and open it to claim your reward.",
1265
- scope: "daily",
1266
- rewardCredits: 10,
1267
- limit: 1,
1268
- completionType: "interaction",
1269
- completionConfig: { triggerId: "bunny_chest" },
1270
- target: { map: "arcade" },
1271
- active: true
1272
- },
1273
- {
1274
- id: ACHIEVEMENT_IDS.LEADERBOARD_TOP3_DAILY,
1275
- title: "Daily Champion",
1276
- description: "Finish in the top 3 of any game leaderboard for the day.",
1277
- scope: "daily",
1278
- rewardCredits: 25,
1279
- limit: 1,
1280
- completionType: "leaderboard_rank",
1281
- completionConfig: {
1282
- rankRewards: [50, 30, 15]
1283
- },
1284
- target: { anyArcadeGame: true },
1285
- active: true
1286
- },
1287
- {
1288
- id: ACHIEVEMENT_IDS.LEADERBOARD_TOP3_WEEKLY,
1289
- title: "Weekly Legend",
1290
- description: "Finish in the top 3 of any game leaderboard for the week.",
1291
- scope: "weekly",
1292
- rewardCredits: 50,
1293
- limit: 1,
1294
- completionType: "leaderboard_rank",
1295
- completionConfig: {
1296
- rankRewards: [100, 60, 30]
1297
- },
1298
- target: { anyArcadeGame: true },
1299
- active: true
1300
- },
1301
- {
1302
- id: ACHIEVEMENT_IDS.FIRST_SCORE_ANY_GAME,
1303
- title: "First Score",
1304
- description: "Submit your first score in any arcade game.",
1305
- scope: "game",
1306
- rewardCredits: 5,
1307
- limit: 1,
1308
- completionType: "first_score",
1309
- completionConfig: {},
1310
- target: { anyArcadeGame: true },
1311
- active: true
1312
- },
1313
- {
1314
- id: ACHIEVEMENT_IDS.PERSONAL_BEST_ANY_GAME,
1315
- title: "Personal Best",
1316
- description: "Beat your personal best score in any arcade game.",
1317
- scope: "daily",
1318
- rewardCredits: 5,
1319
- limit: 3,
1320
- completionType: "personal_best",
1321
- completionConfig: {},
1322
- target: { anyArcadeGame: true },
1323
- active: true
1324
- }
1325
- ];
1326
- // ../constants/src/typescript.ts
1327
- var TypeScriptPackages = {
1328
- tsc: "tsc",
1329
- nativePreview: "@typescript/native-preview",
1330
- nativePreviewBeta: "@typescript/native-preview@beta"
1331
- };
1332
- var TYPESCRIPT_RUNNER = {
1333
- package: TypeScriptPackages.nativePreviewBeta,
1334
- bin: "tsgo"
1335
- };
1336
- // ../constants/src/overworld.ts
1337
- var ITEM_SLUGS = {
1338
- PLAYCADEMY_CREDITS: "PLAYCADEMY_CREDITS",
1339
- PLAYCADEMY_XP: "PLAYCADEMY_XP",
1340
- FOUNDING_MEMBER_BADGE: "FOUNDING_MEMBER_BADGE",
1341
- EARLY_ADOPTER_BADGE: "EARLY_ADOPTER_BADGE",
1342
- FIRST_GAME_BADGE: "FIRST_GAME_BADGE",
1343
- COMMON_SWORD: "COMMON_SWORD",
1344
- SMALL_HEALTH_POTION: "SMALL_HEALTH_POTION",
1345
- SMALL_BACKPACK: "SMALL_BACKPACK",
1346
- LAVA_LAMP: "LAVA_LAMP",
1347
- BOOMBOX: "BOOMBOX",
1348
- CABIN_BED: "CABIN_BED"
1349
- };
1350
- var CURRENCIES = {
1351
- PRIMARY: ITEM_SLUGS.PLAYCADEMY_CREDITS,
1352
- XP: ITEM_SLUGS.PLAYCADEMY_XP
1353
- };
1354
- var BADGES = {
1355
- FOUNDING_MEMBER: ITEM_SLUGS.FOUNDING_MEMBER_BADGE,
1356
- EARLY_ADOPTER: ITEM_SLUGS.EARLY_ADOPTER_BADGE,
1357
- FIRST_GAME: ITEM_SLUGS.FIRST_GAME_BADGE
1358
- };
1359
- // ../constants/src/timeback.ts
1360
- var TIMEBACK_ROUTES = {
1361
- END_ACTIVITY: "/integrations/timeback/end-activity",
1362
- GET_XP: "/integrations/timeback/xp",
1363
- HEARTBEAT: "/integrations/timeback/heartbeat",
1364
- ADVANCE_COURSE: "/integrations/timeback/advance-course"
1365
- };
1366
- // src/core/cache/singleton-cache.ts
1367
- function createSingletonCache() {
1368
- let cachedValue;
1369
- let hasValue = false;
1370
- async function get(loader) {
1371
- if (hasValue) {
1372
- return cachedValue;
1373
- }
1374
- const value = await loader();
1375
- cachedValue = value;
1376
- hasValue = true;
1377
- return value;
1378
- }
1379
- function clear() {
1380
- cachedValue = undefined;
1381
- hasValue = false;
1382
- }
1383
- function has() {
1384
- return hasValue;
1385
- }
1386
- return { get, clear, has };
1387
- }
1388
-
1389
- // src/namespaces/game/credits.ts
1390
- function createCreditsNamespace(client) {
1391
- const creditsIdCache = createSingletonCache();
1392
- async function getCreditsItemId() {
1393
- return creditsIdCache.get(async () => {
1394
- const queryParams = new URLSearchParams({ slug: CURRENCIES.PRIMARY });
1395
- const creditsItem = await client["request"](`/items/resolve?${queryParams.toString()}`, "GET");
1396
- if (!creditsItem || !creditsItem.id) {
1397
- throw new Error("Playcademy Credits item not found in catalog");
1398
- }
1399
- return creditsItem.id;
1400
- });
1401
- }
1402
- return {
1403
- balance: async () => {
1404
- assertPlatformMode(client, "credits.balance()");
1405
- const inventory = await client["request"]("/inventory", "GET");
1406
- const primaryCurrencyInventoryItem = inventory.find((item) => item.item?.slug === CURRENCIES.PRIMARY);
1407
- return primaryCurrencyInventoryItem?.quantity ?? 0;
1408
- },
1409
- add: async (amount) => {
1410
- assertPlatformMode(client, "credits.add()");
1411
- if (amount <= 0) {
1412
- throw new Error("Amount must be positive");
1413
- }
1414
- const creditsItemId = await getCreditsItemId();
1415
- const result = await client["request"]("/inventory/add", "POST", {
1416
- body: {
1417
- itemId: creditsItemId,
1418
- qty: amount
1419
- }
1420
- });
1421
- client["emit"]("inventoryChange", {
1422
- itemId: creditsItemId,
1423
- delta: amount,
1424
- newTotal: result.newTotal
1425
- });
1426
- return result.newTotal;
1427
- },
1428
- spend: async (amount) => {
1429
- assertPlatformMode(client, "credits.spend()");
1430
- if (amount <= 0) {
1431
- throw new Error("Amount must be positive");
1432
- }
1433
- const creditsItemId = await getCreditsItemId();
1434
- const result = await client["request"]("/inventory/remove", "POST", {
1435
- body: {
1436
- itemId: creditsItemId,
1437
- qty: amount
1438
- }
1439
- });
1440
- client["emit"]("inventoryChange", {
1441
- itemId: creditsItemId,
1442
- delta: -amount,
1443
- newTotal: result.newTotal
1444
- });
1445
- return result.newTotal;
1446
- }
1447
- };
1448
- }
1449
1111
  // src/namespaces/game/scores.ts
1450
1112
  function createScoresNamespace(client) {
1451
1113
  return {
@@ -1460,18 +1122,6 @@ function createScoresNamespace(client) {
1460
1122
  }
1461
1123
  };
1462
1124
  }
1463
- // src/namespaces/game/realtime.ts
1464
- function createRealtimeNamespace(client) {
1465
- return {
1466
- token: {
1467
- get: async () => {
1468
- assertPlatformMode(client, "realtime.token.get()");
1469
- const endpoint = client["gameId"] ? `/games/${client["gameId"]}/realtime/token` : "/realtime/token";
1470
- return client["request"](endpoint, "POST");
1471
- }
1472
- }
1473
- };
1474
- }
1475
1125
  // src/core/guards.ts
1476
1126
  var VALID_GRADES = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
1477
1127
  var VALID_SUBJECTS = [
@@ -1491,7 +1141,13 @@ function isValidGrade(value) {
1491
1141
  function isValidSubject(value) {
1492
1142
  return typeof value === "string" && VALID_SUBJECTS.includes(value);
1493
1143
  }
1494
-
1144
+ // ../constants/src/timeback.ts
1145
+ var TIMEBACK_ROUTES = {
1146
+ END_ACTIVITY: "/integrations/timeback/end-activity",
1147
+ GET_XP: "/integrations/timeback/xp",
1148
+ HEARTBEAT: "/integrations/timeback/heartbeat",
1149
+ ADVANCE_COURSE: "/integrations/timeback/advance-course"
1150
+ };
1495
1151
  // src/core/cache/ttl-cache.ts
1496
1152
  function createTTLCache(options) {
1497
1153
  const cache = new Map;
@@ -1953,17 +1609,21 @@ function createTimebackActivityTracker(client) {
1953
1609
  }
1954
1610
  }
1955
1611
  return {
1612
+ currentRunId() {
1613
+ return currentActivity?.runId;
1614
+ },
1956
1615
  startActivity(metadata, options) {
1957
1616
  if (options?.runId !== undefined && !isValidUUID(options.runId)) {
1958
1617
  throw new Error(`startActivity: \`runId\` must be a UUID (received \`${JSON.stringify(options.runId)}\`). Use crypto.randomUUID() or persist a previously-generated UUID.`);
1959
1618
  }
1960
1619
  cleanupListeners();
1961
1620
  const now = Date.now();
1621
+ const runId = options?.runId ?? crypto.randomUUID();
1962
1622
  const heartbeatIntervalMs = normalizeDelayMs(options?.heartbeatIntervalMs, DEFAULT_HEARTBEAT_INTERVAL_MS, false);
1963
1623
  const pausedHeartbeatTimeoutMs = normalizeDelayMs(options?.pausedHeartbeatTimeoutMs ?? options?.hiddenTimeoutMs, DEFAULT_PAUSED_HEARTBEAT_TIMEOUT_MS, false);
1964
1624
  const inactivityTimeoutMs = normalizeDelayMs(options?.inactivityTimeoutMs, DEFAULT_INACTIVITY_TIMEOUT_MS, false);
1965
1625
  currentActivity = {
1966
- runId: options?.runId ?? crypto.randomUUID(),
1626
+ runId,
1967
1627
  resumeId: crypto.randomUUID(),
1968
1628
  startTime: now,
1969
1629
  metadata,
@@ -2006,6 +1666,7 @@ function createTimebackActivityTracker(client) {
2006
1666
  messaging.listen("PLAYCADEMY_PAUSE" /* PAUSE */, boundShellPauseHandler);
2007
1667
  messaging.listen("PLAYCADEMY_RESUME" /* RESUME */, boundShellResumeHandler);
2008
1668
  syncInactivityTracking();
1669
+ return { runId };
2009
1670
  },
2010
1671
  pauseActivity() {
2011
1672
  if (!currentActivity) {
@@ -2189,6 +1850,7 @@ function createTimebackEngine(client) {
2189
1850
  }
2190
1851
  },
2191
1852
  activity: {
1853
+ currentRunId: activityTracker.currentRunId,
2192
1854
  start: activityTracker.startActivity,
2193
1855
  pause: activityTracker.pauseActivity,
2194
1856
  resume: activityTracker.resumeActivity,
@@ -2249,9 +1911,13 @@ function createTimebackNamespace(client) {
2249
1911
  }
2250
1912
  };
2251
1913
  },
1914
+ get currentRunId() {
1915
+ assertPlatformMode(client, "timeback.currentRunId");
1916
+ return engine.activity.currentRunId();
1917
+ },
2252
1918
  startActivity: (metadata, options) => {
2253
1919
  assertPlatformMode(client, "timeback.startActivity()");
2254
- engine.activity.start(metadata, options);
1920
+ return engine.activity.start(metadata, options);
2255
1921
  },
2256
1922
  pauseActivity: () => {
2257
1923
  assertPlatformMode(client, "timeback.pauseActivity()");
@@ -2274,6 +1940,15 @@ function createTimebackNamespace(client) {
2274
1940
  }
2275
1941
  };
2276
1942
  }
1943
+ // src/namespaces/game/users.ts
1944
+ function createUsersNamespace(client) {
1945
+ return {
1946
+ me: async () => {
1947
+ assertPlatformMode(client, "users.me()");
1948
+ return client["request"]("/users/me", "GET");
1949
+ }
1950
+ };
1951
+ }
2277
1952
  // src/namespaces/platform/leaderboard.ts
2278
1953
  async function fetchInternalLeaderboardEntries(client, options) {
2279
1954
  const params = new URLSearchParams({
@@ -2386,231 +2061,6 @@ function createAuthStrategy(token, tokenType) {
2386
2061
  return new GameJwtAuth(token);
2387
2062
  }
2388
2063
 
2389
- // src/core/connection/monitor.ts
2390
- class ConnectionMonitor {
2391
- state = "online";
2392
- callbacks = new Set;
2393
- heartbeatInterval;
2394
- consecutiveFailures = 0;
2395
- isMonitoring = false;
2396
- config;
2397
- constructor(config) {
2398
- this.config = {
2399
- baseUrl: config.baseUrl,
2400
- heartbeatInterval: config.heartbeatInterval ?? 1e4,
2401
- heartbeatTimeout: config.heartbeatTimeout ?? 5000,
2402
- failureThreshold: config.failureThreshold ?? 2,
2403
- enableHeartbeat: config.enableHeartbeat ?? true,
2404
- enableOfflineEvents: config.enableOfflineEvents ?? true
2405
- };
2406
- this._detectInitialState();
2407
- }
2408
- start() {
2409
- if (this.isMonitoring) {
2410
- return;
2411
- }
2412
- this.isMonitoring = true;
2413
- if (this.config.enableOfflineEvents && typeof globalThis.window !== "undefined") {
2414
- globalThis.addEventListener("online", this._handleOnline);
2415
- globalThis.addEventListener("offline", this._handleOffline);
2416
- }
2417
- if (this.config.enableHeartbeat) {
2418
- this._startHeartbeat();
2419
- }
2420
- }
2421
- stop() {
2422
- if (!this.isMonitoring) {
2423
- return;
2424
- }
2425
- this.isMonitoring = false;
2426
- if (typeof globalThis.window !== "undefined") {
2427
- globalThis.removeEventListener("online", this._handleOnline);
2428
- globalThis.removeEventListener("offline", this._handleOffline);
2429
- }
2430
- if (this.heartbeatInterval) {
2431
- clearInterval(this.heartbeatInterval);
2432
- this.heartbeatInterval = undefined;
2433
- }
2434
- }
2435
- onChange(callback) {
2436
- this.callbacks.add(callback);
2437
- return () => this.callbacks.delete(callback);
2438
- }
2439
- getState() {
2440
- return this.state;
2441
- }
2442
- async checkNow() {
2443
- await this._performHeartbeat();
2444
- return this.state;
2445
- }
2446
- reportRequestFailure(error) {
2447
- const isNetworkError = error instanceof TypeError || error instanceof Error && error.message.includes("fetch");
2448
- if (!isNetworkError) {
2449
- return;
2450
- }
2451
- this.consecutiveFailures++;
2452
- if (this.consecutiveFailures >= this.config.failureThreshold) {
2453
- this._setState("degraded", "Multiple consecutive request failures");
2454
- }
2455
- }
2456
- reportRequestSuccess() {
2457
- if (this.consecutiveFailures > 0) {
2458
- this.consecutiveFailures = 0;
2459
- if (this.state === "degraded") {
2460
- this._setState("online", "Requests succeeding again");
2461
- }
2462
- }
2463
- }
2464
- _detectInitialState() {
2465
- if (typeof navigator !== "undefined" && !navigator.onLine) {
2466
- this.state = "offline";
2467
- }
2468
- }
2469
- _handleOnline = () => {
2470
- this.consecutiveFailures = 0;
2471
- this._setState("online", "Browser online event");
2472
- };
2473
- _handleOffline = () => {
2474
- this._setState("offline", "Browser offline event");
2475
- };
2476
- _startHeartbeat() {
2477
- this._performHeartbeat();
2478
- this.heartbeatInterval = setInterval(() => {
2479
- this._performHeartbeat();
2480
- }, this.config.heartbeatInterval);
2481
- }
2482
- async _performHeartbeat() {
2483
- if (typeof navigator !== "undefined" && !navigator.onLine) {
2484
- return;
2485
- }
2486
- try {
2487
- const controller = new AbortController;
2488
- const timeoutId = setTimeout(() => controller.abort(), this.config.heartbeatTimeout);
2489
- const response = await fetch(`${this.config.baseUrl}/ping`, {
2490
- method: "GET",
2491
- signal: controller.signal,
2492
- cache: "no-store"
2493
- });
2494
- clearTimeout(timeoutId);
2495
- if (response.ok) {
2496
- this.consecutiveFailures = 0;
2497
- if (this.state !== "online") {
2498
- this._setState("online", "Heartbeat successful");
2499
- }
2500
- } else {
2501
- this._handleHeartbeatFailure("Heartbeat returned non-OK status");
2502
- }
2503
- } catch (error) {
2504
- this._handleHeartbeatFailure(error instanceof Error ? error.message : "Heartbeat failed");
2505
- }
2506
- }
2507
- _handleHeartbeatFailure(reason) {
2508
- this.consecutiveFailures++;
2509
- if (this.consecutiveFailures >= this.config.failureThreshold) {
2510
- if (typeof navigator !== "undefined" && !navigator.onLine) {
2511
- this._setState("offline", reason);
2512
- } else {
2513
- this._setState("degraded", reason);
2514
- }
2515
- }
2516
- }
2517
- _setState(newState, reason) {
2518
- if (this.state === newState) {
2519
- return;
2520
- }
2521
- const oldState = this.state;
2522
- this.state = newState;
2523
- console.debug(`[ConnectionMonitor] ${oldState} → ${newState}: ${reason}`);
2524
- this.callbacks.forEach((callback) => {
2525
- try {
2526
- callback(newState, reason);
2527
- } catch (error) {
2528
- console.error("[ConnectionMonitor] Error in callback:", error);
2529
- }
2530
- });
2531
- }
2532
- }
2533
- // src/core/connection/utils.ts
2534
- function createDisplayAlert(authContext) {
2535
- return (message, options) => {
2536
- if (authContext?.isInIframe && typeof globalThis.window !== "undefined" && globalThis.window.parent !== globalThis.window) {
2537
- window.parent.postMessage({
2538
- type: "PLAYCADEMY_DISPLAY_ALERT",
2539
- message,
2540
- options
2541
- }, "*");
2542
- } else {
2543
- const prefixMap = { error: "❌", warning: "⚠️", info: "ℹ️" };
2544
- const prefix = (options?.type && prefixMap[options.type]) ?? "ℹ️";
2545
- console.log(`${prefix} ${message}`);
2546
- }
2547
- };
2548
- }
2549
-
2550
- // src/core/connection/manager.ts
2551
- class ConnectionManager {
2552
- monitor;
2553
- authContext;
2554
- disconnectHandler;
2555
- connectionChangeCallback;
2556
- currentState = "online";
2557
- additionalDisconnectHandlers = new Set;
2558
- constructor(config) {
2559
- this.authContext = config.authContext;
2560
- this.disconnectHandler = config.onDisconnect;
2561
- this.connectionChangeCallback = config.onConnectionChange;
2562
- if (config.authContext?.isInIframe) {
2563
- this._setupPlatformListener();
2564
- }
2565
- }
2566
- getState() {
2567
- return this.monitor?.getState() ?? this.currentState;
2568
- }
2569
- async checkNow() {
2570
- if (!this.monitor) {
2571
- return this.currentState;
2572
- }
2573
- return await this.monitor.checkNow();
2574
- }
2575
- reportRequestSuccess() {
2576
- this.monitor?.reportRequestSuccess();
2577
- }
2578
- reportRequestFailure(error) {
2579
- this.monitor?.reportRequestFailure(error);
2580
- }
2581
- onDisconnect(callback) {
2582
- this.additionalDisconnectHandlers.add(callback);
2583
- return () => {
2584
- this.additionalDisconnectHandlers.delete(callback);
2585
- };
2586
- }
2587
- stop() {
2588
- this.monitor?.stop();
2589
- }
2590
- _setupPlatformListener() {
2591
- messaging.listen("PLAYCADEMY_CONNECTION_STATE" /* CONNECTION_STATE */, ({ state, reason }) => {
2592
- this.currentState = state;
2593
- this._handleConnectionChange(state, reason);
2594
- });
2595
- }
2596
- _handleConnectionChange(state, reason) {
2597
- this.connectionChangeCallback?.(state, reason);
2598
- if (state === "offline" || state === "degraded") {
2599
- const context = {
2600
- state,
2601
- reason,
2602
- timestamp: Date.now(),
2603
- displayAlert: createDisplayAlert(this.authContext)
2604
- };
2605
- if (this.disconnectHandler) {
2606
- this.disconnectHandler(context);
2607
- }
2608
- this.additionalDisconnectHandlers.forEach((handler) => {
2609
- handler(context);
2610
- });
2611
- }
2612
- }
2613
- }
2614
2064
  // src/core/transport/retry.ts
2615
2065
  var RETRY_DELAYS_MS = [500, 1500];
2616
2066
  function wait(ms) {
@@ -2760,15 +2210,9 @@ class PlaycademyBaseClient {
2760
2210
  gameId;
2761
2211
  config;
2762
2212
  listeners = {};
2763
- internalClientSessionId;
2764
2213
  authContext;
2765
2214
  initPayload;
2766
- connectionManager;
2767
2215
  launchId;
2768
- _sessionManager = {
2769
- startSession: async (gameId) => this.request(`/games/${gameId}/sessions`, "POST"),
2770
- endSession: async (sessionId, gameId) => this.request(`/games/${gameId}/sessions/${sessionId}`, "DELETE")
2771
- };
2772
2216
  constructor(config) {
2773
2217
  this.baseUrl = config?.baseUrl?.endsWith("/api") ? config.baseUrl : `${config?.baseUrl}/api`;
2774
2218
  this.gameUrl = config?.gameUrl;
@@ -2778,8 +2222,6 @@ class PlaycademyBaseClient {
2778
2222
  this.config = config || {};
2779
2223
  this.authStrategy = createAuthStrategy(config?.token ?? null, config?.tokenType);
2780
2224
  this._detectAuthContext();
2781
- this._initializeInternalSession().catch(() => {});
2782
- this._initializeConnectionMonitor();
2783
2225
  }
2784
2226
  getBaseUrl() {
2785
2227
  const isRelative = this.baseUrl.startsWith("/");
@@ -2817,21 +2259,6 @@ class PlaycademyBaseClient {
2817
2259
  onAuthChange(callback) {
2818
2260
  this.on("authChange", (payload) => callback(payload.token));
2819
2261
  }
2820
- onDisconnect(callback) {
2821
- if (!this.connectionManager) {
2822
- return () => {};
2823
- }
2824
- return this.connectionManager.onDisconnect(callback);
2825
- }
2826
- getConnectionState() {
2827
- return this.connectionManager?.getState() ?? "unknown";
2828
- }
2829
- async checkConnection() {
2830
- if (!this.connectionManager) {
2831
- return "unknown";
2832
- }
2833
- return await this.connectionManager.checkNow();
2834
- }
2835
2262
  _setAuthContext(context) {
2836
2263
  this.authContext = context;
2837
2264
  }
@@ -2861,44 +2288,30 @@ class PlaycademyBaseClient {
2861
2288
  ...this.authStrategy.getHeaders(),
2862
2289
  ...this.launchId ? { "x-playcademy-launch-id": this.launchId } : {}
2863
2290
  };
2864
- try {
2865
- const result = await request({
2866
- path,
2867
- method,
2868
- body: options?.body,
2869
- baseUrl: this.baseUrl,
2870
- extraHeaders: effectiveHeaders,
2871
- raw: options?.raw,
2872
- retryPolicy: options?.retryPolicy
2873
- });
2874
- this.connectionManager?.reportRequestSuccess();
2875
- return result;
2876
- } catch (error) {
2877
- this.connectionManager?.reportRequestFailure(error);
2878
- throw error;
2879
- }
2291
+ return request({
2292
+ path,
2293
+ method,
2294
+ body: options?.body,
2295
+ baseUrl: this.baseUrl,
2296
+ extraHeaders: effectiveHeaders,
2297
+ raw: options?.raw,
2298
+ retryPolicy: options?.retryPolicy
2299
+ });
2880
2300
  }
2881
2301
  async requestGameBackend(path, method, body, headers, options) {
2882
2302
  const effectiveHeaders = {
2883
2303
  ...headers,
2884
2304
  ...this.authStrategy.getHeaders()
2885
2305
  };
2886
- try {
2887
- const result = await request({
2888
- path,
2889
- method,
2890
- body,
2891
- baseUrl: this.getGameBackendUrl(),
2892
- extraHeaders: effectiveHeaders,
2893
- raw: options?.raw,
2894
- retryPolicy: options?.retryPolicy
2895
- });
2896
- this.connectionManager?.reportRequestSuccess();
2897
- return result;
2898
- } catch (error) {
2899
- this.connectionManager?.reportRequestFailure(error);
2900
- throw error;
2901
- }
2306
+ return request({
2307
+ path,
2308
+ method,
2309
+ body,
2310
+ baseUrl: this.getGameBackendUrl(),
2311
+ extraHeaders: effectiveHeaders,
2312
+ raw: options?.raw,
2313
+ retryPolicy: options?.retryPolicy
2314
+ });
2902
2315
  }
2903
2316
  _ensureGameId() {
2904
2317
  if (!this.gameId) {
@@ -2909,49 +2322,6 @@ class PlaycademyBaseClient {
2909
2322
  _detectAuthContext() {
2910
2323
  this.authContext = { isInIframe: isInIframe() };
2911
2324
  }
2912
- _initializeConnectionMonitor() {
2913
- if (typeof globalThis.window === "undefined") {
2914
- return;
2915
- }
2916
- const isEnabled = this.config.enableConnectionMonitoring ?? true;
2917
- if (!isEnabled) {
2918
- return;
2919
- }
2920
- try {
2921
- this.connectionManager = new ConnectionManager({
2922
- baseUrl: this.baseUrl,
2923
- authContext: this.authContext,
2924
- onDisconnect: this.config.onDisconnect,
2925
- onConnectionChange: (state, reason) => {
2926
- this.emit("connectionChange", { state, reason });
2927
- }
2928
- });
2929
- } catch (error) {
2930
- log.error("[Playcademy SDK] Failed to initialize connection manager:", { error });
2931
- }
2932
- }
2933
- async _initializeInternalSession() {
2934
- if (!this.gameId || this.internalClientSessionId) {
2935
- return;
2936
- }
2937
- const shouldAutoStart = this.config.autoStartSession ?? true;
2938
- if (!shouldAutoStart) {
2939
- return;
2940
- }
2941
- try {
2942
- const response = await this._sessionManager.startSession(this.gameId);
2943
- this.internalClientSessionId = response.sessionId;
2944
- log.debug("[Playcademy SDK] Auto-started game session", {
2945
- gameId: this.gameId,
2946
- sessionId: this.internalClientSessionId
2947
- });
2948
- } catch (error) {
2949
- log.error("[Playcademy SDK] Auto-starting session failed for game", {
2950
- gameId: this.gameId,
2951
- error
2952
- });
2953
- }
2954
- }
2955
2325
  users = createUsersNamespace(this);
2956
2326
  }
2957
2327
 
@@ -2960,11 +2330,9 @@ class PlaycademyClient extends PlaycademyBaseClient {
2960
2330
  identity = createIdentityNamespace(this);
2961
2331
  runtime = createRuntimeNamespace(this);
2962
2332
  timeback = createTimebackNamespace(this);
2963
- credits = createCreditsNamespace(this);
2964
2333
  scores = createScoresNamespace(this);
2965
2334
  leaderboard = createLeaderboardFetchNamespace(this);
2966
2335
  demo = createDemoNamespace(this);
2967
- realtime = createRealtimeNamespace(this);
2968
2336
  backend = createBackendNamespace(this);
2969
2337
  static init = init;
2970
2338
  static login = login;
@@ -2976,7 +2344,5 @@ export {
2976
2344
  PlaycademyError,
2977
2345
  PlaycademyClient,
2978
2346
  MessageEvents,
2979
- ConnectionMonitor,
2980
- ConnectionManager,
2981
2347
  ApiError
2982
2348
  };