@mpgd/adapter-ait 0.8.0 → 0.10.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/dist/ad-config.d.ts +2 -1
- package/dist/ad-config.js +4 -1
- package/dist/host.d.ts +87 -9
- package/dist/host.js +1173 -14
- package/dist/index.js +8 -0
- package/dist/local-mock.d.ts +71 -0
- package/dist/local-mock.js +59 -0
- package/package.json +9 -5
package/dist/host.js
CHANGED
|
@@ -1,14 +1,34 @@
|
|
|
1
|
-
import { getTossShareLink, getUserKeyForGame, grantPromotionRewardForGame as grantPromotionReward, isMinVersionSupported, loadFullScreenAd, openGameCenterLeaderboard, requestNotificationAgreement, share, showFullScreenAd, Storage, submitGameCenterLeaderBoardScore, } from '@apps-in-toss/web-framework';
|
|
1
|
+
import { getTossShareLink, getUserKeyForGame, grantPromotionRewardForGame as grantPromotionReward, IAP, isMinVersionSupported, loadFullScreenAd, openGameCenterLeaderboard, requestNotificationAgreement, share, showFullScreenAd, Storage, submitGameCenterLeaderBoardScore, TossAds, } from '@apps-in-toss/web-framework';
|
|
2
2
|
import { assertBridgeRequest, bridgeStorageLoadProtocol, } from '@mpgd/bridge';
|
|
3
3
|
import { dispatchAitLifecycleEvent } from './lifecycle.js';
|
|
4
4
|
const defaultAdTimeoutMs = 60000;
|
|
5
5
|
const defaultAdLoadQueueTimeoutMs = 5000;
|
|
6
6
|
const defaultAdDisplayStartTimeoutMs = 60000;
|
|
7
7
|
const defaultAdMaximumDisplayMs = 30 * 60000;
|
|
8
|
+
const defaultBannerRenderTimeoutMs = 15000;
|
|
9
|
+
/** Leaves five seconds of headroom inside the native IAP 30-second grant callback. */
|
|
10
|
+
const defaultIapProductGrantTimeoutMs = 25000;
|
|
11
|
+
/** Bounds abandoned checkout UI while still allowing the user to finish an interactive purchase. */
|
|
12
|
+
const defaultIapPurchaseSessionTimeoutMs = 30 * 60000;
|
|
13
|
+
/** A provider response is untrusted input; keep restore work bounded per launch. */
|
|
14
|
+
const maximumPendingIapOrders = 20;
|
|
8
15
|
const invalidBridgeRequestId = 'ait-invalid-request';
|
|
9
16
|
const rewardedAdEvidenceSchema = 'apps-in-toss.rewarded-ad.callback.v1';
|
|
17
|
+
const iapEvidenceSchema = 'apps-in-toss.iap.callback.v1';
|
|
10
18
|
const minimumPromotionTossAppVersion = '5.232.0';
|
|
11
19
|
const promotionGrantStoragePrefix = 'mpgd:ait:promotion-grant:v1:';
|
|
20
|
+
/**
|
|
21
|
+
* A client idempotency key must survive a bridge reload. The authoritative
|
|
22
|
+
* backend still owns entitlements; this marker only prevents a second native
|
|
23
|
+
* checkout while the first checkout is known to be terminal or ambiguous.
|
|
24
|
+
*/
|
|
25
|
+
const iapPurchaseAttemptStoragePrefix = 'mpgd:ait:iap-purchase-attempt:v1:';
|
|
26
|
+
const iapCompletedPurchaseAttemptIndexStorageKey = 'mpgd:ait:iap-completed-purchase-index:v1';
|
|
27
|
+
const maximumIndexedCompletedIapPurchaseAttempts = 64;
|
|
28
|
+
/** A crashed pre-checkout attempt can be retried only after provider recovery finds no order. */
|
|
29
|
+
const pendingIapPurchaseAttemptRecoveryAgeMs = defaultIapPurchaseSessionTimeoutMs;
|
|
30
|
+
/** Rotates bounded pending-order recovery so an early rejected order cannot starve later work. */
|
|
31
|
+
const iapPendingOrderCursorStorageKey = 'mpgd:ait:pending-order-cursor:v1';
|
|
12
32
|
const defaultNotificationAgreementTimeoutMs = 120000;
|
|
13
33
|
const notificationTopics = new Set([
|
|
14
34
|
'daily-ready',
|
|
@@ -34,8 +54,10 @@ const defaultDependencies = {
|
|
|
34
54
|
isMinVersionSupported,
|
|
35
55
|
loadFullScreenAd,
|
|
36
56
|
showFullScreenAd,
|
|
57
|
+
tossAds: TossAds,
|
|
37
58
|
openGameCenterLeaderboard,
|
|
38
59
|
submitGameCenterLeaderBoardScore,
|
|
60
|
+
iap: IAP,
|
|
39
61
|
};
|
|
40
62
|
export function installAitHostBridge(options = {}) {
|
|
41
63
|
const bridge = createAitHostBridge(options);
|
|
@@ -51,20 +73,43 @@ export function createAitHostBridge(options = {}) {
|
|
|
51
73
|
const authorizePromotionGrant = options.authorizePromotionGrant;
|
|
52
74
|
const resolvePendingPromotionGrant = options.resolvePendingPromotionGrant;
|
|
53
75
|
const notificationTemplateCodes = normalizeNotificationTemplateCodes(options.notificationTemplateCodes);
|
|
76
|
+
const iapProducts = normalizeIapProducts(options.iapProducts);
|
|
77
|
+
const iapProductGrantTimeoutMs = normalizeIapProductGrantTimeout(options.iapProductGrantTimeoutMs);
|
|
54
78
|
const promotionGrantsInFlight = new Map();
|
|
79
|
+
const iapPurchasesInFlight = new Map();
|
|
80
|
+
let completedIapAttemptRetention = Promise.resolve();
|
|
55
81
|
const notificationSubscriptions = new Set();
|
|
56
82
|
const loadedAdGroupIds = new Set();
|
|
57
83
|
const loadingAdGroups = new Map();
|
|
58
84
|
const activeAdGroupIds = new Set();
|
|
85
|
+
const activeBannerAttachments = new Map();
|
|
86
|
+
const bannerMountOwners = new Map();
|
|
87
|
+
const pendingBannerMountSettlements = new Map();
|
|
88
|
+
let bannerInitialization;
|
|
59
89
|
let warnedUnsupportedAdPreload = false;
|
|
60
90
|
const adTimeoutMs = normalizeTimeout(options.adTimeoutMs);
|
|
61
91
|
const adLoadQueueTimeoutMs = normalizeLoadQueueTimeout(options.adLoadQueueTimeoutMs);
|
|
62
92
|
const adDisplayStartTimeoutMs = normalizeDisplayStartTimeout(options.adDisplayStartTimeoutMs);
|
|
63
93
|
const adMaximumDisplayMs = normalizeMaximumDisplayTimeout(options.adMaximumDisplayMs);
|
|
94
|
+
const bannerRenderTimeoutMs = normalizeBannerRenderTimeout(options.bannerRenderTimeoutMs);
|
|
95
|
+
const bannerAppearance = {
|
|
96
|
+
theme: options.bannerAppearance?.theme ?? 'dark',
|
|
97
|
+
tone: options.bannerAppearance?.tone ?? 'blackAndWhite',
|
|
98
|
+
variant: options.bannerAppearance?.variant ?? 'expanded',
|
|
99
|
+
};
|
|
64
100
|
const adLoadCoordinator = {
|
|
65
101
|
active: undefined,
|
|
66
102
|
waitTimeoutMs: adLoadQueueTimeoutMs,
|
|
67
103
|
};
|
|
104
|
+
const enqueueCompletedIapAttemptRetention = (storage, storageKey) => {
|
|
105
|
+
const scheduled = completedIapAttemptRetention.then(async () => {
|
|
106
|
+
await retainCompletedAitIapPurchaseAttempt(storage, storageKey, iapProductGrantTimeoutMs);
|
|
107
|
+
});
|
|
108
|
+
const next = scheduled.then(() => undefined, () => undefined);
|
|
109
|
+
void next;
|
|
110
|
+
void (completedIapAttemptRetention = next);
|
|
111
|
+
return next;
|
|
112
|
+
};
|
|
68
113
|
return {
|
|
69
114
|
async request(input) {
|
|
70
115
|
try {
|
|
@@ -83,12 +128,24 @@ export function createAitHostBridge(options = {}) {
|
|
|
83
128
|
&& hasConfiguredAdType(adGroupIds, adPlacementTypes, 'rewarded');
|
|
84
129
|
const interstitialAds = adsSupported
|
|
85
130
|
&& hasConfiguredAdType(adGroupIds, adPlacementTypes, 'interstitial');
|
|
131
|
+
const bannerAds = areBannerAdsSupported(dependencies)
|
|
132
|
+
&& hasConfiguredAdType(adGroupIds, adPlacementTypes, 'banner');
|
|
133
|
+
const nativeIap = isAitIapSupported({
|
|
134
|
+
dependencies,
|
|
135
|
+
products: iapProducts,
|
|
136
|
+
prepare: options.prepareIap,
|
|
137
|
+
verifier: options.verifyIapProductGrant,
|
|
138
|
+
entitlementReader: options.readIapEntitlements,
|
|
139
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
140
|
+
});
|
|
86
141
|
return ok(request, {
|
|
87
|
-
nativeIap
|
|
88
|
-
nativeAds: rewardedAds || interstitialAds,
|
|
142
|
+
nativeIap,
|
|
143
|
+
nativeAds: rewardedAds || interstitialAds || bannerAds,
|
|
144
|
+
bannerAds,
|
|
89
145
|
rewardedAds,
|
|
90
146
|
interstitialAds,
|
|
91
147
|
nativeLeaderboard: isGameCenterSupported(dependencies),
|
|
148
|
+
remoteLeaderboard: false,
|
|
92
149
|
achievements: false,
|
|
93
150
|
cloudSave: false,
|
|
94
151
|
socialShare: true,
|
|
@@ -132,7 +189,7 @@ export function createAitHostBridge(options = {}) {
|
|
|
132
189
|
const topic = readNotificationTopic(request.payload);
|
|
133
190
|
const templateCode = notificationTemplateCodes.get(topic);
|
|
134
191
|
if (templateCode === undefined
|
|
135
|
-
|| !
|
|
192
|
+
|| !isAitNativeMethodSupported(dependencies.requestNotificationAgreement)) {
|
|
136
193
|
return ok(request, 'unavailable');
|
|
137
194
|
}
|
|
138
195
|
const result = await requestAitNotificationAgreement(dependencies.requestNotificationAgreement, templateCode);
|
|
@@ -188,15 +245,84 @@ export function createAitHostBridge(options = {}) {
|
|
|
188
245
|
}
|
|
189
246
|
}
|
|
190
247
|
}
|
|
191
|
-
// IAP
|
|
248
|
+
// IAP is opt-in and server-authoritative. Never return demo grants.
|
|
192
249
|
case 'commerce.getProducts':
|
|
193
|
-
return ok(request,
|
|
194
|
-
|
|
195
|
-
|
|
250
|
+
return ok(request, await listAitIapProducts({
|
|
251
|
+
dependencies,
|
|
252
|
+
products: iapProducts,
|
|
253
|
+
prepare: options.prepareIap,
|
|
254
|
+
verifier: options.verifyIapProductGrant,
|
|
255
|
+
entitlementReader: options.readIapEntitlements,
|
|
256
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
257
|
+
}));
|
|
258
|
+
case 'commerce.purchase': {
|
|
259
|
+
const purchase = readCommercePurchase(request.payload);
|
|
260
|
+
const product = iapProducts.byProductId.get(purchase.productId);
|
|
261
|
+
const prepareIap = options.prepareIap;
|
|
262
|
+
const verifyIapProductGrant = options.verifyIapProductGrant;
|
|
263
|
+
const iapSupported = isAitIapSupported({
|
|
264
|
+
dependencies,
|
|
265
|
+
products: iapProducts,
|
|
266
|
+
prepare: prepareIap,
|
|
267
|
+
verifier: verifyIapProductGrant,
|
|
268
|
+
entitlementReader: options.readIapEntitlements,
|
|
269
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
270
|
+
});
|
|
271
|
+
if (product === undefined
|
|
272
|
+
|| !iapSupported
|
|
273
|
+
|| prepareIap === undefined
|
|
274
|
+
|| verifyIapProductGrant === undefined) {
|
|
275
|
+
return ok(request, failedPurchase());
|
|
276
|
+
}
|
|
277
|
+
const persisted = await resolvePersistedAitIapPurchaseAttempt({
|
|
278
|
+
dependencies,
|
|
279
|
+
storage: dependencies.storage,
|
|
280
|
+
product,
|
|
281
|
+
idempotencyKey: purchase.idempotencyKey,
|
|
282
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
283
|
+
});
|
|
284
|
+
if (persisted !== undefined) {
|
|
285
|
+
return ok(request, persisted);
|
|
286
|
+
}
|
|
287
|
+
const isOneTimeProduct = await isAitOneTimeIapProduct(dependencies, product, iapProductGrantTimeoutMs);
|
|
288
|
+
if (!isOneTimeProduct) {
|
|
289
|
+
return ok(request, failedPurchase());
|
|
290
|
+
}
|
|
291
|
+
const purchaseRequestKey = createAitIapPurchaseRequestKey(purchase.productId, purchase.idempotencyKey);
|
|
292
|
+
const existing = iapPurchasesInFlight.get(purchaseRequestKey);
|
|
293
|
+
if (existing !== undefined) {
|
|
294
|
+
return ok(request, await existing);
|
|
295
|
+
}
|
|
296
|
+
const pending = purchaseAitIapProduct({
|
|
297
|
+
dependencies,
|
|
298
|
+
product,
|
|
299
|
+
idempotencyKey: purchase.idempotencyKey,
|
|
300
|
+
prepare: prepareIap,
|
|
301
|
+
verifier: verifyIapProductGrant,
|
|
302
|
+
retainCompletedAttempt: enqueueCompletedIapAttemptRetention,
|
|
303
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
304
|
+
});
|
|
305
|
+
iapPurchasesInFlight.set(purchaseRequestKey, pending);
|
|
306
|
+
try {
|
|
307
|
+
return ok(request, await pending);
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
if (iapPurchasesInFlight.get(purchaseRequestKey) === pending) {
|
|
311
|
+
iapPurchasesInFlight.delete(purchaseRequestKey);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
196
315
|
case 'commerce.restore':
|
|
197
|
-
return ok(request, {
|
|
316
|
+
return ok(request, await restoreAitIapProducts({
|
|
317
|
+
dependencies,
|
|
318
|
+
products: iapProducts,
|
|
319
|
+
prepare: options.prepareIap,
|
|
320
|
+
verifier: options.verifyIapProductGrant,
|
|
321
|
+
entitlementReader: options.readIapEntitlements,
|
|
322
|
+
timeoutMs: iapProductGrantTimeoutMs,
|
|
323
|
+
}));
|
|
198
324
|
case 'commerce.getEntitlements':
|
|
199
|
-
return ok(request,
|
|
325
|
+
return ok(request, await readAitIapEntitlements(options.readIapEntitlements, iapProductGrantTimeoutMs));
|
|
200
326
|
case 'ads.preload': {
|
|
201
327
|
const placementId = readPlacementId(request.payload);
|
|
202
328
|
const adGroupId = adGroupIds.get(placementId);
|
|
@@ -204,7 +330,10 @@ export function createAitHostBridge(options = {}) {
|
|
|
204
330
|
if (adGroupId === undefined || placementType === undefined) {
|
|
205
331
|
return createBridgeError(request.id, 'AIT_AD_UNAVAILABLE', `AIT ad placement is unavailable: ${placementId}`);
|
|
206
332
|
}
|
|
207
|
-
if (
|
|
333
|
+
if (placementType === 'banner') {
|
|
334
|
+
return ok(request, {});
|
|
335
|
+
}
|
|
336
|
+
if (!isAitNativeMethodSupported(dependencies.loadFullScreenAd)) {
|
|
208
337
|
if (!warnedUnsupportedAdPreload) {
|
|
209
338
|
warnedUnsupportedAdPreload = true;
|
|
210
339
|
console.warn('AIT full-screen ads are not supported; configured preload is a no-op.', placementId);
|
|
@@ -259,6 +388,61 @@ export function createAitHostBridge(options = {}) {
|
|
|
259
388
|
const shown = await withLoadedAdSlot(dependencies, adGroupId, loadedAdGroupIds, loadingAdGroups, adLoadCoordinator, activeAdGroupIds, adTimeoutMs, 'interstitial', showInterstitial);
|
|
260
389
|
return ok(request, shown.acquired ? shown.value : { status: 'unavailable' });
|
|
261
390
|
}
|
|
391
|
+
case 'ads.mountBanner': {
|
|
392
|
+
const placementId = readPlacementId(request.payload);
|
|
393
|
+
const surfaceId = readBannerSurfaceId(request.payload);
|
|
394
|
+
const adGroupId = adGroupIds.get(placementId);
|
|
395
|
+
if (adGroupId === undefined
|
|
396
|
+
|| adPlacementTypes.get(placementId) !== 'banner'
|
|
397
|
+
|| !areBannerAdsSupported(dependencies)) {
|
|
398
|
+
return ok(request, { status: 'unavailable' });
|
|
399
|
+
}
|
|
400
|
+
const target = globalThis.document?.getElementById(surfaceId);
|
|
401
|
+
if (target === null || target === undefined) {
|
|
402
|
+
return ok(request, { status: 'failed' });
|
|
403
|
+
}
|
|
404
|
+
pendingBannerMountSettlements.get(surfaceId)?.settleUnavailable();
|
|
405
|
+
const mountOwner = Symbol(surfaceId);
|
|
406
|
+
bannerMountOwners.set(surfaceId, mountOwner);
|
|
407
|
+
activeBannerAttachments.get(surfaceId)?.destroy();
|
|
408
|
+
activeBannerAttachments.delete(surfaceId);
|
|
409
|
+
const initializeBanner = bannerInitialization
|
|
410
|
+
?? initializeAitBannerAds(dependencies, bannerRenderTimeoutMs);
|
|
411
|
+
void (bannerInitialization = initializeBanner);
|
|
412
|
+
if (!await initializeBanner) {
|
|
413
|
+
bannerInitialization = undefined;
|
|
414
|
+
if (bannerMountOwners.get(surfaceId) === mountOwner) {
|
|
415
|
+
bannerMountOwners.delete(surfaceId);
|
|
416
|
+
}
|
|
417
|
+
return ok(request, { status: 'failed' });
|
|
418
|
+
}
|
|
419
|
+
if (bannerMountOwners.get(surfaceId) !== mountOwner) {
|
|
420
|
+
return ok(request, { status: 'unavailable' });
|
|
421
|
+
}
|
|
422
|
+
activeBannerAttachments.get(surfaceId)?.destroy();
|
|
423
|
+
activeBannerAttachments.delete(surfaceId);
|
|
424
|
+
const result = await attachAitBanner({
|
|
425
|
+
dependencies,
|
|
426
|
+
adGroupId,
|
|
427
|
+
surfaceId,
|
|
428
|
+
target,
|
|
429
|
+
timeoutMs: bannerRenderTimeoutMs,
|
|
430
|
+
appearance: bannerAppearance,
|
|
431
|
+
activeAttachments: activeBannerAttachments,
|
|
432
|
+
mountOwner,
|
|
433
|
+
mountOwners: bannerMountOwners,
|
|
434
|
+
pendingSettlements: pendingBannerMountSettlements,
|
|
435
|
+
});
|
|
436
|
+
return ok(request, result);
|
|
437
|
+
}
|
|
438
|
+
case 'ads.unmountBanner': {
|
|
439
|
+
const surfaceId = readBannerSurfaceId(request.payload);
|
|
440
|
+
pendingBannerMountSettlements.get(surfaceId)?.settleUnavailable();
|
|
441
|
+
bannerMountOwners.delete(surfaceId);
|
|
442
|
+
activeBannerAttachments.get(surfaceId)?.destroy();
|
|
443
|
+
activeBannerAttachments.delete(surfaceId);
|
|
444
|
+
return ok(request, {});
|
|
445
|
+
}
|
|
262
446
|
case 'leaderboard.submitScore': {
|
|
263
447
|
if (!isGameCenterSupported(dependencies)) {
|
|
264
448
|
return ok(request, { submitted: false });
|
|
@@ -306,7 +490,7 @@ function getNotificationStatus(topic, templateCodes, subscriptions, dependencies
|
|
|
306
490
|
if (!templateCodes.has(topic)) {
|
|
307
491
|
return 'configuration-required';
|
|
308
492
|
}
|
|
309
|
-
if (!
|
|
493
|
+
if (!isAitNativeMethodSupported(dependencies.requestNotificationAgreement)) {
|
|
310
494
|
return 'unsupported';
|
|
311
495
|
}
|
|
312
496
|
return subscriptions.has(topic) ? 'subscribed' : 'not-subscribed';
|
|
@@ -901,9 +1085,949 @@ function isGameCenterSupported(dependencies) {
|
|
|
901
1085
|
ios: '5.221.0',
|
|
902
1086
|
}));
|
|
903
1087
|
}
|
|
1088
|
+
const aitIapPurchaseAttemptStatus = {
|
|
1089
|
+
pending: 'pending',
|
|
1090
|
+
serverGranted: 'server-granted',
|
|
1091
|
+
completed: 'completed',
|
|
1092
|
+
};
|
|
1093
|
+
function isAitIapSupported(input) {
|
|
1094
|
+
if (input.products.byProductId.size === 0
|
|
1095
|
+
|| input.prepare === undefined
|
|
1096
|
+
|| input.verifier === undefined
|
|
1097
|
+
|| input.entitlementReader === undefined) {
|
|
1098
|
+
return false;
|
|
1099
|
+
}
|
|
1100
|
+
return isAitNativeMethodSupported(input.dependencies.iap.createOneTimePurchaseOrder)
|
|
1101
|
+
&& isAitNativeMethodSupported(input.dependencies.iap.getProductItemList)
|
|
1102
|
+
&& isAitNativeMethodSupported(input.dependencies.iap.getPendingOrders)
|
|
1103
|
+
&& isAitNativeMethodSupported(input.dependencies.iap.completeProductGrant);
|
|
1104
|
+
}
|
|
1105
|
+
async function listAitIapProducts(input) {
|
|
1106
|
+
if (!isAitIapSupported(input)) {
|
|
1107
|
+
return [];
|
|
1108
|
+
}
|
|
1109
|
+
try {
|
|
1110
|
+
const result = await waitForAitIapNativeCall(() => input.dependencies.iap.getProductItemList(), input.timeoutMs);
|
|
1111
|
+
if (result === undefined) {
|
|
1112
|
+
return [];
|
|
1113
|
+
}
|
|
1114
|
+
const products = [];
|
|
1115
|
+
for (const nativeProduct of result.products) {
|
|
1116
|
+
const configured = input.products.bySku.get(nativeProduct.sku);
|
|
1117
|
+
if (configured === undefined) {
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
const product = toAitIapProductInfo(nativeProduct, configured);
|
|
1121
|
+
if (product !== undefined) {
|
|
1122
|
+
products.push(product);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
return products;
|
|
1126
|
+
}
|
|
1127
|
+
catch {
|
|
1128
|
+
// Product metadata is not authoritative. If the native catalog cannot be
|
|
1129
|
+
// read, hide it instead of rendering stale game-owned prices.
|
|
1130
|
+
return [];
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
async function readAitIapEntitlements(reader, timeoutMs) {
|
|
1134
|
+
if (reader === undefined || timeoutMs <= 0) {
|
|
1135
|
+
return [];
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
const entitlements = await waitForAitIapNativeCall(reader, timeoutMs);
|
|
1139
|
+
return entitlements === undefined ? [] : [...entitlements];
|
|
1140
|
+
}
|
|
1141
|
+
catch (error) {
|
|
1142
|
+
// The game authority owns durable purchase state. A read failure must not
|
|
1143
|
+
// turn stale local data into a visible entitlement.
|
|
1144
|
+
console.warn('AIT IAP entitlement read failed; reporting no entitlements.', errorMessage(error));
|
|
1145
|
+
return [];
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Return a durable result before consulting the provider catalog. This makes a
|
|
1150
|
+
* repeated client idempotency key safe after a reload or after the in-memory
|
|
1151
|
+
* coalescing map has been cleared.
|
|
1152
|
+
*/
|
|
1153
|
+
async function resolvePersistedAitIapPurchaseAttempt(input) {
|
|
1154
|
+
const storageKey = aitIapPurchaseAttemptStorageKey(input.product.productId, input.idempotencyKey);
|
|
1155
|
+
let serialized;
|
|
1156
|
+
try {
|
|
1157
|
+
serialized = await waitForAitIapNativeCall(() => input.storage.getItem(storageKey), input.timeoutMs);
|
|
1158
|
+
}
|
|
1159
|
+
catch (error) {
|
|
1160
|
+
console.warn('AIT IAP purchase attempt storage read failed; treating the attempt as pending.', errorMessage(error));
|
|
1161
|
+
return pendingPurchase();
|
|
1162
|
+
}
|
|
1163
|
+
if (serialized === undefined) {
|
|
1164
|
+
return pendingPurchase();
|
|
1165
|
+
}
|
|
1166
|
+
if (serialized === null) {
|
|
1167
|
+
return undefined;
|
|
1168
|
+
}
|
|
1169
|
+
let state;
|
|
1170
|
+
try {
|
|
1171
|
+
state = JSON.parse(serialized);
|
|
1172
|
+
}
|
|
1173
|
+
catch (error) {
|
|
1174
|
+
console.warn('AIT IAP purchase attempt marker is invalid; treating the attempt as pending.', errorMessage(error));
|
|
1175
|
+
return pendingPurchase();
|
|
1176
|
+
}
|
|
1177
|
+
if (!isRecord(state)
|
|
1178
|
+
|| state.productId !== input.product.productId
|
|
1179
|
+
|| state.idempotencyKey !== input.idempotencyKey) {
|
|
1180
|
+
return pendingPurchase();
|
|
1181
|
+
}
|
|
1182
|
+
if (state.status === aitIapPurchaseAttemptStatus.pending) {
|
|
1183
|
+
if (typeof state.orderId === 'string' && isAitIapOrderId(state.orderId)) {
|
|
1184
|
+
return pendingPurchase(state.orderId);
|
|
1185
|
+
}
|
|
1186
|
+
const pendingSince = normalizePendingSince(state.pendingSince);
|
|
1187
|
+
if (pendingSince === undefined
|
|
1188
|
+
|| !isAitIapPendingAttemptPastRecoveryWindow(pendingSince)) {
|
|
1189
|
+
return pendingPurchase();
|
|
1190
|
+
}
|
|
1191
|
+
const hasPendingProviderOrder = await hasAitIapPendingOrderForSku(input.dependencies, input.product.sku, input.timeoutMs);
|
|
1192
|
+
if (hasPendingProviderOrder !== false) {
|
|
1193
|
+
return pendingPurchase();
|
|
1194
|
+
}
|
|
1195
|
+
const cleared = await clearAitIapPurchaseAttempt(input);
|
|
1196
|
+
return cleared ? undefined : pendingPurchase();
|
|
1197
|
+
}
|
|
1198
|
+
if (state.status === aitIapPurchaseAttemptStatus.serverGranted
|
|
1199
|
+
&& typeof state.orderId === 'string'
|
|
1200
|
+
&& isAitIapOrderId(state.orderId)) {
|
|
1201
|
+
return pendingPurchase(state.orderId);
|
|
1202
|
+
}
|
|
1203
|
+
if (state.status === aitIapPurchaseAttemptStatus.completed
|
|
1204
|
+
&& typeof state.orderId === 'string'
|
|
1205
|
+
&& isAitIapOrderId(state.orderId)) {
|
|
1206
|
+
return completedAitIapPurchase(input.product, state.orderId);
|
|
1207
|
+
}
|
|
1208
|
+
return pendingPurchase();
|
|
1209
|
+
}
|
|
1210
|
+
async function persistAitIapPurchaseAttempt(input) {
|
|
1211
|
+
return await writeAitIapStorage(input.storage, aitIapPurchaseAttemptStorageKey(input.product.productId, input.idempotencyKey), JSON.stringify({
|
|
1212
|
+
status: input.status,
|
|
1213
|
+
productId: input.product.productId,
|
|
1214
|
+
idempotencyKey: input.idempotencyKey,
|
|
1215
|
+
...(input.status === aitIapPurchaseAttemptStatus.pending
|
|
1216
|
+
? { pendingSince: new Date().toISOString() }
|
|
1217
|
+
: {}),
|
|
1218
|
+
...(input.orderId === undefined ? {} : { orderId: input.orderId }),
|
|
1219
|
+
}), input.timeoutMs);
|
|
1220
|
+
}
|
|
1221
|
+
async function clearAitIapPurchaseAttempt(input) {
|
|
1222
|
+
return await removeAitIapStorage(input.storage, aitIapPurchaseAttemptStorageKey(input.product.productId, input.idempotencyKey), input.timeoutMs);
|
|
1223
|
+
}
|
|
1224
|
+
async function verifyAndPersistAitIapProductGrant(input) {
|
|
1225
|
+
const startedAt = Date.now();
|
|
1226
|
+
const correlated = await persistAitIapPurchaseAttempt({
|
|
1227
|
+
storage: input.storage,
|
|
1228
|
+
product: input.product,
|
|
1229
|
+
idempotencyKey: input.idempotencyKey,
|
|
1230
|
+
orderId: input.orderId,
|
|
1231
|
+
status: aitIapPurchaseAttemptStatus.pending,
|
|
1232
|
+
timeoutMs: input.timeoutMs,
|
|
1233
|
+
});
|
|
1234
|
+
if (!correlated) {
|
|
1235
|
+
// Never let the backend commit a grant unless the provider order is first
|
|
1236
|
+
// durably tied to the client attempt. Otherwise a lost response could let
|
|
1237
|
+
// the same client idempotency key open a second checkout after restore.
|
|
1238
|
+
return false;
|
|
1239
|
+
}
|
|
1240
|
+
const verificationTimeoutMs = remainingAitIapOperationTimeout(startedAt, input.timeoutMs);
|
|
1241
|
+
if (verificationTimeoutMs === 0) {
|
|
1242
|
+
return false;
|
|
1243
|
+
}
|
|
1244
|
+
const granted = await verifyAitIapProductGrant({
|
|
1245
|
+
verifier: input.verifier,
|
|
1246
|
+
orderId: input.orderId,
|
|
1247
|
+
product: input.product,
|
|
1248
|
+
idempotencyKey: input.orderIdempotencyKey,
|
|
1249
|
+
source: input.source,
|
|
1250
|
+
timeoutMs: verificationTimeoutMs,
|
|
1251
|
+
});
|
|
1252
|
+
if (!granted) {
|
|
1253
|
+
return false;
|
|
1254
|
+
}
|
|
1255
|
+
const remainingTimeoutMs = remainingAitIapOperationTimeout(startedAt, input.timeoutMs);
|
|
1256
|
+
if (remainingTimeoutMs === 0) {
|
|
1257
|
+
return false;
|
|
1258
|
+
}
|
|
1259
|
+
return await persistAitIapPurchaseAttempt({
|
|
1260
|
+
storage: input.storage,
|
|
1261
|
+
product: input.product,
|
|
1262
|
+
idempotencyKey: input.idempotencyKey,
|
|
1263
|
+
orderId: input.orderId,
|
|
1264
|
+
status: aitIapPurchaseAttemptStatus.serverGranted,
|
|
1265
|
+
timeoutMs: remainingTimeoutMs,
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
function remainingAitIapOperationTimeout(startedAt, timeoutMs) {
|
|
1269
|
+
return Math.max(0, timeoutMs - Math.max(0, Date.now() - startedAt));
|
|
1270
|
+
}
|
|
1271
|
+
async function writeAitIapStorage(storage, key, value, timeoutMs) {
|
|
1272
|
+
return await waitForAitIapStorageOperation(() => storage.setItem(key, value), timeoutMs);
|
|
1273
|
+
}
|
|
1274
|
+
async function removeAitIapStorage(storage, key, timeoutMs) {
|
|
1275
|
+
return await waitForAitIapStorageOperation(() => storage.removeItem(key), timeoutMs);
|
|
1276
|
+
}
|
|
1277
|
+
async function waitForAitIapStorageOperation(operation, timeoutMs) {
|
|
1278
|
+
let timeout;
|
|
1279
|
+
const timeoutResult = new Promise((resolve) => {
|
|
1280
|
+
timeout = globalThis.setTimeout(() => resolve(false), timeoutMs);
|
|
1281
|
+
});
|
|
1282
|
+
const operationResult = Promise.resolve()
|
|
1283
|
+
.then(operation)
|
|
1284
|
+
.then(() => true, () => false);
|
|
1285
|
+
try {
|
|
1286
|
+
return await Promise.race([operationResult, timeoutResult]);
|
|
1287
|
+
}
|
|
1288
|
+
finally {
|
|
1289
|
+
if (timeout !== undefined) {
|
|
1290
|
+
globalThis.clearTimeout(timeout);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
function aitIapPurchaseAttemptStorageKey(productId, idempotencyKey) {
|
|
1295
|
+
return `${iapPurchaseAttemptStoragePrefix}${encodeURIComponent(productId)}:${encodeURIComponent(idempotencyKey)}`;
|
|
1296
|
+
}
|
|
1297
|
+
function isAitIapPendingAttemptPastRecoveryWindow(pendingSince) {
|
|
1298
|
+
const startedAt = Date.parse(pendingSince);
|
|
1299
|
+
return Number.isFinite(startedAt)
|
|
1300
|
+
&& Date.now() - startedAt >= pendingIapPurchaseAttemptRecoveryAgeMs;
|
|
1301
|
+
}
|
|
1302
|
+
async function hasAitIapPendingOrderForSku(dependencies, sku, timeoutMs) {
|
|
1303
|
+
try {
|
|
1304
|
+
const result = await waitForAitIapNativeCall(() => dependencies.iap.getPendingOrders(), timeoutMs);
|
|
1305
|
+
if (result === undefined) {
|
|
1306
|
+
return undefined;
|
|
1307
|
+
}
|
|
1308
|
+
return result.orders.some((order) => order.sku === sku && isAitIapOrderId(order.orderId));
|
|
1309
|
+
}
|
|
1310
|
+
catch (error) {
|
|
1311
|
+
console.warn('AIT IAP pending-order lookup failed; preserving the client retry barrier.', errorMessage(error));
|
|
1312
|
+
return undefined;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Keep the completed-attempt index bounded without deleting terminal retry
|
|
1317
|
+
* markers. A client idempotency key may be replayed indefinitely, so removing
|
|
1318
|
+
* its durable result could open a second native checkout. The index is only
|
|
1319
|
+
* bookkeeping for recent entries; all storage failures leave markers intact.
|
|
1320
|
+
*/
|
|
1321
|
+
async function retainCompletedAitIapPurchaseAttempt(storage, storageKey, timeoutMs) {
|
|
1322
|
+
const startedAt = Date.now();
|
|
1323
|
+
try {
|
|
1324
|
+
const serialized = await waitForAitIapNativeCall(() => storage.getItem(iapCompletedPurchaseAttemptIndexStorageKey), timeoutMs);
|
|
1325
|
+
const knownKeys = parseAitIapCompletedPurchaseAttemptIndex(serialized);
|
|
1326
|
+
const keys = [...knownKeys.filter((knownKey) => knownKey !== storageKey), storageKey];
|
|
1327
|
+
const retainedKeys = keys.slice(-maximumIndexedCompletedIapPurchaseAttempts);
|
|
1328
|
+
const retentionTimeoutMs = remainingAitIapOperationTimeout(startedAt, timeoutMs);
|
|
1329
|
+
if (retentionTimeoutMs === 0) {
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
await writeAitIapStorage(storage, iapCompletedPurchaseAttemptIndexStorageKey, JSON.stringify(retainedKeys), retentionTimeoutMs);
|
|
1333
|
+
}
|
|
1334
|
+
catch {
|
|
1335
|
+
// Index maintenance is best effort. The terminal marker remains the
|
|
1336
|
+
// durable retry barrier even when its recent-entry index cannot be written.
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
function parseAitIapCompletedPurchaseAttemptIndex(serialized) {
|
|
1340
|
+
if (serialized === null || serialized === undefined) {
|
|
1341
|
+
return [];
|
|
1342
|
+
}
|
|
1343
|
+
try {
|
|
1344
|
+
const value = JSON.parse(serialized);
|
|
1345
|
+
if (!Array.isArray(value)) {
|
|
1346
|
+
return [];
|
|
1347
|
+
}
|
|
1348
|
+
const keys = value.filter((key) => (typeof key === 'string'
|
|
1349
|
+
&& key.startsWith(iapPurchaseAttemptStoragePrefix)
|
|
1350
|
+
&& key.length <= 4096));
|
|
1351
|
+
return [...new Set(keys)].slice(-maximumIndexedCompletedIapPurchaseAttempts);
|
|
1352
|
+
}
|
|
1353
|
+
catch {
|
|
1354
|
+
return [];
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
async function readAitIapPendingOrderCursor(storage, timeoutMs) {
|
|
1358
|
+
try {
|
|
1359
|
+
const cursor = await waitForAitIapNativeCall(() => storage.getItem(iapPendingOrderCursorStorageKey), timeoutMs);
|
|
1360
|
+
return typeof cursor === 'string' && isAitIapOrderId(cursor) ? cursor : undefined;
|
|
1361
|
+
}
|
|
1362
|
+
catch (error) {
|
|
1363
|
+
console.warn('AIT IAP pending-order cursor read failed; starting from the first eligible order.', errorMessage(error));
|
|
1364
|
+
return undefined;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
async function writeAitIapPendingOrderCursor(storage, orderId, timeoutMs) {
|
|
1368
|
+
return await writeAitIapStorage(storage, iapPendingOrderCursorStorageKey, orderId, timeoutMs);
|
|
1369
|
+
}
|
|
1370
|
+
function rotateAitIapPendingOrders(orders, cursor, limit) {
|
|
1371
|
+
if (orders.length === 0) {
|
|
1372
|
+
return [];
|
|
1373
|
+
}
|
|
1374
|
+
const cursorIndex = cursor === undefined
|
|
1375
|
+
? -1
|
|
1376
|
+
: orders.findIndex(({ order }) => order.orderId === cursor);
|
|
1377
|
+
const startIndex = cursorIndex < 0 ? 0 : (cursorIndex + 1) % orders.length;
|
|
1378
|
+
const selected = [];
|
|
1379
|
+
const count = Math.min(limit, orders.length);
|
|
1380
|
+
for (let offset = 0; offset < count; offset += 1) {
|
|
1381
|
+
const next = orders[(startIndex + offset) % orders.length];
|
|
1382
|
+
if (next !== undefined) {
|
|
1383
|
+
selected.push(next);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return selected;
|
|
1387
|
+
}
|
|
1388
|
+
async function purchaseAitIapProduct(input) {
|
|
1389
|
+
const prepared = await prepareAitIap(input.prepare, {
|
|
1390
|
+
intent: 'purchase',
|
|
1391
|
+
productId: input.product.productId,
|
|
1392
|
+
platformSku: input.product.sku,
|
|
1393
|
+
}, input.timeoutMs);
|
|
1394
|
+
if (!prepared) {
|
|
1395
|
+
return failedPurchase();
|
|
1396
|
+
}
|
|
1397
|
+
const started = await persistAitIapPurchaseAttempt({
|
|
1398
|
+
storage: input.dependencies.storage,
|
|
1399
|
+
product: input.product,
|
|
1400
|
+
idempotencyKey: input.idempotencyKey,
|
|
1401
|
+
status: aitIapPurchaseAttemptStatus.pending,
|
|
1402
|
+
timeoutMs: input.timeoutMs,
|
|
1403
|
+
});
|
|
1404
|
+
if (!started) {
|
|
1405
|
+
// We cannot tell whether a delayed native-storage write eventually
|
|
1406
|
+
// succeeded. Do not open a checkout without a durable retry barrier.
|
|
1407
|
+
return pendingPurchase();
|
|
1408
|
+
}
|
|
1409
|
+
return new Promise((resolve) => {
|
|
1410
|
+
const grantAttempts = new Map();
|
|
1411
|
+
let settled = false;
|
|
1412
|
+
let cleanup;
|
|
1413
|
+
let cleanupRequested = false;
|
|
1414
|
+
let sessionTimeout;
|
|
1415
|
+
let providerOrderId;
|
|
1416
|
+
let grantedOrderId;
|
|
1417
|
+
let markerDeletionStarted = false;
|
|
1418
|
+
const finish = (result) => {
|
|
1419
|
+
if (settled) {
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
settled = true;
|
|
1423
|
+
if (sessionTimeout !== undefined) {
|
|
1424
|
+
globalThis.clearTimeout(sessionTimeout);
|
|
1425
|
+
sessionTimeout = undefined;
|
|
1426
|
+
}
|
|
1427
|
+
if (cleanup === undefined) {
|
|
1428
|
+
cleanupRequested = true;
|
|
1429
|
+
}
|
|
1430
|
+
else {
|
|
1431
|
+
safelyCleanupAitIapPurchase(cleanup);
|
|
1432
|
+
}
|
|
1433
|
+
resolve(result);
|
|
1434
|
+
};
|
|
1435
|
+
const startMarkerDeletion = (clearedResult) => {
|
|
1436
|
+
markerDeletionStarted = true;
|
|
1437
|
+
void clearAitIapPurchaseAttempt({
|
|
1438
|
+
storage: input.dependencies.storage,
|
|
1439
|
+
product: input.product,
|
|
1440
|
+
idempotencyKey: input.idempotencyKey,
|
|
1441
|
+
timeoutMs: input.timeoutMs,
|
|
1442
|
+
}).then((cleared) => {
|
|
1443
|
+
finish(cleared ? clearedResult : pendingPurchase());
|
|
1444
|
+
});
|
|
1445
|
+
};
|
|
1446
|
+
const processProductGrant = (orderId) => {
|
|
1447
|
+
if (markerDeletionStarted) {
|
|
1448
|
+
// Cancellation won the serialization race. Do not let a later queued
|
|
1449
|
+
// grant callback commit after its retry barrier starts disappearing.
|
|
1450
|
+
return Promise.resolve(false);
|
|
1451
|
+
}
|
|
1452
|
+
const existing = grantAttempts.get(orderId);
|
|
1453
|
+
if (existing !== undefined) {
|
|
1454
|
+
return existing;
|
|
1455
|
+
}
|
|
1456
|
+
if (!isAitIapOrderId(orderId)
|
|
1457
|
+
|| (providerOrderId !== undefined && providerOrderId !== orderId)) {
|
|
1458
|
+
return Promise.resolve(false);
|
|
1459
|
+
}
|
|
1460
|
+
providerOrderId = orderId;
|
|
1461
|
+
const attempt = verifyAndPersistAitIapProductGrant({
|
|
1462
|
+
verifier: input.verifier,
|
|
1463
|
+
storage: input.dependencies.storage,
|
|
1464
|
+
orderId,
|
|
1465
|
+
product: input.product,
|
|
1466
|
+
idempotencyKey: input.idempotencyKey,
|
|
1467
|
+
orderIdempotencyKey: createAitIapOrderIdempotencyKey(orderId),
|
|
1468
|
+
source: 'process-product-grant',
|
|
1469
|
+
timeoutMs: input.timeoutMs,
|
|
1470
|
+
}).then((granted) => {
|
|
1471
|
+
if (granted) {
|
|
1472
|
+
grantedOrderId = orderId;
|
|
1473
|
+
}
|
|
1474
|
+
return granted;
|
|
1475
|
+
});
|
|
1476
|
+
grantAttempts.set(orderId, attempt);
|
|
1477
|
+
return attempt;
|
|
1478
|
+
};
|
|
1479
|
+
sessionTimeout = globalThis.setTimeout(() => {
|
|
1480
|
+
// The native SDK may have dispatched an order even when it fails to
|
|
1481
|
+
// deliver a terminal callback. Preserve the marker and let retry or
|
|
1482
|
+
// restore reconcile it instead of opening a second checkout.
|
|
1483
|
+
finish(pendingPurchase(grantedOrderId));
|
|
1484
|
+
}, defaultIapPurchaseSessionTimeoutMs);
|
|
1485
|
+
try {
|
|
1486
|
+
cleanup = input.dependencies.iap.createOneTimePurchaseOrder({
|
|
1487
|
+
options: {
|
|
1488
|
+
sku: input.product.sku,
|
|
1489
|
+
processProductGrant: ({ orderId }) => processProductGrant(orderId),
|
|
1490
|
+
},
|
|
1491
|
+
onEvent: async ({ data }) => {
|
|
1492
|
+
const granted = await (grantAttempts.get(data.orderId) ?? processProductGrant(data.orderId));
|
|
1493
|
+
if (!granted) {
|
|
1494
|
+
finish(pendingPurchase(providerOrderId));
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
const result = completedAitIapPurchase(input.product, data.orderId);
|
|
1498
|
+
const persisted = await persistAitIapPurchaseAttempt({
|
|
1499
|
+
storage: input.dependencies.storage,
|
|
1500
|
+
product: input.product,
|
|
1501
|
+
idempotencyKey: input.idempotencyKey,
|
|
1502
|
+
orderId: data.orderId,
|
|
1503
|
+
status: aitIapPurchaseAttemptStatus.completed,
|
|
1504
|
+
timeoutMs: input.timeoutMs,
|
|
1505
|
+
});
|
|
1506
|
+
if (persisted) {
|
|
1507
|
+
void input.retainCompletedAttempt(input.dependencies.storage, aitIapPurchaseAttemptStorageKey(input.product.productId, input.idempotencyKey));
|
|
1508
|
+
}
|
|
1509
|
+
finish(persisted ? result : pendingPurchase(data.orderId));
|
|
1510
|
+
},
|
|
1511
|
+
onError: (error) => {
|
|
1512
|
+
if (grantedOrderId !== undefined
|
|
1513
|
+
|| providerOrderId !== undefined
|
|
1514
|
+
|| grantAttempts.size > 0
|
|
1515
|
+
|| !isAitIapCancellation(error)) {
|
|
1516
|
+
// A cancellation racing an authoritative grant is ambiguous. Keep
|
|
1517
|
+
// the durable client retry barrier until retry/restore observes
|
|
1518
|
+
// the verifier's eventual result.
|
|
1519
|
+
finish(pendingPurchase(grantedOrderId ?? providerOrderId));
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1522
|
+
startMarkerDeletion(cancelledPurchase());
|
|
1523
|
+
},
|
|
1524
|
+
});
|
|
1525
|
+
if (cleanupRequested) {
|
|
1526
|
+
safelyCleanupAitIapPurchase(cleanup);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
catch {
|
|
1530
|
+
// A malformed SDK can invoke a grant callback and then throw during
|
|
1531
|
+
// registration. Preserve that active order; only a throw with no grant
|
|
1532
|
+
// startup proves there is no authoritative commit racing deletion.
|
|
1533
|
+
if (providerOrderId !== undefined || grantAttempts.size > 0) {
|
|
1534
|
+
finish(pendingPurchase(providerOrderId));
|
|
1535
|
+
return;
|
|
1536
|
+
}
|
|
1537
|
+
startMarkerDeletion(failedPurchase());
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
async function restoreAitIapProducts(input) {
|
|
1542
|
+
const prepare = input.prepare;
|
|
1543
|
+
const verifier = input.verifier;
|
|
1544
|
+
if (!isAitIapSupported(input) || prepare === undefined || verifier === undefined) {
|
|
1545
|
+
return { restoredEntitlements: [] };
|
|
1546
|
+
}
|
|
1547
|
+
const restoreStartedAt = Date.now();
|
|
1548
|
+
const getRemainingRestoreTimeout = () => {
|
|
1549
|
+
return remainingAitIapOperationTimeout(restoreStartedAt, input.timeoutMs);
|
|
1550
|
+
};
|
|
1551
|
+
const prepared = await prepareAitIap(prepare, { intent: 'restore' }, getRemainingRestoreTimeout());
|
|
1552
|
+
if (!prepared) {
|
|
1553
|
+
return { restoredEntitlements: [] };
|
|
1554
|
+
}
|
|
1555
|
+
const postPrepareTimeoutMs = getRemainingRestoreTimeout();
|
|
1556
|
+
const reservedEntitlementReadTimeoutMs = Math.max(1, Math.ceil(postPrepareTimeoutMs / 3));
|
|
1557
|
+
const reconciliationTimeoutMs = Math.max(0, postPrepareTimeoutMs - reservedEntitlementReadTimeoutMs);
|
|
1558
|
+
const reconciliationStartedAt = Date.now();
|
|
1559
|
+
const getRemainingReconciliationTimeout = () => {
|
|
1560
|
+
return Math.min(getRemainingRestoreTimeout(), remainingAitIapOperationTimeout(reconciliationStartedAt, reconciliationTimeoutMs));
|
|
1561
|
+
};
|
|
1562
|
+
const finishRestore = async (locallyRestoredEntitlements = []) => {
|
|
1563
|
+
const entitlementTimeoutMs = getRemainingRestoreTimeout();
|
|
1564
|
+
const authoritativeEntitlements = await readAitIapEntitlements(input.entitlementReader, entitlementTimeoutMs);
|
|
1565
|
+
return {
|
|
1566
|
+
restoredEntitlements: mergeAitIapRestoredEntitlements(locallyRestoredEntitlements, authoritativeEntitlements, input.products),
|
|
1567
|
+
};
|
|
1568
|
+
};
|
|
1569
|
+
if (reconciliationTimeoutMs === 0) {
|
|
1570
|
+
return await finishRestore();
|
|
1571
|
+
}
|
|
1572
|
+
let pendingOrders;
|
|
1573
|
+
try {
|
|
1574
|
+
const pendingOrderTimeoutMs = getRemainingReconciliationTimeout();
|
|
1575
|
+
if (pendingOrderTimeoutMs === 0) {
|
|
1576
|
+
return await finishRestore();
|
|
1577
|
+
}
|
|
1578
|
+
pendingOrders = await waitForAitIapNativeCall(() => input.dependencies.iap.getPendingOrders(), pendingOrderTimeoutMs);
|
|
1579
|
+
}
|
|
1580
|
+
catch {
|
|
1581
|
+
return await finishRestore();
|
|
1582
|
+
}
|
|
1583
|
+
if (pendingOrders === undefined) {
|
|
1584
|
+
return await finishRestore();
|
|
1585
|
+
}
|
|
1586
|
+
const eligibleOrders = [];
|
|
1587
|
+
const seenOrderIds = new Set();
|
|
1588
|
+
for (const order of pendingOrders.orders) {
|
|
1589
|
+
const product = input.products.bySku.get(order.sku);
|
|
1590
|
+
if (product === undefined
|
|
1591
|
+
|| !isAitIapOrderId(order.orderId)
|
|
1592
|
+
|| seenOrderIds.has(order.orderId)) {
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
seenOrderIds.add(order.orderId);
|
|
1596
|
+
eligibleOrders.push({ order, product });
|
|
1597
|
+
}
|
|
1598
|
+
const restoredEntitlements = [];
|
|
1599
|
+
const cursorTimeoutMs = getRemainingReconciliationTimeout();
|
|
1600
|
+
const cursor = cursorTimeoutMs === 0
|
|
1601
|
+
? undefined
|
|
1602
|
+
: await readAitIapPendingOrderCursor(input.dependencies.storage, cursorTimeoutMs);
|
|
1603
|
+
const orders = rotateAitIapPendingOrders(eligibleOrders, cursor, maximumPendingIapOrders);
|
|
1604
|
+
if (eligibleOrders.length > orders.length) {
|
|
1605
|
+
console.warn('AIT IAP pending-order restore reached its per-launch limit.', {
|
|
1606
|
+
limit: maximumPendingIapOrders,
|
|
1607
|
+
ignoredOrderCount: eligibleOrders.length - orders.length,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
for (const selectedOrder of orders) {
|
|
1611
|
+
const { order, product } = selectedOrder;
|
|
1612
|
+
const cursorWriteTimeoutMs = getRemainingReconciliationTimeout();
|
|
1613
|
+
if (cursorWriteTimeoutMs === 0) {
|
|
1614
|
+
break;
|
|
1615
|
+
}
|
|
1616
|
+
const cursorAdvanced = await writeAitIapPendingOrderCursor(input.dependencies.storage, order.orderId, cursorWriteTimeoutMs);
|
|
1617
|
+
if (!cursorAdvanced) {
|
|
1618
|
+
break;
|
|
1619
|
+
}
|
|
1620
|
+
const verificationTimeoutMs = getRemainingReconciliationTimeout();
|
|
1621
|
+
if (verificationTimeoutMs === 0) {
|
|
1622
|
+
break;
|
|
1623
|
+
}
|
|
1624
|
+
const granted = await verifyAitIapProductGrant({
|
|
1625
|
+
verifier,
|
|
1626
|
+
orderId: order.orderId,
|
|
1627
|
+
product,
|
|
1628
|
+
idempotencyKey: createAitIapOrderIdempotencyKey(order.orderId),
|
|
1629
|
+
source: 'pending-order-restore',
|
|
1630
|
+
timeoutMs: verificationTimeoutMs,
|
|
1631
|
+
});
|
|
1632
|
+
if (!granted) {
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
try {
|
|
1636
|
+
const completionTimeoutMs = getRemainingReconciliationTimeout();
|
|
1637
|
+
if (completionTimeoutMs === 0) {
|
|
1638
|
+
break;
|
|
1639
|
+
}
|
|
1640
|
+
const completed = await waitForAitIapNativeCall(() => input.dependencies.iap.completeProductGrant({
|
|
1641
|
+
params: { orderId: order.orderId },
|
|
1642
|
+
}), completionTimeoutMs);
|
|
1643
|
+
if (completed === true) {
|
|
1644
|
+
restoredEntitlements.push({
|
|
1645
|
+
id: product.productId,
|
|
1646
|
+
source: 'purchase',
|
|
1647
|
+
grantedAt: normalizeAitIapGrantTime(order.paymentCompletedDate),
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
catch {
|
|
1652
|
+
// Keep provider state pending when its completion acknowledgement fails.
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
return await finishRestore(restoredEntitlements);
|
|
1656
|
+
}
|
|
1657
|
+
function mergeAitIapRestoredEntitlements(restoredEntitlements, authoritativeEntitlements, products) {
|
|
1658
|
+
const entitlementsById = new Map();
|
|
1659
|
+
for (const entitlement of restoredEntitlements) {
|
|
1660
|
+
entitlementsById.set(entitlement.id, entitlement);
|
|
1661
|
+
}
|
|
1662
|
+
for (const entitlement of authoritativeEntitlements) {
|
|
1663
|
+
if (entitlement.source !== 'purchase'
|
|
1664
|
+
|| !products.byProductId.has(entitlement.id)) {
|
|
1665
|
+
continue;
|
|
1666
|
+
}
|
|
1667
|
+
entitlementsById.set(entitlement.id, entitlement);
|
|
1668
|
+
}
|
|
1669
|
+
return [...entitlementsById.values()];
|
|
1670
|
+
}
|
|
1671
|
+
async function prepareAitIap(prepare, input, timeoutMs) {
|
|
1672
|
+
if (prepare === undefined) {
|
|
1673
|
+
return false;
|
|
1674
|
+
}
|
|
1675
|
+
let timeout;
|
|
1676
|
+
const timeoutResult = new Promise((resolve) => {
|
|
1677
|
+
timeout = globalThis.setTimeout(() => resolve(false), timeoutMs);
|
|
1678
|
+
});
|
|
1679
|
+
const preparationResult = Promise.resolve()
|
|
1680
|
+
.then(async () => prepare(input))
|
|
1681
|
+
.then((result) => result === true, () => false);
|
|
1682
|
+
try {
|
|
1683
|
+
return await Promise.race([preparationResult, timeoutResult]);
|
|
1684
|
+
}
|
|
1685
|
+
finally {
|
|
1686
|
+
if (timeout !== undefined) {
|
|
1687
|
+
globalThis.clearTimeout(timeout);
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
async function isAitOneTimeIapProduct(dependencies, configured, timeoutMs) {
|
|
1692
|
+
try {
|
|
1693
|
+
const result = await waitForAitIapNativeCall(() => dependencies.iap.getProductItemList(), timeoutMs);
|
|
1694
|
+
if (result === undefined) {
|
|
1695
|
+
return false;
|
|
1696
|
+
}
|
|
1697
|
+
const nativeProduct = result.products.find(({ sku }) => sku === configured.sku);
|
|
1698
|
+
if (nativeProduct === undefined) {
|
|
1699
|
+
return false;
|
|
1700
|
+
}
|
|
1701
|
+
return nativeProduct.type === 'CONSUMABLE' || nativeProduct.type === 'NON_CONSUMABLE';
|
|
1702
|
+
}
|
|
1703
|
+
catch {
|
|
1704
|
+
// The provider catalog is the authoritative source for the purchase flow.
|
|
1705
|
+
// Do not route an unknown or unavailable SKU into a one-time order.
|
|
1706
|
+
return false;
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
async function waitForAitIapNativeCall(operation, timeoutMs) {
|
|
1710
|
+
let timeout;
|
|
1711
|
+
const timeoutResult = new Promise((resolve) => {
|
|
1712
|
+
timeout = globalThis.setTimeout(() => resolve(undefined), timeoutMs);
|
|
1713
|
+
});
|
|
1714
|
+
try {
|
|
1715
|
+
const operationResult = operation();
|
|
1716
|
+
return await Promise.race([operationResult, timeoutResult]);
|
|
1717
|
+
}
|
|
1718
|
+
finally {
|
|
1719
|
+
if (timeout !== undefined) {
|
|
1720
|
+
globalThis.clearTimeout(timeout);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
async function verifyAitIapProductGrant(input) {
|
|
1725
|
+
const controller = new AbortController();
|
|
1726
|
+
let timeout;
|
|
1727
|
+
const timeoutResult = new Promise((resolve) => {
|
|
1728
|
+
timeout = globalThis.setTimeout(() => {
|
|
1729
|
+
controller.abort();
|
|
1730
|
+
resolve(false);
|
|
1731
|
+
}, input.timeoutMs);
|
|
1732
|
+
});
|
|
1733
|
+
const verifierResult = Promise.resolve()
|
|
1734
|
+
.then(async () => input.verifier({
|
|
1735
|
+
orderId: input.orderId,
|
|
1736
|
+
productId: input.product.productId,
|
|
1737
|
+
platformSku: input.product.sku,
|
|
1738
|
+
idempotencyKey: input.idempotencyKey,
|
|
1739
|
+
source: input.source,
|
|
1740
|
+
purchasedAt: new Date().toISOString(),
|
|
1741
|
+
signal: controller.signal,
|
|
1742
|
+
timeoutMs: input.timeoutMs,
|
|
1743
|
+
}))
|
|
1744
|
+
.then((result) => result === true, () => false);
|
|
1745
|
+
try {
|
|
1746
|
+
return await Promise.race([verifierResult, timeoutResult]);
|
|
1747
|
+
}
|
|
1748
|
+
finally {
|
|
1749
|
+
if (timeout !== undefined) {
|
|
1750
|
+
globalThis.clearTimeout(timeout);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
function completedAitIapPurchase(product, orderId) {
|
|
1755
|
+
return {
|
|
1756
|
+
status: 'completed',
|
|
1757
|
+
transactionId: orderId,
|
|
1758
|
+
entitlementIds: [product.productId],
|
|
1759
|
+
evidence: createAitIapEvidence(orderId, product.sku, 'process-product-grant'),
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
1762
|
+
function failedPurchase() {
|
|
1763
|
+
return { status: 'failed', entitlementIds: [] };
|
|
1764
|
+
}
|
|
1765
|
+
function cancelledPurchase() {
|
|
1766
|
+
return { status: 'cancelled', entitlementIds: [] };
|
|
1767
|
+
}
|
|
1768
|
+
function pendingPurchase(transactionId) {
|
|
1769
|
+
return {
|
|
1770
|
+
status: 'pending',
|
|
1771
|
+
...(transactionId === undefined ? {} : { transactionId }),
|
|
1772
|
+
entitlementIds: [],
|
|
1773
|
+
};
|
|
1774
|
+
}
|
|
1775
|
+
function createAitIapEvidence(orderId, sku, source) {
|
|
1776
|
+
return {
|
|
1777
|
+
schema: iapEvidenceSchema,
|
|
1778
|
+
payload: { orderId, sku, source },
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
function createAitIapOrderIdempotencyKey(orderId) {
|
|
1782
|
+
return `apps-in-toss:purchase:${encodeURIComponent(orderId)}`;
|
|
1783
|
+
}
|
|
1784
|
+
function createAitIapPurchaseRequestKey(productId, idempotencyKey) {
|
|
1785
|
+
return `${encodeURIComponent(productId)}:${encodeURIComponent(idempotencyKey)}`;
|
|
1786
|
+
}
|
|
1787
|
+
function safelyCleanupAitIapPurchase(cleanup) {
|
|
1788
|
+
try {
|
|
1789
|
+
cleanup();
|
|
1790
|
+
}
|
|
1791
|
+
catch {
|
|
1792
|
+
// The bridge has already reached a terminal result; cleanup failures must
|
|
1793
|
+
// not turn a completed server grant into a client-visible failure.
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
function isAitIapOrderId(value) {
|
|
1797
|
+
return value.length > 0 && value.length <= 2048 && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
1798
|
+
}
|
|
1799
|
+
function isAitIapCancellation(error) {
|
|
1800
|
+
if (isAbortError(error)) {
|
|
1801
|
+
return true;
|
|
1802
|
+
}
|
|
1803
|
+
if (!isRecord(error)) {
|
|
1804
|
+
return false;
|
|
1805
|
+
}
|
|
1806
|
+
const code = typeof error.code === 'string' ? error.code : '';
|
|
1807
|
+
return /CANCEL|ABORT/u.test(code);
|
|
1808
|
+
}
|
|
1809
|
+
function normalizeAitIapGrantTime(value) {
|
|
1810
|
+
if (value.length === 0 || value.length > 2048 || /[\p{Cc}\p{Cf}]/u.test(value)) {
|
|
1811
|
+
return new Date().toISOString();
|
|
1812
|
+
}
|
|
1813
|
+
const parsed = Date.parse(value);
|
|
1814
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : new Date().toISOString();
|
|
1815
|
+
}
|
|
1816
|
+
function toAitIapProductInfo(nativeProduct, configured) {
|
|
1817
|
+
const title = normalizeAitIapDisplayText(nativeProduct.displayName);
|
|
1818
|
+
const description = normalizeAitIapDisplayText(nativeProduct.description);
|
|
1819
|
+
const formattedPrice = normalizeAitIapDisplayText(nativeProduct.displayAmount);
|
|
1820
|
+
if (title === undefined || description === undefined || formattedPrice === undefined) {
|
|
1821
|
+
return undefined;
|
|
1822
|
+
}
|
|
1823
|
+
if (nativeProduct.type === 'SUBSCRIPTION') {
|
|
1824
|
+
// Subscription creation, renewal, and expiry need a different native and
|
|
1825
|
+
// server-authority lifecycle. This bridge only owns one-time orders.
|
|
1826
|
+
console.warn('AIT subscription IAP is unavailable through the one-time order bridge.', {
|
|
1827
|
+
productId: configured.productId,
|
|
1828
|
+
sku: nativeProduct.sku,
|
|
1829
|
+
});
|
|
1830
|
+
return undefined;
|
|
1831
|
+
}
|
|
1832
|
+
let type;
|
|
1833
|
+
if (nativeProduct.type === 'CONSUMABLE') {
|
|
1834
|
+
type = 'consumable';
|
|
1835
|
+
}
|
|
1836
|
+
else if (nativeProduct.type === 'NON_CONSUMABLE') {
|
|
1837
|
+
type = 'non_consumable';
|
|
1838
|
+
}
|
|
1839
|
+
if (type === undefined) {
|
|
1840
|
+
console.warn('AIT native IAP product has an unsupported type; hiding product.', {
|
|
1841
|
+
productId: configured.productId,
|
|
1842
|
+
sku: nativeProduct.sku,
|
|
1843
|
+
nativeType: nativeProduct.type,
|
|
1844
|
+
});
|
|
1845
|
+
return undefined;
|
|
1846
|
+
}
|
|
1847
|
+
return {
|
|
1848
|
+
id: configured.productId,
|
|
1849
|
+
type,
|
|
1850
|
+
title,
|
|
1851
|
+
description,
|
|
1852
|
+
price: {
|
|
1853
|
+
formatted: formattedPrice,
|
|
1854
|
+
currencyCode: configured.currencyCode,
|
|
1855
|
+
},
|
|
1856
|
+
};
|
|
1857
|
+
}
|
|
1858
|
+
function normalizeAitIapDisplayText(value) {
|
|
1859
|
+
const normalized = value.trim();
|
|
1860
|
+
return normalized.length > 0 && normalized.length <= 2048 && !/[\p{Cc}\p{Cf}]/u.test(normalized)
|
|
1861
|
+
? normalized
|
|
1862
|
+
: undefined;
|
|
1863
|
+
}
|
|
1864
|
+
function normalizeIapProducts(input) {
|
|
1865
|
+
const byProductId = new Map();
|
|
1866
|
+
const bySku = new Map();
|
|
1867
|
+
for (const rawProduct of input ?? []) {
|
|
1868
|
+
const productId = typeof rawProduct.productId === 'string'
|
|
1869
|
+
? normalizeAitIapConfigIdentifier(rawProduct.productId, 'productId', 128)
|
|
1870
|
+
: undefined;
|
|
1871
|
+
const sku = typeof rawProduct.sku === 'string'
|
|
1872
|
+
? normalizeAitIapConfigIdentifier(rawProduct.sku, 'sku', 2048)
|
|
1873
|
+
: undefined;
|
|
1874
|
+
const currencyCode = normalizeAitIapCurrencyCode(rawProduct.currencyCode);
|
|
1875
|
+
if (productId === undefined || sku === undefined || currencyCode === undefined) {
|
|
1876
|
+
console.warn('AIT IAP product configuration is invalid; disabling one product.', {
|
|
1877
|
+
productId: rawProduct.productId,
|
|
1878
|
+
sku: rawProduct.sku,
|
|
1879
|
+
});
|
|
1880
|
+
continue;
|
|
1881
|
+
}
|
|
1882
|
+
if (byProductId.has(productId) || bySku.has(sku)) {
|
|
1883
|
+
console.warn('AIT IAP product configuration has a duplicate product id or SKU; disabling one product.', { productId, sku });
|
|
1884
|
+
continue;
|
|
1885
|
+
}
|
|
1886
|
+
const product = {
|
|
1887
|
+
productId: productId,
|
|
1888
|
+
sku,
|
|
1889
|
+
currencyCode,
|
|
1890
|
+
};
|
|
1891
|
+
byProductId.set(product.productId, product);
|
|
1892
|
+
bySku.set(product.sku, product);
|
|
1893
|
+
}
|
|
1894
|
+
return { byProductId, bySku };
|
|
1895
|
+
}
|
|
1896
|
+
function normalizeAitIapConfigIdentifier(value, field, maximumLength) {
|
|
1897
|
+
const normalized = value.trim();
|
|
1898
|
+
if (normalized.length === 0
|
|
1899
|
+
|| normalized.length > maximumLength
|
|
1900
|
+
|| /[\p{Cc}\p{Cf}]/u.test(normalized)) {
|
|
1901
|
+
return undefined;
|
|
1902
|
+
}
|
|
1903
|
+
return normalized;
|
|
1904
|
+
}
|
|
1905
|
+
function normalizeAitIapCurrencyCode(value) {
|
|
1906
|
+
const normalized = value?.trim().toUpperCase() ?? 'KRW';
|
|
1907
|
+
return /^[A-Z]{3}$/u.test(normalized) ? normalized : undefined;
|
|
1908
|
+
}
|
|
904
1909
|
function areFullScreenAdsSupported(dependencies) {
|
|
905
|
-
return
|
|
906
|
-
&&
|
|
1910
|
+
return isAitNativeMethodSupported(dependencies.loadFullScreenAd)
|
|
1911
|
+
&& isAitNativeMethodSupported(dependencies.showFullScreenAd);
|
|
1912
|
+
}
|
|
1913
|
+
function areBannerAdsSupported(dependencies) {
|
|
1914
|
+
return isAitNativeMethodSupported(dependencies.tossAds.initialize)
|
|
1915
|
+
&& isAitNativeMethodSupported(dependencies.tossAds.attachBanner);
|
|
1916
|
+
}
|
|
1917
|
+
function initializeAitBannerAds(dependencies, timeoutMs) {
|
|
1918
|
+
return new Promise((resolve) => {
|
|
1919
|
+
let settled = false;
|
|
1920
|
+
const finish = (initialized) => {
|
|
1921
|
+
if (settled) {
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
settled = true;
|
|
1925
|
+
globalThis.clearTimeout(timer);
|
|
1926
|
+
resolve(initialized);
|
|
1927
|
+
};
|
|
1928
|
+
const timer = globalThis.setTimeout(() => finish(false), timeoutMs);
|
|
1929
|
+
try {
|
|
1930
|
+
dependencies.tossAds.initialize({
|
|
1931
|
+
callbacks: {
|
|
1932
|
+
onInitialized: () => finish(true),
|
|
1933
|
+
onInitializationFailed: () => finish(false),
|
|
1934
|
+
},
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
catch (error) {
|
|
1938
|
+
console.warn('Failed to initialize AIT banner ads.', error);
|
|
1939
|
+
finish(false);
|
|
1940
|
+
}
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
async function attachAitBanner(input) {
|
|
1944
|
+
return new Promise((resolve) => {
|
|
1945
|
+
let settled = false;
|
|
1946
|
+
let terminalStatus;
|
|
1947
|
+
let attachment;
|
|
1948
|
+
const finish = (requestedStatus) => {
|
|
1949
|
+
const ownsSurface = input.mountOwners.get(input.surfaceId) === input.mountOwner;
|
|
1950
|
+
const status = requestedStatus === 'mounted' && !ownsSurface
|
|
1951
|
+
? 'unavailable'
|
|
1952
|
+
: requestedStatus;
|
|
1953
|
+
if (settled) {
|
|
1954
|
+
if (status !== 'mounted' && input.activeAttachments.get(input.surfaceId) === attachment) {
|
|
1955
|
+
attachment?.destroy();
|
|
1956
|
+
input.activeAttachments.delete(input.surfaceId);
|
|
1957
|
+
}
|
|
1958
|
+
if (status !== 'mounted' && ownsSurface) {
|
|
1959
|
+
input.mountOwners.delete(input.surfaceId);
|
|
1960
|
+
}
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
settled = true;
|
|
1964
|
+
terminalStatus = status;
|
|
1965
|
+
globalThis.clearTimeout(timer);
|
|
1966
|
+
if (input.pendingSettlements.get(input.surfaceId)?.mountOwner === input.mountOwner) {
|
|
1967
|
+
input.pendingSettlements.delete(input.surfaceId);
|
|
1968
|
+
}
|
|
1969
|
+
if (status !== 'mounted') {
|
|
1970
|
+
attachment?.destroy();
|
|
1971
|
+
if (input.activeAttachments.get(input.surfaceId) === attachment) {
|
|
1972
|
+
input.activeAttachments.delete(input.surfaceId);
|
|
1973
|
+
}
|
|
1974
|
+
if (ownsSurface) {
|
|
1975
|
+
input.mountOwners.delete(input.surfaceId);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
resolve({ status });
|
|
1979
|
+
};
|
|
1980
|
+
const timer = globalThis.setTimeout(() => finish('failed'), input.timeoutMs);
|
|
1981
|
+
input.pendingSettlements.set(input.surfaceId, {
|
|
1982
|
+
mountOwner: input.mountOwner,
|
|
1983
|
+
settleUnavailable: () => finish('unavailable'),
|
|
1984
|
+
});
|
|
1985
|
+
try {
|
|
1986
|
+
const sdkAttachment = input.dependencies.tossAds.attachBanner(input.adGroupId, input.target, {
|
|
1987
|
+
theme: input.appearance.theme,
|
|
1988
|
+
tone: input.appearance.tone,
|
|
1989
|
+
variant: input.appearance.variant,
|
|
1990
|
+
callbacks: {
|
|
1991
|
+
onAdRendered: () => finish('mounted'),
|
|
1992
|
+
onNoFill: () => finish('unavailable'),
|
|
1993
|
+
onAdFailedToRender: (payload) => {
|
|
1994
|
+
console.warn('Failed to render an AIT banner ad.', input.adGroupId, payload.error);
|
|
1995
|
+
finish('failed');
|
|
1996
|
+
},
|
|
1997
|
+
},
|
|
1998
|
+
});
|
|
1999
|
+
let attachmentDestroyed = false;
|
|
2000
|
+
attachment = {
|
|
2001
|
+
destroy() {
|
|
2002
|
+
if (!attachmentDestroyed) {
|
|
2003
|
+
attachmentDestroyed = true;
|
|
2004
|
+
sdkAttachment.destroy();
|
|
2005
|
+
}
|
|
2006
|
+
},
|
|
2007
|
+
};
|
|
2008
|
+
if (terminalStatus === 'unavailable' || terminalStatus === 'failed') {
|
|
2009
|
+
attachment.destroy();
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
if (input.mountOwners.get(input.surfaceId) !== input.mountOwner) {
|
|
2013
|
+
attachment.destroy();
|
|
2014
|
+
finish('unavailable');
|
|
2015
|
+
return;
|
|
2016
|
+
}
|
|
2017
|
+
const existingAttachment = input.activeAttachments.get(input.surfaceId);
|
|
2018
|
+
if (existingAttachment !== undefined && existingAttachment !== attachment) {
|
|
2019
|
+
existingAttachment.destroy();
|
|
2020
|
+
}
|
|
2021
|
+
input.activeAttachments.set(input.surfaceId, attachment);
|
|
2022
|
+
}
|
|
2023
|
+
catch (error) {
|
|
2024
|
+
console.warn('Failed to attach an AIT banner ad.', input.adGroupId, error);
|
|
2025
|
+
finish('failed');
|
|
2026
|
+
}
|
|
2027
|
+
});
|
|
2028
|
+
}
|
|
2029
|
+
function isAitNativeMethodSupported(method) {
|
|
2030
|
+
return isCapabilitySupported(() => method.isSupported?.() === true);
|
|
907
2031
|
}
|
|
908
2032
|
function isCapabilitySupported(check) {
|
|
909
2033
|
try {
|
|
@@ -995,6 +2119,16 @@ function normalizeDisplayStartTimeout(value) {
|
|
|
995
2119
|
function normalizeMaximumDisplayTimeout(value) {
|
|
996
2120
|
return normalizePositiveTimeout(value, defaultAdMaximumDisplayMs, 'AIT ad maximum display timeout must be a positive finite number.');
|
|
997
2121
|
}
|
|
2122
|
+
function normalizeBannerRenderTimeout(value) {
|
|
2123
|
+
return normalizePositiveTimeout(value, defaultBannerRenderTimeoutMs, 'AIT banner render timeout must be a positive finite number.');
|
|
2124
|
+
}
|
|
2125
|
+
function normalizeIapProductGrantTimeout(value) {
|
|
2126
|
+
const timeout = normalizePositiveTimeout(value, defaultIapProductGrantTimeoutMs, 'AIT IAP product-grant timeout must be a positive finite number.');
|
|
2127
|
+
if (timeout > defaultIapProductGrantTimeoutMs) {
|
|
2128
|
+
throw new Error(`AIT IAP product-grant timeout cannot exceed ${defaultIapProductGrantTimeoutMs}ms.`);
|
|
2129
|
+
}
|
|
2130
|
+
return timeout;
|
|
2131
|
+
}
|
|
998
2132
|
function normalizePositiveTimeout(value, defaultValue, message) {
|
|
999
2133
|
if (value === undefined) {
|
|
1000
2134
|
return defaultValue;
|
|
@@ -1018,10 +2152,35 @@ function readPlacementId(payload) {
|
|
|
1018
2152
|
}
|
|
1019
2153
|
return placementId;
|
|
1020
2154
|
}
|
|
2155
|
+
function readBannerSurfaceId(payload) {
|
|
2156
|
+
const surfaceId = readPayloadRecord(payload).surfaceId;
|
|
2157
|
+
if (typeof surfaceId !== 'string' || surfaceId.length === 0) {
|
|
2158
|
+
throw new TypeError('AIT banner surfaceId must be a valid non-empty element id.');
|
|
2159
|
+
}
|
|
2160
|
+
return surfaceId;
|
|
2161
|
+
}
|
|
1021
2162
|
function readIdempotencyKey(payload, fallback) {
|
|
1022
2163
|
const value = readPayloadRecord(payload).idempotencyKey;
|
|
1023
2164
|
return typeof value === 'string' && value.length > 0 ? value : fallback;
|
|
1024
2165
|
}
|
|
2166
|
+
function readCommercePurchase(payload) {
|
|
2167
|
+
const value = readPayloadRecord(payload);
|
|
2168
|
+
const productId = value.productId;
|
|
2169
|
+
const idempotencyKey = value.idempotencyKey;
|
|
2170
|
+
if (typeof productId !== 'string'
|
|
2171
|
+
|| productId.length === 0
|
|
2172
|
+
|| productId.length > 128
|
|
2173
|
+
|| /[\p{Cc}\p{Cf}]/u.test(productId)) {
|
|
2174
|
+
throw new TypeError('AIT IAP productId must contain 1 to 128 visible characters.');
|
|
2175
|
+
}
|
|
2176
|
+
if (typeof idempotencyKey !== 'string'
|
|
2177
|
+
|| idempotencyKey.length === 0
|
|
2178
|
+
|| idempotencyKey.length > 256
|
|
2179
|
+
|| /[\p{Cc}\p{Cf}]/u.test(idempotencyKey)) {
|
|
2180
|
+
throw new TypeError('AIT IAP idempotencyKey must contain 1 to 256 visible characters.');
|
|
2181
|
+
}
|
|
2182
|
+
return { productId: productId, idempotencyKey };
|
|
2183
|
+
}
|
|
1025
2184
|
function readRequiredIdempotencyKey(payload) {
|
|
1026
2185
|
const value = readPayloadRecord(payload).idempotencyKey;
|
|
1027
2186
|
if (typeof value !== 'string' || value.length === 0 || value.length > 256) {
|