@superwall/runtime 1.2.0 → 1.3.0-beta.3

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.
Files changed (92) hide show
  1. package/README.md +65 -49
  2. package/dist/bridge/base64.d.ts +0 -6
  3. package/dist/bridge/base64.js +5 -25
  4. package/dist/bridge/index.d.ts +2 -30
  5. package/dist/bridge/index.js +2 -49
  6. package/dist/bridge/transport.d.ts +2 -9
  7. package/dist/bridge/transport.js +9 -30
  8. package/dist/config/background.d.ts +16 -0
  9. package/dist/config/background.js +13 -0
  10. package/dist/config/checkout.d.ts +26 -0
  11. package/dist/config/checkout.js +2 -0
  12. package/dist/config/index.d.ts +66 -0
  13. package/dist/config/index.js +4 -0
  14. package/dist/config/localization.d.ts +13 -0
  15. package/dist/config/localization.js +1 -0
  16. package/dist/config/notifications.d.ts +40 -0
  17. package/dist/config/notifications.js +1 -0
  18. package/dist/config/platforms.d.ts +3 -0
  19. package/dist/config/platforms.js +5 -0
  20. package/dist/config/presentation.d.ts +22 -0
  21. package/dist/config/presentation.js +1 -0
  22. package/dist/config/products.d.ts +23 -0
  23. package/dist/config/products.js +10 -0
  24. package/dist/index.d.ts +2 -7
  25. package/dist/index.js +1 -6
  26. package/dist/localization/catalog.d.ts +8 -0
  27. package/dist/localization/catalog.js +21 -0
  28. package/dist/localization/index.d.ts +3 -24
  29. package/dist/localization/index.js +3 -71
  30. package/dist/localization/locale.d.ts +2 -0
  31. package/dist/localization/locale.js +22 -0
  32. package/dist/localization/periods.d.ts +1 -0
  33. package/dist/localization/periods.js +13 -5
  34. package/dist/products/derive.d.ts +4 -0
  35. package/dist/products/derive.js +45 -0
  36. package/dist/{products.d.ts → products/index.d.ts} +6 -14
  37. package/dist/products/index.js +15 -0
  38. package/dist/products/merge.d.ts +5 -0
  39. package/dist/products/merge.js +51 -0
  40. package/dist/session/incoming.d.ts +3 -0
  41. package/dist/session/incoming.js +47 -0
  42. package/dist/session/index.d.ts +7 -102
  43. package/dist/session/index.js +232 -695
  44. package/dist/session/outgoing.d.ts +42 -0
  45. package/dist/session/outgoing.js +70 -0
  46. package/dist/session/purchases.d.ts +18 -0
  47. package/dist/session/purchases.js +44 -0
  48. package/dist/session/reminders.d.ts +11 -0
  49. package/dist/session/reminders.js +41 -0
  50. package/dist/session/requests.d.ts +19 -0
  51. package/dist/session/requests.js +56 -0
  52. package/dist/session/state.d.ts +3 -3
  53. package/dist/session/state.js +14 -39
  54. package/dist/session/types.d.ts +49 -29
  55. package/dist/session/variables.d.ts +3 -7
  56. package/package.json +3 -2
  57. package/src/bridge/base64.ts +10 -46
  58. package/src/bridge/index.ts +7 -77
  59. package/src/bridge/transport.ts +11 -46
  60. package/src/config/background.ts +24 -0
  61. package/src/config/checkout.ts +32 -0
  62. package/src/config/index.ts +102 -0
  63. package/src/config/localization.ts +12 -0
  64. package/src/config/notifications.ts +49 -0
  65. package/src/config/platforms.ts +8 -0
  66. package/src/config/presentation.ts +22 -0
  67. package/src/config/products.ts +39 -0
  68. package/src/index.ts +2 -43
  69. package/src/localization/catalog.ts +45 -0
  70. package/src/localization/index.ts +7 -110
  71. package/src/localization/locale.ts +25 -0
  72. package/src/localization/periods.ts +23 -8
  73. package/src/products/derive.ts +65 -0
  74. package/src/products/index.ts +87 -0
  75. package/src/products/merge.ts +78 -0
  76. package/src/session/incoming.ts +53 -0
  77. package/src/session/index.ts +275 -986
  78. package/src/session/outgoing.ts +132 -0
  79. package/src/session/purchases.ts +66 -0
  80. package/src/session/reminders.ts +56 -0
  81. package/src/session/requests.ts +87 -0
  82. package/src/session/state.ts +19 -59
  83. package/src/session/types.ts +68 -30
  84. package/src/session/variables.ts +3 -7
  85. package/dist/config.d.ts +0 -237
  86. package/dist/config.js +0 -138
  87. package/dist/mock.d.ts +0 -74
  88. package/dist/mock.js +0 -206
  89. package/dist/products.js +0 -105
  90. package/src/config.ts +0 -408
  91. package/src/mock.ts +0 -333
  92. package/src/products.ts +0 -221
