@powly/sdk 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The SDK for games on [Powly](https://powly.gg): the launch handshake with Powly, the player's
4
4
  profile, session tokens and the platform services (saves, leaderboards, achievements, friends,
5
- invites, multiplayer rooms, Twitch chat).
5
+ invites, multiplayer rooms, Twitch chat, sound settings).
6
6
 
7
7
  ## Install
8
8
 
@@ -31,7 +31,7 @@ await powly.leaderboards.submit("high-score", 1200);
31
31
  Without a bundler, load the classic script instead; it defines `window.Powly`:
32
32
 
33
33
  ```html
34
- <script src="https://cdn.jsdelivr.net/npm/@powly/sdk@0.6.0/dist/powly.js"></script>
34
+ <script src="https://cdn.jsdelivr.net/npm/@powly/sdk@0.8.0/dist/powly.js"></script>
35
35
  ```
36
36
 
37
37
  ## Testing
@@ -58,7 +58,7 @@ your backend verifies session tokens or exchanges them for an access token.
58
58
  ## This repository
59
59
 
60
60
  The SDK is developed in Powly's main repository and mirrored here with each release; this is
61
- `@powly/sdk` 0.6.0. Issues are welcome; changes land through the main repository.
61
+ `@powly/sdk` 0.8.0. Issues are welcome; changes land through the main repository.
62
62
 
63
63
  To build it yourself (Node.js 24 or newer):
64
64
 
package/dist/powly.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- /* Powly SDK 0.6.0: types for powly.js and powly.mjs */
1
+ /* Powly SDK 0.8.0: types for powly.js and powly.mjs */
2
2
  /** This SDK's version; Powly's Studio shows it next to the downloads. */
3
- export declare const SDK_VERSION = "0.6.0";
3
+ export declare const SDK_VERSION = "0.8.0";
4
4
 
5
5
  export declare const PROTOCOL = "powly-sdk";
6
6
  export declare const PROTOCOL_VERSION = 1;
@@ -8,6 +8,44 @@ export declare const PROTOCOL_VERSION = 1;
8
8
  export declare const OPTIONS_BUTTON_CORNERS: readonly ["top-left", "top-right", "bottom-left", "bottom-right"];
9
9
  export type OptionsButtonCorner = (typeof OPTIONS_BUTTON_CORNERS)[number];
10
10
  export declare const isOptionsButtonCorner: (value: unknown) => value is OptionsButtonCorner;
