@playcademy/sdk 0.16.0 → 0.16.1-beta.10

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,9 +1,10 @@
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
- import { AUTH_PROVIDER_IDS } from '@playcademy/constants';
7
+ import { GamePermission, AUTH_PROVIDER_IDS } from '@playcademy/constants';
7
8
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
8
9
  import { DomainValidationRecords } from '@playcademy/types/game';
9
10
  import { z } from 'zod';
@@ -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.
@@ -345,6 +374,13 @@ interface PlaycademyConfig {
345
374
  description?: string;
346
375
  /** Game emoji icon */
347
376
  emoji?: string;
377
+ /**
378
+ * Browser permissions to request for the game's iframe (e.g.
379
+ * `['microphone']`). Opt-in per game; only `microphone` and `camera` are
380
+ * delegated this way. Fullscreen, autoplay, and gamepad are granted to
381
+ * every game automatically.
382
+ */
383
+ permissions?: GamePermission[];
348
384
  /** Build command to run before deployment */
349
385
  buildCommand?: string[];
350
386
  /** Path to build output */
@@ -679,6 +715,8 @@ declare const users: drizzle_orm_pg_core.PgTableWithColumns<{
679
715
  interface GameMetadata {
680
716
  description?: string;
681
717
  emoji?: string;
718
+ /** Browser permissions delegated to the game's iframe (opt-in per game). */
719
+ permissions?: GamePermission[];
682
720
  [key: string]: unknown;
683
721
  }
684
722
  /**
@@ -1228,6 +1266,8 @@ declare abstract class PlaycademyBaseClient {
1228
1266
  isInIframe: boolean;
1229
1267
  };
1230
1268
  protected initPayload?: InitPayload;
1269
+ /** Memoized `client.parent` handle; built on first access in child mode. */
1270
+ private parentHandle?;
1231
1271
  protected launchId?: string;
1232
1272
  protected gameOrigin?: string;
1233
1273
  private browserTimeZone?;
@@ -1248,6 +1288,13 @@ declare abstract class PlaycademyBaseClient {
1248
1288
  * Local day context supplied by the platform during iframe initialization.
1249
1289
  */
1250
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;
1251
1298
  /**
1252
1299
  * Sets the authentication token for API requests.
1253
1300
  */
@@ -1394,146 +1441,14 @@ declare function init<T extends PlaycademyBaseClient = PlaycademyBaseClient>(thi
1394
1441
  declare function login(baseUrl: string, email: string, password: string): Promise<LoginResponse>;
1395
1442
 
1396
1443
  /**
1397
- * Playcademy SDK client for game developers.
1398
- * 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.
1399
1447
  */
1400
- declare class PlaycademyClient extends PlaycademyBaseClient {
1401
- /**
1402
- * Connect external identity providers to the user's Playcademy account.
1403
- * - `connect(provider)` - Link Discord, Google, etc. via OAuth popup
1404
- */
1405
- identity: {
1406
- connect: (options: AuthOptions) => Promise<AuthResult>;
1407
- _getContext: () => {
1408
- isInIframe: boolean;
1409
- };
1410
- };
1411
- /**
1412
- * Game runtime lifecycle and asset loading.
1413
- * - `exit()` - Return to Cademy hub
1414
- * - `getGameToken()` - Get short-lived auth token
1415
- * - `assets.url()`, `assets.json()`, `assets.fetch()` - Load game assets
1416
- * - `on('pause')`, `on('resume')` - Handle visibility changes
1417
- */
1418
- runtime: {
1419
- exit: () => void;
1420
- onInit: (handler: (context: GameContextPayload) => void) => void;
1421
- onTokenRefresh: (handler: (data: {
1422
- token: string;
1423
- exp: number;
1424
- }) => void) => void;
1425
- onPause: (handler: () => void) => void;
1426
- onResume: (handler: () => void) => void;
1427
- onForceExit: (handler: () => void) => void;
1428
- onOverlay: (handler: (isVisible: boolean) => void) => void;
1429
- ready: () => void;
1430
- sendTelemetry: (data: {
1431
- fps: number;
1432
- mem: number;
1433
- }) => void;
1434
- removeListener: (eventType: MessageEvents, handler: ((context: GameContextPayload) => void) | ((data: {
1435
- token: string;
1436
- exp: number;
1437
- }) => void) | (() => void) | ((isVisible: boolean) => void)) => void;
1438
- removeAllListeners: () => void;
1439
- getListenerCounts: () => Record<string, number>;
1440
- assets: {
1441
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1442
- fetch: (path: string, options?: RequestInit) => Promise<Response>;
1443
- json: <T = unknown>(path: string) => Promise<T>;
1444
- blob: (path: string) => Promise<Blob>;
1445
- text: (path: string) => Promise<string>;
1446
- arrayBuffer: (path: string) => Promise<ArrayBuffer>;
1447
- };
1448
- };
1449
- /**
1450
- * TimeBack integration for activity tracking and user context.
1451
- *
1452
- * User context (cached from init, refreshable):
1453
- * - `user.role` - User's role (student, parent, teacher, etc.)
1454
- * - `user.enrollments` - Courses the player is enrolled in for this game
1455
- * - `user.refresh({ only: ['enrollments'] })` - Refresh enrollments from server
1456
- * - `user.organizations` - Schools/districts the player belongs to
1457
- * - `user.fetch()` - Refresh user context from server
1458
- *
1459
- * Activity tracking:
1460
- * - `currentRunId` - Current activity run ID, or undefined when inactive
1461
- * - `startActivity(metadata)` - Begin tracking an activity, return its run
1462
- * ID, and automatically handle hidden-tab and visible-tab inactivity
1463
- * with configurable paused-heartbeat timeout behavior
1464
- * - `pauseActivity()` / `resumeActivity()` - Pause/resume timer
1465
- * - `endActivity(scoreData)` - Submit activity results to TimeBack
1466
- */
1467
- timeback: {
1468
- readonly user: TimebackUser;
1469
- readonly currentRunId: string | undefined;
1470
- startActivity: (metadata: _playcademy_types.ActivityData, options?: StartActivityOptions) => StartActivityResult;
1471
- pauseActivity: () => void;
1472
- resumeActivity: () => void;
1473
- endActivity: (data: _playcademy_types.EndActivityScoreData) => Promise<_playcademy_types.EndActivityResponse>;
1474
- course: {
1475
- advance: (options?: {
1476
- subject?: _playcademy_types.TimebackSubject;
1477
- }) => Promise<_playcademy_types.AdvanceCourseResponse>;
1478
- unenroll: (options?: {
1479
- subject?: _playcademy_types.TimebackSubject;
1480
- force?: boolean;
1481
- }) => Promise<_playcademy_types.UnenrollCourseResponse>;
1482
- };
1483
- };
1484
- /**
1485
- * Game score submission and leaderboards.
1486
- * - `submit(score, metadata?)` - Record a game score
1487
- */
1488
- scores: {
1489
- submit: (score: number, metadata?: Record<string, unknown>) => Promise<ScoreSubmission>;
1490
- };
1491
- /**
1492
- * Read-only leaderboard access for the current game scope.
1493
- * - `fetch(options?)` - Fetch leaderboard entries
1494
- */
1495
- leaderboard: {
1496
- fetch: (options?: _playcademy_types.LeaderboardOptions) => Promise<_playcademy_types.GameLeaderboardEntry[]>;
1497
- };
1498
- /**
1499
- * Demo-mode helpers. Methods throw when called outside `client.mode === 'demo'`,
1500
- * so callers should gate on the mode before reaching in.
1501
- * - `profile.get()` - Read the anonymous demo player's profile
1502
- * - `profile.update(updates)` - Update the demo player's profile (today: the required `displayName`)
1503
- * - `end(score, options?)` - Signal to the parent shell that the demo has ended
1504
- */
1505
- demo: {
1506
- profile: {
1507
- get: () => Promise<_playcademy_types.DemoProfile>;
1508
- update: (updates: _playcademy_types.DemoProfileUpdate) => Promise<_playcademy_types.DemoProfile>;
1509
- };
1510
- end: (score: number, options?: DemoEndOptions) => void;
1511
- };
1512
- /**
1513
- * Make requests to your game's custom backend API routes.
1514
- * - `get(path)`, `post(path, body)`, `put()`, `delete()` - HTTP methods
1515
- * - Routes are relative to your game's deployment (e.g., '/hello' → your-game.playcademy.gg/api/hello)
1516
- */
1517
- backend: {
1518
- get<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1519
- post<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1520
- put<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1521
- patch<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1522
- delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1523
- request<T = unknown>(path: string, method: Method, body?: unknown, headers?: Record<string, string>): Promise<T>;
1524
- download(path: string, method?: Method, body?: unknown, headers?: Record<string, string>): Promise<Response>;
1525
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1526
- };
1527
- /** Auto-initializes a PlaycademyClient with context from the environment */
1528
- static init: typeof init;
1529
- /** Authenticates a user with email and password */
1530
- static login: typeof login;
1531
- /** Static identity utilities for OAuth operations */
1532
- static identity: {
1533
- parseOAuthState: typeof parseOAuthState;
1534
- };
1448
+ interface RelayedEndActivityResult {
1449
+ status: 'relayed';
1450
+ runId: string;
1535
1451
  }
1536
-
1537
1452
  /**
1538
1453
  * Options for configuring activity tracking behavior.
1539
1454
  */
@@ -1871,8 +1786,79 @@ type TokenType = 'session' | 'apiKey' | 'gameJwt';
1871
1786
  * - `'standalone'` — game is running outside any iframe (e.g. `bun run dev`
1872
1787
  * or direct-deploy preview) with a mock token and no real platform
1873
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.
1794
+ */
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/`).
1874
1839
  */
1875
- type PlaycademyMode = 'platform' | 'demo' | 'standalone';
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
+ }
1876
1862
  interface ClientConfig {
1877
1863
  baseUrl: string;
1878
1864
  gameUrl?: string;
@@ -1901,6 +1887,8 @@ interface InitPayload {
1901
1887
  launchId?: string;
1902
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`. */
1903
1889
  hasHeartbeatRelay?: boolean;
1890
+ /** Parent game context. Present only when `mode` is `'child'`. */
1891
+ parent?: ParentGameContext;
1904
1892
  }
1905
1893
  /**
1906
1894
  * Simplified user data passed to games via InitPayload
@@ -1935,6 +1923,163 @@ interface ClientEvents {
1935
1923
  };
1936
1924
  }
1937
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
+
1938
2083
  /**
1939
2084
  * Event and message payload types for SDK messaging system
1940
2085
  */
@@ -2043,6 +2188,42 @@ interface DemoEndPayload extends DemoEndOptions {
2043
2188
  }
2044
2189
  type TimebackHeartbeatRelayRequest = Omit<HeartbeatRequest, 'gameId' | 'studentId' | 'windowStartedAtMs' | 'windowSequence'> & {
2045
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;
2046
2227
  };
2047
2228
 
2048
2229
  /**
@@ -2057,6 +2238,243 @@ interface GameTokenResponse {
2057
2238
  baseUrl?: string;
2058
2239
  }
2059
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
+
2060
2478
  /**
2061
2479
  * Scores namespace types
2062
2480
  */
@@ -2160,6 +2578,29 @@ interface BucketFile {
2160
2578
  lastModified: string;
2161
2579
  contentType?: string;
2162
2580
  }
2581
+ /**
2582
+ * Options for a single-page bucket listing
2583
+ */
2584
+ interface BucketListPageOptions {
2585
+ /** Restrict results to keys starting with this prefix */
2586
+ prefix?: string;
2587
+ /** Opaque continuation cursor from the previous page's result */
2588
+ cursor?: string;
2589
+ /** Page size (1-1000); the server may return fewer */
2590
+ limit?: number;
2591
+ /** Roll deeper keys into `prefixes` entries, S3 delimiter style */
2592
+ delimiter?: string;
2593
+ }
2594
+ /**
2595
+ * One page of a bucket listing
2596
+ */
2597
+ interface BucketFilePage {
2598
+ files: BucketFile[];
2599
+ /** Rolled-up common prefixes; present for delimiter listings that found any */
2600
+ prefixes?: string[];
2601
+ /** Present only when more pages remain */
2602
+ cursor?: string;
2603
+ }
2163
2604
  /**
2164
2605
  * KV key entry
2165
2606
  */
@@ -2253,4 +2694,4 @@ interface PlatformTimebackUser extends PlatformTimebackUserContext {
2253
2694
  }
2254
2695
 
2255
2696
  export { PlaycademyClient };
2256
- 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 };
2697
+ export type { AuthCallbackPayload, AuthOptions, AuthProviderType, AuthResult, AuthServerMessage, AuthStateChangePayload, AuthStateUpdate, BetterAuthApiKey, BetterAuthApiKeyResponse, BetterAuthSignInResponse, BucketFile, BucketFilePage, BucketListPageOptions, 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 };