@superwall/runtime 1.2.0 → 1.3.0-beta.4

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 (95) 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 +243 -694
  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/restores.d.ts +6 -0
  53. package/dist/session/restores.js +20 -0
  54. package/dist/session/state.d.ts +3 -3
  55. package/dist/session/state.js +14 -39
  56. package/dist/session/types.d.ts +60 -29
  57. package/dist/session/variables.d.ts +3 -7
  58. package/package.json +3 -2
  59. package/src/bridge/base64.ts +10 -46
  60. package/src/bridge/index.ts +7 -77
  61. package/src/bridge/transport.ts +11 -46
  62. package/src/config/background.ts +24 -0
  63. package/src/config/checkout.ts +32 -0
  64. package/src/config/index.ts +102 -0
  65. package/src/config/localization.ts +12 -0
  66. package/src/config/notifications.ts +49 -0
  67. package/src/config/platforms.ts +8 -0
  68. package/src/config/presentation.ts +22 -0
  69. package/src/config/products.ts +39 -0
  70. package/src/index.ts +2 -43
  71. package/src/localization/catalog.ts +45 -0
  72. package/src/localization/index.ts +7 -110
  73. package/src/localization/locale.ts +25 -0
  74. package/src/localization/periods.ts +23 -8
  75. package/src/products/derive.ts +65 -0
  76. package/src/products/index.ts +87 -0
  77. package/src/products/merge.ts +78 -0
  78. package/src/session/incoming.ts +53 -0
  79. package/src/session/index.ts +286 -985
  80. package/src/session/outgoing.ts +132 -0
  81. package/src/session/purchases.ts +66 -0
  82. package/src/session/reminders.ts +56 -0
  83. package/src/session/requests.ts +87 -0
  84. package/src/session/restores.ts +27 -0
  85. package/src/session/state.ts +19 -59
  86. package/src/session/types.ts +78 -30
  87. package/src/session/variables.ts +3 -7
  88. package/dist/config.d.ts +0 -237
  89. package/dist/config.js +0 -138
  90. package/dist/mock.d.ts +0 -74
  91. package/dist/mock.js +0 -206
  92. package/dist/products.js +0 -105
  93. package/src/config.ts +0 -408
  94. package/src/mock.ts +0 -333
  95. package/src/products.ts +0 -221