11
+ /**
12
+ * A kind of sound the game has (music, drawing sounds…), which Powly's sound menu shows with a
13
+ * volume slider (`volume`, default true), an on/off switch (`toggle`, default true), or both.
14
+ */
15
+ export type AudioChannel = {
16
+ id: string;
17
+ label: string;
18
+ volume?: boolean;
19
+ toggle?: boolean;
20
+ };
21
+ /** One channel's setting: its volume, 0 to 1, and whether it's on. */
22
+ export type ChannelState = {
23
+ volume: number;
24
+ on: boolean;
25
+ };
26
+ /** Channel ids: letters, digits, _ and -, starting with a letter, up to 32. */
27
+ export declare const AUDIO_CHANNEL_ID: RegExp;
28
+ export declare const MAX_AUDIO_CHANNELS = 8;
29
+ export declare const MAX_AUDIO_LABEL = 32;
30
+ /**
31
+ * The player's sound settings from Powly's sound menu. `volume` (0 to 1) is the player's overall
32
+ * volume, `channels` the game's own (by channel id); `muted` silences everything.
33
+ */
34
+ export type AudioState = {
35
+ volume: number;
36
+ muted: boolean;
37
+ channels: Record<string, ChannelState>;
38
+ };
39
+ /** The channels a game sent, cleaned up: valid ids, short labels, no repeats, at most 8. */
40
+ export declare function audioChannelsOf(value: unknown): AudioChannel[];
41
+ /** What a game changes from its own sound menu; channels by id, only the fields given. */
42
+ export type AudioChanges = {
43
+ volume?: number;
44
+ muted?: boolean;
45
+ channels?: Record<string, Partial<ChannelState>>;
46
+ };
47
+ /** A volume between 0 and 1, or null. */
48
+ export declare const volumeOf: (value: unknown) => number | null;
11
49
  export type InitMessage = {
12
50
  protocol: typeof PROTOCOL;
13
51
  version: number;
@@ -23,6 +61,13 @@ export type InitMessage = {
23
61
  * player's own choice wins. Left out: Powly's default (top left).
24
62
  */
25
63
  optionsButton?: OptionsButtonCorner;
64
+ /**
65
+ * The SDK follows Powly's sound menu (SDK 0.8.0 and later): `channels` are the game's own
66
+ * volume controls, shown as sliders. Older SDKs leave it out.
67
+ */
68
+ audio?: {
69
+ channels: AudioChannel[];
70
+ };
26
71
  };
27
72
  export type PlayerProfile = {
28
73
  /** This player's ID in this game: stable, and different in every game. */
@@ -49,12 +94,19 @@ export type ReadyMessage = {
49
94
  pac?: {
50
95
  guard: boolean;
51
96
  };
97
+ /** The player's sound settings when the game starts. Missing from older Powly hosts. */
98
+ audio?: AudioState;
52
99
  };
53
100
  export type FailedMessage = {
54
101
  type: "failed";
55
102
  error: string;
56
103
  };
57
- export type HostMethod = "getSessionToken" | "purchases.open" | "fullscreen.toggle" | "invites.open" | "quit";
104
+ /** What a game may ask the Powly page for. */
105
+ export declare const HOST_METHODS: readonly ["getSessionToken", "purchases.open", "fullscreen.toggle", "invites.open", "players.open", "twitch.connect", "audio.set", "audio.channels", "quit"];
106
+ export type HostMethod = (typeof HOST_METHODS)[number];
107
+ /** "players.open": what Powly's player dialog opens on. */
108
+ export declare const PLAYER_VIEWS: readonly ["profile", "report"];
109
+ export type PlayerView = (typeof PLAYER_VIEWS)[number];
58
110
  export type RequestMessage = {
59
111
  type: "request";
60
112
  id: number;
@@ -66,11 +118,33 @@ export type RequestMessage = {
66
118
  * dialog shows them as in the party, without an Invite button.
67
119
  */
68
120
  members?: string[];
121
+ /** "players.open": the player (their player ID in this game) to show. */
122
+ playerId?: string;
123
+ /** "players.open": open on the profile (the default) or straight on reporting them. */
124
+ view?: PlayerView;
125
+ /** "audio.set": what the game's own sound menu changed. */
126
+ audio?: AudioChanges;
127
+ /** "audio.channels": every channel the game has now (registered later than init). */
128
+ channels?: AudioChannel[];
69
129
  };
70
130
  /** What "invites.open" answers once Powly's dialog closed: the friends the player invited. */
71
131
  export type InvitesOpenResult = {
72
132
  invited: string[];
73
133
  };
134
+ /**
135
+ * What "players.open" answers once Powly's player dialog closed: whether the player has that
136
+ * player blocked now (the game may hide their chat, say). Whether they reported them stays private.
137
+ */
138
+ export type PlayersOpenResult = {
139
+ blocked: boolean;
140
+ };
141
+ /**
142
+ * What "twitch.connect" answers once Powly's Connect Twitch dialog closed: whether the player's
143
+ * Twitch is connected now (the SDK then reads GET /twitch again).
144
+ */
145
+ export type TwitchConnectResult = {
146
+ connected: boolean;
147
+ };
74
148
  export type ResponseMessage = {
75
149
  type: "response";
76
150
  id: number;
@@ -90,9 +164,20 @@ export type HostEventName = "shown" | "pause" | "resume" | "ended";
90
164
  export type EventMessage = {
91
165
  type: "event";
92
166
  event: HostEventName;
167
+ }
168
+ /** The player changed the sound settings (Powly's sound menu, or its M key). */
169
+ | {
170
+ type: "event";
171
+ event: "audio";
172
+ audio: AudioState;
93
173
  };
94
174
  export type HostMessage = ReadyMessage | FailedMessage | ResponseMessage | EventMessage;
95
175
  export declare const isInitMessage: (data: unknown) => data is InitMessage;
176
+ /** A request with a method this Powly doesn't know (from a newer SDK): answered with an error. */
177
+ export declare const isRequestShaped: (data: unknown) => data is {
178
+ type: "request";
179
+ id: number;
180
+ };
96
181
  export declare const isRequestMessage: (data: unknown) => data is RequestMessage;
97
182
 
98
183
  export declare const POWLY_ORIGINS: readonly string[];
@@ -481,14 +566,21 @@ type Events = {
481
566
  };
482
567
  state: TwitchChatState;
483
568
  };
569
+ export type ConnectOptions = {
570
+ /** Ask the player to connect Twitch in Powly's dialog when they haven't. Default false. */
571
+ prompt?: boolean;
572
+ };
484
573
  export type TwitchApi = {
485
574
  /** The game's setting and the player's channel, without opening chat. */
486
575
  info(): Promise<TwitchInfo>;
487
576
  /**
488
577
  * Opens the player's chat when they have a channel to read (`status: "connected"`). Resolves
489
578
  * with the info, once chat is joined (or failed to; it keeps retrying in the background).
579
+ * `prompt`: when the player hasn't connected Twitch, Powly first asks them to in its own dialog
580
+ * (they can connect it there without leaving the game); `status` is still "not_connected" if
581
+ * they closed it.
490
582
  */
491
- connect(): Promise<TwitchInfo>;
583
+ connect(options?: ConnectOptions): Promise<TwitchInfo>;
492
584
  /** Closes chat; `connect()` opens it again. */
493
585
  disconnect(): void;
494
586
  readonly state: TwitchChatState;
@@ -509,6 +601,8 @@ export declare function parseIrcLine(line: string): IrcMessage | null;
509
601
  export declare function chatMessageOf(message: IrcMessage): TwitchChatMessage | null;
510
602
  export declare function createTwitch(options: {
511
603
  getInfo: () => Promise<TwitchInfo>;
604
+ /** Opens Powly's Connect Twitch dialog; resolves with whether Twitch is connected now. */
605
+ prompt?: () => Promise<boolean>;
512
606
  /** Twitch chat's WebSocket URL (tests point it elsewhere). */
513
607
  url?: string;
514
608
  }): TwitchApi & {
@@ -516,6 +610,58 @@ export declare function createTwitch(options: {
516
610
  };
517
611
 
518
612
 
613
+ export type AudioOptions = {
614
+ /**
615
+ * The game's kinds of sound, shown in Powly's sound menu (up to 8): `{ id, label }`, with a
616
+ * volume slider (`volume: false` leaves it out) and an on/off switch (`toggle: false`).
617
+ */
618
+ channels?: AudioChannel[];
619
+ /**
620
+ * Apply the overall volume and mute to the page's sound by itself. Default true; turn it off
621
+ * when the game applies `level()` to everything itself.
622
+ */
623
+ auto?: boolean;
624
+ };
625
+ export type AudioApi = {
626
+ /** The player's overall volume, 0 to 1. */
627
+ readonly volume: number;
628
+ /** Everything silenced (Powly's mute, or its M key). */
629
+ readonly muted: boolean;
630
+ /** The game's channels by id: their volume (0 to 1) and whether they're on. */
631
+ readonly channels: Record<string, ChannelState>;
632
+ /**
633
+ * What to play at, 0 to 1: a channel's volume (0 while it's off), or (no channel) full volume.
634
+ * With `auto` off, the overall volume and mute are in it too.
635
+ */
636
+ level(channel?: string): number;
637
+ /**
638
+ * Adds a channel to Powly's sound menu after init (or changes its label or controls), e.g.
639
+ * once a mode with its own sounds starts. Up to 8 channels.
640
+ */
641
+ register(channel: AudioChannel): Promise<void>;
642
+ /**
643
+ * Changes the settings from the game's own sound menu, so Powly's stays the same:
644
+ * `{ volume, muted, channels: { music: { volume: 0.5 }, drawing: { on: false } } }`. Unknown
645
+ * channels are ignored.
646
+ */
647
+ set(changes: AudioChanges): Promise<void>;
648
+ /** The settings changed (in Powly's sound menu, or with `set`). */
649
+ on(event: "change", listener: (audio: AudioState) => void): () => void;
650
+ };
651
+ /** Volume of the page's sound overall: 0 when muted. */
652
+ export declare const masterLevel: (state: AudioState) => number;
653
+ /**
654
+ * Puts a volume control in front of the page's speakers: Web Audio connections to a real-time
655
+ * AudioContext's destination go through a gain node per context, and media elements' volume is
656
+ * scaled (the volume the game set still reads back unchanged; elements played through Web Audio
657
+ * are left to the gain node). Returns how to set it.
658
+ */
659
+ export declare function installMasterGain(win?: Window & typeof globalThis): {
660
+ set(level: number): void;
661
+ };
662
+
663
+
664
+
519
665
 
520
666
 
521
667
 
@@ -536,6 +682,12 @@ export type InitOptions = {
536
682
  * UI leaves free. Players can still move it, and their choice wins.
537
683
  */
538
684
  optionsButton?: OptionsButtonCorner;
685
+ /**
686
+ * Powly's sound menu (src/audio.ts): the game's own volume `channels` (sliders next to the
687
+ * player's overall volume), and whether the SDK applies the overall volume and mute to the
688
+ * page's sound itself (`auto`, default true).
689
+ */
690
+ audio?: AudioOptions;
539
691
  };
540
692
  export type LeaderboardEntry = {
541
693
  rank: number;
@@ -607,6 +759,25 @@ export type PowlySession = {
607
759
  invited: string[];
608
760
  }>;
609
761
  };
762
+ /**
763
+ * Other players of this game, by their player ID (from rooms, leaderboards, friends…).
764
+ * `open` shows Powly's own dialog over the game (drawn by Powly, not the game) with their
765
+ * profile, where the player can add them as a friend, block or report them; with
766
+ * `{ view: "report" }` it opens straight on reporting them. Games can't file reports
767
+ * themselves: the player always confirms in Powly's dialog. Resolves when it closes, with
768
+ * whether the player has them blocked now (hide their chat, say). Fails for player IDs that
769
+ * aren't from this game.
770
+ */
771
+ players: {
772
+ open(playerId: string, options?: {
773
+ view?: PlayerView;
774
+ }): Promise<PlayersOpenResult>;
775
+ };
776
+ /**
777
+ * The player's sound settings from Powly's options bar: overall volume, mute and the game's
778
+ * channels (`Powly.init({ audio: { channels } })`). Play each channel at `level(channel)`.
779
+ */
780
+ audio: AudioApi;
610
781
  /** Realtime rooms (parties) with other players of this game. */
611
782
  rooms: RoomsApi;
612
783
  /**
package/dist/powly.js CHANGED
@@ -1,8 +1,8 @@
1
- /* Powly SDK 0.6.0: defines window.Powly */
1
+ /* Powly SDK 0.8.0: defines window.Powly */
2
2
  (function () {
3
3
  "use strict";
4
4
  /** This SDK's version; Powly's Studio shows it next to the downloads. */
5
- const SDK_VERSION = "0.6.0";
5
+ const SDK_VERSION = "0.8.0";
6
6
 
7
7
  // The messages between a game (this SDK, inside Powly's iframe) and the Powly page that framed it.
8
8
  // Shared with the host side (apps/web/components/player/sdk-host.ts).
@@ -22,16 +22,61 @@ const OPTIONS_BUTTON_CORNERS = [
22
22
  "bottom-right",
23
23
  ];
24
24
  const isOptionsButtonCorner = (value) => OPTIONS_BUTTON_CORNERS.includes(value);
25
+ /** Channel ids: letters, digits, _ and -, starting with a letter, up to 32. */
26
+ const AUDIO_CHANNEL_ID = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
27
+ const MAX_AUDIO_CHANNELS = 8;
28
+ const MAX_AUDIO_LABEL = 32;
29
+ /** The channels a game sent, cleaned up: valid ids, short labels, no repeats, at most 8. */
30
+ function audioChannelsOf(value) {
31
+ if (!Array.isArray(value))
32
+ return [];
33
+ const channels = [];
34
+ for (const entry of value) {
35
+ if (typeof entry !== "object" || entry === null)
36
+ continue;
37
+ const { id, label, volume, toggle } = entry;
38
+ if (typeof id !== "string" || !AUDIO_CHANNEL_ID.test(id))
39
+ continue;
40
+ if (channels.some((channel) => channel.id === id))
41
+ continue;
42
+ const text = typeof label === "string" ? label.trim().slice(0, MAX_AUDIO_LABEL) : "";
43
+ const slider = volume !== false;
44
+ // Neither a slider nor a switch would show nothing: both, then.
45
+ const onOff = toggle !== false || !slider;
46
+ channels.push({ id, label: text || id, volume: slider, toggle: onOff });
47
+ if (channels.length === MAX_AUDIO_CHANNELS)
48
+ break;
49
+ }
50
+ return channels;
51
+ }
52
+ /** A volume between 0 and 1, or null. */
53
+ const volumeOf = (value) => typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : null;
54
+ /** What a game may ask the Powly page for. */
55
+ const HOST_METHODS = [
56
+ "getSessionToken",
57
+ "purchases.open",
58
+ "fullscreen.toggle",
59
+ "invites.open",
60
+ "players.open",
61
+ "twitch.connect",
62
+ "audio.set",
63
+ "audio.channels",
64
+ "quit",
65
+ ];
66
+ /** "players.open": what Powly's player dialog opens on. */
67
+ const PLAYER_VIEWS = ["profile", "report"];
25
68
  const isInitMessage = (data) => typeof data === "object" &&
26
69
  data !== null &&
27
70
  data.protocol === PROTOCOL &&
28
71
  data.type === "init" &&
29
72
  data.version === PROTOCOL_VERSION;
30
- const isRequestMessage = (data) => typeof data === "object" &&
73
+ /** A request with a method this Powly doesn't know (from a newer SDK): answered with an error. */
74
+ const isRequestShaped = (data) => typeof data === "object" &&
31
75
  data !== null &&
32
76
  data.type === "request" &&
33
- Number.isInteger(data.id) &&
34
- ["getSessionToken", "purchases.open", "fullscreen.toggle", "invites.open", "quit"].includes(data.method);
77
+ Number.isInteger(data.id);
78
+ const isRequestMessage = (data) => isRequestShaped(data) &&
79
+ HOST_METHODS.includes(data.method);
35
80
 
36
81
  // The Powly origins this build of the SDK trusts by default: a game only handshakes with a parent
37
82
  // page on one of them (unless it passes `powlyOrigin` to `Powly.init()` itself). Set at build
@@ -861,6 +906,11 @@ function createRooms(options) {
861
906
  // });
862
907
  // }
863
908
  //
909
+ // A game with a Twitch mode among others (Twitch chat "optional" in Studio) passes
910
+ // `{ prompt: true }` when the player picks that mode: if they haven't connected Twitch, Powly asks
911
+ // them to in its own dialog (drawn by Powly, outside the game), and `connect()` resolves once
912
+ // they did or closed it.
913
+ //
864
914
  // Chat is Twitch IRC over a WebSocket (https://dev.twitch.tv/docs/chat/irc/). The connection comes
865
915
  // back by itself when it drops, and stops when the launch ends.
866
916
  const TWITCH_CHAT_URL = "wss://irc-ws.chat.twitch.tv:443";
@@ -1101,8 +1151,12 @@ function createTwitch(options) {
1101
1151
  };
1102
1152
  return {
1103
1153
  info: options.getInfo,
1104
- async connect() {
1105
- const info = await options.getInfo();
1154
+ async connect(connectOptions = {}) {
1155
+ let info = await options.getInfo();
1156
+ if (info.status === "not_connected" && connectOptions.prompt && options.prompt) {
1157
+ if (await options.prompt())
1158
+ info = await options.getInfo();
1159
+ }
1106
1160
  const next = info.status === "connected" ? info.channel : null;
1107
1161
  if (!next || stopped) {
1108
1162
  disconnect();
@@ -1141,6 +1195,154 @@ function createTwitch(options) {
1141
1195
  };
1142
1196
  }
1143
1197
 
1198
+ // Powly's sound menu for games (`powly.audio`): the player's overall volume, a mute (Powly's M
1199
+ // key), and the kinds of sound the game registers (channels: music, drawing sounds…), each with a
1200
+ // volume slider and an on/off switch, or one of them. The player sets them in Powly's options
1201
+ // bar; the game hears "change".
1202
+ //
1203
+ // const powly = await Powly.init({
1204
+ // audio: { channels: [{ id: "music", label: "Music" }] },
1205
+ // });
1206
+ // await powly.audio.register({ id: "drawing", label: "Drawing sounds", volume: false });
1207
+ // music.volume = powly.audio.level("music");
1208
+ // powly.audio.on("change", () => { music.volume = powly.audio.level("music"); });
1209
+ // if (powly.audio.level("drawing") > 0) playScribble();
1210
+ //
1211
+ // The overall volume and mute apply by themselves (`auto`, on by default): the SDK puts a volume
1212
+ // control in front of the page's speakers, for Web Audio (every connection to an AudioContext's
1213
+ // destination goes through it) and for <audio>/<video> (their volume is scaled). So every game
1214
+ // on this SDK follows Powly's volume, and channels only need the channel's own value:
1215
+ // `level(channel)` is what to play at either way.
1216
+ /** Volume of the page's sound overall: 0 when muted. */
1217
+ const masterLevel = (state) => (state.muted ? 0 : state.volume);
1218
+ /** Live references to objects, for walking them later without keeping them alive. */
1219
+ function weakList() {
1220
+ const seen = new WeakSet();
1221
+ const refs = new Set();
1222
+ return {
1223
+ add(item) {
1224
+ if (seen.has(item))
1225
+ return false;
1226
+ seen.add(item);
1227
+ refs.add(new WeakRef(item));
1228
+ return true;
1229
+ },
1230
+ has: (item) => seen.has(item),
1231
+ *[Symbol.iterator]() {
1232
+ for (const ref of refs) {
1233
+ const item = ref.deref();
1234
+ if (item)
1235
+ yield item;
1236
+ else
1237
+ refs.delete(ref);
1238
+ }
1239
+ },
1240
+ };
1241
+ }
1242
+ /**
1243
+ * Puts a volume control in front of the page's speakers: Web Audio connections to a real-time
1244
+ * AudioContext's destination go through a gain node per context, and media elements' volume is
1245
+ * scaled (the volume the game set still reads back unchanged; elements played through Web Audio
1246
+ * are left to the gain node). Returns how to set it.
1247
+ */
1248
+ function installMasterGain(win = window) {
1249
+ let level = 1;
1250
+ // Web Audio.
1251
+ const gainOf = new WeakMap();
1252
+ const gains = weakList();
1253
+ const Destination = win.AudioDestinationNode;
1254
+ const Offline = win.OfflineAudioContext;
1255
+ const nodeProto = win.AudioNode?.prototype;
1256
+ const connect = nodeProto?.connect;
1257
+ const disconnect = nodeProto?.disconnect;
1258
+ /** The gain node standing in for `target` when it's a real-time context's destination. */
1259
+ const standIn = (target) => {
1260
+ if (!Destination || !(target instanceof Destination))
1261
+ return null;
1262
+ const context = target.context;
1263
+ if (Offline && context instanceof Offline)
1264
+ return null;
1265
+ let gain = gainOf.get(context);
1266
+ if (!gain) {
1267
+ gain = context.createGain();
1268
+ gain.gain.value = level;
1269
+ gains.add(gain);
1270
+ connect?.call(gain, target);
1271
+ gainOf.set(context, gain);
1272
+ }
1273
+ return gain;
1274
+ };
1275
+ if (nodeProto && connect && disconnect) {
1276
+ nodeProto.connect = function (target, ...rest) {
1277
+ const gain = gains.has(this) ? null : standIn(target);
1278
+ if (!gain)
1279
+ return connect.call(this, target, ...rest);
1280
+ connect.call(this, gain, ...rest);
1281
+ // Chaining keeps working: connect() answers what it was given.
1282
+ return target;
1283
+ };
1284
+ nodeProto.disconnect = function (...args) {
1285
+ const gain = gains.has(this) ? null : standIn(args[0]);
1286
+ return gain ? disconnect.call(this, gain, ...args.slice(1)) : disconnect.apply(this, args);
1287
+ };
1288
+ }
1289
+ // Media elements: the volume the game set, and the one played (times `level`).
1290
+ const media = win.HTMLMediaElement?.prototype;
1291
+ const volume = media ? Object.getOwnPropertyDescriptor(media, "volume") : undefined;
1292
+ const wanted = new WeakMap();
1293
+ const elements = weakList();
1294
+ const routed = new WeakSet();
1295
+ const apply = (element) => {
1296
+ const own = wanted.get(element) ?? 1;
1297
+ volume?.set?.call(element, routed.has(element) ? own : own * level);
1298
+ };
1299
+ const track = (element) => {
1300
+ if (!wanted.has(element))
1301
+ wanted.set(element, volume?.get?.call(element) ?? 1);
1302
+ elements.add(element);
1303
+ apply(element);
1304
+ };
1305
+ if (media && volume?.get && volume.set) {
1306
+ const { get, set } = volume;
1307
+ Object.defineProperty(media, "volume", {
1308
+ configurable: true,
1309
+ enumerable: volume.enumerable,
1310
+ get() {
1311
+ return wanted.get(this) ?? get.call(this);
1312
+ },
1313
+ set(value) {
1314
+ // Out of range throws, like the browser's own setter.
1315
+ set.call(this, value);
1316
+ wanted.set(this, value);
1317
+ track(this);
1318
+ },
1319
+ });
1320
+ const play = media.play;
1321
+ media.play = function () {
1322
+ track(this);
1323
+ return play.call(this);
1324
+ };
1325
+ }
1326
+ const createSource = win.AudioContext?.prototype.createMediaElementSource;
1327
+ if (createSource) {
1328
+ win.AudioContext.prototype.createMediaElementSource = function (element) {
1329
+ routed.add(element);
1330
+ track(element);
1331
+ return createSource.call(this, element);
1332
+ };
1333
+ }
1334
+ return {
1335
+ set(next) {
1336
+ level = next;
1337
+ for (const gain of gains)
1338
+ gain.gain.value = level;
1339
+ for (const element of elements)
1340
+ apply(element);
1341
+ },
1342
+ };
1343
+ }
1344
+
1345
+
1144
1346
 
1145
1347
 
1146
1348
 
@@ -1158,6 +1360,8 @@ function createTwitch(options) {
1158
1360
  // const token = await powly.getSessionToken(); // send it to your backend, which verifies it
1159
1361
  // const room = await powly.rooms.create(); // realtime parties (src/rooms.ts)
1160
1362
  // await powly.twitch.connect(); // the streamer's Twitch chat (src/twitch.ts)
1363
+ // await powly.players.open(playerId); // Powly's profile dialog: add, block, report
1364
+ // powly.audio.level("music"); // Powly's sound menu (src/audio.ts)
1161
1365
  //
1162
1366
  // Nothing here is a security boundary: the game runs in the player's browser. Your backend must
1163
1367
  // verify session tokens (JWKS) or exchange them, and Powly checks everything server-side.
@@ -1202,6 +1406,12 @@ function init(options = {}) {
1202
1406
  if (origins.length === 0) {
1203
1407
  return Promise.reject(new PowlyError("This game only runs when launched from Powly."));
1204
1408
  }
1409
+ const audioChannels = audioChannelsOf(options.audio?.channels ?? []);
1410
+ // Before the game's engine makes a sound, so its connections go through the volume control.
1411
+ const auto = options.audio?.auto !== false;
1412
+ if (auto)
1413
+ masterGain ??= installMasterGain();
1414
+ const master = auto ? masterGain : null;
1205
1415
  return new Promise((resolve, reject) => {
1206
1416
  const channels = origins.map((origin) => {
1207
1417
  const channel = new MessageChannel();
@@ -1214,6 +1424,7 @@ function init(options = {}) {
1214
1424
  ...(isOptionsButtonCorner(options.optionsButton) && {
1215
1425
  optionsButton: options.optionsButton,
1216
1426
  }),
1427
+ audio: { channels: audioChannels },
1217
1428
  };
1218
1429
  channel.port1.onmessage = (event) => {
1219
1430
  const data = event.data;
@@ -1222,7 +1433,7 @@ function init(options = {}) {
1222
1433
  for (const other of channels)
1223
1434
  if (other !== channel)
1224
1435
  other.port1.close();
1225
- resolve(createSession(channel.port1, data));
1436
+ resolve(createSession(channel.port1, data, { channels: audioChannels, master }));
1226
1437
  }
1227
1438
  else if (data?.type === "failed") {
1228
1439
  clearTimeout(timer);
@@ -1240,7 +1451,22 @@ function init(options = {}) {
1240
1451
  }, options.timeoutMs ?? 10_000);
1241
1452
  });
1242
1453
  }
1243
- function createSession(port, ready) {
1454
+ /** The page's volume control (src/audio.ts), put in once even if init runs again. */
1455
+ let masterGain = null;
1456
+ /** The sound settings Powly sent, with every channel (on, at full volume, when it sent none). */
1457
+ function audioStateOf(value, channels) {
1458
+ const sent = (typeof value === "object" && value !== null ? value : {});
1459
+ const levels = ((typeof sent.channels === "object" && sent.channels) || {});
1460
+ return {
1461
+ volume: volumeOf(sent.volume) ?? 1,
1462
+ muted: sent.muted === true,
1463
+ channels: Object.fromEntries(channels.map((channel) => {
1464
+ const level = levels[channel.id];
1465
+ return [channel.id, { volume: volumeOf(level?.volume) ?? 1, on: level?.on !== false }];
1466
+ })),
1467
+ };
1468
+ }
1469
+ function createSession(port, ready, sound) {
1244
1470
  let token = ready.token;
1245
1471
  let expiresAt = Date.now() + ready.expiresIn * 1000;
1246
1472
  let refreshing = null;
@@ -1249,6 +1475,23 @@ function createSession(port, ready) {
1249
1475
  const listeners = new Map();
1250
1476
  // "shown" comes once; games that listen for it later still hear it.
1251
1477
  let shown = false;
1478
+ // The player's sound settings; the page's volume follows them (auto).
1479
+ let channels = sound.channels;
1480
+ let audio = audioStateOf(ready.audio, channels);
1481
+ const audioListeners = new Set();
1482
+ sound.master?.set(masterLevel(audio));
1483
+ const setAudio = (next) => {
1484
+ audio = next;
1485
+ sound.master?.set(masterLevel(audio));
1486
+ for (const listener of audioListeners) {
1487
+ try {
1488
+ listener(audio);
1489
+ }
1490
+ catch (error) {
1491
+ console.error("[powly] an audio listener failed", error);
1492
+ }
1493
+ }
1494
+ };
1252
1495
  port.onmessage = (event) => {
1253
1496
  const data = event.data;
1254
1497
  if (data?.type === "response") {
@@ -1262,7 +1505,13 @@ function createSession(port, ready) {
1262
1505
  waiting.reject(new PowlyError(data.error));
1263
1506
  }
1264
1507
  else if (data?.type === "event") {
1265
- const name = data.event;
1508
+ const message = data;
1509
+ if (message.event === "audio") {
1510
+ if ("audio" in message)
1511
+ setAudio(audioStateOf(message.audio, channels));
1512
+ return;
1513
+ }
1514
+ const name = message.event;
1266
1515
  if (name === "shown") {
1267
1516
  if (shown)
1268
1517
  return;
@@ -1328,7 +1577,10 @@ function createSession(port, ready) {
1328
1577
  invite: sendInvite,
1329
1578
  });
1330
1579
  listeners.get("ended")?.add(() => realtime.stop());
1331
- const twitch = createTwitch({ getInfo: () => api("/twitch") });
1580
+ const twitch = createTwitch({
1581
+ getInfo: () => api("/twitch"),
1582
+ prompt: async () => (await call("twitch.connect")).connected,
1583
+ });
1332
1584
  listeners.get("ended")?.add(() => twitch.stop());
1333
1585
  const saves = {
1334
1586
  get: async (key) => {
@@ -1375,6 +1627,52 @@ function createSession(port, ready) {
1375
1627
  return (await call("invites.open", { params, members }));
1376
1628
  },
1377
1629
  },
1630
+ players: {
1631
+ open: async (playerId, options = {}) => (await call("players.open", {
1632
+ playerId,
1633
+ ...(options.view && { view: options.view }),
1634
+ })),
1635
+ },
1636
+ audio: {
1637
+ get volume() {
1638
+ return audio.volume;
1639
+ },
1640
+ get muted() {
1641
+ return audio.muted;
1642
+ },
1643
+ get channels() {
1644
+ return Object.fromEntries(Object.entries(audio.channels).map(([id, state]) => [id, { ...state }]));
1645
+ },
1646
+ level(channel) {
1647
+ const state = channel === undefined ? undefined : audio.channels[channel];
1648
+ const own = state ? (state.on ? state.volume : 0) : 1;
1649
+ return sound.master ? own : own * masterLevel(audio);
1650
+ },
1651
+ async register(channel) {
1652
+ const next = audioChannelsOf([
1653
+ ...channels.filter((existing) => existing.id !== channel?.id),
1654
+ channel,
1655
+ ]);
1656
+ if (!next.some((entry) => entry.id === channel?.id)) {
1657
+ throw new PowlyError(`A channel needs an id of letters, digits, _ and -, and a game has up to ${MAX_AUDIO_CHANNELS}.`);
1658
+ }
1659
+ // Same order as before; a changed channel keeps its place.
1660
+ channels = [
1661
+ ...channels.map((existing) => next.find((entry) => entry.id === existing.id) ?? existing),
1662
+ ...next.filter((entry) => !channels.some((existing) => existing.id === entry.id)),
1663
+ ];
1664
+ const result = await call("audio.channels", { channels });
1665
+ setAudio(audioStateOf(result, channels));
1666
+ },
1667
+ async set(changes) {
1668
+ const result = await call("audio.set", { audio: changes });
1669
+ setAudio(audioStateOf(result, channels));
1670
+ },
1671
+ on(_event, listener) {
1672
+ audioListeners.add(listener);
1673
+ return () => audioListeners.delete(listener);
1674
+ },
1675
+ },
1378
1676
  rooms: realtime.rooms,
1379
1677
  twitch: {
1380
1678
  info: twitch.info,
package/dist/powly.mjs CHANGED
@@ -1,6 +1,6 @@
1
- /* Powly SDK 0.6.0: ES module */
1
+ /* Powly SDK 0.8.0: ES module */
2
2
  /** This SDK's version; Powly's Studio shows it next to the downloads. */
3
- const SDK_VERSION = "0.6.0";
3
+ const SDK_VERSION = "0.8.0";
4
4
 
5
5
  // The messages between a game (this SDK, inside Powly's iframe) and the Powly page that framed it.
6
6
  // Shared with the host side (apps/web/components/player/sdk-host.ts).
@@ -20,16 +20,61 @@ const OPTIONS_BUTTON_CORNERS = [
20
20
  "bottom-right",
21
21
  ];
22
22
  const isOptionsButtonCorner = (value) => OPTIONS_BUTTON_CORNERS.includes(value);
23
+ /** Channel ids: letters, digits, _ and -, starting with a letter, up to 32. */
24
+ const AUDIO_CHANNEL_ID = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
25
+ const MAX_AUDIO_CHANNELS = 8;
26
+ const MAX_AUDIO_LABEL = 32;
27
+ /** The channels a game sent, cleaned up: valid ids, short labels, no repeats, at most 8. */
28
+ function audioChannelsOf(value) {
29
+ if (!Array.isArray(value))
30
+ return [];
31
+ const channels = [];
32
+ for (const entry of value) {
33
+ if (typeof entry !== "object" || entry === null)
34
+ continue;
35
+ const { id, label, volume, toggle } = entry;
36
+ if (typeof id !== "string" || !AUDIO_CHANNEL_ID.test(id))
37
+ continue;
38
+ if (channels.some((channel) => channel.id === id))
39
+ continue;
40
+ const text = typeof label === "string" ? label.trim().slice(0, MAX_AUDIO_LABEL) : "";
41
+ const slider = volume !== false;
42
+ // Neither a slider nor a switch would show nothing: both, then.
43
+ const onOff = toggle !== false || !slider;
44
+ channels.push({ id, label: text || id, volume: slider, toggle: onOff });
45
+ if (channels.length === MAX_AUDIO_CHANNELS)
46
+ break;
47
+ }
48
+ return channels;
49
+ }
50
+ /** A volume between 0 and 1, or null. */
51
+ const volumeOf = (value) => typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : null;
52
+ /** What a game may ask the Powly page for. */
53
+ const HOST_METHODS = [
54
+ "getSessionToken",
55
+ "purchases.open",
56
+ "fullscreen.toggle",
57
+ "invites.open",
58
+ "players.open",
59
+ "twitch.connect",
60
+ "audio.set",
61
+ "audio.channels",
62
+ "quit",
63
+ ];
64
+ /** "players.open": what Powly's player dialog opens on. */
65
+ const PLAYER_VIEWS = ["profile", "report"];
23
66
  const isInitMessage = (data) => typeof data === "object" &&
24
67
  data !== null &&
25
68
  data.protocol === PROTOCOL &&
26
69
  data.type === "init" &&
27
70
  data.version === PROTOCOL_VERSION;
28
- const isRequestMessage = (data) => typeof data === "object" &&
71
+ /** A request with a method this Powly doesn't know (from a newer SDK): answered with an error. */
72
+ const isRequestShaped = (data) => typeof data === "object" &&
29
73
  data !== null &&
30
74
  data.type === "request" &&
31
- Number.isInteger(data.id) &&
32
- ["getSessionToken", "purchases.open", "fullscreen.toggle", "invites.open", "quit"].includes(data.method);
75
+ Number.isInteger(data.id);
76
+ const isRequestMessage = (data) => isRequestShaped(data) &&
77
+ HOST_METHODS.includes(data.method);
33
78
 
34
79
  // The Powly origins this build of the SDK trusts by default: a game only handshakes with a parent
35
80
  // page on one of them (unless it passes `powlyOrigin` to `Powly.init()` itself). Set at build
@@ -859,6 +904,11 @@ function createRooms(options) {
859
904
  // });
860
905
  // }
861
906
  //
907
+ // A game with a Twitch mode among others (Twitch chat "optional" in Studio) passes
908
+ // `{ prompt: true }` when the player picks that mode: if they haven't connected Twitch, Powly asks
909
+ // them to in its own dialog (drawn by Powly, outside the game), and `connect()` resolves once
910
+ // they did or closed it.
911
+ //
862
912
  // Chat is Twitch IRC over a WebSocket (https://dev.twitch.tv/docs/chat/irc/). The connection comes
863
913
  // back by itself when it drops, and stops when the launch ends.
864
914
  const TWITCH_CHAT_URL = "wss://irc-ws.chat.twitch.tv:443";
@@ -1099,8 +1149,12 @@ function createTwitch(options) {
1099
1149
  };
1100
1150
  return {
1101
1151
  info: options.getInfo,
1102
- async connect() {
1103
- const info = await options.getInfo();
1152
+ async connect(connectOptions = {}) {
1153
+ let info = await options.getInfo();
1154
+ if (info.status === "not_connected" && connectOptions.prompt && options.prompt) {
1155
+ if (await options.prompt())
1156
+ info = await options.getInfo();
1157
+ }
1104
1158
  const next = info.status === "connected" ? info.channel : null;
1105
1159
  if (!next || stopped) {
1106
1160
  disconnect();
@@ -1139,6 +1193,154 @@ function createTwitch(options) {
1139
1193
  };
1140
1194
  }
1141
1195
 
1196
+ // Powly's sound menu for games (`powly.audio`): the player's overall volume, a mute (Powly's M
1197
+ // key), and the kinds of sound the game registers (channels: music, drawing sounds…), each with a
1198
+ // volume slider and an on/off switch, or one of them. The player sets them in Powly's options
1199
+ // bar; the game hears "change".
1200
+ //
1201
+ // const powly = await Powly.init({
1202
+ // audio: { channels: [{ id: "music", label: "Music" }] },
1203
+ // });
1204
+ // await powly.audio.register({ id: "drawing", label: "Drawing sounds", volume: false });
1205
+ // music.volume = powly.audio.level("music");
1206
+ // powly.audio.on("change", () => { music.volume = powly.audio.level("music"); });
1207
+ // if (powly.audio.level("drawing") > 0) playScribble();
1208
+ //
1209
+ // The overall volume and mute apply by themselves (`auto`, on by default): the SDK puts a volume
1210
+ // control in front of the page's speakers, for Web Audio (every connection to an AudioContext's
1211
+ // destination goes through it) and for <audio>/<video> (their volume is scaled). So every game
1212
+ // on this SDK follows Powly's volume, and channels only need the channel's own value:
1213
+ // `level(channel)` is what to play at either way.
1214
+ /** Volume of the page's sound overall: 0 when muted. */
1215
+ const masterLevel = (state) => (state.muted ? 0 : state.volume);
1216
+ /** Live references to objects, for walking them later without keeping them alive. */
1217
+ function weakList() {
1218
+ const seen = new WeakSet();
1219
+ const refs = new Set();
1220
+ return {
1221
+ add(item) {
1222
+ if (seen.has(item))
1223
+ return false;
1224
+ seen.add(item);
1225
+ refs.add(new WeakRef(item));
1226
+ return true;
1227
+ },
1228
+ has: (item) => seen.has(item),
1229
+ *[Symbol.iterator]() {
1230
+ for (const ref of refs) {
1231
+ const item = ref.deref();
1232
+ if (item)
1233
+ yield item;
1234
+ else
1235
+ refs.delete(ref);
1236
+ }
1237
+ },
1238
+ };
1239
+ }
1240
+ /**
1241
+ * Puts a volume control in front of the page's speakers: Web Audio connections to a real-time
1242
+ * AudioContext's destination go through a gain node per context, and media elements' volume is
1243
+ * scaled (the volume the game set still reads back unchanged; elements played through Web Audio
1244
+ * are left to the gain node). Returns how to set it.
1245
+ */
1246
+ function installMasterGain(win = window) {
1247
+ let level = 1;
1248
+ // Web Audio.
1249
+ const gainOf = new WeakMap();
1250
+ const gains = weakList();
1251
+ const Destination = win.AudioDestinationNode;
1252
+ const Offline = win.OfflineAudioContext;
1253
+ const nodeProto = win.AudioNode?.prototype;
1254
+ const connect = nodeProto?.connect;
1255
+ const disconnect = nodeProto?.disconnect;
1256
+ /** The gain node standing in for `target` when it's a real-time context's destination. */
1257
+ const standIn = (target) => {
1258
+ if (!Destination || !(target instanceof Destination))
1259
+ return null;
1260
+ const context = target.context;
1261
+ if (Offline && context instanceof Offline)
1262
+ return null;
1263
+ let gain = gainOf.get(context);
1264
+ if (!gain) {
1265
+ gain = context.createGain();
1266
+ gain.gain.value = level;
1267
+ gains.add(gain);
1268
+ connect?.call(gain, target);
1269
+ gainOf.set(context, gain);
1270
+ }
1271
+ return gain;
1272
+ };
1273
+ if (nodeProto && connect && disconnect) {
1274
+ nodeProto.connect = function (target, ...rest) {
1275
+ const gain = gains.has(this) ? null : standIn(target);
1276
+ if (!gain)
1277
+ return connect.call(this, target, ...rest);
1278
+ connect.call(this, gain, ...rest);
1279
+ // Chaining keeps working: connect() answers what it was given.
1280
+ return target;
1281
+ };
1282
+ nodeProto.disconnect = function (...args) {
1283
+ const gain = gains.has(this) ? null : standIn(args[0]);
1284
+ return gain ? disconnect.call(this, gain, ...args.slice(1)) : disconnect.apply(this, args);
1285
+ };
1286
+ }
1287
+ // Media elements: the volume the game set, and the one played (times `level`).
1288
+ const media = win.HTMLMediaElement?.prototype;
1289
+ const volume = media ? Object.getOwnPropertyDescriptor(media, "volume") : undefined;
1290
+ const wanted = new WeakMap();
1291
+ const elements = weakList();
1292
+ const routed = new WeakSet();
1293
+ const apply = (element) => {
1294
+ const own = wanted.get(element) ?? 1;
1295
+ volume?.set?.call(element, routed.has(element) ? own : own * level);
1296
+ };
1297
+ const track = (element) => {
1298
+ if (!wanted.has(element))
1299
+ wanted.set(element, volume?.get?.call(element) ?? 1);
1300
+ elements.add(element);
1301
+ apply(element);
1302
+ };
1303
+ if (media && volume?.get && volume.set) {
1304
+ const { get, set } = volume;
1305
+ Object.defineProperty(media, "volume", {
1306
+ configurable: true,
1307
+ enumerable: volume.enumerable,
1308
+ get() {
1309
+ return wanted.get(this) ?? get.call(this);
1310
+ },
1311
+ set(value) {
1312
+ // Out of range throws, like the browser's own setter.
1313
+ set.call(this, value);
1314
+ wanted.set(this, value);
1315
+ track(this);
1316
+ },
1317
+ });
1318
+ const play = media.play;
1319
+ media.play = function () {
1320
+ track(this);
1321
+ return play.call(this);
1322
+ };
1323
+ }
1324
+ const createSource = win.AudioContext?.prototype.createMediaElementSource;
1325
+ if (createSource) {
1326
+ win.AudioContext.prototype.createMediaElementSource = function (element) {
1327
+ routed.add(element);
1328
+ track(element);
1329
+ return createSource.call(this, element);
1330
+ };
1331
+ }
1332
+ return {
1333
+ set(next) {
1334
+ level = next;
1335
+ for (const gain of gains)
1336
+ gain.gain.value = level;
1337
+ for (const element of elements)
1338
+ apply(element);
1339
+ },
1340
+ };
1341
+ }
1342
+
1343
+
1142
1344
 
1143
1345
 
1144
1346
 
@@ -1156,6 +1358,8 @@ function createTwitch(options) {
1156
1358
  // const token = await powly.getSessionToken(); // send it to your backend, which verifies it
1157
1359
  // const room = await powly.rooms.create(); // realtime parties (src/rooms.ts)
1158
1360
  // await powly.twitch.connect(); // the streamer's Twitch chat (src/twitch.ts)
1361
+ // await powly.players.open(playerId); // Powly's profile dialog: add, block, report
1362
+ // powly.audio.level("music"); // Powly's sound menu (src/audio.ts)
1159
1363
  //
1160
1364
  // Nothing here is a security boundary: the game runs in the player's browser. Your backend must
1161
1365
  // verify session tokens (JWKS) or exchange them, and Powly checks everything server-side.
@@ -1200,6 +1404,12 @@ function init(options = {}) {
1200
1404
  if (origins.length === 0) {
1201
1405
  return Promise.reject(new PowlyError("This game only runs when launched from Powly."));
1202
1406
  }
1407
+ const audioChannels = audioChannelsOf(options.audio?.channels ?? []);
1408
+ // Before the game's engine makes a sound, so its connections go through the volume control.
1409
+ const auto = options.audio?.auto !== false;
1410
+ if (auto)
1411
+ masterGain ??= installMasterGain();
1412
+ const master = auto ? masterGain : null;
1203
1413
  return new Promise((resolve, reject) => {
1204
1414
  const channels = origins.map((origin) => {
1205
1415
  const channel = new MessageChannel();
@@ -1212,6 +1422,7 @@ function init(options = {}) {
1212
1422
  ...(isOptionsButtonCorner(options.optionsButton) && {
1213
1423
  optionsButton: options.optionsButton,
1214
1424
  }),
1425
+ audio: { channels: audioChannels },
1215
1426
  };
1216
1427
  channel.port1.onmessage = (event) => {
1217
1428
  const data = event.data;
@@ -1220,7 +1431,7 @@ function init(options = {}) {
1220
1431
  for (const other of channels)
1221
1432
  if (other !== channel)
1222
1433
  other.port1.close();
1223
- resolve(createSession(channel.port1, data));
1434
+ resolve(createSession(channel.port1, data, { channels: audioChannels, master }));
1224
1435
  }
1225
1436
  else if (data?.type === "failed") {
1226
1437
  clearTimeout(timer);
@@ -1238,7 +1449,22 @@ function init(options = {}) {
1238
1449
  }, options.timeoutMs ?? 10_000);
1239
1450
  });
1240
1451
  }
1241
- function createSession(port, ready) {
1452
+ /** The page's volume control (src/audio.ts), put in once even if init runs again. */
1453
+ let masterGain = null;
1454
+ /** The sound settings Powly sent, with every channel (on, at full volume, when it sent none). */
1455
+ function audioStateOf(value, channels) {
1456
+ const sent = (typeof value === "object" && value !== null ? value : {});
1457
+ const levels = ((typeof sent.channels === "object" && sent.channels) || {});
1458
+ return {
1459
+ volume: volumeOf(sent.volume) ?? 1,
1460
+ muted: sent.muted === true,
1461
+ channels: Object.fromEntries(channels.map((channel) => {
1462
+ const level = levels[channel.id];
1463
+ return [channel.id, { volume: volumeOf(level?.volume) ?? 1, on: level?.on !== false }];
1464
+ })),
1465
+ };
1466
+ }
1467
+ function createSession(port, ready, sound) {
1242
1468
  let token = ready.token;
1243
1469
  let expiresAt = Date.now() + ready.expiresIn * 1000;
1244
1470
  let refreshing = null;
@@ -1247,6 +1473,23 @@ function createSession(port, ready) {
1247
1473
  const listeners = new Map();
1248
1474
  // "shown" comes once; games that listen for it later still hear it.
1249
1475
  let shown = false;
1476
+ // The player's sound settings; the page's volume follows them (auto).
1477
+ let channels = sound.channels;
1478
+ let audio = audioStateOf(ready.audio, channels);
1479
+ const audioListeners = new Set();
1480
+ sound.master?.set(masterLevel(audio));
1481
+ const setAudio = (next) => {
1482
+ audio = next;
1483
+ sound.master?.set(masterLevel(audio));
1484
+ for (const listener of audioListeners) {
1485
+ try {
1486
+ listener(audio);
1487
+ }
1488
+ catch (error) {
1489
+ console.error("[powly] an audio listener failed", error);
1490
+ }
1491
+ }
1492
+ };
1250
1493
  port.onmessage = (event) => {
1251
1494
  const data = event.data;
1252
1495
  if (data?.type === "response") {
@@ -1260,7 +1503,13 @@ function createSession(port, ready) {
1260
1503
  waiting.reject(new PowlyError(data.error));
1261
1504
  }
1262
1505
  else if (data?.type === "event") {
1263
- const name = data.event;
1506
+ const message = data;
1507
+ if (message.event === "audio") {
1508
+ if ("audio" in message)
1509
+ setAudio(audioStateOf(message.audio, channels));
1510
+ return;
1511
+ }
1512
+ const name = message.event;
1264
1513
  if (name === "shown") {
1265
1514
  if (shown)
1266
1515
  return;
@@ -1326,7 +1575,10 @@ function createSession(port, ready) {
1326
1575
  invite: sendInvite,
1327
1576
  });
1328
1577
  listeners.get("ended")?.add(() => realtime.stop());
1329
- const twitch = createTwitch({ getInfo: () => api("/twitch") });
1578
+ const twitch = createTwitch({
1579
+ getInfo: () => api("/twitch"),
1580
+ prompt: async () => (await call("twitch.connect")).connected,
1581
+ });
1330
1582
  listeners.get("ended")?.add(() => twitch.stop());
1331
1583
  const saves = {
1332
1584
  get: async (key) => {
@@ -1373,6 +1625,52 @@ function createSession(port, ready) {
1373
1625
  return (await call("invites.open", { params, members }));
1374
1626
  },
1375
1627
  },
1628
+ players: {
1629
+ open: async (playerId, options = {}) => (await call("players.open", {
1630
+ playerId,
1631
+ ...(options.view && { view: options.view }),
1632
+ })),
1633
+ },
1634
+ audio: {
1635
+ get volume() {
1636
+ return audio.volume;
1637
+ },
1638
+ get muted() {
1639
+ return audio.muted;
1640
+ },
1641
+ get channels() {
1642
+ return Object.fromEntries(Object.entries(audio.channels).map(([id, state]) => [id, { ...state }]));
1643
+ },
1644
+ level(channel) {
1645
+ const state = channel === undefined ? undefined : audio.channels[channel];
1646
+ const own = state ? (state.on ? state.volume : 0) : 1;
1647
+ return sound.master ? own : own * masterLevel(audio);
1648
+ },
1649
+ async register(channel) {
1650
+ const next = audioChannelsOf([
1651
+ ...channels.filter((existing) => existing.id !== channel?.id),
1652
+ channel,
1653
+ ]);
1654
+ if (!next.some((entry) => entry.id === channel?.id)) {
1655
+ throw new PowlyError(`A channel needs an id of letters, digits, _ and -, and a game has up to ${MAX_AUDIO_CHANNELS}.`);
1656
+ }
1657
+ // Same order as before; a changed channel keeps its place.
1658
+ channels = [
1659
+ ...channels.map((existing) => next.find((entry) => entry.id === existing.id) ?? existing),
1660
+ ...next.filter((entry) => !channels.some((existing) => existing.id === entry.id)),
1661
+ ];
1662
+ const result = await call("audio.channels", { channels });
1663
+ setAudio(audioStateOf(result, channels));
1664
+ },
1665
+ async set(changes) {
1666
+ const result = await call("audio.set", { audio: changes });
1667
+ setAudio(audioStateOf(result, channels));
1668
+ },
1669
+ on(_event, listener) {
1670
+ audioListeners.add(listener);
1671
+ return () => audioListeners.delete(listener);
1672
+ },
1673
+ },
1376
1674
  rooms: realtime.rooms,
1377
1675
  twitch: {
1378
1676
  info: twitch.info,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powly/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Powly game SDK: launch handshake, session tokens and platform services.",
6
6
  "license": "MIT",
@@ -46,4 +46,4 @@
46
46
  "example:zip": "node scripts/example-zip.ts",
47
47
  "mirror": "node scripts/mirror.ts"
48
48
  }
49
- }
49
+ }