@@ -1,732 +1,269 @@
1
- import { getLocalizedPeriod } from "../localization/periods";
2
- import { createSuperwallBridge } from "../bridge";
3
- import { productsFromConfig } from "../config";
4
- import { createTranslator, languageCandidates, resolveLocale, } from "../localization";
5
- import { recordFromVariables } from "./variables";
6
- import { createSuperwallProduct, mergeIncomingProducts, mergeProductVariables, productReferenceFromInput, productVariablesFromTemplateVariables, productsByReference, } from "../products";
1
+ import { decodeIncomingMessages } from "../bridge/base64";
2
+ import { createRuntimeTransport } from "../bridge/transport";
3
+ import { normalizePlatform, productIdFor } from "../config";
4
+ import { createTranslator, languageCandidates, resolveLocale } from "../localization";
5
+ import { createProductDeriver, createSuperwallProduct, findProductByStoreId, mergeIncomingProducts, mergeProductVariables, productReferenceFromInput, productVariablesFromTemplateVariables, productsByReference, } from "../products";
6
+ import { snapshotPatchFor } from "./incoming";
7
+ import * as outgoing from "./outgoing";
8
+ import { createPurchaseTracker } from "./purchases";
9
+ import { callbackStateName, createRequestTracker } from "./requests";
10
+ import { trialReminderFor } from "./reminders";
7
11
  import { buildSuperwallState } from "./state";
