@smoud/playable-sdk 1.0.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.
@@ -0,0 +1,604 @@
1
+ // src/events.ts
2
+ var registeredEvents = {};
3
+ function onEvent(event, fn, context, once) {
4
+ let listeners = registeredEvents[event];
5
+ if (!listeners) {
6
+ listeners = registeredEvents[event] = {
7
+ list: []
8
+ };
9
+ }
10
+ listeners.list.push(fn, context || null, once || false);
11
+ }
12
+ function offEvent(event, fn, context) {
13
+ const listeners = registeredEvents[event];
14
+ if (!listeners) return;
15
+ var fnArray = listeners.list;
16
+ if (!fn) {
17
+ fnArray.length = 0;
18
+ } else {
19
+ let i = fnArray.length;
20
+ while (i > 0) {
21
+ i -= 3;
22
+ if (fnArray[i] == fn && (context !== void 0 || fnArray[i + 1] == context)) {
23
+ fnArray.splice(i, 3);
24
+ }
25
+ }
26
+ }
27
+ if (fnArray.length == 0) {
28
+ delete registeredEvents[event];
29
+ }
30
+ }
31
+ function emitEvent(event, a1, a2, a3) {
32
+ var listeners = registeredEvents[event];
33
+ if (!listeners) return;
34
+ const fnArray = listeners.list;
35
+ const len = arguments.length;
36
+ let fn, ctx;
37
+ for (var i = 0; i < fnArray.length; i += 3) {
38
+ fn = fnArray[i];
39
+ ctx = fnArray[i + 1];
40
+ if (fnArray[i + 2]) {
41
+ fnArray.splice(i, 3);
42
+ i -= 3;
43
+ }
44
+ if (len <= 1) fn.call(ctx);
45
+ else if (len == 2) fn.call(ctx, a1);
46
+ else if (len == 3) fn.call(ctx, a1, a2);
47
+ else fn.call(ctx, a1, a2, a3);
48
+ }
49
+ if (fnArray.length == 0) {
50
+ delete registeredEvents[event];
51
+ }
52
+ }
53
+
54
+ // src/protocols.ts
55
+ var uid = 0;
56
+ var NONE = uid++;
57
+ var MRAID = uid++;
58
+ var DAPI = uid++;
59
+ var NUCLEO = uid++;
60
+ var FACEBOOK = uid++;
61
+ var GOOGLE = uid++;
62
+ var MINTEGRAL = uid++;
63
+ var TAPJOY = uid++;
64
+ var TIKTOK = uid++;
65
+ var actualProtocol = NONE;
66
+ function isMraid() {
67
+ return actualProtocol === MRAID;
68
+ }
69
+ function isDapi() {
70
+ return actualProtocol === DAPI;
71
+ }
72
+ function isNucleo() {
73
+ return actualProtocol === NUCLEO;
74
+ }
75
+ function isFacebook() {
76
+ return actualProtocol === FACEBOOK;
77
+ }
78
+ function isGoogle() {
79
+ return actualProtocol === GOOGLE;
80
+ }
81
+ function isMintegral() {
82
+ return actualProtocol === MINTEGRAL;
83
+ }
84
+ function isTapjoy() {
85
+ return actualProtocol === TAPJOY;
86
+ }
87
+ function isTikTok() {
88
+ return actualProtocol === TIKTOK;
89
+ }
90
+ function ensureProtocol() {
91
+ if ("mraid" === AD_PROTOCOL) {
92
+ try {
93
+ mraid.getState();
94
+ actualProtocol = MRAID;
95
+ } catch (error) {
96
+ }
97
+ } else if ("dapi" === AD_PROTOCOL) {
98
+ try {
99
+ dapi.isReady();
100
+ actualProtocol = DAPI;
101
+ } catch (error) {
102
+ }
103
+ } else if ("facebook" === AD_NETWORK) {
104
+ try {
105
+ if (FbPlayableAd) actualProtocol = FACEBOOK;
106
+ } catch (error) {
107
+ }
108
+ } else if ("google" === AD_NETWORK) {
109
+ try {
110
+ if (ExitApi) actualProtocol = GOOGLE;
111
+ } catch (error) {
112
+ }
113
+ } else if ("mintegral" === AD_NETWORK) {
114
+ if (window.gameReady) actualProtocol = MINTEGRAL;
115
+ } else if ("tapjoy" === AD_NETWORK) {
116
+ if (window.TJ_API) actualProtocol = TAPJOY;
117
+ } else if ("tiktok" === AD_NETWORK) {
118
+ if (window.openAppStore) actualProtocol = TIKTOK;
119
+ }
120
+ }
121
+
122
+ // src/core.ts
123
+ var destinationUrl = /android/i.test(navigator.userAgent) ? GOOGLE_PLAY_URL : APP_STORE_URL;
124
+ var isSDKInitialized = false;
125
+ var isProtocolInitialized = false;
126
+ var isForcePaused = false;
127
+ var isInstallClicked = false;
128
+ var initCallback = () => {
129
+ };
130
+ function bootAd() {
131
+ if (sdk.isReady) return;
132
+ emitEvent("boot");
133
+ document.body.oncontextmenu = function() {
134
+ return false;
135
+ };
136
+ initCallback(sdk.maxWidth, sdk.maxHeight);
137
+ emitEvent("ready");
138
+ sdk.isReady = true;
139
+ }
140
+ function changeVolume(value) {
141
+ emitEvent("volume", value);
142
+ }
143
+ function handlePause() {
144
+ changeVolume(0);
145
+ sdk.isPaused = true;
146
+ emitEvent("pause");
147
+ }
148
+ function handleResume() {
149
+ if (isForcePaused) return;
150
+ changeVolume(sdk.volume);
151
+ sdk.isPaused = false;
152
+ emitEvent("resume");
153
+ }
154
+ function mraidIsViewable(viewable) {
155
+ if ("mraid" !== AD_PROTOCOL) return;
156
+ if (viewable) {
157
+ if (sdk.isReady) {
158
+ handleResume();
159
+ } else {
160
+ if (AD_NETWORK == "ironsource") {
161
+ const maxSize = mraid.getMaxSize();
162
+ sdk.maxWidth = Math.floor(maxSize.width);
163
+ sdk.maxHeight = Math.floor(maxSize.height);
164
+ }
165
+ bootAd();
166
+ }
167
+ } else {
168
+ handlePause();
169
+ }
170
+ }
171
+ function dapiIsViewable(event) {
172
+ if ("dapi" !== AD_PROTOCOL) return;
173
+ if (event.isViewable) {
174
+ if (sdk.isReady) {
175
+ handleResume();
176
+ } else {
177
+ var screenSize = dapi.getScreenSize();
178
+ screenSize.width = Math.floor(screenSize.width);
179
+ screenSize.height = Math.floor(screenSize.height);
180
+ bootAd();
181
+ }
182
+ } else {
183
+ handlePause();
184
+ }
185
+ }
186
+ function fireResizeEvent(width, height) {
187
+ handleResize(width, height);
188
+ }
189
+ function startMraidProtocol() {
190
+ if ("mraid" !== AD_PROTOCOL) return;
191
+ if (!isProtocolInitialized) {
192
+ mraid.removeEventListener("ready", startMraidProtocol);
193
+ mraid.addEventListener("viewableChange", function() {
194
+ var isViewable = mraid.isViewable();
195
+ mraidIsViewable(isViewable);
196
+ });
197
+ if (mraid.isViewable() || AD_NETWORK == "adcolony") {
198
+ mraidIsViewable(true);
199
+ }
200
+ mraid.addEventListener("audioVolumeChange", function(newVolume) {
201
+ if (newVolume !== null) {
202
+ if (newVolume > 0) {
203
+ changeVolume(sdk.volume);
204
+ } else {
205
+ changeVolume(0);
206
+ }
207
+ }
208
+ });
209
+ mraid.addEventListener("error", function(t, e) {
210
+ console.log("mraid error: " + t + " action: " + e);
211
+ });
212
+ mraid.addEventListener("sizeChange", function() {
213
+ var maxSize = mraid.getMaxSize();
214
+ fireResizeEvent(maxSize.width, maxSize.height);
215
+ });
216
+ isProtocolInitialized = true;
217
+ }
218
+ }
219
+ function startDapiProtocol() {
220
+ if ("dapi" !== AD_PROTOCOL) return;
221
+ if (!isProtocolInitialized) {
222
+ dapi.removeEventListener("ready", startDapiProtocol);
223
+ var isAudioEnabled = !!dapi.getAudioVolume();
224
+ dapi.addEventListener("audioVolumeChange", function(volume) {
225
+ var isAudioEnabled2 = !!volume;
226
+ if (isAudioEnabled2) {
227
+ changeVolume(sdk.volume);
228
+ } else {
229
+ changeVolume(0);
230
+ }
231
+ });
232
+ dapi.addEventListener("adResized", function(event) {
233
+ var maxSize = dapi.getScreenSize();
234
+ fireResizeEvent(event.width || maxSize.width, event.height || maxSize.height);
235
+ });
236
+ if (dapi.isViewable()) {
237
+ dapiIsViewable({ isViewable: true });
238
+ }
239
+ dapi.addEventListener("viewableChange", dapiIsViewable);
240
+ isProtocolInitialized = true;
241
+ }
242
+ }
243
+ function startDefaultProtocol() {
244
+ if ("none" !== AD_PROTOCOL) return;
245
+ if (!isProtocolInitialized) {
246
+ if ("mintegral" === AD_NETWORK) {
247
+ window.mintGameStart = function() {
248
+ handleResume();
249
+ handleResize(sdk.maxWidth, sdk.maxHeight);
250
+ };
251
+ window.mintGameClose = function() {
252
+ handlePause();
253
+ };
254
+ }
255
+ document.addEventListener("visibilitychange", () => {
256
+ if (document.visibilityState === "visible") {
257
+ if (sdk.isReady) {
258
+ handleResume();
259
+ } else {
260
+ bootAd();
261
+ }
262
+ } else {
263
+ handlePause();
264
+ }
265
+ });
266
+ if (document.readyState === "complete" || document.visibilityState === "visible") {
267
+ bootAd();
268
+ } else {
269
+ window.addEventListener("load", () => {
270
+ bootAd();
271
+ });
272
+ }
273
+ window.addEventListener("resize", function() {
274
+ handleResize();
275
+ });
276
+ if ("tapjoy" === AD_NETWORK && isTapjoy()) {
277
+ var tapjoyApi = {
278
+ skipAd: function() {
279
+ try {
280
+ sdk.finish();
281
+ } catch (e) {
282
+ console.warn("Could not skip ad! | " + e);
283
+ }
284
+ }
285
+ };
286
+ window.TJ_API.setPlayableAPI && window.TJ_API.setPlayableAPI(tapjoyApi);
287
+ }
288
+ isProtocolInitialized = true;
289
+ }
290
+ }
291
+ function finishTapjoy() {
292
+ window.TJ_API.objectiveComplete && window.TJ_API.objectiveComplete();
293
+ window.TJ_API.playableFinished && window.TJ_API.playableFinished();
294
+ window.TJ_API.gameplayFinished && window.TJ_API.gameplayFinished();
295
+ }
296
+ function handleResize(width, height) {
297
+ sdk.maxWidth = Math.floor(width || window.innerWidth);
298
+ sdk.maxHeight = Math.floor(height || window.innerHeight);
299
+ sdk.isLandscape = sdk.maxWidth > sdk.maxHeight;
300
+ emitEvent("resize", sdk.maxWidth, sdk.maxHeight);
301
+ }
302
+ var isListeningToTouchEvents = false;
303
+ var isTouchEventRegistered = false;
304
+ function onUserInteraction(event) {
305
+ if (typeof TouchEvent !== "undefined" && event instanceof TouchEvent) {
306
+ isListeningToTouchEvents = true;
307
+ }
308
+ if (isListeningToTouchEvents && event instanceof MouseEvent) return;
309
+ sdk.interactions += 1;
310
+ emitEvent("interaction", sdk.interactions);
311
+ }
312
+ function registerTouchHandlers() {
313
+ if (!isTouchEventRegistered) {
314
+ document.addEventListener("mousedown", onUserInteraction);
315
+ document.addEventListener("touchstart", onUserInteraction);
316
+ isTouchEventRegistered = true;
317
+ }
318
+ }
319
+ var _sdk = class _sdk {
320
+ /**
321
+ * Initializes the SDK and sets up protocol-specific handlers.
322
+ * This must be called as earlier as possible.
323
+ *
324
+ * @param callback Optional function called when ad container is ready
325
+ * @example
326
+ * // Basic initialization
327
+ * sdk.init();
328
+ *
329
+ * // Initialization with callback
330
+ * sdk.init((width, height) => {
331
+ * new App(width, height)
332
+ * });
333
+ *
334
+ * @fires init When initialization starts
335
+ * @fires boot When the ad begins booting
336
+ * @fires ready When Ad Network is ready and playable ad can be initialized
337
+ */
338
+ static init(callback) {
339
+ if (isSDKInitialized) return;
340
+ ensureProtocol();
341
+ if (callback) initCallback = callback;
342
+ if ("mraid" === AD_PROTOCOL && isMraid()) {
343
+ if (mraid.getState() !== "ready" && "adcolony" !== AD_NETWORK) {
344
+ mraid.addEventListener("ready", startMraidProtocol);
345
+ } else {
346
+ startMraidProtocol();
347
+ }
348
+ } else if ("dapi" === AD_PROTOCOL && isDapi()) {
349
+ window.addEventListener("load", function() {
350
+ dapi.isReady() ? startDapiProtocol() : dapi.addEventListener("ready", startDapiProtocol);
351
+ });
352
+ } else {
353
+ startDefaultProtocol();
354
+ }
355
+ emitEvent("init");
356
+ isSDKInitialized = true;
357
+ }
358
+ /**
359
+ * Starts the playable ad experience.
360
+ * Should be called after all resources are loaded and first frame is rendered.
361
+ *
362
+ * @example
363
+ * // Call just after all resources are preloaded and first frame is rendered
364
+ * sdk.start();
365
+ *
366
+ * @fires start When the playable ad starts
367
+ * @fires resize When the ad container is initially sized
368
+ */
369
+ static start() {
370
+ if (_sdk.isStarted) return;
371
+ _sdk.isStarted = true;
372
+ emitEvent("start");
373
+ registerTouchHandlers();
374
+ if ("mintegral" === AD_NETWORK && isMintegral()) {
375
+ _sdk.resize();
376
+ handlePause();
377
+ window.gameReady && window.gameReady();
378
+ } else {
379
+ if ("tapjoy" === AD_NETWORK && isTapjoy()) {
380
+ window.TJ_API.setPlayableBuild({
381
+ orientation: this.isLandscape ? "landscape" : "portrait",
382
+ buildID: __BUILD_ID__
383
+ });
384
+ }
385
+ _sdk.resize();
386
+ }
387
+ }
388
+ /**
389
+ * Marks the playable ad as finished.
390
+ * This triggers network-specific completion handlers.
391
+ *
392
+ * @example
393
+ * // Call when game/experience is complete
394
+ * sdk.finish();
395
+ *
396
+ * @fires finish When the playable ad is marked as finished
397
+ */
398
+ static finish() {
399
+ _sdk.isFinished = true;
400
+ if ("tapjoy" === AD_NETWORK && isTapjoy()) {
401
+ finishTapjoy();
402
+ } else if ("mintegral" === AD_NETWORK && isMintegral()) {
403
+ window.gameEnd && window.gameEnd();
404
+ } else if ("vungle" === AD_NETWORK) {
405
+ parent.postMessage("complete", "*");
406
+ }
407
+ emitEvent("finish");
408
+ }
409
+ /**
410
+ * Triggers a retry/restart of the playable ad.
411
+ * Behavior varies by ad network.
412
+ *
413
+ * @example
414
+ * // Allow user to try again
415
+ * retryButton.onclick = () => sdk.retry();
416
+ *
417
+ * @fires retry When a retry is triggered
418
+ */
419
+ static retry() {
420
+ if ("mintegral" === AD_NETWORK && isMintegral()) {
421
+ window.gameRetry && window.gameRetry();
422
+ } else if ("nucleo" === AD_PROTOCOL && isNucleo()) {
423
+ NUC.trigger.tryAgain();
424
+ }
425
+ emitEvent("retry");
426
+ }
427
+ /**
428
+ * Triggers the install/download action for the advertised app.
429
+ * Handles different store opening methods across ad networks.
430
+ *
431
+ * @example
432
+ * // Call when user wants to install
433
+ * installButton.onclick = () => sdk.install();
434
+ *
435
+ * @fires finish If the ad hasn't been marked as finished
436
+ * @fires install When the install action is triggered
437
+ */
438
+ static install() {
439
+ if (!_sdk.isFinished) {
440
+ _sdk.isFinished = true;
441
+ let timeout = 0;
442
+ if ("tapjoy" === AD_NETWORK && isTapjoy()) {
443
+ finishTapjoy();
444
+ timeout = 300;
445
+ }
446
+ emitEvent("finish");
447
+ setTimeout(function() {
448
+ _sdk.install();
449
+ }, timeout);
450
+ return;
451
+ }
452
+ if (isInstallClicked) return;
453
+ isInstallClicked = true;
454
+ setTimeout(function() {
455
+ isInstallClicked = false;
456
+ }, 500);
457
+ emitEvent("install");
458
+ if ("mraid" === AD_PROTOCOL && isMraid()) {
459
+ mraid.openStoreUrl ? mraid.openStoreUrl() : mraid.open(destinationUrl);
460
+ } else if ("dapi" === AD_PROTOCOL && isDapi()) {
461
+ dapi.openStoreUrl();
462
+ } else if ("nucleo" === AD_PROTOCOL && isNucleo()) {
463
+ NUC.trigger.convert(destinationUrl);
464
+ } else if ("facebook" == AD_NETWORK && isFacebook()) {
465
+ FbPlayableAd.onCTAClick();
466
+ } else if ("vungle" == AD_NETWORK) {
467
+ parent.postMessage("download", "*");
468
+ } else if ("google" == AD_NETWORK && isGoogle()) {
469
+ ExitApi.exit();
470
+ } else if ("mintegral" === AD_NETWORK && isMintegral()) {
471
+ window.install && window.install();
472
+ } else if ("tapjoy" === AD_NETWORK && isTapjoy()) {
473
+ window.TJ_API.click();
474
+ } else if ("tiktok" === AD_NETWORK && isTikTok()) {
475
+ window.openAppStore();
476
+ } else {
477
+ window.open(destinationUrl);
478
+ }
479
+ }
480
+ /**
481
+ * Trigger force resize event
482
+ * Useful when container size changes need to be manually propagated.
483
+ *
484
+ * @example
485
+ * sdk.resize();
486
+ *
487
+ * @fires resize With current maxWidth and maxHeight
488
+ */
489
+ static resize() {
490
+ handleResize(_sdk.maxWidth, _sdk.maxHeight);
491
+ }
492
+ /**
493
+ * Forces the playable ad into a paused state.
494
+ *
495
+ * @example
496
+ * // Pause the experience
497
+ * pauseButton.onclick = () => sdk.pause();
498
+ *
499
+ * @fires pause When the ad enters paused state
500
+ */
501
+ static pause() {
502
+ if (!isForcePaused) {
503
+ isForcePaused = true;
504
+ handlePause();
505
+ }
506
+ }
507
+ /**
508
+ * Resumes the playable ad from a forced pause state.
509
+ * Only works if the ad was paused via sdk.pause().
510
+ *
511
+ * @example
512
+ * // Resume from pause
513
+ * resumeButton.onclick = () => sdk.resume();
514
+ *
515
+ * @fires resume When the ad resumes from pause
516
+ */
517
+ static resume() {
518
+ if (isForcePaused) {
519
+ isForcePaused = false;
520
+ handleResume();
521
+ }
522
+ }
523
+ /**
524
+ * Registers an event listener.
525
+ *
526
+ * @param event Name of the event to listen for
527
+ * @param fn Callback function to execute when event occurs
528
+ * @param context Optional 'this' context for the callback
529
+ *
530
+ * @example
531
+ * // Listen for user interactions
532
+ * sdk.on('interaction', (count) => {
533
+ * console.log(`User interaction #${count}`);
534
+ * });
535
+ *
536
+ * // Listen for resize with context
537
+ * sdk.on('resize', function(width, height) {
538
+ * this.updateLayout(width, height);
539
+ * }, gameInstance);
540
+ */
541
+ static on(event, fn, context) {
542
+ onEvent(event, fn, context);
543
+ }
544
+ /**
545
+ * Registers a one-time event listener that removes itself after execution.
546
+ *
547
+ * @param event Name of the event to listen for
548
+ * @param fn Callback function to execute when event occurs
549
+ * @param context Optional 'this' context for the callback
550
+ *
551
+ * @example
552
+ * // Listen for first interaction only
553
+ * sdk.once('interaction', () => {
554
+ * console.log('First user interaction occurred!');
555
+ * });
556
+ */
557
+ static once(event, fn, context) {
558
+ onEvent(event, fn, context, true);
559
+ }
560
+ /**
561
+ * Removes an event listener.
562
+ *
563
+ * @param event Name of the event to stop listening for
564
+ * @param fn Optional callback function to remove (if not provided, removes all listeners for the event)
565
+ * @param context Optional 'this' context to match when removing
566
+ *
567
+ * @example
568
+ * // Remove specific listener
569
+ * const handler = () => console.log('Interaction');
570
+ * sdk.off('interaction', handler);
571
+ *
572
+ * // Remove all listeners for an event
573
+ * sdk.off('interaction');
574
+ */
575
+ static off(event, fn, context) {
576
+ offEvent(event, fn, context);
577
+ }
578
+ };
579
+ /** Current version of the SDK */
580
+ _sdk.version = "1.0.0";
581
+ /** Current maximum width of the playable ad container in pixels */
582
+ _sdk.maxWidth = Math.floor(window.innerWidth);
583
+ /** Current maximum height of the playable ad container in pixels */
584
+ _sdk.maxHeight = Math.floor(window.innerHeight);
585
+ /** Indicates if the current orientation is landscape (width > height) */
586
+ _sdk.isLandscape = window.innerWidth > window.innerHeight;
587
+ /** Indicates if the Ad Network is ready and playable ad can be initialized */
588
+ _sdk.isReady = false;
589
+ /** Indicates if all playable ad resources are loaded and gameplay has started */
590
+ _sdk.isStarted = false;
591
+ /** Indicates if the playable ad is currently paused */
592
+ _sdk.isPaused = false;
593
+ /** Indicates if the playable ad has finished */
594
+ _sdk.isFinished = false;
595
+ /** Current volume level (0-1) */
596
+ _sdk.volume = 1;
597
+ /** Number of user interactions with the playable ad */
598
+ _sdk.interactions = 0;
599
+ var sdk = _sdk;
600
+ window.PlayableSDK = sdk;
601
+ export {
602
+ sdk as default,
603
+ sdk
604
+ };