diff --git a/cross_platform.yaml b/cross_platform.yaml index e070b5d..53fb550 100644 --- a/cross_platform.yaml +++ b/cross_platform.yaml @@ -1,5 +1,5 @@ $schema: "https://json-schema.org/draft/2020-12/schema" -$id: "https://adapty.io/crossPlatform/4.3.2/schema" +$id: "https://adapty.io/crossPlatform/4.4.1/schema" title: "Cross Platform Format" $requests: @@ -135,6 +135,28 @@ $requests: properties: success: { const: true } + ### sendAppMessage ### + AdaptyUISendAppMessage.Request: #request + type: object + required: [method, id, message_id, payload] + properties: + method: { const: "adapty_ui_send_app_message" } + id: { type: string, description: "View Id" } + message_id: { type: string, description: "Id of the message, generated by the wrapper; the flow script receives it as the event id" } + payload: + type: object + description: "Message for the flow script, delivered as the `applicationMsg` SDK event" + + AdaptyUISendAppMessage.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: { const: true } + ### presentOnboardingView ### AdaptyUIPresentOnboardingView.Request: #request type: object @@ -424,6 +446,7 @@ $requests: ### getLogLevel ### GetLogLevel.Request: #request type: object + description: "iOS Only" required: [method] properties: method: { const: "get_log_level" } @@ -509,6 +532,7 @@ $requests: ### makePromotedPurchase ### MakePromotedPurchase.Request: #request type: object + description: "iOS Only" required: [method, product] properties: method: { const: "make_promoted_purchase" } @@ -628,6 +652,7 @@ $requests: ### presentCodeRedemptionSheet ### PresentCodeRedemptionSheet.Request: #request type: object + description: "iOS Only" required: [method] properties: method: { const: "present_code_redemption_sheet" } @@ -756,6 +781,7 @@ $requests: ### updateCollectingRefundDataConsent ### UpdateCollectingRefundDataConsent.Request: #request type: object + description: "iOS Only" required: [method, consent] properties: method: { const: "update_collecting_refund_data_consent" } @@ -792,6 +818,7 @@ $requests: ### updateRefundPreference ### UpdateRefundPreference.Request: #request type: object + description: "iOS Only" required: [method, refund_preference] properties: method: { const: "update_refund_preference" } @@ -943,7 +970,9 @@ $events: id: { const: "flow_view_did_receive_analytic_event" } view: { $ref: "#/$defs/AdaptyUI.FlowView" } name: { type: string } - params: { type: object } + params: + type: object + description: "Null fields of objects are dropped at every depth; nulls inside arrays are kept" Event.DidLoadLatestProfile: type: object @@ -954,6 +983,7 @@ $events: Event.DidReceivePromotedPurchase: type: object + description: "iOS Only" required: [id, product] properties: id: { const: "did_receive_promoted_purchase" } @@ -1308,7 +1338,6 @@ $defs: properties: app_account_token: { $ref: "#/$defs/UUID", description: "iOS Only" } obfuscated_account_id: { type: string, description: "Android Only" } - obfuscated_profile_id: { type: string, description: "Android Only" } AdaptyPaywallProduct.Response: #response type: object @@ -1349,8 +1378,8 @@ $defs: type: object required: - amount - - currency_code # iOS Only - - localized_string # iOS Only + - currency_code + - localized_string properties: amount: { type: number } currency_code: { type: string } @@ -1768,7 +1797,7 @@ $defs: billing_issue_detected_at: { $ref: "#/$defs/Date" } starts_at: { $ref: "#/$defs/Date" } cancellation_reason: { type: string } - billing_plan_id: { type: string, description: "iOS Only" } + billing_plan_id: { type: string } commitment: { $ref: "#/$defs/AdaptyProfile.SubscriptionCommitmentInfo" } is_refund: { type: boolean } @@ -1806,7 +1835,7 @@ $defs: - is_refund - is_sandbox - will_renew - - billing_plan_id # iOS Only + - billing_plan_id properties: store: { type: string } vendor_product_id: { type: string } @@ -1829,7 +1858,7 @@ $defs: active_promotional_offer_id: { type: string } offer_id: { type: string } cancellation_reason: { type: string } - billing_plan_id: { type: string, description: "iOS Only" } + billing_plan_id: { type: string } commitment: { $ref: "#/$defs/AdaptyProfile.SubscriptionCommitmentInfo" } AdaptyProfile.SubscriptionCommitmentInfo: #response @@ -1982,6 +2011,7 @@ $defs: properties: type: { type: string, const: "custom" } value: { type: string } + arguments: { type: object } AdaptyUI.Permission: #event description: diff --git a/package.json b/package.json index 26fe00b..8aebe4a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package", "name": "@adapty/core", - "version": "4.3.4", + "version": "4.4.0", "description": "Platform-agnostic core for Adapty JS SDKs", "license": "MIT", "author": "Adapty team ", diff --git a/src/coders/adapty-identify-params.ts b/src/coders/adapty-identify-params.ts index 21d1028..ed98d0c 100644 --- a/src/coders/adapty-identify-params.ts +++ b/src/coders/adapty-identify-params.ts @@ -1,12 +1,9 @@ import type { IPlatformAdapter } from '@/adapters/interfaces'; import * as Input from '@/types/inputs'; +import type { Def } from '@/types/schema'; type Model = Input.IdentifyParamsInput; -type Serializable = { - app_account_token?: string; - obfuscated_account_id?: string; - obfuscated_profile_id?: string; -}; +type Serializable = Def['CustomerIdentityParameters']; export class AdaptyIdentifyParamsCoder { constructor(private readonly platform: IPlatformAdapter) {} diff --git a/src/coders/adapty-paywall-product.test.ts b/src/coders/adapty-paywall-product.test.ts index f81f6a1..e19d221 100644 --- a/src/coders/adapty-paywall-product.test.ts +++ b/src/coders/adapty-paywall-product.test.ts @@ -93,10 +93,18 @@ const mocks: Def['AdaptyPaywallProduct.Response'][] = [ localized_period: '1 year', pricing_terms: { billing_plan_id: 'monthly', - billing_price: { amount: 6.99, localized_string: '$6.99' }, + billing_price: { + amount: 6.99, + currency_code: 'USD', + localized_string: '$6.99', + }, billing_period: { unit: 'month', number_of_units: 1 }, commitment_info: { - price: { amount: 83.88, localized_string: '$83.88' }, + price: { + amount: 83.88, + currency_code: 'USD', + localized_string: '$83.88', + }, period: { unit: 'year', number_of_units: 1 }, }, }, diff --git a/src/coders/adapty-price.test.ts b/src/coders/adapty-price.test.ts index 763568b..0177a50 100644 --- a/src/coders/adapty-price.test.ts +++ b/src/coders/adapty-price.test.ts @@ -11,15 +11,15 @@ const mocks: Def['AdaptyPrice'][] = [ currency_symbol: '$', localized_string: '$9.99', }, - { amount: 9.99 }, + { amount: 9.99, currency_code: 'USD', localized_string: '$9.99' }, ]; function toModel(mock: (typeof mocks)[number]): Model { return { amount: mock.amount, - ...(mock.currency_code && { currencyCode: mock.currency_code }), + currencyCode: mock.currency_code, ...(mock.currency_symbol && { currencySymbol: mock.currency_symbol }), - ...(mock.localized_string && { localizedString: mock.localized_string }), + localizedString: mock.localized_string, }; } @@ -42,4 +42,17 @@ describe('AdaptyPriceCoder', () => { expect(encoded).toStrictEqual(mock); }); + + it.each([ + ['currency_code', undefined], + ['currency_code', null], + ['localized_string', undefined], + ['localized_string', null], + ] as const)('should fail to decode when required %s is %p', (key, value) => { + const mock = { ...mocks[0]!, [key]: value }; + + expect(() => coder.decode(mock as Def['AdaptyPrice'])).toThrow( + key === 'currency_code' ? 'currencyCode' : 'localizedString', + ); + }); }); diff --git a/src/coders/adapty-price.ts b/src/coders/adapty-price.ts index d6be140..b67ac33 100644 --- a/src/coders/adapty-price.ts +++ b/src/coders/adapty-price.ts @@ -15,7 +15,7 @@ export class AdaptyPriceCoder extends SimpleCoder { }, currencyCode: { key: 'currency_code', - required: false, + required: true, type: 'string', }, currencySymbol: { @@ -25,8 +25,16 @@ export class AdaptyPriceCoder extends SimpleCoder { }, localizedString: { key: 'localized_string', - required: false, + required: true, type: 'string', }, }; + // Treat null as missing so required fields reject it + override decode(data: Serializable): Model { + return super.decode( + Object.fromEntries( + Object.entries(data).filter(([, value]) => value !== null), + ) as Serializable, + ); + } } diff --git a/src/coders/adapty-profile.test.ts b/src/coders/adapty-profile.test.ts index fccce59..e3fe668 100644 --- a/src/coders/adapty-profile.test.ts +++ b/src/coders/adapty-profile.test.ts @@ -36,6 +36,7 @@ const mocks: Omit< custom_attributes: {}, subscriptions: { 'monthly.premium.999': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'monthly.premium.999', is_sandbox: true, @@ -52,6 +53,7 @@ const mocks: Omit< store: 'app_store', }, 'weekly.premium.599': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'weekly.premium.599', is_sandbox: true, @@ -131,6 +133,7 @@ const mocks: Omit< custom_attributes: {}, subscriptions: { trial_sub_12: { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'trial_sub_12', is_sandbox: true, @@ -148,6 +151,7 @@ const mocks: Omit< cancellation_reason: 'billing_error', }, 'weekly.premium.599': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'weekly.premium.599', is_sandbox: true, @@ -165,6 +169,7 @@ const mocks: Omit< cancellation_reason: 'voluntarily_cancelled', }, 'monthly.premium.999': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'monthly.premium.999', is_sandbox: true, diff --git a/src/coders/adapty-purchase-result.test.ts b/src/coders/adapty-purchase-result.test.ts index 4bd54a1..f980015 100644 --- a/src/coders/adapty-purchase-result.test.ts +++ b/src/coders/adapty-purchase-result.test.ts @@ -41,6 +41,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ custom_attributes: {}, subscriptions: { 'monthly.premium.999': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'monthly.premium.999', is_sandbox: true, @@ -57,6 +58,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ store: 'app_store', }, 'weekly.premium.599': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'weekly.premium.599', is_sandbox: true, @@ -101,6 +103,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ custom_attributes: {}, subscriptions: { 'monthly.premium.999': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'monthly.premium.999', is_sandbox: true, @@ -117,6 +120,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ store: 'app_store', }, 'weekly.premium.599': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'weekly.premium.599', is_sandbox: true, @@ -162,6 +166,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ custom_attributes: {}, subscriptions: { 'monthly.premium.999': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'monthly.premium.999', is_sandbox: true, @@ -178,6 +183,7 @@ const mocks: TestAdaptyPurchaseResultDef[] = [ store: 'app_store', }, 'weekly.premium.599': { + billing_plan_id: 'up_front', is_lifetime: false, vendor_product_id: 'weekly.premium.599', is_sandbox: true, diff --git a/src/coders/adapty-subscription-pricing-terms.test.ts b/src/coders/adapty-subscription-pricing-terms.test.ts index 1a53808..b323204 100644 --- a/src/coders/adapty-subscription-pricing-terms.test.ts +++ b/src/coders/adapty-subscription-pricing-terms.test.ts @@ -7,20 +7,36 @@ type Model = AdaptySubscriptionPricingTerms; const mocks: Def['AdaptySubscriptionPricingTerms'][] = [ { billing_plan_id: 'monthly', - billing_price: { amount: 6.99, localized_string: '$6.99' }, + billing_price: { + amount: 6.99, + currency_code: 'USD', + localized_string: '$6.99', + }, billing_period: { unit: 'month', number_of_units: 1 }, commitment_info: { - price: { amount: 83.88, localized_string: '$83.88' }, + price: { + amount: 83.88, + currency_code: 'USD', + localized_string: '$83.88', + }, period: { unit: 'year', number_of_units: 1 }, }, }, { // Unknown plans are passed through as is billing_plan_id: 'quarterly', - billing_price: { amount: 59.99 }, + billing_price: { + amount: 59.99, + currency_code: 'EUR', + localized_string: '59,99 €', + }, billing_period: { unit: 'year', number_of_units: 1 }, commitment_info: { - price: { amount: 59.99 }, + price: { + amount: 59.99, + currency_code: 'EUR', + localized_string: '59,99 €', + }, period: { unit: 'year', number_of_units: 1 }, }, }, @@ -29,7 +45,8 @@ const mocks: Def['AdaptySubscriptionPricingTerms'][] = [ function toModel(mock: (typeof mocks)[number]): Model { const price = (p: Def['AdaptyPrice']) => ({ amount: p.amount, - ...(p.localized_string && { localizedString: p.localized_string }), + currencyCode: p.currency_code, + localizedString: p.localized_string, }); const period = (p: Def['AdaptySubscriptionPeriod']) => ({ unit: p.unit as ProductPeriod, diff --git a/src/coders/adapty-subscription.test.ts b/src/coders/adapty-subscription.test.ts index b3c7465..6c3faa4 100644 --- a/src/coders/adapty-subscription.test.ts +++ b/src/coders/adapty-subscription.test.ts @@ -2,9 +2,9 @@ import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscription, CancellationReason, - SubscriptionBillingPlan, VendorStore, } from '@/types'; +import { SubscriptionBillingPlan } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptySubscriptionCoder } from './adapty-subscription'; @@ -32,6 +32,7 @@ const mocks: Def['AdaptyProfile.Subscription'][] = [ { activated_at: '2022-07-09T12:34:56.789Z', billing_issue_detected_at: '2023-08-09T12:34:56.789Z', + billing_plan_id: 'up_front', cancellation_reason: 'User Choice', expires_at: '2023-08-09T12:34:56.789Z', is_active: false, @@ -83,9 +84,7 @@ function toModel(mock: (typeof mocks)[number]): Model { vendorTransactionId: mock.vendor_transaction_id, willRenew: mock.will_renew, ...(mock.offer_id && { offerId: mock.offer_id }), - ...(mock.billing_plan_id && { - billingPlan: mock.billing_plan_id as SubscriptionBillingPlan, - }), + billingPlan: mock.billing_plan_id as SubscriptionBillingPlan, ...(mock.commitment && { commitmentInfo: { billingPeriodNumber: mock.commitment.billing_period_number, @@ -115,4 +114,18 @@ describe('AdaptySubscriptionCoder', () => { expect(encoded).toStrictEqual(mock); }); + + it.each([undefined, null])( + 'should default billing_plan_id %p to up_front like native SDKs', + billingPlanId => { + const mock = { + ...mocks[0]!, + billing_plan_id: billingPlanId, + } as unknown as Def['AdaptyProfile.Subscription']; + + expect(coder.decode(mock).billingPlan).toBe( + SubscriptionBillingPlan.UpFront, + ); + }, + ); }); diff --git a/src/coders/adapty-subscription.ts b/src/coders/adapty-subscription.ts index 01133ab..e2161ca 100644 --- a/src/coders/adapty-subscription.ts +++ b/src/coders/adapty-subscription.ts @@ -1,4 +1,4 @@ -import type { AdaptySubscription } from '../types'; +import { type AdaptySubscription, SubscriptionBillingPlan } from '@/types'; import type { Def } from '@/types/schema'; import type { Properties } from './types'; import { SimpleCoder } from './coder'; @@ -118,7 +118,7 @@ export class AdaptySubscriptionCoder extends SimpleCoder { }, billingPlan: { key: 'billing_plan_id', - required: false, + required: true, type: 'string', }, commitmentInfo: { @@ -135,4 +135,12 @@ export class AdaptySubscriptionCoder extends SimpleCoder { type: 'string', }, }; + + // Native SDKs default a missing billing plan to up_front + override decode(data: Serializable): Model { + return super.decode({ + ...data, + billing_plan_id: data.billing_plan_id ?? SubscriptionBillingPlan.UpFront, + }); + } } diff --git a/src/coders/nested-platform.test.ts b/src/coders/nested-platform.test.ts index a1a0933..425fe84 100644 --- a/src/coders/nested-platform.test.ts +++ b/src/coders/nested-platform.test.ts @@ -26,7 +26,7 @@ const androidProduct: Def['AdaptyPaywallProduct.Response'] = { paywall_name: 'Paywall', localized_description: 'Premium', localized_title: 'Premium Yearly', - price: { amount: 69.99, localized_string: '$69.99' }, + price: { amount: 69.99, currency_code: 'USD', localized_string: '$69.99' }, subscription: { base_plan_id: 'yearly-base', renewal_type: 'autorenewable', diff --git a/src/coders/parse-flow.test.ts b/src/coders/parse-flow.test.ts index 63bac39..363fa5c 100644 --- a/src/coders/parse-flow.test.ts +++ b/src/coders/parse-flow.test.ts @@ -86,6 +86,49 @@ describe('parseFlowEvent — notification events', () => { }); }); +describe('parseFlowEvent — did_perform_action custom', () => { + const parseAction = (action: Record) => + parseFlowEvent( + factory, + JSON.stringify({ + id: 'flow_view_did_perform_action', + view: rawView, + action, + }), + ); + + it('parses custom action value and arguments', () => { + expect( + parseAction({ + type: 'custom', + value: 'open_article', + arguments: { article_id: 42, tags: ['a', 'b'] }, + }), + ).toEqual({ + id: 'flow_view_did_perform_action', + view: decodedView, + action: { + type: 'custom', + value: 'open_article', + args: { article_id: 42, tags: ['a', 'b'] }, + }, + }); + }); + + it.each([undefined, null, 'str', ['a']])( + 'defaults invalid arguments (%p) to an empty object', + args => { + expect( + parseAction({ type: 'custom', value: 'open_article', arguments: args }), + ).toEqual({ + id: 'flow_view_did_perform_action', + view: decodedView, + action: { type: 'custom', value: 'open_article', args: {} }, + }); + }, + ); +}); + describe('parseFlowEvent — did_ask_permission', () => { it('parses event_id, permission and custom_args (snake_case → camelCase)', () => { const input = JSON.stringify({ diff --git a/src/coders/parse-flow.ts b/src/coders/parse-flow.ts index 30995eb..69367d4 100644 --- a/src/coders/parse-flow.ts +++ b/src/coders/parse-flow.ts @@ -282,8 +282,17 @@ function parseFlowUserAction( value: actionObj['value'] as string, openIn: actionObj['open_in'] as WebPresentation, }; - case 'custom': - return { type, value: actionObj['value'] as string }; + case 'custom': { + const args = actionObj['arguments']; + return { + type, + value: actionObj['value'] as string, + args: + typeof args === 'object' && args !== null && !Array.isArray(args) + ? (args as Record) + : {}, + }; + } case 'close': case 'system_back': return { type }; diff --git a/src/index.ts b/src/index.ts index 4d5b890..bfa8a61 100644 --- a/src/index.ts +++ b/src/index.ts @@ -40,6 +40,10 @@ export * from './types/error'; export * from './types/bridge'; export * from './types/flow-events'; export * from './types/onboarding-events'; +export type { + AdaptyFlowMessage, + AdaptyFlowMessageValue, +} from './types/flow-message'; export type { components } from './types/api'; diff --git a/src/types/api.d.ts b/src/types/api.d.ts index fc85e76..2c1407e 100644 --- a/src/types/api.d.ts +++ b/src/types/api.d.ts @@ -87,6 +87,17 @@ export interface components { [{ error: components['defs']['AdaptyError'] }, { success: true }] >; + 'AdaptyUISendAppMessage.Request': { + method: 'adapty_ui_send_app_message'; + id: string; + message_id: string; + payload: Record; + }; + + 'AdaptyUISendAppMessage.Response': OneOf< + [{ error: components['defs']['AdaptyError'] }, { success: true }] + >; + 'AdaptyUIPresentOnboardingView.Request': { method: 'adapty_ui_present_onboarding_view'; id: string; @@ -790,7 +801,6 @@ export interface components { CustomerIdentityParameters: { app_account_token?: string; obfuscated_account_id?: string; - obfuscated_profile_id?: string; }; 'AdaptyPaywallProduct.Response': { @@ -815,9 +825,9 @@ export interface components { AdaptyPrice: { amount: number; - currency_code?: string; + currency_code: string; currency_symbol?: string; - localized_string?: string; + localized_string: string; }; 'AdaptyPromotedProduct.Request': { @@ -1081,7 +1091,7 @@ export interface components { active_promotional_offer_id?: string; offer_id?: string; cancellation_reason?: string; - billing_plan_id?: string; + billing_plan_id: string; commitment?: components['defs']['AdaptyProfile.SubscriptionCommitmentInfo']; }; @@ -1187,6 +1197,7 @@ export interface components { { type: 'custom'; value: string; + arguments?: Record; }, ] >; diff --git a/src/types/bridge.ts b/src/types/bridge.ts index 3b29b4f..ca73b73 100644 --- a/src/types/bridge.ts +++ b/src/types/bridge.ts @@ -15,6 +15,7 @@ export const MethodNames = [ 'adapty_ui_dismiss_flow_view', 'adapty_ui_present_flow_view', 'adapty_ui_show_dialog', + 'adapty_ui_send_app_message', 'adapty_ui_create_onboarding_view', 'adapty_ui_dismiss_onboarding_view', 'adapty_ui_present_onboarding_view', diff --git a/src/types/error.test.ts b/src/types/error.test.ts index 1ab7b45..12c0768 100644 --- a/src/types/error.test.ts +++ b/src/types/error.test.ts @@ -24,10 +24,18 @@ describe('error codes', () => { [1050, 'paymentPendingError'], [1060, 'billingPlanUnavailable'], [3020, 'unidentifiedUserLogout'], + [4001, 'platformNotSupported'], + [4002, 'adaptyNotActivated'], + [4003, 'adaptyUINotActivated'], + [4005, 'activateOnce'], + [4103, 'wrongComponentType'], [4104, 'wrongAssetType'], [4105, 'jsException'], [4106, 'navigatorNotFound'], [4107, 'invalidActionUrl'], + [4108, 'unsupportedUrlScheme'], + [4200, 'webKit'], + [4300, 'platformView'], ] as const)('maps native code %i to %s', (code, name) => { expect(getErrorPrompt(code)).toBe(name); expect(getErrorCode(name)).toBe(code); @@ -54,4 +62,18 @@ describe('error codes', () => { expect(error.codeName).toBe('billingPlanUnavailable'); expect(error.message).toBe('#1060 (billingPlanUnavailable): Unavailable'); }); + + it('names an AdaptyUI code', () => { + const error = new AdaptyError({ + adaptyCode: 4003, + message: 'AdaptyUIError.adaptyUINotActivated', + }); + + expect(getErrorCodeName(4003)).toBe('adaptyUINotActivated'); + expect(error.codeName).toBe('adaptyUINotActivated'); + expect(error.message).toBe( + '#4003 (adaptyUINotActivated): AdaptyUIError.adaptyUINotActivated', + ); + expect(error.message).not.toContain('unknown code'); + }); }); diff --git a/src/types/error.ts b/src/types/error.ts index d6e88ee..8e17bcb 100644 --- a/src/types/error.ts +++ b/src/types/error.ts @@ -152,12 +152,32 @@ const ErrorCodeMapping = Object.freeze({ */ 3202: 'resolverFailure', /** - * Custom Android AdaptyUI codes. + * AdaptyUI codes. */ + 4001: 'platformNotSupported', + /** + * Adapty SDK must be activated before AdaptyUI. + */ + 4002: 'adaptyNotActivated', + /** + * AdaptyUI is not activated (e.g. a view is created without `activateUi`). + */ + 4003: 'adaptyUINotActivated', + 4005: 'activateOnce', + 4103: 'wrongComponentType', 4104: 'wrongAssetType', 4105: 'jsException', 4106: 'navigatorNotFound', 4107: 'invalidActionUrl', + /** + * In-app browser requested for a non-http(s) URL. iOS only. + */ + 4108: 'unsupportedUrlScheme', + 4200: 'webKit', + /** + * Native platform view failed to initialize. + */ + 4300: 'platformView', 9000: 'operationInterrupted', }); @@ -230,10 +250,18 @@ export const ErrorCodeName = Object.freeze({ fetchTimeoutError: 3101, operationInProgress: 3201, resolverFailure: 3202, + platformNotSupported: 4001, + adaptyNotActivated: 4002, + adaptyUINotActivated: 4003, + activateOnce: 4005, + wrongComponentType: 4103, wrongAssetType: 4104, jsException: 4105, navigatorNotFound: 4106, invalidActionUrl: 4107, + unsupportedUrlScheme: 4108, + webKit: 4200, + platformView: 4300, operationInterrupted: 9000, } as const); export type ErrorCodeName = keyof typeof ErrorCodeName; diff --git a/src/types/flow-events.ts b/src/types/flow-events.ts index 3c32053..f9eab34 100644 --- a/src/types/flow-events.ts +++ b/src/types/flow-events.ts @@ -112,7 +112,7 @@ export type FlowUserAction = | { type: 'close' } | { type: 'system_back' } | { type: 'open_url'; value: string; openIn: WebPresentation } - | { type: 'custom'; value: string }; + | { type: 'custom'; value: string; args: Record }; export interface FlowDidPerformActionEvent extends BaseFlowEvent { id: typeof FlowEventId.DidPerformAction; diff --git a/src/types/flow-message.test.ts b/src/types/flow-message.test.ts new file mode 100644 index 0000000..d00f6a5 --- /dev/null +++ b/src/types/flow-message.test.ts @@ -0,0 +1,46 @@ +import type { AdaptyFlowMessage, AdaptyFlowMessageValue } from './flow-message'; + +// Type-level checks: verified by `yarn tsc`. +type JsonAlias = { kind: string; count: number; tags: string[] }; +interface NonJsonInterface { + a: number; +} + +const nested: AdaptyFlowMessage = { + a: 1, + b: 'x', + c: true, + d: null, + e: [1, 'y'], + f: { g: [{ h: null }] }, +}; +const readonlyList: readonly number[] = [1, 2]; +const withReadonly: AdaptyFlowMessage = { list: readonlyList }; +const alias: JsonAlias = { kind: 'k', count: 1, tags: ['t'] }; +const fromAlias: AdaptyFlowMessage = alias; +const value: AdaptyFlowMessageValue = [nested, null]; + +// @ts-expect-error Date is not a JSON value +const withDate: AdaptyFlowMessage = { d: new Date() }; +// @ts-expect-error functions are not JSON values +const withFunction: AdaptyFlowMessage = { f: () => 1 }; +// @ts-expect-error undefined is not a JSON value +const withUndefined: AdaptyFlowMessage = { u: undefined }; +// @ts-expect-error Map is not a JSON value +const withMap: AdaptyFlowMessage = { m: new Map() }; +const iface: NonJsonInterface = { a: 1 }; +// @ts-expect-error interfaces have no implicit index signature +const fromInterface: AdaptyFlowMessage = iface; + +describe('AdaptyFlowMessage', () => { + it('accepts JSON-like values', () => { + expect([nested, withReadonly, fromAlias, value]).toHaveLength(4); + expect([ + withDate, + withFunction, + withUndefined, + withMap, + fromInterface, + ]).toHaveLength(5); + }); +}); diff --git a/src/types/flow-message.ts b/src/types/flow-message.ts new file mode 100644 index 0000000..efd01ea --- /dev/null +++ b/src/types/flow-message.ts @@ -0,0 +1,17 @@ +/** JSON value allowed inside an {@link AdaptyFlowMessage}. */ +export type AdaptyFlowMessageValue = + | string + | number + | boolean + | null + | AdaptyFlowMessage + | readonly AdaptyFlowMessageValue[]; + +/** + * Message exchanged with the flow script: a JSON object, delivered to the + * script as the content of an SDK event. + * Use finite numbers, omit unset properties or use `null`, avoid cycles. + */ +export type AdaptyFlowMessage = { + readonly [key: string]: AdaptyFlowMessageValue; +}; diff --git a/src/types/index.ts b/src/types/index.ts index 1038c73..6eb2986 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -73,7 +73,7 @@ export interface AdaptyPrice { * used to format the price of the product. * The ISO 4217 (USD, EUR). */ - currencyCode?: string; + currencyCode: string; /** * The currency symbol of the locale * used to format the price of the product. @@ -85,7 +85,7 @@ export interface AdaptyPrice { * by the preferred language set on the device. * On Android, the formatted price from Google Play as is. */ - localizedString?: string; + localizedString: string; } /** @@ -537,7 +537,7 @@ export interface AdaptyAccessLevel { readonly willRenew: boolean; /** - * Billing plan of the subscription. Set for App Store purchases only, see {@link store}. + * Billing plan of the subscription. May be absent when the native SDK does not report it. * @readonly */ readonly billingPlan?: SubscriptionBillingPlan; @@ -745,10 +745,10 @@ export interface AdaptySubscription { readonly willRenew: boolean; /** - * Billing plan of the subscription. Set for App Store purchases only, see {@link store}. + * Billing plan of the subscription. `up_front` unless the subscription is billed in installments. * @readonly */ - readonly billingPlan?: SubscriptionBillingPlan; + readonly billingPlan: SubscriptionBillingPlan; /** * Commitment progress of a subscription bought with a commitment billing plan. diff --git a/src/ui-builder/flow-event-mapping.test.ts b/src/ui-builder/flow-event-mapping.test.ts index 8eccf8c..8bb0ebd 100644 --- a/src/ui-builder/flow-event-mapping.test.ts +++ b/src/ui-builder/flow-event-mapping.test.ts @@ -161,3 +161,27 @@ describe('flow-event-mapping — did appear', () => { expect(args).toEqual([]); }); }); + +describe('flow-event-mapping — did_perform_action', () => { + const customEvent = { + id: FlowEventId.DidPerformAction, + view, + action: { + type: 'custom' as const, + value: 'open_article', + args: { article_id: 42 }, + }, + }; + + it('resolves a custom action to onCustomAction', () => { + const resolver = NATIVE_EVENT_RESOLVER[FlowEventId.DidPerformAction]; + expect(resolver(customEvent)).toBe('onCustomAction'); + }); + + it('extracts custom action args as [actionId, arguments]', () => { + expect(extractFlowCallbackArgs('onCustomAction', customEvent)).toEqual([ + 'open_article', + { article_id: 42 }, + ]); + }); +}); diff --git a/src/ui-builder/flow-event-mapping.ts b/src/ui-builder/flow-event-mapping.ts index 744dc95..e735ba9 100644 --- a/src/ui-builder/flow-event-mapping.ts +++ b/src/ui-builder/flow-event-mapping.ts @@ -107,7 +107,7 @@ export function extractFlowCallbackArgs( return [event.action.value, event.action.openIn] as ExtractedArgs; } if (handlerName === 'onCustomAction' && event.action.type === 'custom') { - return [event.action.value] as ExtractedArgs; + return [event.action.value, event.action.args] as ExtractedArgs; } // onCloseButtonPress, onAndroidSystemBack don't take arguments return [] as ExtractedArgs; diff --git a/src/ui-builder/types.ts b/src/ui-builder/types.ts index be61e6c..8975b36 100644 --- a/src/ui-builder/types.ts +++ b/src/ui-builder/types.ts @@ -168,7 +168,16 @@ export interface FlowEventHandlers { * @param {AdaptyError} error - AdaptyError object with error code and message */ onLoadingProductsFailed: (error: AdaptyError) => EventHandlerResult; - onCustomAction: (actionId: string) => EventHandlerResult; + /** + * Called when the user performs a custom action inside the flow. + * + * @param actionId - Custom action id configured in the dashboard + * @param args - Custom action arguments; empty object when none were configured + */ + onCustomAction: ( + actionId: string, + args: Record, + ) => EventHandlerResult; /** * Called when the user taps a URL/link inside the paywall. *