@oasiz/sdk 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,92 +1,157 @@
1
- # @oasiz/sdk
1
+ # Oasiz game SDKs
2
2
 
3
- Typed SDK for integrating games with the Oasiz platform. Handles score submission, haptic feedback, cross-session state persistence, multiplayer room codes, navigation hooks, and app lifecycle events for local development.
3
+ Games on Oasiz can integrate using either of these official SDKs:
4
4
 
5
- ## Install
5
+ | Platform | Package | Use for |
6
+ | --- | --- | --- |
7
+ | **HTML5 / TypeScript** | [`@oasiz/sdk`](#html5--typescript-oasizsdk) (npm) | Canvas, Phaser, custom JS/TS, any browser game |
8
+ | **Unity WebGL** | [Unity runtime](#unity-webgl-sdk) in this repo (`packages/OasizSDK/`) | Unity projects targeting WebGL |
9
+
10
+ Both talk to the same host bridges (`window.submitScore`, `__oasizLeaveGame`, layout APIs, custom DOM events such as `oasiz:pause`, etc.). Unsupported hosts no-op safely; local dev usually logs warnings instead of crashing.
11
+
12
+ ---
13
+
14
+ ## HTML5 / TypeScript (`@oasiz/sdk`)
15
+
16
+ Typed SDK for integrating browser games with the Oasiz platform: score, haptics, cross-session state, multiplayer hooks, layout (safe area, leaderboard visibility), graphics performance, navigation (back / leave), and lifecycle events.
17
+
18
+ ### Install
6
19
 
7
20
  ```bash
8
- npm install @oasiz/sdk@^0.1.0
21
+ npm install @oasiz/sdk
9
22
  ```
10
23
 
24
+ The published package includes ESM, CommonJS, and TypeScript declarations.
25
+
11
26
  ## Quick start
12
27
 
13
28
  ```ts
14
29
  import { oasiz } from "@oasiz/sdk";
15
30
 
16
- // 1. Emit score normalization config once on init
17
- oasiz.emitScoreConfig({
18
- anchors: [
19
- { raw: 30, normalized: 100 },
20
- { raw: 60, normalized: 300 },
21
- { raw: 120, normalized: 600 },
22
- { raw: 300, normalized: 950 },
23
- ],
24
- });
31
+ // 0. Optional local app preview for web development
32
+ if (import.meta.env.DEV) {
33
+ oasiz.enableAppSimulator();
34
+ }
25
35
 
26
- // 2. Load persisted state at the start of each session
36
+ // 1. Load persisted state at the start of each session
27
37
  const state = oasiz.loadGameState();
28
38
  let level = typeof state.level === "number" ? state.level : 1;
29
39
 
30
- // 3. Save state at checkpoints
40
+ // 2. Save state at checkpoints
31
41
  oasiz.saveGameState({ level, coins: 42 });
32
42
 
33
- // 4. Trigger haptics on key events
43
+ // 3. Trigger haptics on key events
34
44
  oasiz.triggerHaptic("medium");
35
45
 
36
- // 5. Submit score when the game ends
46
+ // 4. Respect the host's top safe area (percent of viewport height → CSS vh)
47
+ document.documentElement.style.setProperty(
48
+ "--safe-top",
49
+ `${oasiz.safeAreaTop}vh`,
50
+ );
51
+
52
+ // 5. Pick graphics settings for this device
53
+ const graphics = oasiz.getGraphicsPerformance();
54
+ renderer.setPixelRatio(graphics.tier === "high" ? 1.5 : graphics.tier === "medium" ? 1.25 : 1);
55
+
56
+ // 6. Submit score when the game ends
37
57
  oasiz.submitScore(score);
38
- ```
39
58
 
40
- ---
59
+ // 7. Optionally hide the leaderboard while a custom overlay is open
60
+ oasiz.setLeaderboardVisible(false);
61
+
62
+ // 8. Optionally surface console logs in-game while debugging
63
+ oasiz.enableLogOverlay({
64
+ enabled: new URLSearchParams(window.location.search).has("oasizLogs"),
65
+ collapsed: true,
66
+ });
67
+ ```
41
68
 
42
- ## Score
69
+ ### Local app simulator
43
70
 
44
- ### `oasiz.submitScore(score: number)`
71
+ #### `oasiz.enableAppSimulator(options?: AppSimulatorOptions): AppSimulatorHandle`
45
72
 
46
- Submit the player's final score at game over. Call this exactly once per session, when the game ends. The platform handles leaderboard persistence do not track high scores locally.
73
+ Opt-in local web helper for previewing a game inside Oasiz-style mobile chrome. It simulates the app back button, leaderboard pill, like/comment hub, comments modal, and leaderboard modal while also injecting local safe-area and viewport-inset bridge values.
47
74
 
48
75
  ```ts
49
- private onGameOver(): void {
50
- oasiz.submitScore(Math.floor(this.score));
76
+ if (import.meta.env.DEV) {
77
+ oasiz.enableAppSimulator();
51
78
  }
52
- ```
53
79
 
54
- - `score` must be a non-negative integer. Floats are floored automatically.
55
- - Do not call on intermediate scores or level completions, only on final game over.
56
-
57
- ---
58
-
59
- ### `oasiz.emitScoreConfig(config)`
80
+ oasiz.onBackButton(() => {
81
+ togglePauseMenu();
82
+ });
83
+ ```
60
84
 
61
- Maps raw score values to the platform's normalized 0–1000 scale. Call once during initialization, not every frame.
85
+ By default, the game is placed inside a centered phone-sized box so developers can resize their browser around the same shape the app uses. The default device is `iphone-17-pro-max` (`440 × 956` CSS pixels). You can change the preview:
62
86
 
63
87
  ```ts
64
- oasiz.emitScoreConfig({
65
- anchors: [
66
- { raw: 10, normalized: 100 }, // beginner
67
- { raw: 30, normalized: 300 }, // good
68
- { raw: 75, normalized: 600 }, // great
69
- { raw: 200, normalized: 950 }, // godlike
70
- ],
88
+ const appPreview = oasiz.enableAppSimulator({
89
+ device: "iphone-17-pro-max",
90
+ likes: 2400,
91
+ comments: 18,
92
+ score: 12400,
71
93
  });
94
+
95
+ debugCommentsButton.onclick = () => appPreview.openComments();
96
+ debugLeaderboardButton.onclick = () => appPreview.openLeaderboard();
72
97
  ```
73
98
 
74
- **Anchor rules:**
75
- - Exactly 4 anchors required.
76
- - `raw` values must be strictly increasing.
77
- - `normalized` values must end at exactly `950`.
78
- - Choose thresholds based on realistic player skill bands.
99
+ Set `frame: false` if your own dev harness already renders the game in a phone frame.
100
+
101
+ The simulator includes the back-button test bridge, so Escape, browser Back, and the simulated app back button all route through the same `oasiz.onBackButton(...)` handler when back override is active. Use `enableBackButtonTesting()` directly only when you want back simulation without app chrome.
102
+
103
+ Supported `device` presets:
104
+
105
+ | Device option | CSS viewport |
106
+ | --- | --- |
107
+ | `iphone-11` | `414 × 896` |
108
+ | `iphone-11-pro` | `375 × 812` |
109
+ | `iphone-11-pro-max` | `414 × 896` |
110
+ | `iphone-12-mini` | `375 × 812` |
111
+ | `iphone-12` | `390 × 844` |
112
+ | `iphone-12-pro` | `390 × 844` |
113
+ | `iphone-12-pro-max` | `428 × 926` |
114
+ | `iphone-13-mini` | `375 × 812` |
115
+ | `iphone-13` | `390 × 844` |
116
+ | `iphone-13-pro` | `390 × 844` |
117
+ | `iphone-13-pro-max` | `428 × 926` |
118
+ | `iphone-14` | `390 × 844` |
119
+ | `iphone-14-plus` | `428 × 926` |
120
+ | `iphone-14-pro` | `393 × 852` |
121
+ | `iphone-14-pro-max` | `430 × 932` |
122
+ | `iphone-15` | `393 × 852` |
123
+ | `iphone-15-plus` | `430 × 932` |
124
+ | `iphone-15-pro` | `393 × 852` |
125
+ | `iphone-15-pro-max` | `430 × 932` |
126
+ | `iphone-16` | `393 × 852` |
127
+ | `iphone-16-plus` | `430 × 932` |
128
+ | `iphone-16-pro` | `402 × 874` |
129
+ | `iphone-16-pro-max` | `440 × 956` |
130
+ | `iphone-16e` | `390 × 844` |
131
+ | `iphone-17` | `402 × 874` |
132
+ | `iphone-17-pro` | `402 × 874` |
133
+ | `iphone-17-pro-max` | `440 × 956` |
134
+ | `iphone-17e` | `390 × 844` |
135
+ | `iphone-air` | `420 × 912` |
136
+
137
+ ### Score
138
+
139
+ #### `oasiz.submitScore(score: number)`
79
140
 
80
- **Practical guidance by game type:**
81
- - Survival / time games → use seconds survived as `raw`
82
- - Score accumulation games → use points as `raw`
83
- - Puzzle games → use level reached or stars earned as `raw`
141
+ Submit the player's final score at game over. Call this exactly once per session, when the game ends. The platform handles leaderboard persistence — do not track high scores locally.
84
142
 
85
- ---
143
+ ```ts
144
+ private onGameOver(): void {
145
+ oasiz.submitScore(Math.floor(this.score));
146
+ }
147
+ ```
148
+
149
+ - `score` must be a non-negative integer. Floats are floored automatically.
150
+ - Do not call on intermediate scores or level completions, only on final game over.
86
151
 
87
- ## Haptics
152
+ ### Haptics
88
153
 
89
- ### `oasiz.triggerHaptic(type: HapticType)`
154
+ #### `oasiz.triggerHaptic(type: HapticType)`
90
155
 
91
156
  Trigger native haptic feedback. Always guard with the user's haptics setting.
92
157
 
@@ -95,7 +160,7 @@ type HapticType = "light" | "medium" | "heavy" | "success" | "error";
95
160
  ```
96
161
 
97
162
  | Type | When to use |
98
- |---|---|
163
+ | --- | --- |
99
164
  | `"light"` | UI button taps, menu navigation, D-pad press |
100
165
  | `"medium"` | Collecting items, standard collisions, scoring |
101
166
  | `"heavy"` | Explosions, major impacts, screen shake |
@@ -126,20 +191,45 @@ private onGameOver(): void {
126
191
 
127
192
  Haptics are throttled internally (50ms cooldown) to prevent spam.
128
193
 
129
- ---
194
+ ### Debugging
195
+
196
+ #### `oasiz.enableLogOverlay(options?: LogOverlayOptions)`
197
+
198
+ Mount an opt-in in-game console viewer for local debugging, QA sessions, or creator support. It mirrors `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` into a floating overlay inside the game iframe. The overlay can be collapsed, repositioned by dragging the top bar, and resized from the bottom-right corner while the action buttons remain clickable.
130
199
 
131
- ## Game state persistence
200
+ ```ts
201
+ const logOverlay = oasiz.enableLogOverlay({
202
+ enabled: new URLSearchParams(window.location.search).has("oasizLogs"),
203
+ collapsed: true,
204
+ });
205
+
206
+ console.log("[Boot] Scene ready");
207
+
208
+ // Optional cleanup if your game tears down and remounts
209
+ logOverlay.destroy();
210
+ ```
211
+
212
+ Options:
213
+
214
+ - `enabled`: defaults to `true`. Pass your own flag or query-param check here.
215
+ - `collapsed`: start with only the toggle pill visible.
216
+ - `maxEntries`: cap retained log lines. Defaults to `200`.
217
+ - `title`: optional label shown at the top of the panel. Defaults to `SDK Logs`.
218
+
219
+ The returned handle supports `show()`, `hide()`, `clear()`, `isVisible()`, and `destroy()`.
220
+
221
+ ### Game state persistence
132
222
 
133
223
  Persist cross-session data such as unlocked levels, inventory, or lifetime stats. State is stored per-user per-game in the Oasiz backend — available across devices and app reinstalls.
134
224
 
135
- ### `oasiz.loadGameState(): Record<string, unknown>`
225
+ #### `oasiz.loadGameState(): Record<string, unknown>`
136
226
 
137
227
  Returns the player's saved state synchronously. Returns `{}` if no state has been saved yet. Call once at the start of the game.
138
228
 
139
229
  ```ts
140
230
  private initFromSavedState(): void {
141
231
  const state = oasiz.loadGameState();
142
- this.level = typeof state.level === "number" ? state.level : 1;
232
+ this.level = typeof state.level === "number" ? state.level : 1;
143
233
  this.lifetimeHits = typeof state.lifetimeHits === "number" ? state.lifetimeHits : 0;
144
234
  this.unlockedSkins = Array.isArray(state.unlockedSkins) ? state.unlockedSkins : [];
145
235
  }
@@ -147,7 +237,7 @@ private initFromSavedState(): void {
147
237
 
148
238
  Always validate the shape of loaded data — it may be `{}` on first play.
149
239
 
150
- ### `oasiz.saveGameState(state: Record<string, unknown>)`
240
+ #### `oasiz.saveGameState(state: Record<string, unknown>)`
151
241
 
152
242
  Queues a debounced save. Saves are batched automatically — call freely at checkpoints without worrying about request spam.
153
243
 
@@ -164,11 +254,12 @@ private onLevelComplete(): void {
164
254
  ```
165
255
 
166
256
  **Rules:**
257
+
167
258
  - State must be a plain JSON object (not an array or primitive).
168
259
  - Do not use `localStorage` for cross-session progress — use `saveGameState` so data syncs across platforms.
169
260
  - Do not store scores here — scores are submitted via `submitScore`.
170
261
 
171
- ### `oasiz.flushGameState()`
262
+ #### `oasiz.flushGameState()`
172
263
 
173
264
  Forces an immediate write, bypassing the debounce. Use at important checkpoints like game over or before the page unloads.
174
265
 
@@ -180,19 +271,122 @@ private onGameOver(): void {
180
271
  }
181
272
  ```
182
273
 
183
- ---
274
+ ### Layout
275
+
276
+ Use runtime viewport insets instead of direct CSS `env(safe-area-inset-*)` reads or hardcoded offsets. The SDK resolves host-provided Oasiz values first, then browser CSS `env(safe-area-inset-*)`, then legacy `constant(safe-area-inset-*)`, and finally `0`.
277
+
278
+ The top inset preserves the existing Oasiz game-safe top behavior: host chrome, invite UI, and leaderboard clearance can contribute to it. Left, right, and bottom are device safe-area insets today and may include future host UI obstructions.
279
+
280
+ #### `oasiz.getViewportInsets(): ViewportInsets`
281
+
282
+ Returns effective viewport insets in both CSS pixels and normalized percentages:
283
+
284
+ ```ts
285
+ const insets = oasiz.getViewportInsets();
286
+ hud.style.paddingTop = `${insets.pixels.top}px`;
287
+ hud.style.paddingRight = `${insets.pixels.right}px`;
288
+ hud.style.paddingBottom = `${insets.pixels.bottom}px`;
289
+ hud.style.paddingLeft = `${insets.pixels.left}px`;
290
+ ```
291
+
292
+ Percentages use the matching active viewport axis:
293
+
294
+ - `top` / `bottom` are percentages of viewport height
295
+ - `left` / `right` are percentages of viewport width
296
+
297
+ Hosts may expose pixels via `window.getViewportInsets()` or `window.__OASIZ_VIEWPORT_INSETS__`, for example `{ top, right, bottom, left }` or `{ pixels: { top, right, bottom, left } }`. Hosts may expose percentages via `window.getViewportInsetsPercent()`, `window.__OASIZ_VIEWPORT_INSETS_PERCENT__`, or a `percent` object. Per-side globals such as `window.__OASIZ_SAFE_AREA_BOTTOM__` are also supported.
298
+
299
+ #### `oasiz.getSafeAreaTop(): number`
300
+
301
+ Legacy alias for `oasiz.getViewportInsets().percent.top`. Returns the top inset as a percentage of viewport height (0–100). To get pixels in JavaScript, prefer `oasiz.getViewportInsets().pixels.top`. In CSS, the percent value matches **`vh`** units (for example `12.5vh` for 12.5% of the viewport height). Unsupported hosts return `0`.
302
+
303
+ ```ts
304
+ const safeTopPct = oasiz.getSafeAreaTop();
305
+ document.documentElement.style.setProperty("--safe-top", `${safeTopPct}vh`);
306
+ ```
307
+
308
+ #### `oasiz.safeAreaTop`
309
+
310
+ Getter alias for `getSafeAreaTop()`.
311
+
312
+ #### `oasiz.viewportInsets`
313
+
314
+ Getter alias for `getViewportInsets()`.
315
+
316
+ Recommended CSS pattern:
317
+
318
+ ```css
319
+ :root {
320
+ --safe-top: 0px;
321
+ }
322
+
323
+ #top-bar {
324
+ padding-top: var(--safe-top);
325
+ }
326
+ ```
327
+
328
+ #### `oasiz.setLeaderboardVisible(visible: boolean): void`
329
+
330
+ Show or hide the host leaderboard UI from inside the game. This only affects the leaderboard; back and social controls remain visible. Calls `window.__oasizSetLeaderboardVisible` when present.
331
+
332
+ ```ts
333
+ function openCustomOverlay(): void {
334
+ oasiz.setLeaderboardVisible(false);
335
+ }
336
+
337
+ function closeCustomOverlay(): void {
338
+ oasiz.setLeaderboardVisible(true);
339
+ }
340
+ ```
184
341
 
185
- ## Lifecycle
342
+ Unsupported hosts safely no-op.
343
+
344
+ ### Graphics performance
345
+
346
+ #### `oasiz.getGraphicsPerformance(): GraphicsPerformanceMetric`
347
+
348
+ Returns a recommended FPS target and suggested rendering tier:
349
+
350
+ ```ts
351
+ const graphics = oasiz.getGraphicsPerformance();
352
+
353
+ switch (graphics.tier) {
354
+ case "high":
355
+ enablePostProcessing();
356
+ renderer.setPixelRatio(1.5);
357
+ break;
358
+ case "medium":
359
+ renderer.setPixelRatio(1.25);
360
+ break;
361
+ case "low":
362
+ disableHeavyParticles();
363
+ renderer.setPixelRatio(1);
364
+ break;
365
+ case "minimal":
366
+ disableOptionalEffects();
367
+ renderer.setPixelRatio(0.75);
368
+ break;
369
+ }
370
+ ```
371
+
372
+ The returned object is `{ fps, tier }`, where `fps` is the recommended render target and `tier` is `"minimal"`, `"low"`, `"medium"`, or `"high"`. Hosts can inject measured values with `window.getGraphicsPerformance()` or `window.__OASIZ_GRAPHICS_PERFORMANCE__`; otherwise the SDK estimates from browser, device, and WebGL capability signals.
373
+
374
+ #### `oasiz.graphicsPerformance`
375
+
376
+ Getter alias for `getGraphicsPerformance()`.
377
+
378
+ ### Lifecycle
186
379
 
187
380
  The platform dispatches lifecycle events when the app goes to the background or returns to the foreground. Subscribe to pause game loops and audio accordingly.
188
381
 
189
- ### `oasiz.onPause(callback: () => void): Unsubscribe`
190
- ### `oasiz.onResume(callback: () => void): Unsubscribe`
382
+ #### `oasiz.onPause(callback: () => void): Unsubscribe`
383
+
384
+ #### `oasiz.onResume(callback: () => void): Unsubscribe`
191
385
 
192
386
  Both return an unsubscribe function.
193
387
 
194
388
  ```ts
195
- const offPause = oasiz.onPause(() => {
389
+ const offPause = oasiz.onPause(() => {
196
390
  this.gameLoop.stop();
197
391
  this.bgMusic.pause();
198
392
  });
@@ -207,19 +401,17 @@ offPause();
207
401
  offResume();
208
402
  ```
209
403
 
210
- ---
211
-
212
- ## Navigation
404
+ ### Navigation
213
405
 
214
406
  Use navigation hooks when your game needs to control back behavior (Android back / web Escape) or participate in host-driven close events.
215
407
 
216
- ### `oasiz.onBackButton(callback: () => void): Unsubscribe`
408
+ #### `oasiz.onBackButton(callback: () => void): Unsubscribe`
217
409
 
218
410
  Registers a callback for platform back actions. While at least one back listener is subscribed, back actions are routed to your game instead of immediately closing it.
219
411
 
220
412
  Use this for pause menus, in-game overlays, or custom back-stack behavior.
221
413
 
222
- If your callback throws, Oasiz falls back to closing the game and returning the player to Oasiz home before rethrowing the error for debugging/reporting.
414
+ **If your callback throws**, the SDK calls `leaveGame()` (host close) and **rethrows** the error so you still see it in devtools or error reporting. Non-`Error` throws are normalized to an `Error` (strings become the message; otherwise `"Back button callback failed."`).
223
415
 
224
416
  ```ts
225
417
  const offBack = oasiz.onBackButton(() => {
@@ -234,7 +426,30 @@ const offBack = oasiz.onBackButton(() => {
234
426
  offBack();
235
427
  ```
236
428
 
237
- ### `oasiz.leaveGame(): void`
429
+ #### `oasiz.enableBackButtonTesting(options?: BackButtonTestingOptions): BackButtonTestingHandle`
430
+
431
+ Opt-in local web helper for testing back override behavior without the Oasiz app bridge. Call it before registering `onBackButton` in local development:
432
+
433
+ ```ts
434
+ if (import.meta.env.DEV) {
435
+ oasiz.enableBackButtonTesting();
436
+ }
437
+
438
+ const offBack = oasiz.onBackButton(() => {
439
+ closePauseMenuOrOpenIt();
440
+ });
441
+ ```
442
+
443
+ While a back listener is active, the helper maps Escape to the same `oasiz:back` event the app sends. By default it also traps one browser-history entry so the browser Back button dispatches `oasiz:back` instead of leaving the page.
444
+
445
+ ```ts
446
+ const backTest = oasiz.enableBackButtonTesting({ browserHistory: false });
447
+ testBackButton.onclick = () => backTest.triggerBack();
448
+ ```
449
+
450
+ The returned handle also exposes `triggerLeave()` and `destroy()`. This helper is for local/dev web testing; in the app, the real bridge still owns back behavior.
451
+
452
+ #### `oasiz.leaveGame(): void`
238
453
 
239
454
  Programmatically request the host to close the current game (for example, from a Quit button inside your game UI).
240
455
 
@@ -269,14 +484,14 @@ const offLeave = oasiz.onLeaveGame(() => {
269
484
  offLeave();
270
485
  ```
271
486
 
272
- ---
273
-
274
- ## Multiplayer
487
+ ### Multiplayer
275
488
 
276
- ### `oasiz.shareRoomCode(code: string | null)`
489
+ #### `oasiz.shareRoomCode(code: string | null, options?: { inviteOverride?: boolean })`
277
490
 
278
491
  Notify the platform of the active multiplayer room so friends can join via the invite system. Pass `null` when leaving a room.
279
492
 
493
+ Set `inviteOverride: true` when your game wants to hide the platform invite pill and render its own invite button/UI. The platform still tracks the room code, but your game owns the invite entry point.
494
+
280
495
  ```ts
281
496
  import { insertCoin, getRoomCode } from "playroomkit";
282
497
  import { oasiz } from "@oasiz/sdk";
@@ -288,7 +503,26 @@ oasiz.shareRoomCode(getRoomCode());
288
503
  oasiz.shareRoomCode(null);
289
504
  ```
290
505
 
291
- ### Read-only injected values
506
+ ```ts
507
+ // Game-owned invite UI: hide the platform pill, keep room tracking
508
+ oasiz.shareRoomCode(getRoomCode(), { inviteOverride: true });
509
+ ```
510
+
511
+ #### `oasiz.openInviteModal(): void`
512
+
513
+ Opens the platform invite-friends UI when the bridge is available. Typically used together with `shareRoomCode` (for example, your own invite button calls this).
514
+
515
+ ```ts
516
+ import { openInviteModal, shareRoomCode } from "@oasiz/sdk";
517
+
518
+ shareRoomCode("ABCD", { inviteOverride: true });
519
+
520
+ inviteButton.addEventListener("click", () => {
521
+ openInviteModal();
522
+ });
523
+ ```
524
+
525
+ #### Read-only injected values
292
526
 
293
527
  These are populated by the platform before the game loads. Always check for `undefined` before using.
294
528
 
@@ -302,25 +536,31 @@ if (oasiz.roomCode) {
302
536
  }
303
537
 
304
538
  // Player identity for multiplayer games
305
- const name = oasiz.playerName;
539
+ const name = oasiz.playerName;
306
540
  const avatar = oasiz.playerAvatar;
307
541
  ```
308
542
 
309
- ---
310
-
311
- ## Named exports
543
+ ### Named exports
312
544
 
313
545
  All methods are also available as named exports if you prefer not to use the `oasiz` namespace object:
314
546
 
315
547
  ```ts
316
548
  import {
317
549
  submitScore,
318
- emitScoreConfig,
550
+ share,
319
551
  triggerHaptic,
320
552
  loadGameState,
321
553
  saveGameState,
322
554
  flushGameState,
323
555
  shareRoomCode,
556
+ openInviteModal,
557
+ enableAppSimulator,
558
+ enableLogOverlay,
559
+ enableBackButtonTesting,
560
+ getGraphicsPerformance,
561
+ getSafeAreaTop,
562
+ getViewportInsets,
563
+ setLeaderboardVisible,
324
564
  onPause,
325
565
  onResume,
326
566
  onBackButton,
@@ -333,18 +573,232 @@ import {
333
573
  } from "@oasiz/sdk";
334
574
  ```
335
575
 
576
+ ### TypeScript types
577
+
578
+ ```ts
579
+ import type {
580
+ AppSimulatorDevice,
581
+ AppSimulatorDeviceName,
582
+ AppSimulatorHandle,
583
+ AppSimulatorOptions,
584
+ AppSimulatorOrientation,
585
+ BackButtonTestingHandle,
586
+ BackButtonTestingOptions,
587
+ GameState,
588
+ GraphicsPerformanceMetric,
589
+ GraphicsPerformanceTier,
590
+ HapticType,
591
+ LogOverlayEntry,
592
+ LogOverlayHandle,
593
+ LogOverlayLevel,
594
+ LogOverlayOptions,
595
+ ShareRequest,
596
+ ShareRoomCodeOptions,
597
+ Unsubscribe,
598
+ } from "@oasiz/sdk";
599
+ ```
600
+
336
601
  ---
337
602
 
338
- ## TypeScript types
603
+ ## Unity WebGL SDK
604
+
605
+ C# API and **WebGL-only** `OasizBridge.jslib` live in this repository at **`packages/OasizSDK/`**. Copy the **`OasizSDK`** folder into your Unity project under **`Assets/`** (for example `Assets/OasizSDK`).
606
+
607
+ ### Setup
608
+
609
+ 1. Copy `packages/OasizSDK` from this repo into `Assets/OasizSDK`.
610
+ 2. Ensure the **WebGL** platform is selected for release builds; the `.jslib` under `Runtime/Plugins/WebGL/` is included automatically for WebGL.
611
+ 3. Add an **`OasizSDK`** component to a persistent GameObject early (for example a bootstrap scene), **or** rely on `OasizSDK.Instance` which creates a `DontDestroyOnLoad` object. The component registers listeners for `oasiz:pause`, `oasiz:resume`, `oasiz:back`, and `oasiz:leave` via `SendMessage`.
612
+
613
+ ### Quick start
614
+
615
+ ```csharp
616
+ using Oasiz;
617
+ using UnityEngine;
618
+
619
+ public class GameManager : MonoBehaviour
620
+ {
621
+ void Start()
622
+ {
623
+ // Ensure the singleton is initialized early
624
+ _ = OasizSDK.Instance;
625
+
626
+ // Subscribe to lifecycle events
627
+ OasizSDK.OnPause += OnPause;
628
+ OasizSDK.OnResume += OnResume;
629
+
630
+ // Offset UI for the host's top safe area (0–100 percent of Screen.height)
631
+ float safeTopPct = OasizSDK.SafeAreaTop;
632
+ float safeTopPx = safeTopPct / 100f * Screen.height;
633
+ Debug.Log($"Safe area top: {safeTopPx}px ({safeTopPct}% of height)");
634
+
635
+ // Pick visual settings for the current device
636
+ GraphicsPerformanceMetric graphics = OasizSDK.GetGraphicsPerformance();
637
+ Debug.Log($"Graphics tier: {graphics.tier} ({graphics.fps} FPS target)");
638
+
639
+ // Emit score normalization anchors
640
+ OasizSDK.EmitScoreConfig(new ScoreConfig(
641
+ new ScoreAnchor(10, 100),
642
+ new ScoreAnchor(30, 300),
643
+ new ScoreAnchor(75, 600),
644
+ new ScoreAnchor(200, 950)
645
+ ));
646
+ }
647
+
648
+ void OnGameOver(int finalScore)
649
+ {
650
+ OasizSDK.SubmitScore(finalScore);
651
+ OasizSDK.FlushGameState();
652
+ OasizSDK.SetLeaderboardVisible(true);
653
+ }
654
+
655
+ void OnGameplayStart()
656
+ {
657
+ OasizSDK.SetLeaderboardVisible(false);
658
+ }
659
+
660
+ void OnPause() => Time.timeScale = 0f;
661
+ void OnResume() => Time.timeScale = 1f;
662
+
663
+ void OnDestroy()
664
+ {
665
+ OasizSDK.OnPause -= OnPause;
666
+ OasizSDK.OnResume -= OnResume;
667
+ }
668
+ }
669
+ ```
339
670
 
340
- ```ts
341
- import type { HapticType, ScoreConfig, ScoreAnchor, GameState } from "@oasiz/sdk";
671
+ ### API parity (TypeScript → C#)
672
+
673
+ | HTML5 (`@oasiz/sdk`) | Unity (`Oasiz` namespace) |
674
+ | --- | --- |
675
+ | `oasiz.submitScore(n)` | `OasizSDK.SubmitScore(int)` |
676
+ | `oasiz.triggerHaptic(type)` | `OasizSDK.TriggerHaptic(HapticType)` |
677
+ | `oasiz.loadGameState()` | `OasizSDK.LoadGameState()` → `Dictionary<string, object>` |
678
+ | `oasiz.saveGameState(obj)` | `OasizSDK.SaveGameState(Dictionary<string, object>)` |
679
+ | `oasiz.flushGameState()` | `OasizSDK.FlushGameState()` |
680
+ | `oasiz.getViewportInsets()` / `viewportInsets` | `OasizSDK.GetViewportInsets()` (`ViewportInsets`, each side 0–100, % of matching viewport axis) |
681
+ | `oasiz.getSafeAreaTop()` / `safeAreaTop` | `OasizSDK.GetSafeAreaTop()` / `OasizSDK.SafeAreaTop` (`float`, 0–100, % of viewport height; legacy alias for top viewport inset) |
682
+ | `oasiz.setLeaderboardVisible(v)` | `OasizSDK.SetLeaderboardVisible(bool)` |
683
+ | `oasiz.getGraphicsPerformance()` / `graphicsPerformance` | `OasizSDK.GetGraphicsPerformance()` / `OasizSDK.GraphicsPerformance` (`GraphicsPerformanceMetric`, recommended FPS plus `minimal` / `low` / `medium` / `high`) |
684
+ | `oasiz.onPause` / `onResume` | `OasizSDK.OnPause` / `OnResume` static events |
685
+ | `oasiz.onBackButton` | `OasizSDK.OnBackButton` or `SubscribeBackButton(Action)` (reference-counts `__oasizSetBackOverride`) |
686
+ | `oasiz.enableBackButtonTesting()` | `OasizSDK.EnableBackButtonTesting()` (WebGL local/dev helper for Escape/browser Back testing) |
687
+ | `oasiz.onLeaveGame` | `OasizSDK.OnLeaveGame` |
688
+ | `oasiz.leaveGame()` | `OasizSDK.LeaveGame()` |
689
+ | `oasiz.share(request)` | `OasizSDK.Share(ShareRequest)` |
690
+ | `oasiz.shareRoomCode` | `OasizSDK.ShareRoomCode(string, ShareRoomCodeOptions)` |
691
+ | `oasiz.openInviteModal()` | `OasizSDK.OpenInviteModal()` |
692
+ | `oasiz.gameId` / `roomCode` / ... | `OasizSDK.GameId` / `RoomCode` / `PlayerName` / `PlayerAvatar` |
693
+ | -- | `OasizSDK.EmitScoreConfig(ScoreConfig)` → `window.emitScoreConfig` (Unity-only helper for normalized score UI) |
694
+ | `oasiz.enableLogOverlay` | `OasizSDK.EnableLogOverlay(LogOverlayOptions)` (see note below) |
695
+ | -- | `OasizSDK.AppendLogOverlay(level, message, stackTrace)` (see note below) |
696
+
697
+ ### Local back-button testing (Unity WebGL)
698
+
699
+ For local WebGL builds outside the Oasiz app, install the dev bridge before testing your subscribed back handler:
700
+
701
+ ```csharp
702
+ #if DEVELOPMENT_BUILD || UNITY_EDITOR
703
+ OasizSDK.EnableBackButtonTesting();
704
+ #endif
705
+
706
+ Action unsubscribeBack = OasizSDK.SubscribeBackButton(() =>
707
+ {
708
+ TogglePauseMenu();
709
+ });
710
+ ```
711
+
712
+ While the override is active, Escape and the browser Back button dispatch the same `oasiz:back` event that the app bridge sends. You can disable either input with `OasizSDK.EnableBackButtonTesting(keyboard: false)` or `OasizSDK.EnableBackButtonTesting(browserHistory: false)`.
713
+
714
+ ### Share (Unity)
715
+
716
+ HTML5 **`oasiz.share`** returns a **Promise** you can `await`. Unity **`OasizSDK.Share(ShareRequest)`** returns **`void`**: C# validation throws **`ArgumentException`** with the same rules as TypeScript (at least one of text, score, or image; non-negative integer score; `http(s)` or `data:image/...;base64,...` image). The call forwards JSON to **`window.__oasizShareRequest`**. If the host promise rejects, the **WebGL `.jslib` logs the error** to the browser console.
717
+
718
+ ```csharp
719
+ OasizSDK.Share(new ShareRequest
720
+ {
721
+ Text = "Beat this run!",
722
+ Score = 1200,
723
+ Image = "https://example.com/card.png",
724
+ });
725
+ ```
726
+
727
+ ### Types
728
+
729
+ ```csharp
730
+ // Haptic feedback intensity
731
+ public enum HapticType { Light, Medium, Heavy, Success, Error }
732
+
733
+ // Score normalization (exactly 4 anchors required)
734
+ public struct ScoreAnchor { public int raw; public int normalized; }
735
+ public struct ScoreConfig { public ScoreAnchor[] anchors; }
736
+
737
+ // Host share sheet (text / score / image URL or data URL)
738
+ public class ShareRequest
739
+ {
740
+ public string Text { get; set; }
741
+ public int? Score { get; set; }
742
+ public string Image { get; set; }
743
+ }
744
+
745
+ // Multiplayer invite options
746
+ public class ShareRoomCodeOptions { public bool InviteOverride { get; set; } }
747
+
748
+ // Log overlay configuration
749
+ public class LogOverlayOptions
750
+ {
751
+ public bool Enabled { get; set; } = true;
752
+ public bool Collapsed { get; set; } = false;
753
+ public int MaxEntries { get; set; } = 200;
754
+ public string Title { get; set; } = "SDK Logs";
755
+ }
756
+
757
+ // Log overlay lifecycle handle
758
+ public class LogOverlayHandle
759
+ {
760
+ public void Clear();
761
+ public void Hide();
762
+ public void Show();
763
+ public bool IsVisible();
764
+ public void Destroy();
765
+ }
342
766
  ```
343
767
 
768
+ ### Back button and errors
769
+
770
+ Matching the HTML5 SDK: if any **`OnBackButton`** handler throws, **`OasizSDK.LeaveGame()`** is invoked and the **original exception is rethrown** (`throw;` preserves the stack trace). Use **`SubscribeBackButton`** when you want an unsubscribe delegate; you can also use `OnBackButton +=` / `-=` directly.
771
+
772
+ ```csharp
773
+ // Subscribe with automatic unsubscribe support
774
+ var offBack = OasizSDK.SubscribeBackButton(() =>
775
+ {
776
+ if (isPaused)
777
+ Resume();
778
+ else
779
+ Pause();
780
+ });
781
+
782
+ // Unsubscribe when no longer needed
783
+ offBack();
784
+ ```
785
+
786
+ ### Editor vs WebGL builds
787
+
788
+ In the **Unity Editor**, bridge calls are mostly **logged** and return safe defaults (for example safe area `0`, `null` platform IDs). Real host integration applies to **WebGL player** builds running inside Oasiz.
789
+
790
+ ### Log overlay (Unity)
791
+
792
+ The C# API for the log overlay exists for API compatibility, but the **default `OasizBridge.jslib` in this repo does not inject DOM UI** — `EnableLogOverlay` / `AppendLogOverlay` are no-ops at the JavaScript layer. Use Unity's console and device logs for debugging unless you replace or extend the `.jslib` on your side.
793
+
794
+ `AppendLogOverlay(level, message, stackTrace)` lets you pipe `Debug.Log` output into the overlay manually, since many embedded WebViews do not route Unity player logs through `console.log`. Valid levels: `"debug"`, `"log"`, `"info"`, `"warn"`, `"error"`.
795
+
344
796
  ---
345
797
 
346
798
  ## Local development
347
799
 
800
+ ### HTML5 / TypeScript
801
+
348
802
  All methods safely no-op when the platform bridges are not injected. In development mode a console warning is logged so you know the call was made:
349
803
 
350
804
  ```
@@ -352,3 +806,7 @@ All methods safely no-op when the platform bridges are not injected. In developm
352
806
  ```
353
807
 
354
808
  No crashes, no special setup required for local dev.
809
+
810
+ ### Unity WebGL
811
+
812
+ The `.jslib` logs warnings when `window.*` bridges are missing (for example `submitScore`, `__oasizLeaveGame`). The Editor path avoids calling native plugins and prints `Debug.Log` for most operations instead.