8
- export * from "./types";
9
- const permissionTypeToStateName = (permissionType) => permissionType.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
10
- const callbackNameToStateName = (name) => {
11
- const segments = name
12
- .replace(/[^a-zA-Z0-9]/g, " ")
13
- .trim()
14
- .replace(/\s+/g, " ")
15
- .split(" ")
16
- .filter(Boolean);
17
- if (segments.length === 0) {
18
- return "callback";
19
- }
20
- return segments
21
- .map((segment, index) => index === 0
22
- ? segment.charAt(0).toLowerCase() + segment.slice(1)
23
- : segment.charAt(0).toUpperCase() + segment.slice(1))
24
- .join("");
25
- };
26
- const initialTrialState = (config) => {
27
- switch (config?.introductoryOfferEligibility) {
28
- case "alwaysEligible":
29
- return { eligible: true };
30
- case "alwaysIneligible":
31
- return { eligible: false };
32
- default:
33
- return {};
34
- }
35
- };
36
- const DAY_MS = 24 * 60 * 60 * 1000;
37
- /**
38
- * Mirrors the schema editor's computeTrialPeriodEndDate: "Jul 23, 2026",
39
- * month name localized to the active locale where the runtime supports it.
40
- */
41
- const computeTrialPeriodEndDate = (trialPeriodDays, language) => {
42
- const parsedDays = typeof trialPeriodDays === "number" ? trialPeriodDays : Number(trialPeriodDays);
43
- if (!Number.isFinite(parsedDays) || parsedDays <= 0) {
44
- return undefined;
45
- }
46
- const endDate = new Date();
47
- endDate.setDate(endDate.getDate() + Math.trunc(parsedDays));
48
- let month;
49
- try {
50
- month = endDate.toLocaleString(language?.replace(/_/g, "-") ?? "default", { month: "short" });
51
- }
52
- catch {
53
- month = endDate.toLocaleString("default", { month: "short" });
54
- }
55
- return `${month} ${endDate.getDate()}, ${endDate.getFullYear()}`;
56
- };
57
- const createRequestId = (prefix) => {
58
- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
59
- return `${prefix}-${crypto.randomUUID()}`;
60
- }
61
- return `${prefix}-${Math.random().toString(36).slice(2)}`;
62
- };
63
- class SuperwallSessionImpl {
64
- bridge;
65
- listeners = new Set();
66
- pendingPurchases = new Map();
67
- pendingPermissions = new Map();
68
- pendingCallbacks = new Map();
69
- eventHandlers = new Map();
70
- snapshot;
71
- translator;
72
- localeOverride;
73
- rawProducts;
74
- localizedProductsCache;
75
- constructor(options = {}) {
76
- this.bridge = options.bridge ?? createSuperwallBridge(options);
77
- const products = options.products ?? productsFromConfig(options.config);
78
- this.rawProducts = products;
79
- const variables = options.variables ?? {};
80
- const locale = resolveLocale(undefined, options.config?.localization);
81
- this.translator = createTranslator(options.config?.localization, locale);
82
- this.snapshot = {
83
- status: "idle",
84
- config: options.config,
85
- products,
86
- productsByReference: productsByReference(products),
87
- variables,
88
- device: {},
89
- user: {},
90
- params: {},
91
- trial: initialTrialState(options.config),
92
- locale,
93
- permissionStatuses: {},
94
- callbackStates: {},
95
- state: buildSuperwallState({ variables, products }),
96
- messages: [...this.bridge.messages],
97
- };
98
- this.bridge.addListener((message) => {
99
- this.handleIncomingMessage(message);
100
- this.emit(message.event_name, message);
101
- this.emit("message", message);
102
- });
103
- }
104
- /**
105
- * Subscribes to a single incoming SDK event by name, or "message" for all
106
- * incoming messages. Returns an unsubscribe function.
107
- */
108
- on(event, handler) {
109
- const handlers = this.handlersFor(event) ?? new Set();
110
- this.eventHandlers.set(event, handlers);
111
- handlers.add(handler);
112
- return () => {
113
- handlers.delete(handler);
114
- };
115
- }
116
- /**
117
- * `on`/`emit` enforce that handlers stored under an event name only ever
118
- * receive that event's payload; TypeScript cannot carry that key↔value
119
- * correlation through a heterogeneous store (microsoft/TypeScript#47109),
120
- * so this accessor is the one place it is asserted.
121
- */
122
- handlersFor(event) {
123
- return this.eventHandlers.get(event);
124
- }
125
- emit(event, payload) {
126
- const handlers = this.handlersFor(event);
127
- if (!handlers)
128
- return;
129
- for (const handler of handlers) {
130
- handler(payload);
131
- }
132
- }
133
- subscribe = (listener) => {
134
- this.listeners.add(listener);
135
- return () => {
136
- this.listeners.delete(listener);
137
- };
12
+ const createSession = (options) => {
13
+ const transport = options.transport ?? createRuntimeTransport(options.transportKind);
14
+ const listeners = new Set();
15
+ const handlers = {};
16
+ const purchases = createPurchaseTracker();
17
+ const requests = createRequestTracker();
18
+ const derive = createProductDeriver();
19
+ let raw = [];
20
+ let localeOverride;
21
+ let translator = createTranslator(options.config?.localization, resolveLocale(undefined, options.config?.localization));
22
+ let snapshot = {
23
+ status: "idle",
24
+ config: options.config,
25
+ products: [],
26
+ productsByReference: {},
27
+ variables: {},
28
+ device: {},
29
+ user: {},
30
+ params: {},
31
+ introductoryOffer: {},
32
+ locale: translator.locale,
33
+ permissionStatuses: {},
34
+ callbackStates: {},
35
+ state: buildSuperwallState({ variables: {}, products: [] }),
138
36
  };
139
- getSnapshot = () => this.snapshot;
140
- get products() {
141
- return this.snapshot.products;
142
- }
143
- get config() {
144
- return this.snapshot.config;
145
- }
146
- get locale() {
147
- return this.snapshot.locale;
148
- }
149
- /**
150
- * Resolves a message key for the active locale, interpolating `{name}`
151
- * params. Unknown keys return the key itself, so literal copy is safe.
152
- */
153
- t = (key, values) => this.translator.t(key, values);
154
- /** Overrides the locale (normally auto-detected from the device). */
155
- setLocale(locale) {
156
- this.localeOverride = locale;
157
- this.patch({});
158
- }
159
- configure(config) {
160
- if (config === this.snapshot.config) {
161
- return;
162
- }
163
- const patch = { config };
164
- // Reseed product slots from the new config unless the SDK has already
165
- // delivered real products (the SDK always wins over config seeds).
166
- const hasSdkProducts = this.rawProducts.some((product) => product.source === "sdk");
167
- if (!hasSdkProducts) {
168
- this.rawProducts = productsFromConfig(config);
37
+ const commit = (patch) => {
38
+ const next = { ...snapshot, ...patch };
39
+ const deviceLocale = next.device.deviceLocale ?? next.device.deviceLanguageCode;
40
+ const requested = localeOverride ?? (typeof deviceLocale === "string" ? deviceLocale : undefined);
41
+ const locale = resolveLocale(requested, next.config?.localization);
42
+ if (locale !== translator.locale || next.config !== snapshot.config) {
43
+ translator = createTranslator(next.config?.localization, locale);
169
44
  }
170
- // Re-derive forced trial eligibility; "automatic" keeps whatever the SDK
171
- // has signaled so far.
172
- if (config.introductoryOfferEligibility === "alwaysEligible" ||
173
- config.introductoryOfferEligibility === "alwaysIneligible") {
174
- patch.trial = initialTrialState(config);
45
+ const products = derive(raw, languageCandidates(requested));
46
+ if (products !== next.products) {
47
+ next.products = products;
48
+ next.productsByReference = productsByReference(products);
175
49
  }
176
- this.patch(patch);
177
- }
178
- start(options = {}) {
179
- if (this.snapshot.status !== "listening") {
180
- this.bridge.start();
181
- this.patch({ status: "listening" });
182
- }
183
- if (options.sendPing) {
184
- this.ping(options.ping);
185
- }
186
- }
187
- postMessage(message) {
188
- this.bridge.postMessage(message);
189
- this.patch({ messages: this.bridge.messages });
190
- }
191
- accept(messages) {
192
- this.bridge.accept(messages);
193
- }
194
- accept64(message) {
195
- this.bridge.accept64(message);
196
- }
197
- ping(message = {}) {
198
- this.postMessage({
199
- event_name: "ping",
200
- substitutions: [],
201
- page_styles: [],
202
- version: "4.0.0",
203
- ...message,
204
- });
205
- }
206
- close() {
207
- this.postMessage({ event_name: "close" });
208
- }
209
- /**
210
- * Asks the SDK to restore purchases. The message protocol has no restore
211
- * result event, so this cannot resolve with an outcome; a successful restore
212
- * typically dismisses the paywall or arrives as `transaction_complete`
213
- * (observable via `on("transaction_complete", ...)`).
214
- */
215
- restore() {
216
- this.postMessage({ event_name: "restore" });
217
- }
218
- openUrl(url, options = {}) {
219
- this.postMessage({
220
- event_name: "open_url",
221
- url,
222
- browser_type: options.browserType,
223
- });
224
- }
225
- openExternalUrl(url) {
226
- this.postMessage({
227
- event_name: "open_url_external",
228
- url,
229
- });
230
- }
231
- openDeepLink(link) {
232
- this.postMessage({
233
- event_name: "open_deep_link",
234
- link,
235
- });
236
- }
237
- custom(data) {
238
- this.postMessage({
239
- event_name: "custom",
240
- data,
241
- });
242
- }
243
- customPlacement(name, params = {}) {
244
- this.postMessage({
245
- event_name: "custom_placement",
246
- name,
247
- params,
248
- });
249
- }
250
- requestStoreReview(reviewType) {
251
- this.postMessage({
252
- event_name: "request_store_review",
253
- review_type: reviewType,
254
- });
255
- }
256
- setUserAttributes(attributes) {
257
- this.postMessage({
258
- event_name: "user_attribute_updated",
259
- attributes: Object.entries(attributes).map(([key, value]) => ({
260
- key,
261
- value,
262
- })),
263
- });
264
- }
265
- pageView(input) {
266
- this.postMessage({
267
- event_name: "page_view",
268
- type: input.type,
269
- page_name: input.name,
270
- page_node_id: input.name,
271
- navigation_node_id: input.navigationId,
272
- flow_position: input.position,
273
- previous_page_node_id: input.previousName,
274
- previous_flow_position: input.previousPosition,
275
- time_on_previous_page_ms: input.timeOnPreviousMs,
276
- });
277
- }
278
- scheduleTrialReminder(input) {
279
- this.postMessage({
280
- event_name: "schedule_notification",
281
- id: input.id,
282
- type: "TRIAL_STARTED",
283
- title: input.title,
284
- subtitle: input.subtitle,
285
- body: input.body,
286
- delay: input.delayMs,
287
- });
288
- }
289
- hapticFeedback(hapticType) {
290
- this.postMessage({
291
- event_name: "haptic_feedback",
292
- haptic_type: hapticType,
293
- });
294
- }
295
- requestPermission(permissionType) {
296
- const requestId = createRequestId(`permission-${permissionType}`);
297
- const result = new Promise((resolve) => {
298
- this.pendingPermissions.set(requestId, { resolve });
299
- });
300
- this.postMessage({
301
- event_name: "request_permission",
302
- permission_type: permissionType,
303
- request_id: requestId,
304
- });
305
- return result;
306
- }
307
- requestCallback(name, options = {}) {
308
- const requestId = createRequestId(`callback-${name}`);
309
- const behavior = options.behavior ?? "blocking";
310
- const result = new Promise((resolve) => {
311
- this.pendingCallbacks.set(requestId, { name, resolve });
312
- });
313
- this.postMessage({
314
- event_name: "request_callback",
315
- request_id: requestId,
316
- name,
317
- behavior,
318
- variables: options.variables,
50
+ snapshot = {
51
+ ...next,
52
+ locale,
53
+ state: buildSuperwallState({
54
+ variables: next.variables,
55
+ products: next.products,
56
+ paywall: next.paywall,
57
+ lastTransaction: next.lastTransaction,
58
+ permissionStatuses: next.permissionStatuses,
59
+ callbackStates: next.callbackStates,
60
+ introductoryOffer: next.introductoryOffer,
61
+ }),
62
+ };
63
+ for (const listener of listeners)
64
+ listener();
65
+ };
66
+ const post = (message) => {
67
+ transport.postMessage(message);
68
+ };
69
+ const t = (key, values) => translator.t(key, values);
70
+ const emit = (event, payload) => {
71
+ handlers[event]?.forEach((handler) => handler(payload));
72
+ };
73
+ const devicePlatform = () => normalizePlatform(typeof snapshot.device.platform === "string" ? snapshot.device.platform : undefined);
74
+ const resolveProduct = (input) => {
75
+ const reference = productReferenceFromInput(input);
76
+ const existing = snapshot.productsByReference[reference];
77
+ if (existing)
78
+ return existing;
79
+ const slot = snapshot.config?.products?.[reference];
80
+ if (slot === undefined || typeof input !== "string")
81
+ return createSuperwallProduct(input);
82
+ return createSuperwallProduct({
83
+ reference,
84
+ productId: productIdFor(slot, devicePlatform()),
85
+ source: "inline",
319
86
  });
320
- // TData is the caller's claim about the SDK-owned payload — the same
321
- // unverifiable-claim seam as `createSuperwallSession`.
322
- return result;
323
- }
324
- purchase(input, options = {}) {
325
- const product = this.resolveProduct(input);
326
- const timeoutMs = options.timeoutMs ?? this.snapshot.config?.purchaseTimeoutMs;
327
- // A retry for the same product replaces the previous attempt: settle the
328
- // old promise and disarm its timer so it can't fire against the new one.
329
- this.cancelPendingPurchase(product.reference, "superseded");
330
- const result = new Promise((resolve) => {
331
- const pending = { product, resolve };
332
- if (timeoutMs !== undefined) {
333
- pending.timeoutId = setTimeout(() => {
334
- this.failPurchase(product.reference, "timeout");
335
- }, timeoutMs);
336
- }
337
- this.pendingPurchases.set(product.reference, pending);
87
+ };
88
+ const productOfTransaction = (message) => {
89
+ if (message.product !== undefined)
90
+ return resolveProduct(message.product);
91
+ return (findProductByStoreId(snapshot.products, message.product_identifier) ??
92
+ createSuperwallProduct(message.product_identifier ?? "unknown"));
93
+ };
94
+ const withoutPending = (reference) => snapshot.pendingPurchase?.reference === reference ? undefined : snapshot.pendingPurchase;
95
+ const recordFailure = (failure) => {
96
+ commit({
97
+ pendingPurchase: withoutPending(failure.product.reference),
98
+ lastPurchaseFailure: failure,
338
99
  });
339
- this.patch({
340
- pendingPurchase: {
341
- reference: product.reference,
342
- product,
343
- },
100
+ };
101
+ const settleTransaction = (message) => {
102
+ const pending = purchases.take(message);
103
+ const product = pending?.product ?? productOfTransaction(message);
104
+ const result = message.event_name === "transaction_complete"
105
+ ? { status: "completed", product, message }
106
+ : { status: "abandoned", product, message };
107
+ pending?.resolve(result);
108
+ commit({
109
+ pendingPurchase: pending
110
+ ? withoutPending(pending.product.reference)
111
+ : snapshot.pendingPurchase,
112
+ lastTransaction: result,
344
113
  lastPurchaseFailure: undefined,
345
114
  });
346
- this.postMessage({
347
- event_name: "purchase",
348
- product: product.reference,
349
- product_identifier: product.productIdentifier ?? product.productId ?? product.id,
350
- should_dismiss: options.shouldDismiss ?? this.snapshot.config?.dismissOnPurchase,
351
- });
352
- return result;
353
- }
354
- getProduct(reference) {
355
- return this.snapshot.productsByReference[reference];
356
- }
357
- handleIncomingMessage(message) {
115
+ };
116
+ const handleIncoming = (message) => {
358
117
  switch (message.event_name) {
359
118
  case "paywall_open":
360
- // A (re)presentation resets transaction state: settle any in-flight
361
- // purchases so their timers and promises can't leak into the new view.
362
- for (const reference of Array.from(this.pendingPurchases.keys())) {
363
- this.cancelPendingPurchase(reference, "superseded");
364
- }
365
- this.patch({
366
- paywall: {
367
- id: message.paywall_id,
368
- identifier: message.paywall_identifier,
369
- },
370
- pendingPurchase: undefined,
371
- lastTransaction: undefined,
372
- lastPurchaseFailure: undefined,
373
- messages: this.bridge.messages,
374
- });
119
+ purchases.failAll("superseded");
375
120
  break;
376
121
  case "products":
377
- this.setProducts(mergeIncomingProducts(this.rawProducts, message.products));
122
+ raw = mergeIncomingProducts(raw, message.products);
378
123
  break;
379
124
  case "template_variables": {
380
- const productVariables = productVariablesFromTemplateVariables(message.variables);
381
- this.patch({
382
- variables: message.variables,
383
- device: recordFromVariables(message.variables, "device"),
384
- user: recordFromVariables(message.variables, "user"),
385
- params: recordFromVariables(message.variables, "params"),
386
- messages: this.bridge.messages,
387
- });
388
- if (productVariables.size > 0) {
389
- this.setProducts(mergeProductVariables(this.rawProducts, productVariables));
390
- }
125
+ const variables = productVariablesFromTemplateVariables(message.variables);
126
+ if (variables.size > 0)
127
+ raw = mergeProductVariables(raw, variables);
391
128
  break;
392
129
  }
393
- case "template_substitutions_prefix": {
394
- // The SDK signals introductory-offer eligibility by switching the
395
- // substitutions prefix to "freeTrial". Config overrides win.
396
- if (this.snapshot.config?.introductoryOfferEligibility === "alwaysEligible")
397
- break;
398
- if (this.snapshot.config?.introductoryOfferEligibility === "alwaysIneligible")
399
- break;
400
- this.patch({
401
- trial: { eligible: message.prefix === "freeTrial" },
402
- messages: this.bridge.messages,
130
+ case "freeTrial_start": {
131
+ const reminder = trialReminderFor(snapshot.config, message, {
132
+ products: raw,
133
+ t,
134
+ locale: snapshot.locale,
135
+ paywallIdentifier: snapshot.paywall?.identifier,
403
136
  });
137
+ if (reminder)
138
+ post(reminder);
404
139
  break;
405
140
  }
406
- case "experiment":
407
- this.patch({
408
- experiment: {
409
- experimentId: message.experimentId,
410
- variantId: message.variantId,
411
- campaignId: message.campaignId,
412
- },
413
- messages: this.bridge.messages,
414
- });
415
- break;
416
- case "freeTrial_start":
417
- this.scheduleConfiguredTrialReminder(message);
418
- this.patch({ messages: this.bridge.messages });
419
- break;
420
141
  case "transaction_complete":
421
- this.resolvePurchase(message);
422
- break;
423
142
  case "transaction_abandon":
424
- this.resolvePurchase(message);
143
+ settleTransaction(message);
144
+ break;
145
+ case "transaction_fail":
146
+ case "transaction_timeout": {
147
+ const pending = purchases.find(message);
148
+ const failure = pending && purchases.fail(pending.product.reference, "sdk");
149
+ if (failure)
150
+ recordFailure(failure);
425
151
  break;
152
+ }
426
153
  case "permission_result":
427
- this.resolvePermission(message);
154
+ requests.resolvePermission(message);
428
155
  break;
429
- case "callback_result":
430
- this.resolveCallback(message);
156
+ case "callback_result": {
157
+ const name = callbackStateName(requests.resolveCallback(message) ?? message.name);
158
+ commit({
159
+ callbackStates: {
160
+ ...snapshot.callbackStates,
161
+ [name]: { result: message.status, data: message.data },
162
+ },
163
+ });
431
164
  break;
165
+ }
432
166
  default:
433
- this.patch({ messages: this.bridge.messages });
434
167
  break;
435
168
  }
436
- }
437
- /**
438
- * Auto-schedules the config's trial reminder when the SDK reports a trial
439
- * started. Static configs run title/subtitle/body through `t()`; dynamic
440
- * configs (functions) compute the notification from the trial context.
441
- */
442
- scheduleConfiguredTrialReminder(message) {
443
- const reminder = this.snapshot.config?.notifications?.trialReminder;
444
- if (!reminder)
445
- return;
446
- if (!message.trial_end_date)
447
- return;
448
- const trialEndMs = typeof message.trial_end_date === "number"
449
- ? message.trial_end_date
450
- : Date.parse(message.trial_end_date);
451
- if (Number.isNaN(trialEndMs))
452
- return;
453
- let notification;
454
- if (typeof reminder === "function") {
455
- const product = message.product_identifier
456
- ? this.rawProducts.find((candidate) => candidate.productIdentifier === message.product_identifier ||
457
- candidate.productId === message.product_identifier)
458
- : undefined;
459
- const resolved = reminder({
460
- trialEndDate: new Date(trialEndMs),
461
- productIdentifier: message.product_identifier,
462
- product,
463
- t: this.t,
464
- locale: this.snapshot.locale,
465
- });
466
- if (!resolved)
467
- return;
468
- notification = resolved;
469
- }
470
- else {
471
- if (reminder.enabled === false)
472
- return;
473
- const beforeTrialEndDays = reminder.beforeTrialEndDays ?? 1;
474
- notification = {
475
- title: this.t(reminder.title),
476
- subtitle: reminder.subtitle ? this.t(reminder.subtitle) : undefined,
477
- body: this.t(reminder.body),
478
- delayMs: trialEndMs - beforeTrialEndDays * DAY_MS - Date.now(),
169
+ commit(snapshotPatchFor(snapshot, message) ?? {});
170
+ emit(message.event_name, message);
171
+ emit("message", message);
172
+ };
173
+ transport.addListener(handleIncoming);
174
+ const requestCallback = (name, callbackOptions = {}) => {
175
+ const behavior = callbackOptions.behavior ?? "blocking";
176
+ const { requestId, result } = requests.callback(name, behavior);
177
+ post(outgoing.requestCallback({ requestId, name, behavior, variables: callbackOptions.variables }));
178
+ // TData is the caller's claim about the SDK-owned payload — the same
179
+ // unverifiable-claim seam as `createSuperwallSession`.
180
+ return result;
181
+ };
182
+ return {
183
+ on: (event, handler) => {
184
+ const set = handlers[event] ?? new Set();
185
+ if (!handlers[event])
186
+ Object.assign(handlers, { [event]: set });
187
+ set.add(handler);
188
+ return () => {
189
+ set.delete(handler);
479
190
  };
480
- }
481
- if (notification.delayMs <= 0)
482
- return;
483
- this.postMessage({
484
- event_name: "schedule_notification",
485
- id: `${this.snapshot.paywall?.identifier ?? "paywall"}_TRIAL_STARTED`,
486
- type: "TRIAL_STARTED",
487
- title: notification.title,
488
- subtitle: notification.subtitle,
489
- body: notification.body,
490
- delay: notification.delayMs,
491
- });
492
- }
493
- setProducts(products) {
494
- this.rawProducts = products;
495
- this.patch({ messages: this.bridge.messages });
496
- }
497
- /**
498
- * The runtime's derived-variables layer — the headless equivalent of the
499
- * schema editor's buildStateIndex computeds. Raw SDK values are kept
500
- * internally; every snapshot derives from them so locale changes re-derive
501
- * cleanly. Currently derives:
502
- * - `period` / `periodly` localized with the shared translation table
503
- * - `trialPeriodEndDate` from `trialPeriodDays` when the SDK omits it
504
- */
505
- deriveProducts(raw, languages) {
506
- const cacheKey = languages.join(",");
507
- if (this.localizedProductsCache &&
508
- this.localizedProductsCache.raw === raw &&
509
- this.localizedProductsCache.languages === cacheKey) {
510
- return this.localizedProductsCache.products;
511
- }
512
- const products = raw.map((product) => {
513
- const { period, periodly, trialPeriodDays, trialPeriodEndDate } = product.variables;
514
- const derivedEndDate = trialPeriodEndDate === undefined
515
- ? computeTrialPeriodEndDate(trialPeriodDays, languages[0])
516
- : undefined;
517
- if (typeof period !== "string" &&
518
- typeof periodly !== "string" &&
519
- derivedEndDate === undefined) {
520
- return product;
521
- }
522
- return {
523
- ...product,
524
- variables: {
525
- ...product.variables,
526
- ...(typeof period === "string"
527
- ? { period: getLocalizedPeriod(period, [...languages]) }
528
- : {}),
529
- ...(typeof periodly === "string"
530
- ? { periodly: getLocalizedPeriod(periodly, [...languages]) }
531
- : {}),
532
- ...(derivedEndDate !== undefined ? { trialPeriodEndDate: derivedEndDate } : {}),
533
- },
191
+ },
192
+ subscribe: (listener) => {
193
+ listeners.add(listener);
194
+ return () => {
195
+ listeners.delete(listener);
534
196
  };
535
- });
536
- this.localizedProductsCache = { raw, languages: cacheKey, products };
537
- return products;
538
- }
539
- resolveProduct(input) {
540
- const reference = productReferenceFromInput(input);
541
- const existing = this.snapshot.productsByReference[reference];
542
- if (existing) {
543
- return existing;
544
- }
545
- return createSuperwallProduct(input);
546
- }
547
- resolveProductFromTransaction(message) {
548
- if (message.product) {
549
- return this.resolveProduct(message.product);
550
- }
551
- if (message.product_identifier) {
552
- const product = this.snapshot.products.find((candidate) => candidate.productIdentifier === message.product_identifier ||
553
- candidate.productId === message.product_identifier ||
554
- candidate.id === message.product_identifier);
555
- if (product) {
556
- return product;
197
+ },
198
+ getSnapshot: () => snapshot,
199
+ t,
200
+ setLocale: (locale) => {
201
+ localeOverride = locale;
202
+ commit({});
203
+ },
204
+ configure: (config) => {
205
+ if (config !== snapshot.config)
206
+ commit({ config });
207
+ },
208
+ start: (startOptions = {}) => {
209
+ if (snapshot.status !== "listening") {
210
+ transport.startListening();
211
+ commit({ status: "listening" });
557
212
  }
558
- }
559
- return createSuperwallProduct(message.product_identifier ?? message.product ?? "unknown");
560
- }
561
- /**
562
- * Attributes a transaction message to a pending purchase. Explicit product
563
- * info on the message must match the pending purchase — an unrelated
564
- * transaction (e.g. a restore completing another product) must not resolve
565
- * it. Only a bare transaction with a single pending purchase falls back to
566
- * that purchase, since some SDK versions omit product info.
567
- */
568
- pendingPurchaseForTransaction(message) {
569
- if (message.product) {
570
- return this.pendingPurchases.get(message.product);
571
- }
572
- if (message.product_identifier) {
573
- for (const pending of this.pendingPurchases.values()) {
574
- if (pending.product.productIdentifier === message.product_identifier ||
575
- pending.product.productId === message.product_identifier ||
576
- pending.product.id === message.product_identifier) {
577
- return pending;
578
- }
213
+ if (startOptions.sendPing)
214
+ post(outgoing.ping());
215
+ },
216
+ postMessage: post,
217
+ accept: (messages) => {
218
+ for (const message of messages)
219
+ transport.accept(message);
220
+ },
221
+ accept64: (message) => {
222
+ let decoded;
223
+ try {
224
+ decoded = decodeIncomingMessages(message);
579
225
  }
580
- return undefined;
581
- }
582
- return this.pendingPurchases.size === 1 ? this.firstPendingPurchase() : undefined;
583
- }
584
- resolvePurchase(message) {
585
- const pending = this.pendingPurchaseForTransaction(message);
586
- const product = pending?.product ?? this.resolveProductFromTransaction(message);
587
- const result = message.event_name === "transaction_complete"
588
- ? { status: "completed", product, message }
589
- : { status: "abandoned", product, message };
590
- if (pending) {
591
- if (pending.timeoutId !== undefined) {
592
- clearTimeout(pending.timeoutId);
226
+ catch (error) {
227
+ options.onDecodeError?.(error);
228
+ return;
593
229
  }
594
- this.pendingPurchases.delete(pending.product.reference);
595
- pending.resolve(result);
596
- }
597
- const clearsSnapshotPending = pending !== undefined &&
598
- this.snapshot.pendingPurchase?.reference === pending.product.reference;
599
- this.patch({
600
- pendingPurchase: clearsSnapshotPending ? undefined : this.snapshot.pendingPurchase,
601
- lastTransaction: result,
602
- lastPurchaseFailure: undefined,
603
- messages: this.bridge.messages,
604
- });
605
- }
606
- failPurchase(reference, reason) {
607
- const failure = this.cancelPendingPurchase(reference, reason);
608
- if (!failure)
609
- return;
610
- this.patch({
611
- pendingPurchase: this.snapshot.pendingPurchase?.reference === reference
612
- ? undefined
613
- : this.snapshot.pendingPurchase,
614
- lastPurchaseFailure: failure,
615
- });
616
- }
617
- /**
618
- * Settles and removes a pending purchase as failed without touching the
619
- * snapshot. Returns the failure, or undefined if nothing was pending.
620
- */
621
- cancelPendingPurchase(reference, reason) {
622
- const pending = this.pendingPurchases.get(reference);
623
- if (!pending)
624
- return undefined;
625
- if (pending.timeoutId !== undefined) {
626
- clearTimeout(pending.timeoutId);
627
- }
628
- this.pendingPurchases.delete(reference);
629
- const failure = {
630
- status: "failed",
631
- product: pending.product,
632
- reason,
633
- };
634
- pending.resolve(failure);
635
- return failure;
636
- }
637
- firstPendingPurchase() {
638
- for (const pending of this.pendingPurchases.values()) {
639
- return pending;
640
- }
641
- return undefined;
642
- }
643
- resolvePermission(message) {
644
- const pending = this.pendingPermissions.get(message.request_id);
645
- if (pending) {
646
- this.pendingPermissions.delete(message.request_id);
647
- pending.resolve(message.status);
648
- }
649
- this.patch({
650
- permissionStatuses: {
651
- ...this.snapshot.permissionStatuses,
652
- [permissionTypeToStateName(message.permission_type)]: message.status,
653
- },
654
- messages: this.bridge.messages,
655
- });
656
- }
657
- resolveCallback(message) {
658
- const pending = this.pendingCallbacks.get(message.request_id);
659
- const callbackName = callbackNameToStateName(pending?.name ?? message.name);
660
- if (pending) {
661
- this.pendingCallbacks.delete(message.request_id);
662
- pending.resolve({
663
- status: message.status,
664
- data: message.data,
665
- message,
230
+ for (const entry of decoded)
231
+ transport.accept(entry);
232
+ },
233
+ close: () => post(outgoing.close()),
234
+ restore: () => post(outgoing.restore()),
235
+ openUrl: (url, urlOptions = {}) => post(outgoing.openUrl(url, urlOptions.browserType)),
236
+ openExternalUrl: (url) => post(outgoing.openExternalUrl(url)),
237
+ openDeepLink: (link) => post(outgoing.openDeepLink(link)),
238
+ customPlacement: (name, params = {}) => post(outgoing.customPlacement(name, params)),
239
+ requestStoreReview: (reviewType) => post(outgoing.requestStoreReview(reviewType)),
240
+ pageView: (input) => post(outgoing.pageView(input)),
241
+ hapticFeedback: (hapticType) => post(outgoing.hapticFeedback(hapticType)),
242
+ requestPermission: (permissionType) => {
243
+ const { requestId, result } = requests.permission(permissionType);
244
+ post(outgoing.requestPermission(permissionType, requestId));
245
+ return result;
246
+ },
247
+ requestCallback,
248
+ purchase: (input, purchaseOptions = {}) => {
249
+ const product = resolveProduct(input);
250
+ const result = purchases.begin(product);
251
+ commit({
252
+ pendingPurchase: { reference: product.reference, product },
253
+ lastPurchaseFailure: undefined,
666
254
  });
667
- }
668
- this.patch({
669
- callbackStates: {
670
- ...this.snapshot.callbackStates,
671
- [callbackName]: {
672
- result: message.status,
673
- data: message.data,
674
- },
675
- },
676
- messages: this.bridge.messages,
677
- });
678
- }
679
- patch(patch) {
680
- const nextSnapshot = {
681
- ...this.snapshot,
682
- ...patch,
683
- };
684
- // The bridge's log is one mutable array; snapshots must be immutable
685
- // views of it. Copy when it grew, keep the previous copy otherwise so
686
- // memoized consumers see a stable identity.
687
- nextSnapshot.messages =
688
- this.bridge.messages.length === this.snapshot.messages.length
689
- ? this.snapshot.messages
690
- : [...this.bridge.messages];
691
- const deviceLocale = nextSnapshot.device.deviceLocale ?? nextSnapshot.device.deviceLanguageCode;
692
- const requestedLocale = this.localeOverride ?? (typeof deviceLocale === "string" ? deviceLocale : undefined);
693
- const locale = resolveLocale(requestedLocale, nextSnapshot.config?.localization);
694
- if (locale !== this.translator.locale || nextSnapshot.config !== this.snapshot.config) {
695
- this.translator = createTranslator(nextSnapshot.config?.localization, locale);
696
- }
697
- const products = this.deriveProducts(this.rawProducts, languageCandidates(requestedLocale));
698
- if (products !== nextSnapshot.products) {
699
- nextSnapshot.products = products;
700
- nextSnapshot.productsByReference = productsByReference(products);
701
- }
702
- this.snapshot = {
703
- ...nextSnapshot,
704
- locale,
705
- state: buildSuperwallState({
706
- variables: nextSnapshot.variables,
707
- products: nextSnapshot.products,
708
- paywall: nextSnapshot.paywall,
709
- lastTransaction: nextSnapshot.lastTransaction,
710
- permissionStatuses: nextSnapshot.permissionStatuses,
711
- callbackStates: nextSnapshot.callbackStates,
712
- trial: nextSnapshot.trial,
713
- }),
714
- };
715
- for (const listener of this.listeners) {
716
- listener();
717
- }
718
- }
719
- }
720
- /**
721
- * Creates a runtime session.
722
- *
723
- * `TProduct` is the caller's declaration of what SDK-delivered products look
724
- * like (custom template variables layered over the known ones). The runtime
725
- * cannot verify it — the SDK owns the values — so this downcast is the single
726
- * seam where the claim is applied; every refined type downstream derives from
727
- * it.
728
- */
255
+ post(outgoing.purchase(product, purchaseOptions.shouldDismiss ?? snapshot.config?.dismissOnPurchase));
256
+ return result;
257
+ },
258
+ };
259
+ };
260
+ // TProduct is the caller's claim about what host-delivered products look like;
261
+ // the host owns the values, so the claim is applied here, once.
729
262
  export const createSuperwallSession = (options = {}) => {
730
- const session = new SuperwallSessionImpl(options);
263
+ const session = createSession(options);
731
264
  return session;
732
265
  };
266
+ export { PING_VERSION } from "./outgoing";
267
+ export { buildSuperwallState, } from "./state";
268
+ export * from "./types";
269
+ export { recordFromVariables, } from "./variables";