@playcademy/sdk 0.16.1-beta.3 → 0.16.1-beta.5

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/types.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import * as _playcademy_types from '@playcademy/types';
2
2
  import { GameManifest, LocalDayContext } from '@playcademy/types';
3
3
  export { AuthenticatedUser, DeveloperStatusEnumType, DeveloperStatusResponse, DeveloperStatusValue, GameCourseMetrics, GameLeaderboardEntry, GameManifest, GameMetricComparisonKind, GameMetricComparisonMetric, GameMetricComparisonRow, GameMetricComparisonRowStatus, GameMetricsProxyResponse, GameMetricsResponse, GameMetricsUnsupportedReason, GamePlatform, GameRunMetrics, GameRunMetricsComparison, GameRunMetricsComparisonStatus, GameRunMetricsComparisonSummary, GameTimebackIntegration, GameType, GameUser, LeaderboardEntry, LeaderboardOptions, LeaderboardTimeframe, LocalDayContext, LocalDaySource, ManifestV1, ManifestV2, ManifestVersions, PopulateStudentResponse, UserEnrollment, UserInfo, UserOrganization, UserRank, UserRankResponse, UserRoleEnumType, UserScore, UserTimebackData } from '@playcademy/types';
4
- import { TimebackCourseConfig, CourseConfig, OrganizationConfig, ComponentConfig, ResourceConfig, ComponentResourceConfig, TimebackGrade, TimebackSubject, HeartbeatRequest } from '@playcademy/types/timeback';
4
+ import { TimebackCourseConfig, CourseConfig, OrganizationConfig, ComponentConfig, ResourceConfig, ComponentResourceConfig, TimebackGrade, TimebackSubject, ELevel, EndActivityRequest, HeartbeatRequest, EndActivityScoreData, EndActivityResponse } from '@playcademy/types/timeback';
5
+ export { ELevel } from '@playcademy/types/timeback';
5
6
  import { TimebackUserRole, UserEnrollment, UserOrganization, UserInfo } from '@playcademy/types/user';
6
7
  import { GamePermission, AUTH_PROVIDER_IDS } from '@playcademy/constants';
7
8
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
@@ -30,6 +31,13 @@ interface RetryPolicy {
30
31
  retryDelaysMs?: readonly number[];
31
32
  }
32
33
 
34
+ /**
35
+ * Base error class for Cademy SDK specific errors.
36
+ */
37
+ declare class PlaycademyError extends Error {
38
+ constructor(message: string);
39
+ }
40
+
33
41
  /**
34
42
  * @fileoverview Playcademy Messaging System
35
43
  *
@@ -158,11 +166,32 @@ declare enum MessageEvents {
158
166
  */
159
167
  DEMO_END = "PLAYCADEMY_DEMO_END",
160
168
  /**
161
- * Game shares its latest TimeBack heartbeat window with the parent shell.
162
- * The shell can relay this payload during top-level page teardown, which is
163
- * more reliable than relying only on cross-origin iframe unload events.
169
+ * Game shares its latest TimeBack heartbeat window with the embedding
170
+ * window. The hub relays this payload during top-level page teardown
171
+ * (more reliable than cross-origin iframe unload events); in child mode
172
+ * this stream is the heartbeat's only delivery path.
164
173
  */
165
174
  TIMEBACK_HEARTBEAT_RELAY = "PLAYCADEMY_TIMEBACK_HEARTBEAT_RELAY",
175
+ /**
176
+ * Game announces its tracker opened a run (startActivity).
177
+ * Today only child-mode games emit this: the parent opens its own
178
+ * Timeback run on receipt, so tracked time starts when the lesson
179
+ * does, not when the iframe boots.
180
+ */
181
+ TIMEBACK_ACTIVITY_START = "PLAYCADEMY_TIMEBACK_ACTIVITY_START",
182
+ /**
183
+ * Game relays its full end-activity report instead of POSTing it to
184
+ * its own backend. Today only child-mode games emit this: the parent
185
+ * reports the result to Timeback under its own identity.
186
+ */
187
+ TIMEBACK_ACTIVITY_END = "PLAYCADEMY_TIMEBACK_ACTIVITY_END",
188
+ /**
189
+ * Child game → parent game. An opaque checkpoint of the child's
190
+ * internal state, streamed during play so the parent always holds a
191
+ * near-current copy (the death-time postMessage hop is unreliable;
192
+ * continuous checkpointing is the design). Latest wins.
193
+ */
194
+ CHECKPOINT = "PLAYCADEMY_CHECKPOINT",
166
195
  /**
167
196
  * Notifies about authentication state changes.
168
197
  * Can be sent in both directions depending on auth flow.
@@ -1237,6 +1266,8 @@ declare abstract class PlaycademyBaseClient {
1237
1266
  isInIframe: boolean;
1238
1267
  };
1239
1268
  protected initPayload?: InitPayload;
1269
+ /** Memoized `client.parent` handle; built on first access in child mode. */
1270
+ private parentHandle?;
1240
1271
  protected launchId?: string;
1241
1272
  protected gameOrigin?: string;
1242
1273
  private browserTimeZone?;
