@superwall/runtime 1.1.1 → 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
@@ -0,0 +1,10 @@
1
+ export const isPlatformProductIds = (input) => typeof input === "object" && input !== null && !("productId" in input);
2
+ export const productIdFor = (input, platform) => {
3
+ if (typeof input === "string")
4
+ return input;
5
+ if (!isPlatformProductIds(input))
6
+ return input.productId;
7
+ if (platform !== undefined)
8
+ return input[platform];
9
+ return Object.values(input).find((id) => typeof id === "string");
10
+ };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,7 @@
1
1
  export * from "./bridge";
2
- export * from "./bridge/base64";
3
- export * from "./bridge/transport";
4
2
  export * from "./config";
5
3
  export * from "./localization";
6
- export * from "./mock";
7
4
  export * from "./products";
8
5
  export * from "./session";
9
- export * from "./session/state";
10
- export * from "./session/variables";
11
- export { buildTransport, buildWebKitTransport, createTransportLogger, EditorTransport, EnabledProductSchema, IncomingMessageSchema, InitializationParamsSchema, MessageDirection, OutgoingMessagePingSchema, OutgoingMessageSchema, PageStyles, PermissionStatusSchema, PermissionTypeSchema, Platform, ProductIdentifierAndTypeSchema, SubsSchema, TransportKind, unwrap, wrap, } from "@superwall/protocol";
12
- export type { ITransport, ProductIdentifierAndType, TIncomingHandler, TIncomingMessage, TIncomingMessageCallbackResult, TIncomingMessageExperiment, TIncomingMessageFreeTrialStart, TIncomingMessagePaywallOpen, TIncomingMessagePermissionResult, TIncomingMessageProducts, TIncomingMessageTemplateVariables, TIncomingMessageTransactionAbandon, TIncomingMessageTransactionComplete, TInitializationParams, TMessage, TOutgoingMessage, TPageStyles, TPaywallControllerOptions, TPermissionStatus, TPermissionTypeMessage, WrappedMessage, WrappedMessagePayload, } from "@superwall/protocol";
6
+ export { pendingHostMessages, TransportKind } from "@superwall/protocol";
7
+ export type { ITransport, TEventTrackingBehavior, TIncomingMessage, TOutgoingMessage, TPermissionStatus, TPermissionTypeMessage, } from "@superwall/protocol";
package/dist/index.js CHANGED
@@ -1,11 +1,6 @@
1
1
  export * from "./bridge";
2
- export * from "./bridge/base64";
3
- export * from "./bridge/transport";
4
2
  export * from "./config";
5
3
  export * from "./localization";
6
- export * from "./mock";
7
4
  export * from "./products";
8
5
  export * from "./session";
