@superwall/runtime 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +93 -0
  3. package/dist/bridge/base64.d.ts +9 -0
  4. package/dist/bridge/base64.js +34 -0
  5. package/dist/bridge/index.d.ts +30 -0
  6. package/dist/bridge/index.js +49 -0
  7. package/dist/bridge/transport.d.ts +14 -0
  8. package/dist/bridge/transport.js +43 -0
  9. package/dist/config.d.ts +237 -0
  10. package/dist/config.js +138 -0
  11. package/dist/index.d.ts +12 -0
  12. package/dist/index.js +11 -0
  13. package/dist/localization/index.d.ts +24 -0
  14. package/dist/localization/index.js +71 -0
  15. package/dist/localization/periods.d.ts +1 -0
  16. package/dist/localization/periods.js +753 -0
  17. package/dist/mock.d.ts +74 -0
  18. package/dist/mock.js +206 -0
  19. package/dist/products.d.ts +62 -0
  20. package/dist/products.js +105 -0
  21. package/dist/session/index.d.ts +103 -0
  22. package/dist/session/index.js +732 -0
  23. package/dist/session/state.d.ts +27 -0
  24. package/dist/session/state.js +60 -0
  25. package/dist/session/types.d.ts +93 -0
  26. package/dist/session/types.js +1 -0
  27. package/dist/session/variables.d.ts +121 -0
  28. package/dist/session/variables.js +5 -0
  29. package/package.json +51 -0
  30. package/src/bridge/base64.ts +56 -0
  31. package/src/bridge/index.ts +77 -0
  32. package/src/bridge/transport.ts +63 -0
  33. package/src/config.ts +408 -0
  34. package/src/index.ts +57 -0
  35. package/src/localization/index.ts +110 -0
  36. package/src/localization/periods.ts +790 -0
  37. package/src/mock.ts +333 -0
  38. package/src/products.ts +221 -0
  39. package/src/session/index.ts +1066 -0
  40. package/src/session/state.ts +112 -0
  41. package/src/session/types.ts +123 -0
  42. package/src/session/variables.ts +139 -0