@@ -0,0 +1,132 @@
1
+ import type { TOutgoingMessage, TPermissionTypeMessage } from "@superwall/protocol";
2
+ import type { SuperwallProduct } from "../products";
3
+
4
+ export type Outgoing<E extends TOutgoingMessage["event_name"]> = Extract<
5
+ TOutgoingMessage,
6
+ { event_name: E }
7
+ >;
8
+
9
+ export const PING_VERSION = "4.0.0";
10
+
11
+ export const ping = (): Outgoing<"ping"> => ({
12
+ event_name: "ping",
13
+ substitutions: [],
14
+ page_styles: [],
15
+ version: PING_VERSION,
16
+ });
17
+
18
+ export const close = (): Outgoing<"close"> => ({ event_name: "close" });
19
+
20
+ export const restore = (): Outgoing<"restore"> => ({ event_name: "restore" });
21
+
22
+ export const openUrl = (url: string, browserType?: "payment_sheet"): Outgoing<"open_url"> => ({
23
+ event_name: "open_url",
24
+ url,
25
+ ...(browserType === undefined ? {} : { browser_type: browserType }),
26
+ });
27
+
28
+ export const openExternalUrl = (url: string): Outgoing<"open_url_external"> => ({
29
+ event_name: "open_url_external",
30
+ url,
31
+ });
32
+
33
+ export const openDeepLink = (link: string): Outgoing<"open_deep_link"> => ({
34
+ event_name: "open_deep_link",
35
+ link,
36
+ });
37
+
38
+ export const customPlacement = (
39
+ name: string,
40
+ params: Record<string, unknown>,
41
+ ): Outgoing<"custom_placement"> => ({ event_name: "custom_placement", name, params });
42
+
43
+ export const requestStoreReview = (
44
+ reviewType: Outgoing<"request_store_review">["review_type"],
45
+ ): Outgoing<"request_store_review"> => ({
46
+ event_name: "request_store_review",
47
+ review_type: reviewType,
48
+ });
49
+
50
+ export const hapticFeedback = (
51
+ hapticType: Outgoing<"haptic_feedback">["haptic_type"],
52
+ ): Outgoing<"haptic_feedback"> => ({ event_name: "haptic_feedback", haptic_type: hapticType });
53
+
54
+ export type PageViewInput = {
55
+ type: Outgoing<"page_view">["type"];
56
+ name: string;
57
+ navigationId: string;
58
+ position: number;
59
+ previousName?: string;
60
+ previousPosition?: number;
61
+ timeOnPreviousMs?: number;
62
+ };
63
+
64
+ export const pageView = (input: PageViewInput): Outgoing<"page_view"> => ({
65
+ event_name: "page_view",
66
+ type: input.type,
67
+ page_name: input.name,
68
+ page_node_id: input.name,
69
+ navigation_node_id: input.navigationId,
70
+ flow_position: input.position,
71
+ ...(input.previousName === undefined ? {} : { previous_page_node_id: input.previousName }),
72
+ ...(input.previousPosition === undefined
73
+ ? {}
74
+ : { previous_flow_position: input.previousPosition }),
75
+ ...(input.timeOnPreviousMs === undefined
76
+ ? {}
77
+ : { time_on_previous_page_ms: input.timeOnPreviousMs }),
78
+ });
79
+
80
+ export type NotificationInput = {
81
+ id: string;
82
+ title: string;
83
+ subtitle?: string;
84
+ body: string;
85
+ delayMs: number;
86
+ };
87
+
88
+ export const scheduleNotification = (
89
+ input: NotificationInput,
90
+ ): Outgoing<"schedule_notification"> => ({
91
+ event_name: "schedule_notification",
92
+ id: input.id,
93
+ type: "TRIAL_STARTED",
94
+ title: input.title,
95
+ ...(input.subtitle === undefined ? {} : { subtitle: input.subtitle }),
96
+ body: input.body,
97
+ delay: input.delayMs,
98
+ });
99
+
100
+ export const requestPermission = (
101
+ permissionType: TPermissionTypeMessage,
102
+ requestId: string,
103
+ ): Outgoing<"request_permission"> => ({
104
+ event_name: "request_permission",
105
+ permission_type: permissionType,
106
+ request_id: requestId,
107
+ });
108
+
109
+ export type CallbackRequestInput = {
110
+ requestId: string;
111
+ name: string;
112
+ behavior: "blocking" | "non-blocking";
113
+ variables?: Record<string, unknown>;
114
+ };
115
+
116
+ export const requestCallback = (input: CallbackRequestInput): Outgoing<"request_callback"> => ({
117
+ event_name: "request_callback",
118
+ request_id: input.requestId,
119
+ name: input.name,
120
+ behavior: input.behavior,
121
+ ...(input.variables === undefined ? {} : { variables: input.variables }),
122
+ });
123
+
124
+ export const purchase = (
125
+ product: SuperwallProduct,
126
+ shouldDismiss: boolean | undefined,
127
+ ): Outgoing<"purchase"> => ({
128
+ event_name: "purchase",
129
+ product: product.reference,
130
+ ...(product.productId === undefined ? {} : { product_identifier: product.productId }),
131
+ ...(shouldDismiss === undefined ? {} : { should_dismiss: shouldDismiss }),
132
+ });
@@ -0,0 +1,66 @@
1
+ import type { SuperwallProduct } from "../products";
2
+ import type { SuperwallPurchaseFailure, SuperwallPurchaseResult } from "./types";
3
+
4
+ export type PendingPurchase = {
5
+ product: SuperwallProduct;
6
+ resolve: (result: SuperwallPurchaseResult) => void;
7
+ };
8
+
9
+ export type TransactionReference = {
10
+ product?: string;
11
+ product_identifier?: string;
12
+ };
13
+
14
+ export type PurchaseTracker = {
15
+ begin: (product: SuperwallProduct) => Promise<SuperwallPurchaseResult>;
16
+ fail: (
17
+ reference: string,
18
+ reason: SuperwallPurchaseFailure["reason"],
19
+ ) => SuperwallPurchaseFailure | undefined;
20
+ failAll: (reason: SuperwallPurchaseFailure["reason"]) => void;
21
+ find: (message: TransactionReference) => PendingPurchase | undefined;
22
+ take: (message: TransactionReference) => PendingPurchase | undefined;
23
+ };
24
+
25
+ export const createPurchaseTracker = (): PurchaseTracker => {
26
+ const pending = new Map<string, PendingPurchase>();
27
+
28
+ const fail: PurchaseTracker["fail"] = (reference, reason) => {
29
+ const entry = pending.get(reference);
30
+ if (!entry) return undefined;
31
+ pending.delete(reference);
32
+ const failure: SuperwallPurchaseFailure = { status: "failed", product: entry.product, reason };
33
+ entry.resolve(failure);
34
+ return failure;
35
+ };
36
+
37
+ const find: PurchaseTracker["find"] = (message) => {
38
+ if (message.product !== undefined) return pending.get(message.product);
39
+ if (message.product_identifier !== undefined) {
40
+ for (const entry of pending.values()) {
41
+ if (entry.product.productId === message.product_identifier) return entry;
42
+ }
43
+ return undefined;
44
+ }
45
+ return pending.size === 1 ? pending.values().next().value : undefined;
46
+ };
47
+
48
+ return {
49
+ begin: (product) => {
50
+ fail(product.reference, "superseded");
51
+ return new Promise((resolve) => {
52
+ pending.set(product.reference, { product, resolve });
53
+ });
54
+ },
55
+ fail,
56
+ failAll: (reason) => {
57
+ for (const reference of Array.from(pending.keys())) fail(reference, reason);
58
+ },
59
+ find,
60
+ take: (message) => {
61
+ const entry = find(message);
62
+ if (entry) pending.delete(entry.product.reference);
63
+ return entry;
64
+ },
65
+ };
66
+ };
@@ -0,0 +1,56 @@
1
+ import type { TIncomingMessageFreeTrialStart } from "@superwall/protocol";
2
+ import type { SuperwallConfig, SuperwallTrialReminderNotification } from "../config";
3
+ import { findProductByStoreId, type SuperwallProduct } from "../products";
4
+ import { scheduleNotification, type Outgoing } from "./outgoing";
5
+
6
+ const DAY_MS = 24 * 60 * 60 * 1000;
7
+
8
+ export type TrialReminderContext = {
9
+ products: readonly SuperwallProduct[];
10
+ t: (key: string, values?: Record<string, string | number>) => string;
11
+ locale: string;
12
+ paywallIdentifier: string | undefined;
13
+ };
14
+
15
+ const trialEndOf = (message: TIncomingMessageFreeTrialStart): number | undefined => {
16
+ if (message.trial_end_date === undefined) return undefined;
17
+ const ms =
18
+ typeof message.trial_end_date === "number"
19
+ ? message.trial_end_date
20
+ : Date.parse(message.trial_end_date);
21
+ return Number.isNaN(ms) ? undefined : ms;
22
+ };
23
+
24
+ export const trialReminderFor = (
25
+ config: SuperwallConfig | undefined,
26
+ message: TIncomingMessageFreeTrialStart,
27
+ context: TrialReminderContext,
28
+ ): Outgoing<"schedule_notification"> | undefined => {
29
+ const reminder = config?.notifications?.trialReminder;
30
+ const trialEndMs = trialEndOf(message);
31
+ if (!reminder || trialEndMs === undefined) return undefined;
32
+
33
+ let notification: SuperwallTrialReminderNotification | null | undefined;
34
+ if (typeof reminder === "function") {
35
+ notification = reminder({
36
+ trialEndDate: new Date(trialEndMs),
37
+ productIdentifier: message.product_identifier,
38
+ product: findProductByStoreId(context.products, message.product_identifier),
39
+ t: context.t,
40
+ locale: context.locale,
41
+ });
42
+ } else if (reminder.enabled !== false) {
43
+ notification = {
44
+ title: context.t(reminder.title),
45
+ ...(reminder.subtitle === undefined ? {} : { subtitle: context.t(reminder.subtitle) }),
46
+ body: context.t(reminder.body),
47
+ delayMs: trialEndMs - (reminder.beforeTrialEndDays ?? 1) * DAY_MS - Date.now(),
48
+ };
49
+ }
50
+
51
+ if (!notification || notification.delayMs <= 0) return undefined;
52
+ return scheduleNotification({
53
+ id: `${context.paywallIdentifier ?? "paywall"}_TRIAL_STARTED`,
54
+ ...notification,
55
+ });
56
+ };
@@ -0,0 +1,87 @@
1
+ import type {
2
+ TIncomingMessageCallbackResult,
3
+ TIncomingMessagePermissionResult,
4
+ TPermissionStatus,
5
+ TPermissionTypeMessage,
6
+ } from "@superwall/protocol";
7
+ import type { SuperwallCallbackResult } from "./types";
8
+
9
+ export const createRequestId = (prefix: string): string => {
10
+ const unique =
11
+ typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
12
+ ? crypto.randomUUID()
13
+ : Math.random().toString(36).slice(2);
14
+ return `${prefix}-${unique}`;
15
+ };
16
+
17
+ export const permissionStateName = (permissionType: TPermissionTypeMessage): string =>
18
+ permissionType.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
19
+
20
+ export const callbackStateName = (name: string): string => {
21
+ const segments = name
22
+ .replace(/[^a-zA-Z0-9]/g, " ")
23
+ .trim()
24
+ .split(/\s+/)
25
+ .filter(Boolean);
26
+ if (segments.length === 0) return "callback";
27
+ return segments
28
+ .map((segment, index) =>
29
+ index === 0
30
+ ? segment.charAt(0).toLowerCase() + segment.slice(1)
31
+ : segment.charAt(0).toUpperCase() + segment.slice(1),
32
+ )
33
+ .join("");
34
+ };
35
+
36
+ export type CallbackBehavior = "blocking" | "non-blocking";
37
+
38
+ export type RequestTracker = {
39
+ permission: (permissionType: TPermissionTypeMessage) => {
40
+ requestId: string;
41
+ result: Promise<TPermissionStatus>;
42
+ };
43
+ callback: (
44
+ name: string,
45
+ behavior: CallbackBehavior,
46
+ ) => { requestId: string; result: Promise<SuperwallCallbackResult> };
47
+ resolvePermission: (message: TIncomingMessagePermissionResult) => void;
48
+ resolveCallback: (message: TIncomingMessageCallbackResult) => string | undefined;
49
+ };
50
+
51
+ export const createRequestTracker = (): RequestTracker => {
52
+ const permissions = new Map<string, (status: TPermissionStatus) => void>();
53
+ const callbacks = new Map<
54
+ string,
55
+ { name: string; resolve: (result: SuperwallCallbackResult) => void }
56
+ >();
57
+
58
+ return {
59
+ permission: (permissionType) => {
60
+ const requestId = createRequestId(`permission-${permissionType}`);
61
+ const result = new Promise<TPermissionStatus>((resolve) => {
62
+ permissions.set(requestId, resolve);
63
+ });
64
+ return { requestId, result };
65
+ },
66
+ callback: (name, behavior) => {
67
+ const requestId = createRequestId(`${callbackStateName(name)}-${behavior}`);
68
+ const result = new Promise<SuperwallCallbackResult>((resolve) => {
69
+ callbacks.set(requestId, { name, resolve });
70
+ });
71
+ return { requestId, result };
72
+ },
73
+ resolvePermission: (message) => {
74
+ const resolve = permissions.get(message.request_id);
75
+ if (!resolve) return;
76
+ permissions.delete(message.request_id);
77
+ resolve(message.status);
78
+ },
79
+ resolveCallback: (message) => {
80
+ const entry = callbacks.get(message.request_id);
81
+ if (!entry) return undefined;
82
+ callbacks.delete(message.request_id);
83
+ entry.resolve({ status: message.status, data: message.data, message });
84
+ return entry.name;
85
+ },
86
+ };
87
+ };
@@ -0,0 +1,27 @@
1
+ import type { SuperwallRestoreResult } from "./types";
2
+
3
+ export type RestoreTracker = {
4
+ begin: () => Promise<SuperwallRestoreResult>;
5
+ settle: (status: SuperwallRestoreResult["status"]) => void;
6
+ };
7
+
8
+ export const createRestoreTracker = (): RestoreTracker => {
9
+ let resolve: ((result: SuperwallRestoreResult) => void) | undefined;
10
+ let pending: Promise<SuperwallRestoreResult> | undefined;
11
+
12
+ return {
13
+ begin: () => {
14
+ if (pending) return pending;
15
+ pending = new Promise((settle) => {
16
+ resolve = settle;
17
+ });
18
+ return pending;
19
+ },
20
+ settle: (status) => {
21
+ const settled = resolve;
22
+ resolve = undefined;
23
+ pending = undefined;
24
+ settled?.({ status });
25
+ },
26
+ };
27
+ };
@@ -1,5 +1,5 @@
1
1
  import type { TIncomingMessageCallbackResult, TPermissionStatus } from "@superwall/protocol";