@@ -1257,6 +1288,13 @@ declare abstract class PlaycademyBaseClient {
1257
1288
  * Local day context supplied by the platform during iframe initialization.
1258
1289
  */
1259
1290
  get localDay(): LocalDayContext | undefined;
1291
+ /**
1292
+ * Null outside `mode: 'child'` even if a payload smuggled in a `parent`
1293
+ * block, so `if (client.parent)` is a reliable child-mode test. The
1294
+ * returned handle is the wire block plus `checkpoint()`, memoized so
1295
+ * `client.parent === client.parent`.
1296
+ */
1297
+ get parent(): ParentGameHandle | null;
1260
1298
  /**
1261
1299
  * Sets the authentication token for API requests.
1262
1300
  */
@@ -1403,153 +1441,14 @@ declare function init<T extends PlaycademyBaseClient = PlaycademyBaseClient>(thi
1403
1441
  declare function login(baseUrl: string, email: string, password: string): Promise<LoginResponse>;
1404
1442
 
1405
1443
  /**
1406
- * Playcademy SDK client for game developers.
1407
- * Provides namespaced access to platform features for games running inside Cademy.
1444
+ * `endActivity()`'s resolution in child mode: the report was relayed to the
1445
+ * parent game rather than POSTed to the platform, so no platform award data
1446
+ * (courseId, xpAwarded) exists. The parent reports under its own identity.
1408
1447
  */
1409
- declare class PlaycademyClient extends PlaycademyBaseClient {
1410
- /**
1411
- * Connect external identity providers to the user's Playcademy account.
1412
- * - `connect(provider)` - Link Discord, Google, etc. via OAuth popup
1413
- */
1414
- identity: {
1415
- connect: (options: AuthOptions) => Promise<AuthResult>;
1416
- _getContext: () => {
1417
- isInIframe: boolean;
1418
- };
1419
- };
1420
- /**
1421
- * Game runtime lifecycle and asset loading.
1422
- * - `exit()` - Return to Cademy hub
1423
- * - `getGameToken()` - Get short-lived auth token
1424
- * - `assets.url()`, `assets.json()`, `assets.fetch()` - Load game assets
1425
- * - `on('pause')`, `on('resume')` - Handle visibility changes
1426
- */
1427
- runtime: {
1428
- exit: () => void;
1429
- onInit: (handler: (context: GameContextPayload) => void) => void;
1430
- onTokenRefresh: (handler: (data: {
1431
- token: string;
1432
- exp: number;
1433
- }) => void) => void;
1434
- onPause: (handler: () => void) => void;
1435
- onResume: (handler: () => void) => void;
1436
- onForceExit: (handler: () => void) => void;
1437
- onOverlay: (handler: (isVisible: boolean) => void) => void;
1438
- ready: () => void;
1439
- sendTelemetry: (data: {
1440
- fps: number;
1441
- mem: number;
1442
- }) => void;
1443
- removeListener: (eventType: MessageEvents, handler: ((context: GameContextPayload) => void) | ((data: {
1444
- token: string;
1445
- exp: number;
1446
- }) => void) | (() => void) | ((isVisible: boolean) => void)) => void;
1447
- removeAllListeners: () => void;
1448
- getListenerCounts: () => Record<string, number>;
1449
- assets: {
1450
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1451
- fetch: (path: string, options?: RequestInit) => Promise<Response>;
1452
- json: <T = unknown>(path: string) => Promise<T>;
1453
- blob: (path: string) => Promise<Blob>;
1454
- text: (path: string) => Promise<string>;
1455
- arrayBuffer: (path: string) => Promise<ArrayBuffer>;
1456
- };
1457
- };
1458
- /**
1459
- * TimeBack integration for activity tracking and user context.
1460
- *
1461
- * User context (cached from init, refreshable):
1462
- * - `user.role` - User's role (student, parent, teacher, etc.)
1463
- * - `user.enrollments` - Courses the player is enrolled in for this game
1464
- * - `user.refresh({ only: ['enrollments'] })` - Refresh enrollments from server
1465
- * - `user.organizations` - Schools/districts the player belongs to
1466
- * - `user.fetch()` - Refresh user context from server
1467
- *
1468
- * Activity tracking:
1469
- * - `currentRunId` - Current activity run ID, or undefined when inactive
1470
- * - `startActivity(metadata)` - Begin tracking an activity, return its run
1471
- * ID, and automatically handle hidden-tab and visible-tab inactivity
1472
- * with configurable paused-heartbeat timeout behavior
1473
- * - `pauseActivity()` / `resumeActivity()` - Pause/resume timer
1474
- * - `endActivity(scoreData)` - Submit activity results to TimeBack
1475
- */
1476
- timeback: {
1477
- assessments: {
1478
- start: (input: _playcademy_types.StartAssessmentInput) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
1479
- latest: (options: _playcademy_types.GetLatestAssessmentOptions) => Promise<_playcademy_types.LatestAssessmentResult | null>;
1480
- get: (attemptId: string) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
1481
- save: (attemptId: string, input: _playcademy_types.SaveAssessmentInput) => Promise<_playcademy_types.AssessmentSaveResult>;
1482
- submit: (attemptId: string, input: _playcademy_types.SubmitAssessmentInput) => Promise<_playcademy_types.AssessmentSubmitResult>;
1483
- };
1484
- readonly user: TimebackUser;
1485
- readonly currentRunId: string | undefined;
1486
- startActivity: (metadata: _playcademy_types.ActivityData, options?: StartActivityOptions) => StartActivityResult;
1487
- pauseActivity: () => void;
1488
- resumeActivity: () => void;
1489
- endActivity: (data: _playcademy_types.EndActivityScoreData) => Promise<_playcademy_types.EndActivityResponse>;
1490
- course: {
1491
- advance: (options?: {
1492
- subject?: _playcademy_types.TimebackSubject;
1493
- }) => Promise<_playcademy_types.AdvanceCourseResponse>;
1494
- unenroll: (options?: {
1495
- subject?: _playcademy_types.TimebackSubject;
1496
- force?: boolean;
1497
- }) => Promise<_playcademy_types.UnenrollCourseResponse>;
1498
- };
1499
- };
1500
- /**
1501
- * Game score submission and leaderboards.
1502
- * - `submit(score, metadata?)` - Record a game score
1503
- */
1504
- scores: {
1505
- submit: (score: number, metadata?: Record<string, unknown>) => Promise<ScoreSubmission>;
1506
- };
1507
- /**
1508
- * Read-only leaderboard access for the current game scope.
1509
- * - `fetch(options?)` - Fetch leaderboard entries
1510
- */
1511
- leaderboard: {
1512
- fetch: (options?: _playcademy_types.LeaderboardOptions) => Promise<_playcademy_types.GameLeaderboardEntry[]>;
1513
- };
1514
- /**
1515
- * Demo-mode helpers. Methods throw when called outside `client.mode === 'demo'`,
1516
- * so callers should gate on the mode before reaching in.
1517
- * - `profile.get()` - Read the anonymous demo player's profile
1518
- * - `profile.update(updates)` - Update the demo player's profile (today: the required `displayName`)
1519
- * - `end(score, options?)` - Signal to the parent shell that the demo has ended
1520
- */
1521
- demo: {
1522
- profile: {
1523
- get: () => Promise<_playcademy_types.DemoProfile>;
1524
- update: (updates: _playcademy_types.DemoProfileUpdate) => Promise<_playcademy_types.DemoProfile>;
1525
- };
1526
- end: (score: number, options?: DemoEndOptions) => void;
1527
- };
1528
- /**
1529
- * Make requests to your game's custom backend API routes.
1530
- * - `get(path)`, `post(path, body)`, `put()`, `delete()` - HTTP methods
1531
- * - Routes are relative to your game's deployment (e.g., '/hello' → your-game.playcademy.gg/api/hello)
1532
- */
1533
- backend: {
1534
- get<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1535
- post<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1536
- put<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1537
- patch<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1538
- delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1539
- request<T = unknown>(path: string, method: Method, body?: unknown, headers?: Record<string, string>): Promise<T>;
1540
- download(path: string, method?: Method, body?: unknown, headers?: Record<string, string>): Promise<Response>;
1541
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1542
- };
1543
- /** Auto-initializes a PlaycademyClient with context from the environment */
1544
- static init: typeof init;
1545
- /** Authenticates a user with email and password */
1546
- static login: typeof login;
1547
- /** Static identity utilities for OAuth operations */
1548
- static identity: {
1549
- parseOAuthState: typeof parseOAuthState;
1550
- };
1448
+ interface RelayedEndActivityResult {
1449
+ status: 'relayed';
1450
+ runId: string;
1551
1451
  }
1552
-
1553
1452
  /**
1554
1453
  * Options for configuring activity tracking behavior.
1555
1454
  */
@@ -1887,8 +1786,79 @@ type TokenType = 'session' | 'apiKey' | 'gameJwt';
1887
1786
  * - `'standalone'` — game is running outside any iframe (e.g. `bun run dev`
1888
1787
  * or direct-deploy preview) with a mock token and no real platform
1889
1788
  * context. API calls will not succeed; use this to branch UX locally.
1789
+ * - `'child'` — game is embedded by another game (the parent), which ran
1790
+ * the INIT handshake itself and included a `parent` block in the payload.
1791
+ * The user and token are real (the parent's own). Direct Timeback
1792
+ * reporting is suppressed and relayed to the parent instead; read
1793
+ * `client.parent` for the parent's identity and launch instructions.
1890
1794
  */
1891
- type PlaycademyMode = 'platform' | 'demo' | 'standalone';
1795
+ type PlaycademyMode = 'platform' | 'demo' | 'standalone' | 'child';
1796
+ /**
1797
+ * What a parent game asks a child game to deliver.
1798
+ *
1799
+ * This contract is platform-defined so any parent can launch any child
1800
+ * without pair-specific vocabularies. `lessonId` addresses the child's own
1801
+ * catalog; the child maps it to internal content. Pair-specific extras
1802
+ * belong in `extensions`, which the platform never interprets (the same
1803
+ * split LTI makes between its resource link and custom claims).
1804
+ *
1805
+ * Parent and child ship independently, so children should still validate
1806
+ * the intent at runtime; SDK compatibility floors manage version skew.
1807
+ */
1808
+ interface LaunchIntent {
1809
+ /** The activity to deliver, addressed in the child's own catalog. */
1810
+ lessonId: string;
1811
+ /** Pedagogy stage of the lesson (the platform's E1-E4 taxonomy). */
1812
+ eLevel: ELevel;
1813
+ /** Pair-specific extras. Never interpreted by the platform. */
1814
+ extensions?: Record<string, unknown>;
1815
+ }
1816
+ /**
1817
+ * What `client.parent` actually returns: the parent's wire context plus
1818
+ * the child's one capability toward it. The wire block
1819
+ * (`ParentGameContext`) stays a pure serializable payload; this handle
1820
+ * wraps it. Null outside child mode, so `if (client.parent)` remains the
1821
+ * child-launch test.
1822
+ */
1823
+ type ParentGameHandle = ParentGameContext & {
1824
+ /**
1825
+ * Streams an opaque checkpoint of this game's state to the parent,
1826
+ * so an interrupted launch can resume later (the parent hands it
1827
+ * back as `client.parent.resume`). Call it whenever your state
1828
+ * meaningfully changes — never wait for teardown, the closing-tab
1829
+ * message hop is unreliable. State must be JSON-serializable and
1830
+ * under 64KB; anything else is dropped with a warning. This is not
1831
+ * your save system: the parent holds it for resume only.
1832
+ */
1833
+ checkpoint(state: unknown): void;
1834
+ };
1835
+ /**
1836
+ * The parent game's block in a `mode: 'child'` INIT payload. Present only
1837
+ * when a parent game launched this client (see the parent-child game
1838
+ * embedding proposal, `docs/dev/timeback/`).
1839
+ */
1840
+ interface ParentGameContext {
1841
+ /** The parent game's own platform game ID (NOT this game's ID). */
1842
+ gameId: string;
1843
+ /** What the parent wants this child to deliver. */
1844
+ intent: LaunchIntent;
1845
+ /**
1846
+ * An earlier launch's checkpoint state, when the parent is resuming
1847
+ * an interrupted lesson. Opaque: this game wrote it via
1848
+ * `client.parent.checkpoint()`, and only this game can interpret it.
1849
+ * Validate it like the intent — a blob from an older build of this
1850
+ * game should be ignored, not trusted.
1851
+ */
1852
+ resume?: unknown;
1853
+ /**
1854
+ * The interrupted run id, present when the parent is resuming a
1855
+ * lesson. Consumed by the SDK: the launch's first `startActivity()`
1856
+ * adopts it automatically, which is what continues the platform run.
1857
+ * Games never read this; pass an explicit `runId` to
1858
+ * `startActivity()` to start a deliberate fresh attempt instead.
1859
+ */
1860
+ resumeRunId?: string;
1861
+ }
1892
1862
  interface ClientConfig {
1893
1863
  baseUrl: string;
1894
1864
  gameUrl?: string;
@@ -1917,6 +1887,8 @@ interface InitPayload {
1917
1887
  launchId?: string;
1918
1888
  /** When `true`, the parent shell provides a heartbeat relay via postMessage, so the SDK can skip its own `fetch({ keepalive })` beacon on pagehide. Defaults to `false`. */
1919
1889
  hasHeartbeatRelay?: boolean;
1890
+ /** Parent game context. Present only when `mode` is `'child'`. */
1891
+ parent?: ParentGameContext;
1920
1892
  }
1921
1893
  /**
1922
1894
  * Simplified user data passed to games via InitPayload
@@ -1951,6 +1923,163 @@ interface ClientEvents {
1951
1923
  };
1952
1924
  }
1953
1925
 
1926
+ /**
1927
+ * Playcademy SDK client for game developers.
1928
+ * Provides namespaced access to platform features for games running inside Cademy.
1929
+ */
1930
+ declare class PlaycademyClient extends PlaycademyBaseClient {
1931
+ /**
1932
+ * Connect external identity providers to the user's Playcademy account.
1933
+ * - `connect(provider)` - Link Discord, Google, etc. via OAuth popup
1934
+ */
1935
+ identity: {
1936
+ connect: (options: AuthOptions) => Promise<AuthResult>;
1937
+ _getContext: () => {
1938
+ isInIframe: boolean;
1939
+ };
1940
+ };
1941
+ /**
1942
+ * Game runtime lifecycle and asset loading.
1943
+ * - `exit()` - Return to Cademy hub
1944
+ * - `getGameToken()` - Get short-lived auth token
1945
+ * - `assets.url()`, `assets.json()`, `assets.fetch()` - Load game assets
1946
+ * - `on('pause')`, `on('resume')` - Handle visibility changes
1947
+ */
1948
+ runtime: {
1949
+ exit: () => void;
1950
+ onInit: (handler: (context: GameContextPayload) => void) => void;
1951
+ onTokenRefresh: (handler: (data: {
1952
+ token: string;
1953
+ exp: number;
1954
+ }) => void) => void;
1955
+ onPause: (handler: () => void) => void;
1956
+ onResume: (handler: () => void) => void;
1957
+ onForceExit: (handler: () => void) => void;
1958
+ onOverlay: (handler: (isVisible: boolean) => void) => void;
1959
+ ready: () => void;
1960
+ sendTelemetry: (data: {
1961
+ fps: number;
1962
+ mem: number;
1963
+ }) => void;
1964
+ removeListener: (eventType: MessageEvents, handler: ((context: GameContextPayload) => void) | ((data: {
1965
+ token: string;
1966
+ exp: number;
1967
+ }) => void) | (() => void) | ((isVisible: boolean) => void)) => void;
1968
+ removeAllListeners: () => void;
1969
+ getListenerCounts: () => Record<string, number>;
1970
+ assets: {
1971
+ url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1972
+ fetch: (path: string, options?: RequestInit) => Promise<Response>;
1973
+ json: <T = unknown>(path: string) => Promise<T>;
1974
+ blob: (path: string) => Promise<Blob>;
1975
+ text: (path: string) => Promise<string>;
1976
+ arrayBuffer: (path: string) => Promise<ArrayBuffer>;
1977
+ };
1978
+ };
1979
+ /**
1980
+ * TimeBack integration for activity tracking and user context.
1981
+ *
1982
+ * User context (cached from init, refreshable):
1983
+ * - `user.role` - User's role (student, parent, teacher, etc.)
1984
+ * - `user.enrollments` - Courses the player is enrolled in for this game
1985
+ * - `user.refresh({ only: ['enrollments'] })` - Refresh enrollments from server
1986
+ * - `user.organizations` - Schools/districts the player belongs to
1987
+ * - `user.fetch()` - Refresh user context from server
1988
+ *
1989
+ * Activity tracking:
1990
+ * - `currentRunId` - Current activity run ID, or undefined when inactive
1991
+ * - `startActivity(metadata)` - Begin tracking an activity, return its run
1992
+ * ID, and automatically handle hidden-tab and visible-tab inactivity
1993
+ * with configurable paused-heartbeat timeout behavior
1994
+ * - `pauseActivity()` / `resumeActivity()` - Pause/resume timer
1995
+ * - `endActivity(scoreData)` - Submit activity results to TimeBack
1996
+ */
1997
+ timeback: {
1998
+ assessments: {
1999
+ start: (input: _playcademy_types.StartAssessmentInput) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
2000
+ latest: (options: _playcademy_types.GetLatestAssessmentOptions) => Promise<_playcademy_types.LatestAssessmentResult | null>;
2001
+ get: (attemptId: string) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
2002
+ save: (attemptId: string, input: _playcademy_types.SaveAssessmentInput) => Promise<_playcademy_types.AssessmentSaveResult>;
2003
+ submit: (attemptId: string, input: _playcademy_types.SubmitAssessmentInput) => Promise<_playcademy_types.AssessmentSubmitResult>;
2004
+ };
2005
+ readonly user: TimebackUser;
2006
+ readonly currentRunId: string | undefined;
2007
+ startActivity: (metadata: _playcademy_types.ActivityData, options?: StartActivityOptions) => StartActivityResult;
2008
+ pauseActivity: () => void;
2009
+ resumeActivity: () => void;
2010
+ endActivity: (data: _playcademy_types.EndActivityScoreData) => Promise<_playcademy_types.EndActivityResponse | RelayedEndActivityResult>;
2011
+ course: {
2012
+ advance: (options?: {
2013
+ subject?: _playcademy_types.TimebackSubject;
2014
+ }) => Promise<_playcademy_types.AdvanceCourseResponse>;
2015
+ unenroll: (options?: {
2016
+ subject?: _playcademy_types.TimebackSubject;
2017
+ force?: boolean;
2018
+ }) => Promise<_playcademy_types.UnenrollCourseResponse>;
2019
+ };
2020
+ };
2021
+ /**
2022
+ * Game score submission and leaderboards.
2023
+ * - `submit(score, metadata?)` - Record a game score
2024
+ */
2025
+ scores: {
2026
+ submit: (score: number, metadata?: Record<string, unknown>) => Promise<ScoreSubmission>;
2027
+ };
2028
+ /**
2029
+ * Read-only leaderboard access for the current game scope.
2030
+ * - `fetch(options?)` - Fetch leaderboard entries
2031
+ */
2032
+ leaderboard: {
2033
+ fetch: (options?: _playcademy_types.LeaderboardOptions) => Promise<_playcademy_types.GameLeaderboardEntry[]>;
2034
+ };
2035
+ /**
2036
+ * Demo-mode helpers. Methods throw when called outside `client.mode === 'demo'`,
2037
+ * so callers should gate on the mode before reaching in.
2038
+ * - `profile.get()` - Read the anonymous demo player's profile
2039
+ * - `profile.update(updates)` - Update the demo player's profile (today: the required `displayName`)
2040
+ * - `end(score, options?)` - Signal to the parent shell that the demo has ended
2041
+ */
2042
+ demo: {
2043
+ profile: {
2044
+ get: () => Promise<_playcademy_types.DemoProfile>;
2045
+ update: (updates: _playcademy_types.DemoProfileUpdate) => Promise<_playcademy_types.DemoProfile>;
2046
+ };
2047
+ end: (score: number, options?: DemoEndOptions) => void;
2048
+ };
2049
+ /**
2050
+ * Make requests to your game's custom backend API routes.
2051
+ * - `get(path)`, `post(path, body)`, `put()`, `delete()` - HTTP methods
2052
+ * - Routes are relative to your game's deployment (e.g., '/hello' → your-game.playcademy.gg/api/hello)
2053
+ */
2054
+ backend: {
2055
+ get<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
2056
+ post<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
2057
+ put<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
2058
+ patch<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
2059
+ delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
2060
+ request<T = unknown>(path: string, method: Method, body?: unknown, headers?: Record<string, string>): Promise<T>;
2061
+ download(path: string, method?: Method, body?: unknown, headers?: Record<string, string>): Promise<Response>;
2062
+ url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
2063
+ };
2064
+ /**
2065
+ * Launch other Playcademy games as embedded children (platform mode only).
2066
+ * - `launch({ slug, container, intent })` - Mount a child game in a nested
2067
+ * iframe with `mode: 'child'`; returns a session handle with `finished`
2068
+ * and `closed` promises and `close()`
2069
+ */
2070
+ embed: {
2071
+ launch(options: EmbedLaunchOptions): EmbedSession;
2072
+ };
2073
+ /** Auto-initializes a PlaycademyClient with context from the environment */
2074
+ static init: typeof init;
2075
+ /** Authenticates a user with email and password */
2076
+ static login: typeof login;
2077
+ /** Static identity utilities for OAuth operations */
2078
+ static identity: {
2079
+ parseOAuthState: typeof parseOAuthState;
2080
+ };
2081
+ }
2082
+
1954
2083
  /**
1955
2084
  * Event and message payload types for SDK messaging system
1956
2085
  */
@@ -2059,6 +2188,42 @@ interface DemoEndPayload extends DemoEndOptions {
2059
2188
  }
2060
2189
  type TimebackHeartbeatRelayRequest = Omit<HeartbeatRequest, 'gameId' | 'studentId' | 'windowStartedAtMs' | 'windowSequence'> & {
2061
2190
  windowStartedAtMs: number;
2191
+ /**
2192
+ * Marks a closed heartbeat window from the child's 15s accounting
2193
+ * cadence: the window's totals are final, its key never recurs, and
2194
+ * the parent forwards it exactly once (retries are safe against the
2195
+ * server's first-write-wins window dedupe). Absent on the 1s display
2196
+ * snapshots of the still-open window.
2197
+ */
2198
+ windowClosed?: boolean;
2199
+ };
2200
+ /**
2201
+ * Wire payload for `PLAYCADEMY_CHECKPOINT`. An opaque snapshot of the
2202
+ * child game's internal state; the SDK and the parent never interpret
2203
+ * `state`. The parent stamps the resume envelope's `childRunId` from the
2204
+ * activity-start announcement, so the checkpoint itself carries no ids.
2205
+ */
2206
+ interface ChildCheckpointRelay {
2207
+ state: unknown;
2208
+ }
2209
+ /**
2210
+ * Wire payload for `PLAYCADEMY_TIMEBACK_ACTIVITY_START`. A child-mode game
2211
+ * announces that its tracker opened a run, so the parent can open its own
2212
+ * Timeback run at the moment the lesson actually begins.
2213
+ */
2214
+ type TimebackActivityStartRelay = Pick<TimebackHeartbeatRelayRequest, 'runId' | 'resumeId' | 'activityData'>;
2215
+ /**
2216
+ * Wire payload for `PLAYCADEMY_TIMEBACK_ACTIVITY_END`. The same end-activity
2217
+ * body a platform-mode game would POST to its backend, relayed to the parent
2218
+ * instead. `timingData.durationSeconds` is the full active sitting and
2219
+ * `sessionTimingData` carries the FULL session totals: a relayed window is
2220
+ * never marked persisted (a postMessage hand-off proves nothing about the
2221
+ * parent's POST), so the parent reconciles these totals against the windows
2222
+ * the server confirmed before reporting the completion's remainder.
2223
+ */
2224
+ type TimebackActivityEndRelay = Omit<EndActivityRequest, 'gameId' | 'studentId' | 'xpEarned'> & {
2225
+ /** The child's XP suggestion; the parent decides the actual award. */
2226
+ xpEarned?: number;
2062
2227
  };
2063
2228
 
2064
2229
  /**
@@ -2073,6 +2238,243 @@ interface GameTokenResponse {
2073
2238
  baseUrl?: string;
2074
2239
  }
2075
2240
 
2241
+ /**
2242
+ * Public types for the launch protocol's parent side: the embedded
2243
+ * child-game session behind `client.embed.launch()`. Only what `launch()`
2244
+ * callers touch lives here; the implementation and its constructor-side
2245
+ * plumbing contracts live in `core/launch/session.ts`.
2246
+ */
2247
+
2248
+ /**
2249
+ * How a child launch is recorded on this game's Timeback course.
2250
+ * The same metadata you would give `startActivity()` if your own document
2251
+ * were running the lesson: the embed session runs the whole
2252
+ * start-through-end lifecycle for you, stamped with this.
2253
+ */
2254
+ interface EmbedTimebackRecording {
2255
+ /** The activity on this game's own course the launch is recorded as. */
2256
+ activityId: string;
2257
+ /** Display name for dashboards; prettified from `activityId` when omitted. */
2258
+ activityName?: string;
2259
+ /** With `subject`, routes the recording to one of this game's courses. */
2260
+ grade: TimebackGrade;
2261
+ /** With `grade`, routes the recording to one of this game's courses. */
2262
+ subject: TimebackSubject;
2263
+ /** Course id hint, same semantics as `startActivity()`. */
2264
+ courseId?: string;
2265
+ }
2266
+ /**
2267
+ * Everything a parent needs to resume an interrupted launch later. The
2268
+ * parent persists this wherever the interruption demands (memory for
2269
+ * exit-and-return, localStorage for tab close, its backend KV for
2270
+ * cross-device) and hands it back via `embed.launch({ resume })`.
2271
+ */
2272
+ interface EmbedResumeEnvelope {
2273
+ /**
2274
+ * The child's opaque checkpoint state, exactly as it last reported
2275
+ * it. Never introspect it: only the child can interpret its own
2276
+ * state, and it validates the blob on the way back in.
2277
+ */
2278
+ state: unknown;
2279
+ /**
2280
+ * The child's own run id from the interrupted launch, when a run was
2281
+ * active. On resume it crosses to the child, whose SDK re-announces
2282
+ * it automatically at the next launch's first start; the announced match
2283
+ * is what makes reusing `parentRunId` safe.
2284
+ */
2285
+ childRunId?: string;
2286
+ /**
2287
+ * The interrupted platform run, when Timeback reporting was active.
2288
+ * Reused (with a fresh sitting id) only when the child accepts the
2289
+ * resume; otherwise a fresh run is minted.
2290
+ */
2291
+ parentRunId?: string;
2292
+ }
2293
+ /**
2294
+ * Custom persistence for resume envelopes, passed as `launch()`'s
2295
+ * `resume` option. The default (when `resume` is omitted) is a built-in
2296
+ * localStorage store keyed by user, parent game, child game, and the
2297
+ * intent's lesson identity; supply your own store to keep envelopes
2298
+ * elsewhere (for example your backend, for cross-device resume).
2299
+ */
2300
+ interface EmbedResumeStore {
2301
+ /**
2302
+ * Returns the stored envelope for this lesson identity, or
2303
+ * null/undefined when there is nothing to resume. May be async; the
2304
+ * boot waits for it before the child's INIT is sent.
2305
+ */
2306
+ load(): EmbedResumeEnvelope | null | undefined | Promise<EmbedResumeEnvelope | null | undefined>;
2307
+ /**
2308
+ * Persists the latest envelope. Called on every checkpoint the child
2309
+ * relays (envelopes are capped at 64KB) and again when run identity
2310
+ * is minted. Writes should be synchronous or fire-and-forget: the
2311
+ * SDK never blocks on them, and a throw costs that envelope's
2312
+ * persistence, never the launch. Returned promises are used only for
2313
+ * ordering: `save` and `clear` run strictly in call order, so a slow
2314
+ * async save cannot land after the completion's clear.
2315
+ */
2316
+ save(envelope: EmbedResumeEnvelope): void;
2317
+ /** Deletes the stored envelope. Called once when the launch completes. */
2318
+ clear(): void;
2319
+ }
2320
+ /**
2321
+ * Play-time totals for a child launch, measured by the child's own
2322
+ * tracker (the parent's document is idle while the student plays).
2323
+ */
2324
+ interface EmbedSessionTiming {
2325
+ /** Seconds of active play. */
2326
+ activeSeconds: number;
2327
+ /** Seconds the child's tracker classified as paused or inactive, when known. */
2328
+ inactiveSeconds?: number;
2329
+ }
2330
+ /**
2331
+ * The launch's activity record, resolved by `session.finished`.
2332
+ *
2333
+ * `'completed'` carries the child's report and the `end()` capability;
2334
+ * `'abandoned'` means the session ended first (child exit or `close()`);
2335
+ * `'failed'` means the launch never happened. Failure is a state to
2336
+ * render, not an exception to catch — `finished` never rejects.
2337
+ */
2338
+ type EmbedActivity = EmbedActivityCompleted | EmbedActivityAbandoned | EmbedActivityFailed;
2339
+ /** The child called `endActivity()` and its report was relayed. */
2340
+ interface EmbedActivityCompleted {
2341
+ status: 'completed';
2342
+ /** Correct answers, from the child's report. */
2343
+ correct: number;
2344
+ /** Total questions, from the child's report. */
2345
+ total: number;
2346
+ timing: EmbedSessionTiming;
2347
+ /**
2348
+ * The child's full relayed end-activity body: its own activity ids,
2349
+ * suggested XP, and extensions. Audit data — the parent decides what
2350
+ * actually reaches the platform, via `end()`.
2351
+ */
2352
+ childReport: TimebackActivityEndRelay;
2353
+ /**
2354
+ * Posts the launch's completion to the parent's own backend: the
2355
+ * parent-minted run id, the `timeback` recording, the caller's score
2356
+ * and XP decision, and the child's ids as audit extensions. Requires
2357
+ * the `timeback` option at launch. Calling twice returns the same
2358
+ * promise, so a launch can never double-report from the client.
2359
+ */
2360
+ end(scores: EndActivityScoreData): Promise<EndActivityResponse>;
2361
+ }
2362
+ /**
2363
+ * The session ended (child exit or `close()`) before a report arrived.
2364
+ * Played time has already reached the platform through forwarded
2365
+ * heartbeats; an abandoned launch leaves no completion, exactly like a
2366
+ * student wandering away from any other game.
2367
+ */
2368
+ interface EmbedActivityAbandoned {
2369
+ status: 'abandoned';
2370
+ timing: EmbedSessionTiming;
2371
+ /**
2372
+ * The final resume envelope, when the child checkpointed during the
2373
+ * launch. Persist it (see `EmbedResumeEnvelope`) and pass it back to
2374
+ * `embed.launch({ resume })` to pick the lesson up later. Absent
2375
+ * when the child never checkpointed.
2376
+ */
2377
+ resume?: EmbedResumeEnvelope;
2378
+ }
2379
+ /** The launch never happened: the child could not be resolved or booted. */
2380
+ interface EmbedActivityFailed {
2381
+ status: 'failed';
2382
+ /** Why — unknown slug, missing deployment URL, INIT error or timeout. */
2383
+ error: PlaycademyError;
2384
+ }
2385
+ /**
2386
+ * Handle for one embedded child-game session.
2387
+ */
2388
+ interface EmbedSession {
2389
+ /** The mounted child iframe. Useful for focus management. */
2390
+ readonly iframe: HTMLIFrameElement;
2391
+ /**
2392
+ * The latest resume envelope, live during play; null until the child
2393
+ * first checkpoints. Read it on your own cadence to persist
2394
+ * mid-lesson (for example a debounced upload to your backend), so a
2395
+ * closed tab can resume on another device.
2396
+ */
2397
+ readonly checkpoint: EmbedResumeEnvelope | null;
2398
+ /**
2399
+ * Resolves the launch's activity record when it ends — the
2400
+ * `animation.finished` idiom. Never rejects: operational failures
2401
+ * resolve as `{ status: 'failed', error }`.
2402
+ */
2403
+ readonly finished: Promise<EmbedActivity>;
2404
+ /**
2405
+ * Resolves when the session is torn down and the iframe is unmounted:
2406
+ * on child exit, `close()`, boot failure, or when the SDK detects the
2407
+ * iframe was removed from the DOM. `finished` can resolve earlier than
2408
+ * this (a completed child usually shows a results screen before
2409
+ * exiting), so use `closed` to dismiss surrounding UI.
2410
+ */
2411
+ readonly closed: Promise<void>;
2412
+ /**
2413
+ * Tears the session down: unmounts the iframe and stops all listeners.
2414
+ * Resolves a still-pending `finished` as `'abandoned'`. Safe to call
2415
+ * more than once. Calling it is the deterministic path; the SDK also
2416
+ * tears down when the child exits, and detects an iframe removed
2417
+ * without `close()` within ~5 seconds, so nothing leaks either way.
2418
+ */
2419
+ close(): void;
2420
+ }
2421
+
2422
+ /**
2423
+ * Options for `client.embed.launch()`.
2424
+ */
2425
+ interface EmbedLaunchOptions {
2426
+ /** Slug of the child game to launch. Resolved to a game id at launch time. */
2427
+ slug: string;
2428
+ /** Element the child iframe is mounted into. The iframe fills it. */
2429
+ container: HTMLElement;
2430
+ /**
2431
+ * What the child should deliver. This is the platform-defined
2432
+ * {@link LaunchIntent} contract; it crosses the iframe in the INIT
2433
+ * payload's `parent` block and surfaces in the child as `client.parent.intent`.
2434
+ */
2435
+ intent: LaunchIntent;
2436
+ /**
2437
+ * Whether and how an interrupted launch can resume.
2438
+ *
2439
+ * Omitted (the default): the SDK persists the child's latest
2440
+ * checkpoint in localStorage, keyed by user, this game, the child,
2441
+ * and the intent's lesson identity. The next launch with the same
2442
+ * identity resumes automatically; completion clears the entry. Inert
2443
+ * for children that never call `client.parent.checkpoint()`.
2444
+ *
2445
+ * `false`: no persistence and no automatic resume. The manual surface
2446
+ * (`session.checkpoint`, the abandoned outcome's `resume`) still works.
2447
+ *
2448
+ * An {@link EmbedResumeEnvelope}: fully manual, one-shot. The launch
2449
+ * resumes from exactly this envelope and nothing is persisted.
2450
+ *
2451
+ * An {@link EmbedResumeStore}: delegate persistence (for example to
2452
+ * your backend, for cross-device resume).
2453
+ *
2454
+ * Whatever the policy, the child receives only the opaque `state`
2455
+ * (as `client.parent.resume`) and decides whether to use it; run ids
2456
+ * stay parent-side and drive run continuity when the child accepts.
2457
+ */
2458
+ resume?: false | EmbedResumeEnvelope | EmbedResumeStore;
2459
+ /**
2460
+ * Records the launch on this game's Timeback course: the metadata
2461
+ * you would have given `startActivity()` if your own document were
2462
+ * running the lesson. Stays in the parent SDK, stamping every
2463
+ * forwarded heartbeat and the final completion; it never crosses the
2464
+ * iframe. Omit for a pure UX embed.
2465
+ */
2466
+ timeback?: EmbedTimebackRecording;
2467
+ /**
2468
+ * Overrides the child's resolved deployment URL. Intended for local
2469
+ * development, where the child runs on a dev server the platform
2470
+ * doesn't know about. With `gameUrl` set, a slug that fails to
2471
+ * resolve degrades to a warning (the slug stands in as the child's
2472
+ * game id) instead of failing the launch, so an unregistered child
2473
+ * still launches locally.
2474
+ */
2475
+ gameUrl?: string;
2476
+ }
2477
+
2076
2478
  /**
2077
2479
  * Scores namespace types
2078
2480
  */
@@ -2269,4 +2671,4 @@ interface PlatformTimebackUser extends PlatformTimebackUserContext {
2269
2671
  }
2270
2672
 
2271
2673
  export { PlaycademyClient };
2272
- export type { AuthCallbackPayload, AuthOptions, AuthProviderType, AuthResult, AuthServerMessage, AuthStateChangePayload, AuthStateUpdate, BetterAuthApiKey, BetterAuthApiKeyResponse, BetterAuthSignInResponse, BucketFile, ClientConfig, ClientEvents, CourseMastery, CourseXp, DemoEndOptions, DemoEndPayload, DevUploadEvent, DevUploadHooks, EventListeners, ExternalGame, FetchedGame, Game, GameContextPayload, GameCustomHostname, GameInitUser, GameRow as GameRecord, GameTokenResponse, GetHighestGradeMasteredOptions, GetMasteryOptions, GetXpOptions, HighestGradeMasteredResponse, HostedGame, InitErrorPayload, InitPayload, KVKeyEntry, KVKeyMetadata, KVSeedEntry, KVStatsResponse, KeyEventPayload, LoginResponse, MasteryResponse, PlatformTimebackUser, PlatformTimebackUserContext, PlaycademyMode, PlaycademyServerClientConfig, PlaycademyServerClientState, ScoreSubmission, StartActivityOptions, StartActivityResult, TelemetryPayload, TimebackEnrollment, TimebackHeartbeatRelayRequest, TimebackInitContext, TimebackOrganization, TimebackUser, TimebackUserContext, TimebackUserHighestGradeMastered, TimebackUserMastery, TimebackUserRefreshField, TimebackUserRefreshOptions, TimebackUserXp, TokenRefreshPayload, TokenType, UpsertGameMetadataInput, UserRow as User, XpResponse };
2674
+ export type { AuthCallbackPayload, AuthOptions, AuthProviderType, AuthResult, AuthServerMessage, AuthStateChangePayload, AuthStateUpdate, BetterAuthApiKey, BetterAuthApiKeyResponse, BetterAuthSignInResponse, BucketFile, ChildCheckpointRelay, ClientConfig, ClientEvents, CourseMastery, CourseXp, DemoEndOptions, DemoEndPayload, DevUploadEvent, DevUploadHooks, EmbedActivity, EmbedActivityAbandoned, EmbedActivityCompleted, EmbedActivityFailed, EmbedLaunchOptions, EmbedResumeEnvelope, EmbedResumeStore, EmbedSession, EmbedSessionTiming, EmbedTimebackRecording, EventListeners, ExternalGame, FetchedGame, Game, GameContextPayload, GameCustomHostname, GameInitUser, GameRow as GameRecord, GameTokenResponse, GetHighestGradeMasteredOptions, GetMasteryOptions, GetXpOptions, HighestGradeMasteredResponse, HostedGame, InitErrorPayload, InitPayload, KVKeyEntry, KVKeyMetadata, KVSeedEntry, KVStatsResponse, KeyEventPayload, LaunchIntent, LoginResponse, MasteryResponse, ParentGameContext, ParentGameHandle, PlatformTimebackUser, PlatformTimebackUserContext, PlaycademyMode, PlaycademyServerClientConfig, PlaycademyServerClientState, ScoreSubmission, StartActivityOptions, StartActivityResult, TelemetryPayload, TimebackActivityEndRelay, TimebackActivityStartRelay, TimebackEnrollment, TimebackHeartbeatRelayRequest, TimebackInitContext, TimebackOrganization, TimebackUser, TimebackUserContext, TimebackUserHighestGradeMastered, TimebackUserMastery, TimebackUserRefreshField, TimebackUserRefreshOptions, TimebackUserXp, TokenRefreshPayload, TokenType, UpsertGameMetadataInput, UserRow as User, XpResponse };