@base44-preview/sdk 0.8.48-pr.145.de7eff3 → 0.8.48-pr.276.4f760f9

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 (71) hide show
  1. package/dist/iap/account-token.d.ts +14 -0
  2. package/dist/iap/account-token.js +43 -0
  3. package/dist/iap/config.d.ts +18 -0
  4. package/dist/iap/config.js +99 -0
  5. package/dist/iap/errors.d.ts +89 -0
  6. package/dist/iap/errors.js +66 -0
  7. package/dist/iap/errors.types.d.ts +74 -0
  8. package/dist/iap/errors.types.js +7 -0
  9. package/dist/iap/events/emitter.d.ts +28 -0
  10. package/dist/iap/events/emitter.js +33 -0
  11. package/dist/iap/events/events.types.d.ts +124 -0
  12. package/dist/iap/events/events.types.js +1 -0
  13. package/dist/iap/iap.types.d.ts +618 -0
  14. package/dist/iap/iap.types.js +1 -0
  15. package/dist/iap/index.d.ts +120 -0
  16. package/dist/iap/index.js +140 -0
  17. package/dist/iap/ingest/device.d.ts +7 -0
  18. package/dist/iap/ingest/device.js +191 -0
  19. package/dist/iap/ingest/device.types.d.ts +80 -0
  20. package/dist/iap/ingest/device.types.js +1 -0
  21. package/dist/iap/ingest/mappers.d.ts +66 -0
  22. package/dist/iap/ingest/mappers.js +248 -0
  23. package/dist/iap/ingest/matrix.d.ts +55 -0
  24. package/dist/iap/ingest/matrix.js +202 -0
  25. package/dist/iap/ingest/notifications.d.ts +70 -0
  26. package/dist/iap/ingest/notifications.js +238 -0
  27. package/dist/iap/read/derive.d.ts +40 -0
  28. package/dist/iap/read/derive.js +112 -0
  29. package/dist/iap/read/read.d.ts +47 -0
  30. package/dist/iap/read/read.js +215 -0
  31. package/dist/iap/read/read.types.d.ts +174 -0
  32. package/dist/iap/read/read.types.js +1 -0
  33. package/dist/iap/runtime/base64.d.ts +34 -0
  34. package/dist/iap/runtime/base64.js +131 -0
  35. package/dist/iap/runtime/clock.d.ts +13 -0
  36. package/dist/iap/runtime/clock.js +11 -0
  37. package/dist/iap/runtime/webcrypto.d.ts +14 -0
  38. package/dist/iap/runtime/webcrypto.js +66 -0
  39. package/dist/iap/server-api/client.d.ts +16 -0
  40. package/dist/iap/server-api/client.js +140 -0
  41. package/dist/iap/server-api/jwt.d.ts +3 -0
  42. package/dist/iap/server-api/jwt.js +70 -0
  43. package/dist/iap/server-api/server-api.types.d.ts +155 -0
  44. package/dist/iap/server-api/server-api.types.js +12 -0
  45. package/dist/iap/store/collapse.d.ts +27 -0
  46. package/dist/iap/store/collapse.js +85 -0
  47. package/dist/iap/store/descriptors.d.ts +46 -0
  48. package/dist/iap/store/descriptors.js +90 -0
  49. package/dist/iap/store/entities-store.d.ts +43 -0
  50. package/dist/iap/store/entities-store.js +348 -0
  51. package/dist/iap/store/rows.types.d.ts +233 -0
  52. package/dist/iap/store/rows.types.js +1 -0
  53. package/dist/iap/store/schemas.d.ts +68 -0
  54. package/dist/iap/store/schemas.js +214 -0
  55. package/dist/iap/store/store-errors.d.ts +52 -0
  56. package/dist/iap/store/store-errors.js +103 -0
  57. package/dist/iap/store/store.types.d.ts +193 -0
  58. package/dist/iap/store/store.types.js +1 -0
  59. package/dist/iap/verify/apple-roots.d.ts +18 -0
  60. package/dist/iap/verify/apple-roots.js +121 -0
  61. package/dist/iap/verify/payload-checks.d.ts +30 -0
  62. package/dist/iap/verify/payload-checks.js +20 -0
  63. package/dist/iap/verify/verifier.d.ts +36 -0
  64. package/dist/iap/verify/verifier.js +161 -0
  65. package/dist/iap/verify/verify.types.d.ts +292 -0
  66. package/dist/iap/verify/verify.types.js +15 -0
  67. package/dist/iap/version.d.ts +13 -0
  68. package/dist/iap/version.js +13 -0
  69. package/dist/index.d.ts +11 -0
  70. package/dist/modules/functions.js +2 -6
  71. package/package.json +33 -3
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The namespace every Base44 in-app purchase account token is derived under.
3
+ *
4
+ * A fixed, arbitrary version-4 UUID. It must never change: the native shell
5
+ * derives the same value independently, and Apple has already signed the
6
+ * results into transactions that will keep renewing.
7
+ */
8
+ export declare const IAP_APP_ACCOUNT_TOKEN_NAMESPACE = "8f2b6a1e-4c5d-4e7a-9b3f-6d1a2c8e5f04";
9
+ /**
10
+ * Derives the account token for a Base44 user id.
11
+ *
12
+ * @throws {TypeError} when the user id is empty.
13
+ */
14
+ export declare function appAccountTokenFor(base44UserId: string): string;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Mapping a Base44 user to the UUID Apple signs into their purchases.
3
+ *
4
+ * StoreKit accepts a UUID at purchase time (`appAccountToken`) and Apple
5
+ * returns the same value in every resulting transaction — including renewals
6
+ * years later. That signed round trip is the entire attribution mechanism: it
7
+ * is the only way to know whose purchase a transaction is, without trusting
8
+ * anything the client claims.
9
+ *
10
+ * The mapping is a deterministic version-5 UUID of the user id under a fixed
11
+ * namespace, so it is a pure function. The shell, the web app and the backend
12
+ * all derive the same UUID from the same user id with no lookup table to keep
13
+ * in sync, and nothing to migrate.
14
+ *
15
+ * Two consequences worth knowing:
16
+ *
17
+ * - The namespace is part of the contract. Changing it orphans every purchase
18
+ * already attributed under the old one.
19
+ * - The mapping is one-way in practice. Recovering a user id means deriving
20
+ * the UUID for a candidate user and comparing, not inverting the hash.
21
+ *
22
+ * @internal
23
+ */
24
+ import { v5 as uuidv5 } from "uuid";
25
+ /**
26
+ * The namespace every Base44 in-app purchase account token is derived under.
27
+ *
28
+ * A fixed, arbitrary version-4 UUID. It must never change: the native shell
29
+ * derives the same value independently, and Apple has already signed the
30
+ * results into transactions that will keep renewing.
31
+ */
32
+ export const IAP_APP_ACCOUNT_TOKEN_NAMESPACE = "8f2b6a1e-4c5d-4e7a-9b3f-6d1a2c8e5f04";
33
+ /**
34
+ * Derives the account token for a Base44 user id.
35
+ *
36
+ * @throws {TypeError} when the user id is empty.
37
+ */
38
+ export function appAccountTokenFor(base44UserId) {
39
+ if (typeof base44UserId !== "string" || base44UserId.length === 0) {
40
+ throw new TypeError("a Base44 user id is required to derive an account token");
41
+ }
42
+ return uuidv5(base44UserId, IAP_APP_ACCOUNT_TOKEN_NAMESPACE);
43
+ }
@@ -0,0 +1,18 @@
1
+ import type { IapConfig, IapProductConfig } from "./iap.types.js";
2
+ import type { IapServerApiConfig } from "./server-api/server-api.types.js";
3
+ /** A validated configuration, with every default filled in. */
4
+ export interface ResolvedIapConfig {
5
+ readonly bundleId: string;
6
+ readonly appAppleId: number;
7
+ readonly products: Readonly<Record<string, IapProductConfig>>;
8
+ readonly testMode: boolean;
9
+ readonly allowLocalTesting: boolean;
10
+ readonly serverApi?: IapServerApiConfig;
11
+ }
12
+ /**
13
+ * Validates a configuration and fills in defaults.
14
+ *
15
+ * @throws {IapConfigError} `IAP_INVALID_CONFIG` for anything malformed, or
16
+ * `IAP_ONLINE_CHECKS_UNSUPPORTED` when online certificate checks are asked for.
17
+ */
18
+ export declare function resolveConfig(config: IapConfig): ResolvedIapConfig;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Configuration validation.
3
+ *
4
+ * Runs once, when the client is created, and refuses to build a client it
5
+ * cannot operate correctly. Failing at deploy time is the whole point: the
6
+ * alternative is discovering a missing `appAppleId` when Apple sends the first
7
+ * refund notification.
8
+ *
9
+ * @internal
10
+ */
11
+ import { IapConfigError } from "./errors.js";
12
+ const PRODUCT_TYPES = new Set([
13
+ "consumable",
14
+ "nonConsumable",
15
+ "nonRenewingSubscription",
16
+ "autoRenewableSubscription",
17
+ ]);
18
+ function invalid(message) {
19
+ throw new IapConfigError("IAP_INVALID_CONFIG", message);
20
+ }
21
+ /**
22
+ * Validates a configuration and fills in defaults.
23
+ *
24
+ * @throws {IapConfigError} `IAP_INVALID_CONFIG` for anything malformed, or
25
+ * `IAP_ONLINE_CHECKS_UNSUPPORTED` when online certificate checks are asked for.
26
+ */
27
+ export function resolveConfig(config) {
28
+ var _a;
29
+ if (!config || typeof config !== "object") {
30
+ invalid("an in-app purchase configuration object is required");
31
+ }
32
+ if (typeof config.bundleId !== "string" || config.bundleId.trim().length === 0) {
33
+ invalid("'bundleId' is required, e.g. \"com.example.app\"");
34
+ }
35
+ // A very common mix-up: passing the bundle id where the numeric id belongs.
36
+ if (typeof config.appAppleId === "string") {
37
+ invalid("'appAppleId' must be a number — the numeric App Store id from App Store " +
38
+ "Connect under App Information, not the bundle id");
39
+ }
40
+ if (typeof config.appAppleId !== "number" ||
41
+ !Number.isInteger(config.appAppleId) ||
42
+ config.appAppleId <= 0) {
43
+ invalid("'appAppleId' must be a positive integer, e.g. 1234567890");
44
+ }
45
+ if (!config.products || typeof config.products !== "object") {
46
+ invalid("'products' is required, keyed by product identifier");
47
+ }
48
+ for (const [productId, product] of Object.entries(config.products)) {
49
+ if (!product || typeof product !== "object") {
50
+ invalid(`product ${JSON.stringify(productId)} must be an object`);
51
+ }
52
+ if (!PRODUCT_TYPES.has(product.type)) {
53
+ invalid(`product ${JSON.stringify(productId)} has type ${JSON.stringify(product.type)}; expected one of ${[...PRODUCT_TYPES].join(", ")}`);
54
+ }
55
+ // Apple never expires a non-renewing subscription, so this number is the
56
+ // only thing that decides when access ends. Missing it would silently
57
+ // grant the product forever.
58
+ if (product.type === "nonRenewingSubscription") {
59
+ const days = product.nonRenewingDurationDays;
60
+ if (typeof days !== "number" || !Number.isFinite(days) || days <= 0) {
61
+ invalid(`product ${JSON.stringify(productId)} is a nonRenewingSubscription, so it ` +
62
+ "needs 'nonRenewingDurationDays' — Apple does not expire these, so the " +
63
+ "app decides how long they last");
64
+ }
65
+ }
66
+ }
67
+ // `null` is treated as absent, not as invalid: a secret that was never set
68
+ // arrives that way, and the right answer then is "the API is not configured"
69
+ // — which the call itself reports clearly — rather than refusing to start.
70
+ if (config.serverApi !== undefined && config.serverApi !== null) {
71
+ const api = config.serverApi;
72
+ if (typeof api !== "object") {
73
+ invalid("'serverApi' must be an object, or left out entirely");
74
+ }
75
+ for (const field of ["keyId", "issuerId", "privateKeyP8"]) {
76
+ if (typeof api[field] !== "string" || api[field].trim().length === 0) {
77
+ invalid(`'serverApi.${field}' is required when serverApi is supplied`);
78
+ }
79
+ }
80
+ if (!api.privateKeyP8.includes("PRIVATE KEY")) {
81
+ invalid("'serverApi.privateKeyP8' does not look like a .p8 file. Pass its whole " +
82
+ "contents, including the BEGIN and END lines.");
83
+ }
84
+ }
85
+ if (config.onlineChecks === true) {
86
+ throw new IapConfigError("IAP_ONLINE_CHECKS_UNSUPPORTED", "'onlineChecks' asks for certificate revocation lookups, which this version " +
87
+ "does not implement. Leave it unset. Certificate validity is evaluated at " +
88
+ "each payload's own signedDate, which is what Apple's own library does with " +
89
+ "online checks off.");
90
+ }
91
+ return {
92
+ bundleId: config.bundleId,
93
+ appAppleId: config.appAppleId,
94
+ products: { ...config.products },
95
+ testMode: config.testMode === true,
96
+ allowLocalTesting: config.allowLocalTesting === true,
97
+ serverApi: (_a = config.serverApi) !== null && _a !== void 0 ? _a : undefined,
98
+ };
99
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Error classes for the in-app purchase module.
3
+ *
4
+ * Each class carries a `code` from `errors.types.ts`. Nothing here imports the
5
+ * runtime helpers, so the runtime layer can throw these freely.
6
+ *
7
+ * @internal
8
+ */
9
+ import type { IapApiErrorCode, IapConfigErrorCode, IapSetupErrorCode, IapStoreErrorCode, IapVerificationErrorCode } from "./errors.types.js";
10
+ /** Base class, so a caller can catch every error this module raises at once. */
11
+ export declare class IapError extends Error {
12
+ /** Stable machine-readable code. */
13
+ readonly code: string;
14
+ constructor(code: string, message: string, options?: {
15
+ cause?: unknown;
16
+ });
17
+ }
18
+ /**
19
+ * A signed Apple token was rejected.
20
+ *
21
+ * Deny by default: anything that raises this must be treated as "not
22
+ * entitled", never as "probably fine".
23
+ */
24
+ export declare class IapVerificationError extends IapError {
25
+ readonly code: IapVerificationErrorCode;
26
+ constructor(code: IapVerificationErrorCode, message: string, options?: {
27
+ cause?: unknown;
28
+ });
29
+ }
30
+ /** The module cannot start, or was asked for something its configuration does not allow. */
31
+ export declare class IapConfigError extends IapError {
32
+ readonly code: IapConfigErrorCode;
33
+ constructor(code: IapConfigErrorCode, message: string, options?: {
34
+ cause?: unknown;
35
+ });
36
+ }
37
+ /**
38
+ * The app's Base44 setup is not usable — an entity is missing, or its schema
39
+ * has drifted from what the SDK writes.
40
+ *
41
+ * This is loud on purpose. A silently dropped field means purchase data is
42
+ * being lost, which is worse than an outage.
43
+ */
44
+ export declare class IapSetupError extends IapError {
45
+ readonly code: IapSetupErrorCode;
46
+ /** The entity the problem was found on. */
47
+ readonly entityName?: string;
48
+ /** Fields the entity dropped, when the code is `IAP_ENTITY_SCHEMA_DRIFT`. */
49
+ readonly missingFields?: string[];
50
+ constructor(code: IapSetupErrorCode, message: string, details?: {
51
+ entityName?: string;
52
+ missingFields?: string[];
53
+ cause?: unknown;
54
+ });
55
+ }
56
+ /** A read or write against the app's entities failed. */
57
+ export declare class IapStoreError extends IapError {
58
+ readonly code: IapStoreErrorCode;
59
+ /** The entity being read or written. */
60
+ readonly entityName?: string;
61
+ constructor(code: IapStoreErrorCode, message: string, details?: {
62
+ entityName?: string;
63
+ cause?: unknown;
64
+ });
65
+ }
66
+ /** An App Store Server API call failed. */
67
+ export declare class IapApiError extends IapError {
68
+ readonly code: IapApiErrorCode;
69
+ /** The HTTP status Apple returned. */
70
+ readonly httpStatus?: number;
71
+ /** Apple's own numeric error code from the response body, e.g. `4040010`. */
72
+ readonly appleErrorCode?: number;
73
+ /** Apple's own error message from the response body. */
74
+ readonly appleErrorMessage?: string;
75
+ /**
76
+ * When rate-limited: the value of Apple's `Retry-After` header.
77
+ *
78
+ * Apple sends an **absolute UNIX millisecond timestamp** here, not a delay.
79
+ * Compare it against `Date.now()`; do not use it as a duration.
80
+ */
81
+ readonly retryAfter?: number;
82
+ constructor(code: IapApiErrorCode, message: string, details?: {
83
+ httpStatus?: number;
84
+ appleErrorCode?: number;
85
+ appleErrorMessage?: string;
86
+ retryAfter?: number;
87
+ cause?: unknown;
88
+ });
89
+ }
@@ -0,0 +1,66 @@
1
+ /** Base class, so a caller can catch every error this module raises at once. */
2
+ export class IapError extends Error {
3
+ constructor(code, message, options) {
4
+ super(message);
5
+ this.name = "IapError";
6
+ this.code = code;
7
+ // `cause` is set by hand rather than passed to super: the emit target is
8
+ // es2018, whose Error constructor takes no options bag.
9
+ if (options && "cause" in options) {
10
+ this.cause = options.cause;
11
+ }
12
+ }
13
+ }
14
+ /**
15
+ * A signed Apple token was rejected.
16
+ *
17
+ * Deny by default: anything that raises this must be treated as "not
18
+ * entitled", never as "probably fine".
19
+ */
20
+ export class IapVerificationError extends IapError {
21
+ constructor(code, message, options) {
22
+ super(code, message, options);
23
+ this.name = "IapVerificationError";
24
+ }
25
+ }
26
+ /** The module cannot start, or was asked for something its configuration does not allow. */
27
+ export class IapConfigError extends IapError {
28
+ constructor(code, message, options) {
29
+ super(code, message, options);
30
+ this.name = "IapConfigError";
31
+ }
32
+ }
33
+ /**
34
+ * The app's Base44 setup is not usable — an entity is missing, or its schema
35
+ * has drifted from what the SDK writes.
36
+ *
37
+ * This is loud on purpose. A silently dropped field means purchase data is
38
+ * being lost, which is worse than an outage.
39
+ */
40
+ export class IapSetupError extends IapError {
41
+ constructor(code, message, details) {
42
+ super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
43
+ this.name = "IapSetupError";
44
+ this.entityName = details === null || details === void 0 ? void 0 : details.entityName;
45
+ this.missingFields = details === null || details === void 0 ? void 0 : details.missingFields;
46
+ }
47
+ }
48
+ /** A read or write against the app's entities failed. */
49
+ export class IapStoreError extends IapError {
50
+ constructor(code, message, details) {
51
+ super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
52
+ this.name = "IapStoreError";
53
+ this.entityName = details === null || details === void 0 ? void 0 : details.entityName;
54
+ }
55
+ }
56
+ /** An App Store Server API call failed. */
57
+ export class IapApiError extends IapError {
58
+ constructor(code, message, details) {
59
+ super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
60
+ this.name = "IapApiError";
61
+ this.httpStatus = details === null || details === void 0 ? void 0 : details.httpStatus;
62
+ this.appleErrorCode = details === null || details === void 0 ? void 0 : details.appleErrorCode;
63
+ this.appleErrorMessage = details === null || details === void 0 ? void 0 : details.appleErrorMessage;
64
+ this.retryAfter = details === null || details === void 0 ? void 0 : details.retryAfter;
65
+ }
66
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Error codes the in-app purchase module can raise.
3
+ *
4
+ * Every code is a stable string. Generated code and support tooling branch on
5
+ * these, so a code is never renamed — a new situation gets a new code.
6
+ */
7
+ /**
8
+ * Why a signed Apple token was rejected.
9
+ *
10
+ * The first eight come straight from the verification algorithm Apple
11
+ * describes; the last two are this SDK's own.
12
+ */
13
+ export type IapVerificationErrorCode =
14
+ /** The token is not three base64url segments separated by dots. */
15
+ "INVALID_JWS_FORMAT"
16
+ /** The JWS header named an algorithm other than `ES256`. */
17
+ | "UNSUPPORTED_ALG"
18
+ /** The `x5c` header did not carry exactly three certificates. */
19
+ | "INVALID_CHAIN_LENGTH"
20
+ /** A certificate failed to parse, was outside its validity window, or lacked a required marker. */
21
+ | "INVALID_CERTIFICATE"
22
+ /** A certificate was revoked. Only reachable with online checks, which v1 does not support. */
23
+ | "CERTIFICATE_REVOKED"
24
+ /** The signature did not verify against the leaf certificate's public key. */
25
+ | "INVALID_SIGNATURE"
26
+ /** The payload's `bundleId`, or its `appAppleId` in production, did not match the configuration. */
27
+ | "INVALID_APP_IDENTIFIER"
28
+ /** The payload's `environment` was not one this app accepts. */
29
+ | "INVALID_ENVIRONMENT"
30
+ /** A transient failure. Retrying may succeed. */
31
+ | "RETRYABLE_VERIFICATION_FAILURE"
32
+ /**
33
+ * The chain anchored at a root this SDK cannot verify against — an RSA root.
34
+ *
35
+ * Current App Store tokens chain to Apple Root CA - G3, which is ECDSA
36
+ * P-384. Apple Root CA - G2 and Apple Inc. Root are RSA and are pinned for
37
+ * completeness, but v1 verifies ECDSA signatures only. This is never
38
+ * downgraded to a pass.
39
+ */
40
+ | "UNSUPPORTED_CERT_ALGORITHM";
41
+ /** Why the module refused to start, or could not use its configuration. */
42
+ export type IapConfigErrorCode =
43
+ /** A required configuration field was missing or malformed. */
44
+ "IAP_INVALID_CONFIG"
45
+ /** `onlineChecks: true` was requested. Certificate revocation lookups are not implemented in v1. */
46
+ | "IAP_ONLINE_CHECKS_UNSUPPORTED"
47
+ /** The runtime has no WebCrypto. Needs Deno, Node 18 or later, or a secure browser context. */
48
+ | "IAP_WEBCRYPTO_UNAVAILABLE"
49
+ /** The runtime has no `fetch`. Needs Deno, Node 18 or later, or a browser. */
50
+ | "IAP_FETCH_UNAVAILABLE"
51
+ /** An App Store Server API call was made without `serverApi` credentials configured. */
52
+ | "IAP_SERVER_API_NOT_CONFIGURED";
53
+ /** Why the app's own Base44 setup is not usable for in-app purchases. */
54
+ export type IapSetupErrorCode =
55
+ /** One of the four required entities does not exist in this app. */
56
+ "IAP_ENTITY_MISSING"
57
+ /** An entity exists but silently dropped a field the SDK wrote. Its schema has drifted. */
58
+ | "IAP_ENTITY_SCHEMA_DRIFT"
59
+ /** The client was created without service-role credentials, so it cannot write. */
60
+ | "IAP_SERVICE_ROLE_REQUIRED";
61
+ /** Why a read or write against the app's entities failed. */
62
+ export type IapStoreErrorCode =
63
+ /** The write did not land. Callers must not report success to Apple or finish a transaction. */
64
+ "IAP_WRITE_FAILED"
65
+ /** The read did not complete. */
66
+ | "IAP_READ_FAILED";
67
+ /** Why an App Store Server API call failed. */
68
+ export type IapApiErrorCode =
69
+ /** Apple answered with an error status. Inspect `appleErrorCode` for which. */
70
+ "IAP_API_ERROR"
71
+ /** Apple rate-limited the call. `retryAfter` carries the absolute timestamp to retry after. */
72
+ | "IAP_API_RATE_LIMITED"
73
+ /** The transaction id exists in neither the production nor the sandbox environment. */
74
+ | "IAP_API_TRANSACTION_NOT_FOUND";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Error codes the in-app purchase module can raise.
3
+ *
4
+ * Every code is a stable string. Generated code and support tooling branch on
5
+ * these, so a code is never renamed — a new situation gets a new code.
6
+ */
7
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Delivering events to the app's handlers.
3
+ *
4
+ * Two rules, both about not letting an app's own code break Apple's contract:
5
+ *
6
+ * 1. **A handler runs after the write, never before.** An event means the data
7
+ * behind it is already stored.
8
+ * 2. **A handler can never change the outcome.** If one throws, the throw is
9
+ * swallowed and reported; the HTTP response Apple sees is unaffected.
10
+ *
11
+ * Events are dispatched *synchronously* before the response is returned, not
12
+ * after it. A Base44 backend function has no way to run work once it has
13
+ * answered — there is no `waitUntil` — so anything deferred until after the
14
+ * response is simply lost when the isolate stops.
15
+ *
16
+ * @internal
17
+ */
18
+ import type { IapEvent, IapEventHandler } from "./events.types.js";
19
+ /** Reports a handler that threw. Defaults to a single console line. */
20
+ export type IapHandlerFailureReporter = (event: IapEvent, error: unknown) => void;
21
+ /** The event bus for one client. */
22
+ export interface IapEmitter {
23
+ /** Registers a handler. Returns a function that removes it. */
24
+ onEvent(handler: IapEventHandler): () => void;
25
+ /** Delivers events to every handler, swallowing their failures. */
26
+ emit(events: readonly IapEvent[]): Promise<void>;
27
+ }
28
+ export declare function createEmitter(reportFailure?: IapHandlerFailureReporter): IapEmitter;
@@ -0,0 +1,33 @@
1
+ function defaultReporter(event, error) {
2
+ // Deliberately one line and not re-thrown. A broken handler must not take
3
+ // the webhook down with it, and it must not be silent either.
4
+ console.error(`[base44 iap] an onEvent handler failed for ${event.type}:`, error instanceof Error ? error.message : error);
5
+ }
6
+ export function createEmitter(reportFailure = defaultReporter) {
7
+ const handlers = new Set();
8
+ return {
9
+ onEvent(handler) {
10
+ handlers.add(handler);
11
+ return () => {
12
+ handlers.delete(handler);
13
+ };
14
+ },
15
+ async emit(events) {
16
+ if (handlers.size === 0 || events.length === 0)
17
+ return;
18
+ // A snapshot, so a handler that registers another one during dispatch
19
+ // does not change what this round delivers.
20
+ const current = [...handlers];
21
+ for (const event of events) {
22
+ for (const handler of current) {
23
+ try {
24
+ await handler(event);
25
+ }
26
+ catch (error) {
27
+ reportFailure(event, error);
28
+ }
29
+ }
30
+ }
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * What happened, in the app's own vocabulary.
3
+ *
4
+ * Apple's notification types describe *its* billing system. These describe
5
+ * what the app has to do about it, which is a much shorter list: something was
6
+ * bought, something was taken away, a subscription changed shape.
7
+ *
8
+ * Every ingestion path produces these, and `onEvent` handlers receive them
9
+ * after the write has landed — so a handler that sends an email or grants a
10
+ * bonus can trust that the data behind it is already stored.
11
+ */
12
+ import type { IapEnvironment } from "../verify/verify.types.js";
13
+ import type { IapRecordSource } from "../store/rows.types.js";
14
+ /** The kinds of event this module emits. */
15
+ export type IapEventType =
16
+ /** A one-time purchase completed. */
17
+ "purchase.completed"
18
+ /** Apple refunded a purchase. Take the content back. */
19
+ | "purchase.refunded"
20
+ /** Apple declined a refund request. Nothing to do. */
21
+ | "purchase.refund_declined"
22
+ /** A refund was reversed after a dispute. **Give the content back.** */
23
+ | "purchase.refund_reversed"
24
+ /** A family member's shared access ended. */
25
+ | "purchase.revoked"
26
+ /** Apple wants consumption data for a refund request, within a deadline. */
27
+ | "refund.consumption_requested"
28
+ /** A subscription started, either new or after a lapse. */
29
+ | "subscription.started"
30
+ /** A subscription renewed. */
31
+ | "subscription.renewed"
32
+ /** The customer changed plan, effective immediately. */
33
+ | "subscription.plan_changed"
34
+ /** The customer changed plan, effective at the next renewal. */
35
+ | "subscription.plan_change_scheduled"
36
+ /** The customer undid a scheduled plan change. */
37
+ | "subscription.plan_change_cancelled"
38
+ /** Automatic renewal was turned on or off. */
39
+ | "subscription.auto_renew_changed"
40
+ /** A payment failed. Check `inGracePeriod` before withdrawing access. */
41
+ | "subscription.billing_issue"
42
+ /** A billing grace period ended without a successful payment. */
43
+ | "subscription.grace_period_ended"
44
+ /** A subscription ended. */
45
+ | "subscription.expired"
46
+ /** The customer redeemed an offer. */
47
+ | "subscription.offer_redeemed"
48
+ /** A price increase was announced or accepted. */
49
+ | "subscription.price_increase"
50
+ /** Apple extended one subscriber's renewal date. */
51
+ | "subscription.renewal_extended"
52
+ /** A mass renewal-date extension finished. */
53
+ | "subscription.mass_extension_result"
54
+ /** A test notification arrived, confirming the webhook works. */
55
+ | "apple.test_received"
56
+ /** A notification type this version stores but does not act on. */
57
+ | "apple.unhandled"
58
+ /** A notification type Apple added after this version shipped. */
59
+ | "apple.unknown"
60
+ /** A launch-time sync completed. */
61
+ | "sync.applied";
62
+ /** Why a subscription started. */
63
+ export type IapStartReason = "initial" | "resubscribe";
64
+ /** Why a subscription renewed. */
65
+ export type IapRenewReason = "renewal" | "billing_recovery";
66
+ /** Why a subscription ended. */
67
+ export type IapExpiryReason = "voluntary" | "billing" | "price_increase" | "product_unavailable" | "other";
68
+ /**
69
+ * One thing that happened.
70
+ *
71
+ * The identifying fields are all optional because not every event has them: a
72
+ * mass-extension result concerns no single customer, and a purchase made
73
+ * before the customer logged in has no `appUserId` until a later sync attaches
74
+ * one.
75
+ */
76
+ export interface IapEvent {
77
+ /** What happened. */
78
+ type: IapEventType;
79
+ /** The Base44 user this concerns, when it could be resolved. */
80
+ appUserId: string | null;
81
+ /** The subscription chain involved. */
82
+ originalTransactionId?: string;
83
+ /** The transaction involved. */
84
+ transactionId?: string;
85
+ /** The product involved. */
86
+ productId?: string;
87
+ /** Which App Store environment this came from. */
88
+ environment: IapEnvironment;
89
+ /** When Apple says it happened, in epoch milliseconds. */
90
+ occurredAt: number;
91
+ /** Apple's notification id, when this came from a notification. */
92
+ notificationUUID?: string;
93
+ /** Where this event came from. */
94
+ source: IapRecordSource;
95
+ /** Apple's own notification type, when there was one. */
96
+ notificationType?: string;
97
+ /** Apple's own notification subtype, when there was one. */
98
+ subtype?: string;
99
+ /** Why a subscription started. Only on `subscription.started`. */
100
+ startReason?: IapStartReason;
101
+ /** Why a subscription renewed. Only on `subscription.renewed`. */
102
+ renewReason?: IapRenewReason;
103
+ /** Why a subscription ended. Only on `subscription.expired`. */
104
+ expiryReason?: IapExpiryReason;
105
+ /** Whether automatic renewal is now on. Only on `subscription.auto_renew_changed`. */
106
+ autoRenewEnabled?: boolean;
107
+ /**
108
+ * Whether a billing grace period is running.
109
+ *
110
+ * Only on `subscription.billing_issue`. When true, Apple's requirement is to
111
+ * **keep providing full service** — the customer has not lapsed yet.
112
+ */
113
+ inGracePeriod?: boolean;
114
+ /** Where a price increase stands. Only on `subscription.price_increase`. */
115
+ priceIncreaseConsent?: "pending" | "accepted";
116
+ /** When Apple stops accepting consumption data. Only on `refund.consumption_requested`. */
117
+ deadlineAt?: number;
118
+ /** How many entitlements a sync disagreed with the server about. Only on `sync.applied`. */
119
+ mismatches?: number;
120
+ /** The decoded payload behind this event, for anything the fields above omit. */
121
+ payload?: unknown;
122
+ }
123
+ /** A function called after an event's data has been stored. */
124
+ export type IapEventHandler = (event: IapEvent) => void | Promise<void>;
@@ -0,0 +1 @@
1
+ export {};