2
- import type { SuperwallProduct } from "../products";
2
+ import { productVariablesFromTemplateVariables, type SuperwallProduct } from "../products";
3
3
 
4
4
  export type SuperwallSdkState = Readonly<Record<string, unknown>>;
5
5
 
@@ -15,43 +15,11 @@ export type SuperwallCallbackStates = Readonly<Record<string, SuperwallCallbackS
15
15
  export type BuildSuperwallStateOptions<TProduct extends SuperwallProduct = SuperwallProduct> = {
16
16
  variables: Readonly<Record<string, unknown>>;
17
17
  products: readonly TProduct[];
18
- paywall?: {
19
- id: string;
20
- identifier: string;
21
- };
22
- lastTransaction?: {
23
- status: "completed" | "abandoned";
24
- product: TProduct;
25
- };
18
+ paywall?: { id: string; identifier: string };
19
+ lastTransaction?: { status: "completed" | "abandoned"; product: TProduct };
26
20
  permissionStatuses?: SuperwallPermissionStatuses;
27
21
  callbackStates?: SuperwallCallbackStates;
28
- trial?: { eligible?: boolean };
29
- };
30
-
31
- const isRecord = (value: unknown): value is Record<string, unknown> =>
32
- typeof value === "object" && value !== null && !Array.isArray(value);
33
-
34
- const productStateFromVariables = (variables: Readonly<Record<string, unknown>>) => {
35
- const products: Record<string, unknown> = {};
36
-
37
- if (Array.isArray(variables.products)) {
38
- for (const entry of variables.products) {
39
- if (!isRecord(entry)) continue;
40
-
41
- for (const [reference, productVariables] of Object.entries(entry)) {
42
- products[reference] = productVariables;
43
- }
44
- }
45
- }
46
-
47
- for (const reference of ["primary", "secondary", "tertiary"]) {
48
- const productVariables = variables[reference];
49
- if (isRecord(productVariables) && !products[reference]) {
50
- products[reference] = productVariables;
51
- }
52
- }
53
-
54
- return products;
22
+ introductoryOffer?: { eligible?: boolean };
55
23
  };