package/dist/config.js ADDED
@@ -0,0 +1,138 @@
1
+ export const SUPERWALL_PLATFORMS = ["ios", "android", "web"];
2
+ export const normalizePlatform = (value) => {
3
+ const normalized = (value ?? "").toLowerCase();
4
+ return SUPERWALL_PLATFORMS.find((platform) => platform === normalized);
5
+ };
6
+ export const isPlatformProductIds = (input) => typeof input === "object" && input !== null && !("productId" in input);
7
+ /**
8
+ * The store identifier a slot resolves to on a platform. A per-platform slot
9
+ * with no entry for the platform resolves to nothing; with no platform known
10
+ * at all it falls back to its first entry.
11
+ */
12
+ export const productIdFor = (input, platform) => {
13
+ if (typeof input === "string")
14
+ return input;
15
+ if (!isPlatformProductIds(input))
16
+ return input.productId;
17
+ if (platform !== undefined)
18
+ return input[platform];
19
+ return Object.values(input).find((id) => typeof id === "string");
20
+ };
21
+ const DRAWER_DEFAULTS = { height: 70, cornerRadius: 15 };
22
+ const POPUP_DEFAULTS = { width: 80, height: 60, cornerRadius: 15 };
23
+ const dimension = (label, value, fallback) => {
24
+ const resolved = value ?? fallback;
25
+ if (!Number.isFinite(resolved) || resolved <= 0) {
26
+ throw new Error(`presentation.${label} must be a positive number, got ${String(value)}`);
27
+ }
28
+ return resolved;
29
+ };
30
+ export const presentationStyleWire = (presentation) => {
31
+ switch (presentation?.style ?? "fullscreen") {
32
+ case "fullscreen":
33
+ return { type: "FULLSCREEN" };
34
+ case "modal":
35
+ return { type: "MODAL" };
36
+ case "push":
37
+ return { type: "PUSH" };
38
+ case "noAnimation":
39
+ return { type: "NO_ANIMATION" };
40
+ case "drawer":
41
+ return {
42
+ type: "DRAWER",
43
+ height: dimension("drawer.height", presentation?.drawer?.height, DRAWER_DEFAULTS.height),
44
+ corner_radius: dimension("drawer.cornerRadius", presentation?.drawer?.cornerRadius, DRAWER_DEFAULTS.cornerRadius),
45
+ };
46
+ case "popup":
47
+ return {
48
+ type: "POPUP",
49
+ width: dimension("popup.width", presentation?.popup?.width, POPUP_DEFAULTS.width),
50
+ height: dimension("popup.height", presentation?.popup?.height, POPUP_DEFAULTS.height),
51
+ corner_radius: dimension("popup.cornerRadius", presentation?.popup?.cornerRadius, POPUP_DEFAULTS.cornerRadius),
52
+ };
53
+ }
54
+ };
55
+ const ELIGIBILITY_WIRE = {
56
+ automatic: "automatic",
57
+ alwaysEligible: "always_eligible",
58
+ alwaysIneligible: "always_ineligible",
59
+ };
60
+ const CHECKOUT_WIRE = {
61
+ external: "EXTERNAL",
62
+ sheet: "PAYWALL_EMBEDDED",
63
+ applePay: "PAYWALL_APPLE_PAY",
64
+ };
65
+ export const webCheckoutDestinationOf = (checkout) => {
66
+ const mode = checkoutModeOf(checkout);
67
+ return mode === undefined ? undefined : CHECKOUT_WIRE[mode];
68
+ };
69
+ export const paywallSettingsOf = (config) => {
70
+ const background = backgroundOf(config?.background);
71
+ const destination = webCheckoutDestinationOf(config?.checkout);
72
+ return {
73
+ presentation_style: presentationStyleWire(config?.presentation),
74
+ feature_gating: config?.featureGating === "gated" ? "gated" : "non_gated",
75
+ on_device_cache: config?.onDeviceCacheEnabled ?? true,
76
+ scroll_enabled: config?.scrollEnabled ?? true,
77
+ game_controller_enabled: config?.gameControllerEnabled ?? false,
78
+ introductory_offer_eligibility: ELIGIBILITY_WIRE[config?.introductoryOfferEligibility ?? "automatic"],
79
+ ...(destination === undefined ? {} : { web_checkout_destination: destination }),
80
+ ...(background === undefined ? {} : { background_color_hex: background.light }),
81
+ ...(background?.dark === undefined ? {} : { dark_background_color_hex: background.dark }),
82
+ };
83
+ };
84
+ export const checkoutModeOf = (checkout) => (typeof checkout === "string" ? checkout : checkout?.mode);
85
+ export const checkoutPrefetchOf = (checkout) => (typeof checkout === "object" ? checkout.prefetch : undefined);
86
+ export const backgroundOf = (background) => {
87
+ if (background === undefined)
88
+ return undefined;
89
+ if (typeof background === "string") {
90
+ const light = background.trim();
91
+ return light === "" ? undefined : { light };
92
+ }
93
+ const light = background.light?.trim();
94
+ if (!light)
95
+ return undefined;
96
+ const dark = background.dark?.trim();
97
+ return dark ? { light, dark } : { light };
98
+ };
99
+ /**
100
+ * Declares the paywall's contract: product slots, presentation, gating,
101
+ * notifications, and localization. Consumed by the runtime session at render
102
+ * time and by the Superwall build pipeline at push time.
103
+ */
104
+ export const defineSuperwallConfig = (config) => config;
105
+ export const normalizeProductSlot = (input, platform) => ({ productId: productIdFor(input, platform) });
106
+ export const checkoutNeedsPaymentUi = (checkout) => {
107
+ const mode = checkoutModeOf(checkout);
108
+ return mode === "sheet" || mode === "applePay";
109
+ };
110
+ /**
111
+ * Materializes the config's product slots as products so references exist
112
+ * before the SDK (or mock host) delivers real product data.
113
+ */
114
+ export const productsFromConfig = (config, platform) => Object.entries(config?.products ?? {}).map(([reference, input]) => {
115
+ const slot = normalizeProductSlot(input, platform);
116
+ return {
117
+ reference,
118
+ product: reference,
119
+ id: slot.productId,
120
+ productId: slot.productId,
121
+ productIdentifier: slot.productId,
122
+ variables: {},
123
+ source: "inline",
124
+ };
125
+ });
126
+ /** The framework's paywall generation — v4 is the visual editor, v5 is code. */
127
+ export const SUPERWALL_GENERATION = 5;
128
+ /**
129
+ * Document semantics as `<html>` data attributes — the snapshot's half of the
130
+ * two-layer contract. The build stamps these statically (no flash before
131
+ * hydration) and `SuperwallProvider` reasserts them at runtime (dev has no
132
+ * build step). The platform's serve-time stylesheet (live.css) owns what they
133
+ * mean, so their interpretation can evolve fleet-wide without republishing.
134
+ */
135
+ export const documentAttributes = (config) => ({
136
+ "data-sw-generation": String(SUPERWALL_GENERATION),
137
+ "data-sw-scroll": String(config?.scrollEnabled ?? true),
138
+ });
@@ -0,0 +1,12 @@
1
+ export * from "./bridge";
2
+ export * from "./bridge/base64";
3
+ export * from "./bridge/transport";
4
+ export * from "./config";
5
+ export * from "./localization";
6
+ export * from "./mock";
7
+ export * from "./products";
8
+ 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";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export * from "./bridge";
2
+ export * from "./bridge/base64";
3
+ export * from "./bridge/transport";
4
+ export * from "./config";
5
+ export * from "./localization";
6
+ export * from "./mock";
7
+ export * from "./products";
8
+ 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";
@@ -0,0 +1,24 @@
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;
@@ -0,0 +1,71 @@
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
+ };
@@ -0,0 +1 @@
1
+ export declare function getLocalizedPeriod(value: string, languages: string[]): string;