9
- export * from "./session/state";
10
- export * from "./session/variables";
11
- export { buildTransport, buildWebKitTransport, createTransportLogger, EditorTransport, EnabledProductSchema, IncomingMessageSchema, InitializationParamsSchema, MessageDirection, OutgoingMessagePingSchema, OutgoingMessageSchema, PageStyles, PermissionStatusSchema, PermissionTypeSchema, Platform, ProductIdentifierAndTypeSchema, SubsSchema, TransportKind, unwrap, wrap, } from "@superwall/protocol";
6
+ export { pendingHostMessages, TransportKind } from "@superwall/protocol";
@@ -0,0 +1,8 @@
1
+ import type { SuperwallLocalizationConfig } from "../config/localization";
2
+ export type SuperwallTranslateValues = Record<string, string | number>;
3
+ export type SuperwallTranslator = {
4
+ t: (key: string, values?: SuperwallTranslateValues) => string;
5
+ locale: string;
6
+ locales: readonly string[];
7
+ };
8
+ export declare const createTranslator: (localization: SuperwallLocalizationConfig | undefined, locale: string) => SuperwallTranslator;
@@ -0,0 +1,21 @@
1
+ const lookupMessage = (messages, key) => {
2
+ let current = messages;
3
+ for (const segment of key.split(".")) {
4
+ if (typeof current !== "object" || current === null)
5
+ return undefined;
6
+ current = current[segment];
7
+ }
8
+ return typeof current === "string" ? current : undefined;
9
+ };
10
+ const interpolate = (template, values = {}) => template.replace(/\{(\w+)\}/g, (match, name) => name in values ? String(values[name]) : match);
11
+ export const createTranslator = (localization, locale) => {
12
+ const messages = localization?.messages;
13
+ const defaultLocale = localization?.defaultLocale ?? "en";
14
+ return {
15
+ t: (key, values) => interpolate(lookupMessage(messages?.[locale], key) ??
16
+ lookupMessage(messages?.[defaultLocale], key) ??
17
+ key, values),
18
+ locale,
19
+ locales: messages ? Object.keys(messages) : [defaultLocale],
20
+ };
21
+ };
@@ -1,24 +1,3 @@
1
- import type { SuperwallLocalizationConfig } from "../config";
2
- export type SuperwallTranslateValues = Record<string, string | number>;
3
- export type SuperwallTranslator = {
4
- /**
5
- * Resolves a message key ("paywall.title") for the active locale,
6
- * interpolating `{name}` params. Unknown keys return the key itself, so
7
- * passing literal copy through `t()` is always safe.
8
- */
9
- t: (key: string, values?: SuperwallTranslateValues) => string;
10
- locale: string;
11
- /** Locales with a message catalog. */
12
- locales: readonly string[];
13
- };
14
- /**
15
- * Language candidates for the shared period-translation table
16
- * ("de-DE" / "de_DE" → ["de_DE", "de"]), matching its underscore keys.
17
- */
18
- export declare const languageCandidates: (locale: string | undefined) => string[];
19
- /**
20
- * Picks the best available locale: exact match ("pt-BR"), then language
21
- * ("pt"), then the default locale.
22
- */
23
- export declare const resolveLocale: (requested: string | undefined, localization: SuperwallLocalizationConfig | undefined) => string;
24
- export declare const createTranslator: (localization: SuperwallLocalizationConfig | undefined, locale: string) => SuperwallTranslator;
1
+ export { createTranslator, type SuperwallTranslateValues, type SuperwallTranslator, } from "./catalog";
2
+ export { resolveLocale } from "./locale";
3
+ export { getLocalizedPeriod, languageCandidates } from "./periods";
@@ -1,71 +1,3 @@
1
- const lookupMessage = (messages, key) => {
2
- if (!messages)
3
- return undefined;
4
- let current = messages;
5
- for (const segment of key.split(".")) {
6
- if (typeof current !== "object" || current === null)
7
- return undefined;
8
- current = current[segment];
9
- }
10
- return typeof current === "string" ? current : undefined;
11
- };
12
- const interpolate = (template, values = {}) => template.replace(/\{(\w+)\}/g, (match, name) => name in values ? String(values[name]) : match);
13
- /**
14
- * Language candidates for the shared period-translation table
15
- * ("de-DE" / "de_DE" → ["de_DE", "de"]), matching its underscore keys.
16
- */
17
- export const languageCandidates = (locale) => {
18
- if (!locale)
19
- return ["en"];
20
- const normalized = locale.replace(/-/g, "_");
21
- const [language] = normalized.split("_");
22
- const candidates = [normalized];
23
- if (language && language !== normalized) {
24
- candidates.push(language.toLowerCase());
25
- }
26
- return candidates;
27
- };
28
- /** Normalizes "en_US" / "en-us" → "en-US"; returns [exact, language] candidates. */
29
- const localeCandidates = (locale) => {
30
- const normalized = locale.replace(/_/g, "-");
31
- const [language, region] = normalized.split("-");
32
- const candidates = [];
33
- if (language && region) {
34
- candidates.push(`${language.toLowerCase()}-${region.toUpperCase()}`);
35
- }
36
- if (language) {
37
- candidates.push(language.toLowerCase());
38
- }
39
- return candidates;
40
- };
41
- /**
42
- * Picks the best available locale: exact match ("pt-BR"), then language
43
- * ("pt"), then the default locale.
44
- */
45
- export const resolveLocale = (requested, localization) => {
46
- const defaultLocale = localization?.defaultLocale ?? "en";
47
- const messages = localization?.messages;
48
- if (!requested || !messages)
49
- return defaultLocale;
50
- const available = Object.keys(messages);
51
- const availableLower = new Map(available.map((locale) => [locale.toLowerCase(), locale]));
52
- for (const candidate of localeCandidates(requested)) {
53
- const match = availableLower.get(candidate.toLowerCase());
54
- if (match)
55
- return match;
56
- }
57
- return defaultLocale;
58
- };
59
- export const createTranslator = (localization, locale) => {
60
- const messages = localization?.messages;
61
- const defaultLocale = localization?.defaultLocale ?? "en";
62
- const t = (key, values) => {
63
- const resolved = lookupMessage(messages?.[locale], key) ?? lookupMessage(messages?.[defaultLocale], key);
64
- return interpolate(resolved ?? key, values);
65
- };
66
- return {
67
- t,
68
- locale,
69
- locales: messages ? Object.keys(messages) : [defaultLocale],
70
- };
71
- };
1
+ export { createTranslator, } from "./catalog";
2
+ export { resolveLocale } from "./locale";
3
+ export { getLocalizedPeriod, languageCandidates } from "./periods";
@@ -0,0 +1,2 @@
1
+ import type { SuperwallLocalizationConfig } from "../config/localization";
2
+ export declare const resolveLocale: (requested: string | undefined, localization: SuperwallLocalizationConfig | undefined) => string;
@@ -0,0 +1,22 @@
1
+ const localeCandidates = (locale) => {
2
+ const [language, region] = locale.replace(/_/g, "-").split("-");
3
+ const candidates = [];
4
+ if (language && region)
5
+ candidates.push(`${language.toLowerCase()}-${region.toUpperCase()}`);
6
+ if (language)
7
+ candidates.push(language.toLowerCase());
8
+ return candidates;
9
+ };
10
+ export const resolveLocale = (requested, localization) => {
11
+ const defaultLocale = localization?.defaultLocale ?? "en";
12
+ const messages = localization?.messages;
13
+ if (!requested || !messages)
14
+ return defaultLocale;
15
+ const available = new Map(Object.keys(messages).map((locale) => [locale.toLowerCase(), locale]));
16
+ for (const candidate of localeCandidates(requested)) {
17
+ const match = available.get(candidate.toLowerCase());
18
+ if (match)
19
+ return match;
20
+ }
21
+ return defaultLocale;
22
+ };
@@ -1 +1,2 @@
1
+ export declare const languageCandidates: (locale: string | undefined) => string[];
1
2
  export declare function getLocalizedPeriod(value: string, languages: string[]): string;