56
24
 
57
25
  export const buildSuperwallState = <TProduct extends SuperwallProduct = SuperwallProduct>({
@@ -61,52 +29,44 @@ export const buildSuperwallState = <TProduct extends SuperwallProduct = Superwal
61
29
  lastTransaction,
62
30
  permissionStatuses = {},
63
31
  callbackStates = {},
64
- trial,
32
+ introductoryOffer,
65
33
  }: BuildSuperwallStateOptions<TProduct>): SuperwallSdkState => {
66
- const productState = productStateFromVariables(variables);
34
+ const productState: Record<string, unknown> = Object.fromEntries(
35
+ productVariablesFromTemplateVariables(variables),
36
+ );
67
37
 
68
- if (trial?.eligible !== undefined) {
69
- productState.hasIntroductoryOffer = trial.eligible;
38
+ if (introductoryOffer?.eligible !== undefined) {
39
+ productState.hasIntroductoryOffer = introductoryOffer.eligible;
70
40
  }
71
41
 
72
42
  for (const product of products) {
73
- const existingProductState = productState[product.reference];
43
+ const existing = productState[product.reference];
74
44
  productState[product.reference] = {
75
- ...(isRecord(existingProductState) ? existingProductState : {}),
45
+ ...(typeof existing === "object" && existing !== null ? existing : {}),
76
46
  ...product.variables,
77
47
  productId: product.productId,
78
- productIdentifier: product.productIdentifier,
79
48
  source: product.source,
80
49
  };
81
50
  }
82
51
 
83
- const transactionState = {
84
- didAbandonTransaction: lastTransaction?.status === "abandoned",
85
- didCompleteTransaction: lastTransaction?.status === "completed",
86
- };
87
-
88
52
  productState.abandonedProductId =
89
53
  lastTransaction?.status === "abandoned" ? lastTransaction.product.reference : "";
90
54
  productState.purchasedProductId =
91
55
  lastTransaction?.status === "completed" ? lastTransaction.product.reference : "";
92
-
93
56
  if (lastTransaction) {
94
- const transactionProduct = lastTransaction.product;
95
57
  productState[lastTransaction.status === "completed" ? "purchased" : "abandoned"] =
96
- transactionProduct.variables;
58
+ lastTransaction.product.variables;
97
59
  }
98
60
 
99
- const state: Record<string, unknown> = {
61
+ return {
100
62
  ...variables,
101
- state: transactionState,
63
+ state: {
64
+ didAbandonTransaction: lastTransaction?.status === "abandoned",
65
+ didCompleteTransaction: lastTransaction?.status === "completed",
66
+ },
102
67
  products: productState,
103
68
  permissions: permissionStatuses,
104
69
  callbacks: callbackStates,
70
+ ...(paywall ? { paywall } : {}),
105
71
  };
106
-
107
- if (paywall) {
108
- state.paywall = paywall;
109
- }
110
-
111
- return state;
112
72
  };
@@ -1,13 +1,20 @@
1
1
  import type {
2
+ ITransport,
3
+ TEventTrackingBehavior,
2
4
  TIncomingMessage,
3
5
  TIncomingMessageCallbackResult,
4
6
  TIncomingMessageTransactionAbandon,
5
7
  TIncomingMessageTransactionComplete,
6
8
  TOutgoingMessage,
9
+ TPermissionStatus,
10
+ TPermissionTypeMessage,
11
+ TransportKind,
7
12
  } from "@superwall/protocol";
8
- import type { SuperwallBridge, SuperwallBridgeOptions, SuperwallMessageLogEntry } from "../bridge";
9
13
  import type { SuperwallConfig } from "../config";
10
- import type { SuperwallProduct } from "../products";
14
+ import type { SuperwallTranslateValues } from "../localization";
15
+ import type { SuperwallProduct, SuperwallProductInput } from "../products";
16
+ import type { Outgoing, PageViewInput } from "./outgoing";
17
+ import type { CallbackBehavior } from "./requests";
11
18
  import type {
12
19
  SuperwallCallbackStates,
13
20
  SuperwallPermissionStatuses,
@@ -47,13 +54,23 @@ export type SuperwallTransaction<TProduct extends SuperwallProduct = SuperwallPr
47
54
  export type SuperwallPurchaseFailure<out TProduct extends SuperwallProduct = SuperwallProduct> = {
48
55
  status: "failed";
49
56
  product: TProduct;
50
- /**
51
- * "timeout": no transaction message arrived in time. "superseded": a newer
52
- * purchase for the same product, or a paywall re-open, replaced this one.
53
- */
54
- reason: "timeout" | "superseded";
57
+ reason: "sdk" | "superseded";
55
58
  };
56
59
 
60
+ export type SuperwallRestoreState = {
61
+ status: "started" | "completed" | "failed";
62
+ };
63
+
64
+ /**
65
+ * How a restore ended.
66
+ *
67
+ * Deliberately no product list and no reason. The SDK announces a restored
68
+ * transaction with `transaction_restore`, which carries no payload, and reports
69
+ * "nothing to restore" as `restore_fail` like any other failure — the message it
70
+ * logs for that case never reaches the paywall.
71
+ */
72
+ export type SuperwallRestoreResult = { status: "restored" | "failed" };
73
+
57
74
  export type SuperwallPurchaseResult<TProduct extends SuperwallProduct = SuperwallProduct> =
58
75
  | SuperwallTransaction<TProduct>
59
76
  | SuperwallPurchaseFailure<TProduct>;
@@ -64,11 +81,7 @@ export type SuperwallCallbackResult<TData = Record<string, unknown>> = {
64
81
  message: TIncomingMessageCallbackResult;
65
82
  };
66
83
 
67
- export type SuperwallTrialState = {
68
- /**
69
- * Whether the user is eligible for an introductory offer. `undefined` until
70
- * the SDK signals eligibility (or the config forces it).
71
- */
84
+ export type SuperwallIntroductoryOfferState = {
72
85
  eligible?: boolean;
73
86
  };
74
87
 
@@ -83,12 +96,13 @@ export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = Sup
83
96
  user: SuperwallUserVariables;
84
97
  params: SuperwallPlacementParams;
85
98
  experiment?: SuperwallExperiment;
86
- trial: SuperwallTrialState;
99
+ introductoryOffer: SuperwallIntroductoryOfferState;
100
+ restore?: SuperwallRestoreState;
101
+ eventTrackingBehavior?: TEventTrackingBehavior;
87
102
  locale: string;
88
103
  state: SuperwallSdkState;
89
104
  permissionStatuses: SuperwallPermissionStatuses;
90
105
  callbackStates: SuperwallCallbackStates;
91
- messages: readonly SuperwallMessageLogEntry[];
92
106
  pendingPurchase?: SuperwallPendingPurchase<TProduct>;
93
107
  lastTransaction?: SuperwallTransaction<TProduct>;
94
108
  lastPurchaseFailure?: SuperwallPurchaseFailure<TProduct>;
@@ -96,28 +110,62 @@ export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = Sup
96
110
 
97
111
  export type SuperwallPurchaseOptions = {
98
112
  shouldDismiss?: boolean;
99
- /** Resolve as `{ status: "failed", reason: "timeout" }` if no transaction message arrives in time. */
100
- timeoutMs?: number;
101
113
  };
102
114
 
103
- export type SuperwallEventMap = {
104
- [E in TIncomingMessage["event_name"]]: Extract<TIncomingMessage, { event_name: E }>;
105
- } & {
106
- /** Fires for every incoming message. */
107
- message: TIncomingMessage;
115
+ export type SuperwallCallbackOptions = {
116
+ behavior?: CallbackBehavior;
117
+ variables?: Record<string, unknown>;
108
118
  };
109
119
 
110
- export type SuperwallEventName = keyof SuperwallEventMap & string;
120
+ export type SuperwallEventName = TIncomingMessage["event_name"] | "message";
121
+
122
+ export type SuperwallEventMap = {
123
+ [E in SuperwallEventName]: E extends "message"
124
+ ? TIncomingMessage
125
+ : Extract<TIncomingMessage, { event_name: E }>;
126
+ };
111
127
 
112
128
  export type SuperwallSessionStartOptions = {
113
129
  sendPing?: boolean;
114
- ping?: Partial<Extract<TOutgoingMessage, { event_name: "ping" }>>;
115
130
  };
116
131
 
117
- export type SuperwallSessionOptions<TProduct extends SuperwallProduct = SuperwallProduct> =
118
- SuperwallBridgeOptions & {
119
- bridge?: SuperwallBridge;
120
- config?: SuperwallConfig;
121
- products?: readonly TProduct[];
122
- variables?: Record<string, unknown>;
123
- };
132
+ export type SuperwallSessionOptions = {
133
+ config?: SuperwallConfig;
134
+ transport?: ITransport;
135
+ transportKind?: TransportKind;
136
+ onDecodeError?: (error: unknown) => void;
137
+ };
138
+
139
+ export interface SuperwallSession<out TProduct extends SuperwallProduct = SuperwallProduct> {
140
+ on: <E extends SuperwallEventName>(
141
+ event: E,
142
+ handler: (payload: SuperwallEventMap[E]) => void,
143
+ ) => () => void;
144
+ subscribe: (listener: () => void) => () => void;
145
+ getSnapshot: () => SuperwallRuntimeSnapshot<TProduct>;
146
+ t: (key: string, values?: SuperwallTranslateValues) => string;
147
+ setLocale: (locale: string | undefined) => void;
148
+ configure: (config: SuperwallConfig) => void;
149
+ start: (options?: SuperwallSessionStartOptions) => void;
150
+ postMessage: (message: TOutgoingMessage) => void;
151
+ accept: (messages: TIncomingMessage[]) => void;
152
+ accept64: (message: string) => void;
153
+ close: () => void;
154
+ restore: () => Promise<SuperwallRestoreResult>;
155
+ openUrl: (url: string, options?: { browserType?: "payment_sheet" }) => void;
156
+ openExternalUrl: (url: string) => void;
157
+ openDeepLink: (link: string) => void;
158
+ customPlacement: (name: string, params?: Record<string, unknown>) => void;
159
+ requestStoreReview: (reviewType: Outgoing<"request_store_review">["review_type"]) => void;
160
+ pageView: (input: PageViewInput) => void;
161
+ hapticFeedback: (hapticType: Outgoing<"haptic_feedback">["haptic_type"]) => void;
162
+ requestPermission: (permissionType: TPermissionTypeMessage) => Promise<TPermissionStatus>;
163
+ requestCallback: <TData extends Record<string, unknown> = Record<string, unknown>>(
164
+ name: string,
165
+ options?: SuperwallCallbackOptions,
166
+ ) => Promise<SuperwallCallbackResult<TData>>;
167
+ purchase: (
168
+ input: SuperwallProductInput,
169
+ options?: SuperwallPurchaseOptions,
170
+ ) => Promise<SuperwallPurchaseResult<TProduct>>;
171
+ }
@@ -41,13 +41,6 @@ export type SuperwallCapability = {
41
41
  eventNames?: readonly string[];
42
42
  };
43
43
 
44
- /**
45
- * Device variables the native SDK delivers via `template_variables`. The names
46
- * mirror the SDK's device template exactly — there is no index signature, so a
47
- * key the SDK does not send is a compile error rather than `undefined` on a
48
- * device. Every field is optional: availability varies by platform and SDK
49
- * version, and a paywall must render without any of them.
50
- */
51
44
  export type SuperwallDeviceVariables = {
52
45
  publicApiKey?: string;
53
46
  platform?: string;
@@ -75,6 +68,9 @@ export type SuperwallDeviceVariables = {
75
68
  interfaceStyleMode?: string;
76
69
  timezoneOffset?: number;
77
70
  radioType?: string;
71
+ fontSize?: number;
72
+ fontScale?: number;
73
+ preferredContentSizeCategory?: string;
78
74
  isLowPowerModeEnabled?: boolean;
79
75
  isApplePayAvailable?: boolean;
80
76
  isMac?: boolean;