@@ -660,19 +660,19 @@ const periodTranslations = {
660
660
  quarterly: "ત્રિમાસિક",
661
661
  },
662
662
  };
663
+ const DYNAMIC_UNITS = ["day", "week", "month", "year"];
663
664
  const formatDynamicPeriod = (count, unit, locale) => {
664
665
  try {
665
666
  return new Intl.NumberFormat(locale.replace(/_/g, "-"), {
666
667
  style: "unit",
667
- unit: (unit.endsWith("s") ? unit.slice(0, -1) : unit),
668
+ unit,
668
669
  unitDisplay: "long",
669
670
  })
670
671
  .format(count)
671
672
  .replace(/\u00a0/g, " ");
672
673
  }
673
674
  catch {
674
- const singularUnit = unit.endsWith("s") ? unit.slice(0, -1) : unit;
675
- return `${count} ${count === 1 ? singularUnit : `${singularUnit}s`}`;
675
+ return `${count} ${count === 1 ? unit : `${unit}s`}`;
676
676
  }
677
677
  };
678
678
  const dynamicPeriodlyFormatters = {
@@ -716,8 +716,9 @@ const getDynamicLocalizedPeriod = (value, languages) => {
716
716
  }
717
717
  const count = Number.parseInt(match[1], 10);
718
718
  const rawUnit = match[2];
719
- const unit = rawUnit.endsWith("s") ? rawUnit.slice(0, -1) : rawUnit;
720
- if (!["day", "week", "month", "year"].includes(unit) || !Number.isFinite(count)) {
719
+ const singular = rawUnit.endsWith("s") ? rawUnit.slice(0, -1) : rawUnit;
720
+ const unit = DYNAMIC_UNITS.find((candidate) => candidate === singular);
721
+ if (!unit) {
721
722
  return null;
722
723
  }
723
724
  if (periodlyMatch) {
@@ -725,6 +726,13 @@ const getDynamicLocalizedPeriod = (value, languages) => {
725
726
  }
726
727
  return formatDynamicLocalizedValue(count, unit, languages);
727
728
  };
729
+ export const languageCandidates = (locale) => {
730
+ if (!locale)
731
+ return ["en"];
732
+ const normalized = locale.replace(/-/g, "_");
733
+ const [language] = normalized.split("_");
734
+ return language && language !== normalized ? [normalized, language.toLowerCase()] : [normalized];
735
+ };
728
736
  export function getLocalizedPeriod(value, languages) {
729
737
  for (const lang of languages) {
730
738
  const translations = periodTranslations[lang];
@@ -0,0 +1,4 @@
1
+ import type { SuperwallProduct } from "./index";
2
+ export declare const trialPeriodEndDate: (trialPeriodDays: unknown, language: string | undefined) => string | undefined;
3
+ export type ProductDeriver = (raw: readonly SuperwallProduct[], languages: readonly string[]) => readonly SuperwallProduct[];
4
+ export declare const createProductDeriver: () => ProductDeriver;
@@ -0,0 +1,45 @@
1
+ import { getLocalizedPeriod } from "../localization/periods";
2
+ export const trialPeriodEndDate = (trialPeriodDays, language) => {
3
+ const days = typeof trialPeriodDays === "number" ? trialPeriodDays : Number(trialPeriodDays);
4
+ if (!Number.isFinite(days) || days <= 0)
5
+ return undefined;
6
+ const endDate = new Date();
7
+ endDate.setDate(endDate.getDate() + Math.trunc(days));
8
+ let month;
9
+ try {
10
+ month = endDate.toLocaleString(language?.replace(/_/g, "-") ?? "default", { month: "short" });
11
+ }
12
+ catch {
13
+ month = endDate.toLocaleString("default", { month: "short" });
14
+ }
15
+ return `${month} ${endDate.getDate()}, ${endDate.getFullYear()}`;
16
+ };
17
+ const localizeProduct = (product, languages) => {
18
+ const { period, periodly, trialPeriodDays, trialPeriodEndDate: endDate } = product.variables;
19
+ const derivedEndDate = endDate === undefined ? trialPeriodEndDate(trialPeriodDays, languages[0]) : undefined;
20
+ if (typeof period !== "string" && typeof periodly !== "string" && derivedEndDate === undefined) {
21
+ return product;
22
+ }
23
+ return {
24
+ ...product,
25
+ variables: {
26
+ ...product.variables,
27
+ ...(typeof period === "string" ? { period: getLocalizedPeriod(period, [...languages]) } : {}),
28
+ ...(typeof periodly === "string"
29
+ ? { periodly: getLocalizedPeriod(periodly, [...languages]) }
30
+ : {}),
31
+ ...(derivedEndDate === undefined ? {} : { trialPeriodEndDate: derivedEndDate }),
32
+ },
33
+ };
34
+ };
35
+ export const createProductDeriver = () => {
36
+ let last;
37
+ return (raw, languages) => {
38
+ const key = languages.join(",");
39
+ if (last && last.raw === raw && last.key === key)
40
+ return last.products;
41
+ const products = raw.map((product) => localizeProduct(product, languages));
42
+ last = { raw, key, products };
43
+ return products;
44
+ };
45
+ };
@@ -1,4 +1,3 @@
1
- import type { ProductIdentifierAndType, TIncomingMessageProducts, TIncomingMessageTemplateVariables } from "@superwall/protocol";
2
1
  export type SuperwallKnownProductVariables = {
3
2
  identifier?: string;
4
3
  price?: string;
@@ -34,29 +33,22 @@ export type SuperwallKnownProductVariables = {
34
33
  isSubscribed?: boolean;
35
34
  };
36
35
  export type SuperwallProductVariables = SuperwallKnownProductVariables;
37
- export type SuperwallProductSource = "sdk" | "inline" | "placeholder" | "unknown";
36
+ export type SuperwallProductSource = "sdk" | "inline" | "unknown";
38
37
  export type SuperwallProduct<TVariables extends SuperwallProductVariables = SuperwallProductVariables> = {
39
38
  reference: string;
40
- product: string;
41
- id?: string;
42
39
  productId?: string;
43
- productIdentifier?: string;
44
40
  variables: TVariables;
45
41
  source: SuperwallProductSource;
46
42
  };
47
- export type SuperwallProductInput<TProduct extends SuperwallProduct = SuperwallProduct> = string | TProduct | {
43
+ export type SuperwallProductInput = string | {
48
44
  reference: string;
49
- product?: string;
50
- id?: string;
51
45
  productId?: string;
52
- productIdentifier?: string;
53
46
  variables?: SuperwallProductVariables;
54
47
  source?: SuperwallProductSource;
55
48
  };
56
- export declare const createSuperwallProduct: (input: SuperwallProductInput, variables?: SuperwallProductVariables) => SuperwallProduct;
49
+ export declare const createSuperwallProduct: (input: SuperwallProductInput) => SuperwallProduct;
57
50
  export declare const productReferenceFromInput: (input: SuperwallProductInput) => string;
58
51
  export declare const productsByReference: <TProduct extends SuperwallProduct>(products: readonly TProduct[]) => Readonly<Record<string, TProduct>>;
59
- export declare const productVariablesFromTemplateVariables: (variables: TIncomingMessageTemplateVariables["variables"]) => Map<string, SuperwallProductVariables>;
60
- export declare const productsFromIncomingMessage: (message: TIncomingMessageProducts) => SuperwallProduct[];
61
- export declare const mergeIncomingProducts: (current: readonly SuperwallProduct[], incoming: readonly ProductIdentifierAndType[]) => SuperwallProduct[];
62
- export declare const mergeProductVariables: (current: readonly SuperwallProduct[], variables: Map<string, SuperwallProductVariables>) => SuperwallProduct[];
52
+ export declare const findProductByStoreId: <TProduct extends SuperwallProduct>(products: readonly TProduct[], productId: string | undefined) => TProduct | undefined;
53
+ export { mergeIncomingProducts, mergeProductVariables, productVariablesFromTemplateVariables, } from "./merge";
54
+ export { createProductDeriver, trialPeriodEndDate } from "./derive";
@@ -0,0 +1,15 @@
1
+ export const createSuperwallProduct = (input) => {
2
+ if (typeof input === "string")
3
+ return { reference: input, variables: {}, source: "unknown" };
4
+ return {
5
+ reference: input.reference,
6
+ ...(input.productId === undefined ? {} : { productId: input.productId }),
7
+ variables: input.variables ?? {},
8
+ source: input.source ?? "unknown",
9
+ };
10
+ };
11
+ export const productReferenceFromInput = (input) => typeof input === "string" ? input : input.reference;
12
+ export const productsByReference = (products) => Object.fromEntries(products.map((product) => [product.reference, product]));
13
+ export const findProductByStoreId = (products, productId) => productId === undefined ? undefined : products.find((product) => product.productId === productId);
14
+ export { mergeIncomingProducts, mergeProductVariables, productVariablesFromTemplateVariables, } from "./merge";
15
+ export { createProductDeriver, trialPeriodEndDate } from "./derive";
@@ -0,0 +1,5 @@
1
+ import type { ProductIdentifierAndType, TIncomingMessageTemplateVariables } from "@superwall/protocol";
2
+ import { type SuperwallProduct, type SuperwallProductVariables } from "./index";
3
+ export declare const productVariablesFromTemplateVariables: (variables: TIncomingMessageTemplateVariables["variables"]) => Map<string, SuperwallProductVariables>;
4
+ export declare const mergeIncomingProducts: (current: readonly SuperwallProduct[], incoming: readonly ProductIdentifierAndType[]) => SuperwallProduct[];
5
+ export declare const mergeProductVariables: (current: readonly SuperwallProduct[], variables: ReadonlyMap<string, SuperwallProductVariables>) => SuperwallProduct[];
@@ -0,0 +1,51 @@
1
+ import { createSuperwallProduct, } from "./index";
2
+ const LEGACY_REFERENCES = ["primary", "secondary", "tertiary"];
3
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ /**
5
+ * SDK-delivered variable records are trusted, not validated: the declared
6
+ * shapes are the SDK's side of the protocol contract. Numeric-looking fields
7
+ * arrive as strings ("59.99", "7"), which is why they are typed
8
+ * `string | number` — coerce with `Number()` before doing arithmetic.
9
+ */
10
+ const asProductVariables = (record) => record;
11
+ export const productVariablesFromTemplateVariables = (variables) => {
12
+ const result = new Map();
13
+ if (Array.isArray(variables.products)) {
14
+ for (const entry of variables.products) {
15
+ if (!isRecord(entry))
16
+ continue;
17
+ for (const [reference, productVariables] of Object.entries(entry)) {
18
+ if (isRecord(productVariables))
19
+ result.set(reference, asProductVariables(productVariables));
20
+ }
21
+ }
22
+ }
23
+ for (const reference of LEGACY_REFERENCES) {
24
+ const productVariables = variables[reference];
25
+ if (isRecord(productVariables) && !result.has(reference)) {
26
+ result.set(reference, asProductVariables(productVariables));
27
+ }
28
+ }
29
+ return result;
30
+ };
31
+ const indexed = (products) => new Map(products.map((product) => [product.reference, product]));
32
+ export const mergeIncomingProducts = (current, incoming) => {
33
+ const next = indexed(current);
34
+ for (const { product: reference, productId } of incoming) {
35
+ next.set(reference, {
36
+ reference,
37
+ productId,
38
+ variables: next.get(reference)?.variables ?? {},
39
+ source: "sdk",
40
+ });
41
+ }
42
+ return Array.from(next.values());
43
+ };
44
+ export const mergeProductVariables = (current, variables) => {
45
+ const next = indexed(current);
46
+ for (const [reference, productVariables] of variables) {
47
+ const existing = next.get(reference) ?? createSuperwallProduct({ reference, source: "sdk" });
48
+ next.set(reference, { ...existing, variables: productVariables });
49
+ }
50
+ return Array.from(next.values());
51
+ };
@@ -0,0 +1,3 @@
1
+ import type { TIncomingMessage } from "@superwall/protocol";
2
+ import type { SuperwallRuntimeSnapshot } from "./types";
3
+ export declare const snapshotPatchFor: (snapshot: SuperwallRuntimeSnapshot, message: TIncomingMessage) => Partial<SuperwallRuntimeSnapshot> | undefined;
@@ -0,0 +1,47 @@
1
+ import { permissionStateName } from "./requests";
2
+ import { recordFromVariables } from "./variables";
3
+ export const snapshotPatchFor = (snapshot, message) => {
4
+ switch (message.event_name) {
5
+ case "paywall_open":
6
+ return {
7
+ paywall: { id: message.paywall_id, identifier: message.paywall_identifier },
8
+ pendingPurchase: undefined,
9
+ lastTransaction: undefined,
10
+ lastPurchaseFailure: undefined,
11
+ };
12
+ case "template_variables":
13
+ return {
14
+ variables: message.variables,
15
+ device: recordFromVariables(message.variables, "device"),
16
+ user: recordFromVariables(message.variables, "user"),
17
+ params: recordFromVariables(message.variables, "params"),
18
+ };
19
+ case "template_substitutions_prefix":
20
+ return { introductoryOffer: { eligible: message.prefix === "freeTrial" } };
21
+ case "experiment":
22
+ return {
23
+ experiment: {
24
+ experimentId: message.experimentId,
25
+ variantId: message.variantId,
26
+ campaignId: message.campaignId,
27
+ },
28
+ };
29
+ case "restore_start":
30
+ return { restore: { status: "started" } };
31
+ case "restore_complete":
32
+ return { restore: { status: "completed" } };
33
+ case "restore_fail":
34
+ return { restore: { status: "failed" } };
35
+ case "event_tracking_behavior":
36
+ return { eventTrackingBehavior: message.behavior };
37
+ case "permission_result":
38
+ return {
39
+ permissionStatuses: {
40
+ ...snapshot.permissionStatuses,
41
+ [permissionStateName(message.permission_type)]: message.status,
42
+ },
43
+ };
44
+ default:
45
+ return undefined;
46
+ }
47
+ };
@@ -1,103 +1,8 @@
1
- import { type TIncomingMessage, type TOutgoingMessage, type TPermissionStatus, type TPermissionTypeMessage } from "@superwall/protocol";
2
- import { type SuperwallConfig } from "../config";
3
- import { type SuperwallTranslateValues } from "../localization";
4
- import { type SuperwallProduct, type SuperwallProductInput } from "../products";
5
- import type { SuperwallCallbackResult, SuperwallEventMap, SuperwallEventName, SuperwallPurchaseOptions, SuperwallPurchaseResult, SuperwallRuntimeSnapshot, SuperwallSessionOptions, SuperwallSessionStartOptions } from "./types";
1
+ import { type SuperwallProduct } from "../products";
2
+ import type { SuperwallSession, SuperwallSessionOptions } from "./types";
3
+ export declare const createSuperwallSession: <TProduct extends SuperwallProduct = SuperwallProduct>(options?: SuperwallSessionOptions) => SuperwallSession<TProduct>;
4
+ export { PING_VERSION, type PageViewInput } from "./outgoing";
5
+ export type { CallbackBehavior } from "./requests";
6
+ export { buildSuperwallState, type BuildSuperwallStateOptions, type SuperwallCallbackState, type SuperwallCallbackStates, type SuperwallPermissionStatuses, type SuperwallSdkState, } from "./state";
6
7
  export * from "./types";
7
- export type PageViewInput = {
8
- type: Extract<TOutgoingMessage, {
9
- event_name: "page_view";
10
- }>["type"];
11
- name: string;
12
- navigationId: string;
13
- position: number;
14
- previousName?: string;
15
- previousPosition?: number;
16
- timeOnPreviousMs?: number;
17
- };
18
- /**
19
- * The session's public contract, separated from the implementation so the
20
- * product generic can be declared covariant (`out`): `TProduct` appears in
21
- * output positions only, so a session refined with custom product variables
22
- * is always usable where a base session is expected (e.g. a shared React
23
- * context). The implementation is written against the base `SuperwallProduct`
24
- * — refinement happens once, in `createSuperwallSession`.
25
- */
26
- export interface SuperwallSession<out TProduct extends SuperwallProduct = SuperwallProduct> {
27
- /**
28
- * Subscribes to a single incoming SDK event by name, or "message" for all
29
- * incoming messages. Returns an unsubscribe function.
30
- */
31
- on: <E extends SuperwallEventName>(event: E, handler: (payload: SuperwallEventMap[E]) => void) => () => void;
32
- /** Subscribes to snapshot changes (`useSyncExternalStore`-compatible). */
33
- subscribe: (listener: () => void) => () => void;
34
- getSnapshot: () => SuperwallRuntimeSnapshot<TProduct>;
35
- readonly products: readonly TProduct[];
36
- readonly config: SuperwallConfig | undefined;
37
- readonly locale: string;
38
- /**
39
- * Resolves a message key for the active locale, interpolating `{name}`
40
- * params. Unknown keys return the key itself, so literal copy is safe.
41
- */
42
- t: (key: string, values?: SuperwallTranslateValues) => string;
43
- /** Overrides the locale (normally auto-detected from the device). */
44
- setLocale: (locale: string | undefined) => void;
45
- configure: (config: SuperwallConfig) => void;
46
- start: (options?: SuperwallSessionStartOptions) => void;
47
- postMessage: (message: TOutgoingMessage) => void;
48
- accept: (messages: TIncomingMessage[]) => void;
49
- accept64: (message: string) => void;
50
- ping: (message?: Partial<Extract<TOutgoingMessage, {
51
- event_name: "ping";
52
- }>>) => void;
53
- close: () => void;
54
- /**
55
- * Asks the SDK to restore purchases. The message protocol has no restore
56
- * result event; successful restores surface as `transaction_complete` or a
57
- * dismissed paywall.
58
- */
59
- restore: () => void;
60
- openUrl: (url: string, options?: {
61
- browserType?: "payment_sheet";
62
- }) => void;
63
- openExternalUrl: (url: string) => void;
64
- openDeepLink: (link: string) => void;
65
- custom: (data: string) => void;
66
- customPlacement: (name: string, params?: Record<string, unknown>) => void;
67
- requestStoreReview: (reviewType: Extract<TOutgoingMessage, {
68
- event_name: "request_store_review";
69
- }>["review_type"]) => void;
70
- setUserAttributes: (attributes: Record<string, string>) => void;
71
- pageView: (input: PageViewInput) => void;
72
- scheduleTrialReminder: (input: {
73
- id: string;
74
- title: string;
75
- subtitle?: string;
76
- body: string;
77
- delayMs: number;
78
- }) => void;
79
- hapticFeedback: (hapticType: Extract<TOutgoingMessage, {
80
- event_name: "haptic_feedback";
81
- }>["haptic_type"]) => void;
82
- requestPermission: (permissionType: TPermissionTypeMessage) => Promise<TPermissionStatus>;
83
- requestCallback: <TData extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: {
84
- behavior?: "blocking" | "non-blocking";
85
- variables?: Record<string, unknown>;
86
- }) => Promise<SuperwallCallbackResult<TData>>;
87
- /**
88
- * Starts a purchase and resolves with the outcome — never throws for flow
89
- * results: `{ status: "completed" | "abandoned" | "failed" }`.
90
- */
91
- purchase: (input: SuperwallProductInput, options?: SuperwallPurchaseOptions) => Promise<SuperwallPurchaseResult<TProduct>>;
92
- getProduct: (reference: string) => TProduct | undefined;
93
- }
94
- /**
95
- * Creates a runtime session.
96
- *
97
- * `TProduct` is the caller's declaration of what SDK-delivered products look
98
- * like (custom template variables layered over the known ones). The runtime
99
- * cannot verify it — the SDK owns the values — so this downcast is the single
100
- * seam where the claim is applied; every refined type downstream derives from
101
- * it.
102
- */
103
- export declare const createSuperwallSession: <TProduct extends SuperwallProduct = SuperwallProduct>(options?: SuperwallSessionOptions<TProduct>) => SuperwallSession<TProduct>;
8
+ export { recordFromVariables, type SuperwallCapability, type SuperwallCustomerInfo, type SuperwallDeviceEntitlement, type SuperwallDeviceTransaction, type SuperwallDeviceVariables, type SuperwallExperiment, type SuperwallPlacementParams, type SuperwallUserVariables, } from "./variables";