@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.
- package/dist/iap/account-token.d.ts +14 -0
- package/dist/iap/account-token.js +43 -0
- package/dist/iap/config.d.ts +18 -0
- package/dist/iap/config.js +99 -0
- package/dist/iap/errors.d.ts +89 -0
- package/dist/iap/errors.js +66 -0
- package/dist/iap/errors.types.d.ts +74 -0
- package/dist/iap/errors.types.js +7 -0
- package/dist/iap/events/emitter.d.ts +28 -0
- package/dist/iap/events/emitter.js +33 -0
- package/dist/iap/events/events.types.d.ts +124 -0
- package/dist/iap/events/events.types.js +1 -0
- package/dist/iap/iap.types.d.ts +618 -0
- package/dist/iap/iap.types.js +1 -0
- package/dist/iap/index.d.ts +120 -0
- package/dist/iap/index.js +140 -0
- package/dist/iap/ingest/device.d.ts +7 -0
- package/dist/iap/ingest/device.js +191 -0
- package/dist/iap/ingest/device.types.d.ts +80 -0
- package/dist/iap/ingest/device.types.js +1 -0
- package/dist/iap/ingest/mappers.d.ts +66 -0
- package/dist/iap/ingest/mappers.js +248 -0
- package/dist/iap/ingest/matrix.d.ts +55 -0
- package/dist/iap/ingest/matrix.js +202 -0
- package/dist/iap/ingest/notifications.d.ts +70 -0
- package/dist/iap/ingest/notifications.js +238 -0
- package/dist/iap/read/derive.d.ts +40 -0
- package/dist/iap/read/derive.js +112 -0
- package/dist/iap/read/read.d.ts +47 -0
- package/dist/iap/read/read.js +215 -0
- package/dist/iap/read/read.types.d.ts +174 -0
- package/dist/iap/read/read.types.js +1 -0
- package/dist/iap/runtime/base64.d.ts +34 -0
- package/dist/iap/runtime/base64.js +131 -0
- package/dist/iap/runtime/clock.d.ts +13 -0
- package/dist/iap/runtime/clock.js +11 -0
- package/dist/iap/runtime/webcrypto.d.ts +14 -0
- package/dist/iap/runtime/webcrypto.js +66 -0
- package/dist/iap/server-api/client.d.ts +16 -0
- package/dist/iap/server-api/client.js +140 -0
- package/dist/iap/server-api/jwt.d.ts +3 -0
- package/dist/iap/server-api/jwt.js +70 -0
- package/dist/iap/server-api/server-api.types.d.ts +155 -0
- package/dist/iap/server-api/server-api.types.js +12 -0
- package/dist/iap/store/collapse.d.ts +27 -0
- package/dist/iap/store/collapse.js +85 -0
- package/dist/iap/store/descriptors.d.ts +46 -0
- package/dist/iap/store/descriptors.js +90 -0
- package/dist/iap/store/entities-store.d.ts +43 -0
- package/dist/iap/store/entities-store.js +348 -0
- package/dist/iap/store/rows.types.d.ts +233 -0
- package/dist/iap/store/rows.types.js +1 -0
- package/dist/iap/store/schemas.d.ts +68 -0
- package/dist/iap/store/schemas.js +214 -0
- package/dist/iap/store/store-errors.d.ts +52 -0
- package/dist/iap/store/store-errors.js +103 -0
- package/dist/iap/store/store.types.d.ts +193 -0
- package/dist/iap/store/store.types.js +1 -0
- package/dist/iap/verify/apple-roots.d.ts +18 -0
- package/dist/iap/verify/apple-roots.js +121 -0
- package/dist/iap/verify/payload-checks.d.ts +30 -0
- package/dist/iap/verify/payload-checks.js +20 -0
- package/dist/iap/verify/verifier.d.ts +36 -0
- package/dist/iap/verify/verifier.js +161 -0
- package/dist/iap/verify/verify.types.d.ts +292 -0
- package/dist/iap/verify/verify.types.js +15 -0
- package/dist/iap/version.d.ts +13 -0
- package/dist/iap/version.js +13 -0
- package/dist/index.d.ts +11 -0
- package/dist/modules/functions.js +2 -6
- package/package.json +33 -3
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Signing the token the App Store Server API needs.
|
|
3
|
+
*
|
|
4
|
+
* A short-lived ES256 JWT, made from the In-App Purchase key. Two details are
|
|
5
|
+
* easy to get wrong:
|
|
6
|
+
*
|
|
7
|
+
* - The `.p8` file is PEM-armoured PKCS#8, so the armour comes off before
|
|
8
|
+
* WebCrypto will import it.
|
|
9
|
+
* - A JOSE signature is raw `r ‖ s`, which is exactly what WebCrypto's ECDSA
|
|
10
|
+
* sign returns — so unlike a certificate signature it needs **no** DER
|
|
11
|
+
* conversion. Doing one anyway produces a token Apple rejects.
|
|
12
|
+
*
|
|
13
|
+
* A fresh token is minted per request with a five-minute life, matching what
|
|
14
|
+
* Apple's own library does. Apple's ceiling is 60 minutes.
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
import { base64ToBytes, bytesToBase64Url } from "../runtime/base64.js";
|
|
19
|
+
import { getSubtle, utf8 } from "../runtime/webcrypto.js";
|
|
20
|
+
import { IapConfigError } from "../errors.js";
|
|
21
|
+
/** How long a minted token lasts. Apple allows up to 60 minutes. */
|
|
22
|
+
const TOKEN_LIFETIME_SECONDS = 5 * 60;
|
|
23
|
+
/** The audience Apple requires. */
|
|
24
|
+
const AUDIENCE = "appstoreconnect-v1";
|
|
25
|
+
function stripPemArmour(pem) {
|
|
26
|
+
return pem
|
|
27
|
+
.replace(/-----BEGIN [^-]+-----/g, "")
|
|
28
|
+
.replace(/-----END [^-]+-----/g, "")
|
|
29
|
+
.replace(/\s+/g, "");
|
|
30
|
+
}
|
|
31
|
+
async function importSigningKey(privateKeyP8) {
|
|
32
|
+
let der;
|
|
33
|
+
try {
|
|
34
|
+
der = base64ToBytes(stripPemArmour(privateKeyP8));
|
|
35
|
+
}
|
|
36
|
+
catch (cause) {
|
|
37
|
+
throw new IapConfigError("IAP_INVALID_CONFIG", "the In-App Purchase private key is not valid base64. Pass the whole .p8 " +
|
|
38
|
+
"file contents, including its BEGIN and END lines.", { cause });
|
|
39
|
+
}
|
|
40
|
+
const copy = new Uint8Array(der.length);
|
|
41
|
+
copy.set(der);
|
|
42
|
+
try {
|
|
43
|
+
return await getSubtle().importKey("pkcs8", copy.buffer, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
|
|
44
|
+
}
|
|
45
|
+
catch (cause) {
|
|
46
|
+
throw new IapConfigError("IAP_INVALID_CONFIG", "the In-App Purchase private key could not be read as a P-256 key. Check it " +
|
|
47
|
+
"is the In-App Purchase key from App Store Connect, not an App Store " +
|
|
48
|
+
"Connect team key.", { cause });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Mints a bearer token for the App Store Server API. */
|
|
52
|
+
export async function mintServerApiToken(config, bundleId, nowMs) {
|
|
53
|
+
const key = await importSigningKey(config.privateKeyP8);
|
|
54
|
+
const issuedAt = Math.floor(nowMs / 1000);
|
|
55
|
+
const header = bytesToBase64Url(utf8(JSON.stringify({ alg: "ES256", kid: config.keyId, typ: "JWT" })));
|
|
56
|
+
const payload = bytesToBase64Url(utf8(JSON.stringify({
|
|
57
|
+
iss: config.issuerId,
|
|
58
|
+
iat: issuedAt,
|
|
59
|
+
exp: issuedAt + TOKEN_LIFETIME_SECONDS,
|
|
60
|
+
aud: AUDIENCE,
|
|
61
|
+
bid: bundleId,
|
|
62
|
+
})));
|
|
63
|
+
const signingInput = utf8(`${header}.${payload}`);
|
|
64
|
+
const input = new Uint8Array(signingInput.length);
|
|
65
|
+
input.set(signingInput);
|
|
66
|
+
const signature = await getSubtle().sign({ name: "ECDSA", hash: { name: "SHA-256" } }, key, input.buffer);
|
|
67
|
+
// Already raw r ‖ s. This must NOT go through the DER converter that
|
|
68
|
+
// certificate signatures need.
|
|
69
|
+
return `${header}.${payload}.${bytesToBase64Url(new Uint8Array(signature))}`;
|
|
70
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The App Store Server API surface.
|
|
3
|
+
*
|
|
4
|
+
* Everything here needs an **In-App Purchase key**, from App Store Connect
|
|
5
|
+
* under Users and Access, Integrations. It is not an App Store Connect team
|
|
6
|
+
* key: Apple scopes each key family to its own APIs. The key downloads once,
|
|
7
|
+
* so it belongs in Base44 secrets rather than in code.
|
|
8
|
+
*
|
|
9
|
+
* None of it is needed to verify a purchase or to know whether a customer is
|
|
10
|
+
* entitled. It only unlocks talking *to* Apple.
|
|
11
|
+
*/
|
|
12
|
+
/** Credentials for the App Store Server API. */
|
|
13
|
+
export interface IapServerApiConfig {
|
|
14
|
+
/** The key's identifier, shown next to it in App Store Connect. */
|
|
15
|
+
keyId: string;
|
|
16
|
+
/** Your issuer id, from the Integrations page. */
|
|
17
|
+
issuerId: string;
|
|
18
|
+
/**
|
|
19
|
+
* The private key, as downloaded.
|
|
20
|
+
*
|
|
21
|
+
* The whole `.p8` file contents including the `-----BEGIN PRIVATE KEY-----`
|
|
22
|
+
* lines. Store it in Base44 secrets, never in source.
|
|
23
|
+
*/
|
|
24
|
+
privateKeyP8: string;
|
|
25
|
+
}
|
|
26
|
+
/** Whether the app delivered what the customer paid for. */
|
|
27
|
+
export type IapDeliveryStatus = "DELIVERED" | "UNDELIVERED_QUALITY_ISSUE" | "UNDELIVERED_WRONG_ITEM" | "UNDELIVERED_SERVER_OUTAGE" | "UNDELIVERED_OTHER";
|
|
28
|
+
/** What the app would prefer Apple do about a refund. */
|
|
29
|
+
export type IapRefundPreference = "DECLINE" | "GRANT_FULL" | "GRANT_PRORATED";
|
|
30
|
+
/**
|
|
31
|
+
* Consumption data for a disputed purchase.
|
|
32
|
+
*
|
|
33
|
+
* Apple's consent rules are strict, and they are the app's responsibility, not
|
|
34
|
+
* this SDK's: consent must be freely given, specific, informed and
|
|
35
|
+
* unambiguous, must not be gathered through the App Tracking Transparency
|
|
36
|
+
* prompt, and must be disclosed in the app's privacy labels. Without consent,
|
|
37
|
+
* the correct action is to send nothing at all.
|
|
38
|
+
*/
|
|
39
|
+
export interface ConsumptionRequestBody {
|
|
40
|
+
/**
|
|
41
|
+
* Whether the customer consented to sharing this data.
|
|
42
|
+
*
|
|
43
|
+
* Must be `true`. Apple rejects the call otherwise, and sending data without
|
|
44
|
+
* consent would be wrong regardless.
|
|
45
|
+
*/
|
|
46
|
+
customerConsented: true;
|
|
47
|
+
/** Whether the app delivered the purchase. */
|
|
48
|
+
deliveryStatus: IapDeliveryStatus;
|
|
49
|
+
/** Whether a free sample, trial or functional description was offered before purchase. */
|
|
50
|
+
sampleContentProvided: boolean;
|
|
51
|
+
/** What the app would prefer Apple do. */
|
|
52
|
+
refundPreference?: IapRefundPreference;
|
|
53
|
+
/**
|
|
54
|
+
* How much of the purchase was used, in thousandths of a percent (0 to 100000).
|
|
55
|
+
*
|
|
56
|
+
* Must be 0 unless `deliveryStatus` is `DELIVERED`, and must be omitted
|
|
57
|
+
* entirely for auto-renewable subscriptions.
|
|
58
|
+
*/
|
|
59
|
+
consumptionPercentage?: number;
|
|
60
|
+
}
|
|
61
|
+
/** The token identifying a test notification Apple was asked to send. */
|
|
62
|
+
export interface TestNotificationResult {
|
|
63
|
+
/** Pass this to `getTestNotificationStatus` to see what happened. */
|
|
64
|
+
testNotificationToken: string;
|
|
65
|
+
}
|
|
66
|
+
/** Why one delivery attempt did or did not work. */
|
|
67
|
+
export type SendAttemptResult = "SUCCESS" | "CIRCULAR_REDIRECT" | "INVALID_RESPONSE" | "NO_RESPONSE" | "OTHER" | "PREMATURE_CLOSE" | "SOCKET_ISSUE" | "TIMED_OUT" | "TLS_ISSUE" | "UNSUCCESSFUL_HTTP_RESPONSE_CODE" | "UNSUPPORTED_CHARSET";
|
|
68
|
+
/** One attempt Apple made to deliver a notification. */
|
|
69
|
+
export interface SendAttempt {
|
|
70
|
+
/** When Apple tried. */
|
|
71
|
+
attemptDate: number;
|
|
72
|
+
/** How it went. */
|
|
73
|
+
sendAttemptResult: SendAttemptResult;
|
|
74
|
+
}
|
|
75
|
+
/** What became of a test notification. */
|
|
76
|
+
export interface TestNotificationStatus {
|
|
77
|
+
/** Every attempt Apple made, in order. */
|
|
78
|
+
sendAttempts: SendAttempt[];
|
|
79
|
+
/** The payload Apple sent, so it can be replayed. */
|
|
80
|
+
signedPayload?: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Calls to Apple's own servers.
|
|
84
|
+
*
|
|
85
|
+
* Always present on the module. Every method throws
|
|
86
|
+
* `IAP_SERVER_API_NOT_CONFIGURED` until `serverApi` credentials are supplied,
|
|
87
|
+
* so the shape of the module never depends on configuration.
|
|
88
|
+
*/
|
|
89
|
+
export interface IapServerApiModule {
|
|
90
|
+
/**
|
|
91
|
+
* Answers Apple's request for consumption data about a disputed purchase.
|
|
92
|
+
*
|
|
93
|
+
* Apple allows **12 hours** in production and only **5 minutes** in sandbox,
|
|
94
|
+
* and only wants an answer if the customer consented. With no consent flow,
|
|
95
|
+
* do not call this — sending nothing is the correct behaviour, not a
|
|
96
|
+
* failure.
|
|
97
|
+
*
|
|
98
|
+
* @param transactionId - The disputed transaction.
|
|
99
|
+
* @param body - The consumption data, including the customer's consent.
|
|
100
|
+
* @returns Promise that resolves when Apple has accepted the data.
|
|
101
|
+
* @throws {Error} An `IapApiError` when Apple rejects the call, or an `IapConfigError` when no key is configured.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```typescript
|
|
105
|
+
* // Answer a refund request the customer consented to
|
|
106
|
+
* await iap.serverApi.sendConsumptionInformation(transactionId, {
|
|
107
|
+
* customerConsented: true,
|
|
108
|
+
* deliveryStatus: "DELIVERED",
|
|
109
|
+
* sampleContentProvided: false,
|
|
110
|
+
* consumptionPercentage: 100000,
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
sendConsumptionInformation(transactionId: string, body: ConsumptionRequestBody): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Asks Apple to send a test notification to the configured URL.
|
|
117
|
+
*
|
|
118
|
+
* The quickest way to prove a webhook is reachable, before any real purchase
|
|
119
|
+
* exists. Apple sends to the URL registered for whichever environment the
|
|
120
|
+
* key belongs to, so the URLs have to be set up first.
|
|
121
|
+
*
|
|
122
|
+
* @returns Promise resolving to the token identifying this test.
|
|
123
|
+
* @throws {Error} An `IapApiError` when Apple rejects the call, or an `IapConfigError` when no key is configured.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // Prove the webhook works
|
|
128
|
+
* const { testNotificationToken } = await iap.serverApi.requestTestNotification();
|
|
129
|
+
* const status = await iap.serverApi.getTestNotificationStatus(testNotificationToken);
|
|
130
|
+
* console.log(status.sendAttempts.at(-1)?.sendAttemptResult);
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
requestTestNotification(): Promise<TestNotificationResult>;
|
|
134
|
+
/**
|
|
135
|
+
* Reports what became of a test notification.
|
|
136
|
+
*
|
|
137
|
+
* `SUCCESS` on the last attempt means the webhook is reachable and answered
|
|
138
|
+
* correctly. Anything else names the problem — a timeout, a TLS failure, a
|
|
139
|
+
* bad status code.
|
|
140
|
+
*
|
|
141
|
+
* @param testNotificationToken - The token from `requestTestNotification`.
|
|
142
|
+
* @returns Promise resolving to every delivery attempt, and the payload Apple sent.
|
|
143
|
+
* @throws {Error} An `IapApiError` when Apple rejects the call, or an `IapConfigError` when no key is configured.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```typescript
|
|
147
|
+
* // Check a test notification, allowing for Apple's delay
|
|
148
|
+
* const status = await iap.serverApi.getTestNotificationStatus(token);
|
|
149
|
+
* for (const attempt of status.sendAttempts) {
|
|
150
|
+
* console.log(new Date(attempt.attemptDate), attempt.sendAttemptResult);
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
getTestNotificationStatus(testNotificationToken: string): Promise<TestNotificationStatus>;
|
|
155
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The App Store Server API surface.
|
|
3
|
+
*
|
|
4
|
+
* Everything here needs an **In-App Purchase key**, from App Store Connect
|
|
5
|
+
* under Users and Access, Integrations. It is not an App Store Connect team
|
|
6
|
+
* key: Apple scopes each key family to its own APIs. The key downloads once,
|
|
7
|
+
* so it belongs in Base44 secrets rather than in code.
|
|
8
|
+
*
|
|
9
|
+
* None of it is needed to verify a purchase or to know whether a customer is
|
|
10
|
+
* entitled. It only unlocks talking *to* Apple.
|
|
11
|
+
*/
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Folding duplicate rows into one.
|
|
3
|
+
*
|
|
4
|
+
* Base44 cannot enforce a unique column, so two writes racing for the same
|
|
5
|
+
* natural key can both create a row. Reads therefore never assume one row per
|
|
6
|
+
* key — they collapse whatever they find, which makes correctness independent
|
|
7
|
+
* of whether a repair pass has run.
|
|
8
|
+
*
|
|
9
|
+
* The fold reproduces what a guarded merge would have produced: newest row
|
|
10
|
+
* first, then the first non-null value for each field. So a loser row's
|
|
11
|
+
* `finishedAt`, or a renewal token the newest row happens to lack, survives.
|
|
12
|
+
*
|
|
13
|
+
* Pure, and therefore testable without a network.
|
|
14
|
+
*
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
import type { IapEntityDescriptor } from "./store.types.js";
|
|
18
|
+
/** One row per natural key, plus how many duplicates were folded away. */
|
|
19
|
+
export interface CollapseResult<T> {
|
|
20
|
+
readonly rows: T[];
|
|
21
|
+
readonly collapsed: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Collapses rows to one per natural key, preserving input order of first
|
|
25
|
+
* appearance.
|
|
26
|
+
*/
|
|
27
|
+
export declare function collapseDuplicates<T>(descriptor: IapEntityDescriptor<T>, rows: readonly T[]): CollapseResult<T>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
function cursorValue(descriptor, row) {
|
|
2
|
+
const facets = Object.keys(descriptor.cursors);
|
|
3
|
+
if (facets.length === 0)
|
|
4
|
+
return 0;
|
|
5
|
+
const column = descriptor.cursors[facets[0]];
|
|
6
|
+
const value = row[column];
|
|
7
|
+
return typeof value === "number" ? value : 0;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Orders two candidates for the same key, newest first.
|
|
11
|
+
*
|
|
12
|
+
* The order is total and deterministic — cursor, then creation time, then the
|
|
13
|
+
* record id — because two backend instances must give the same customer the
|
|
14
|
+
* same answer. An unstable tie-break would make entitlement flap.
|
|
15
|
+
*/
|
|
16
|
+
function compareNewestFirst(descriptor, a, b) {
|
|
17
|
+
var _a, _b, _c, _d;
|
|
18
|
+
const byCursor = cursorValue(descriptor, b) - cursorValue(descriptor, a);
|
|
19
|
+
if (byCursor !== 0)
|
|
20
|
+
return byCursor;
|
|
21
|
+
const aRecord = a;
|
|
22
|
+
const bRecord = b;
|
|
23
|
+
const byCreated = ((_a = bRecord.created_date) !== null && _a !== void 0 ? _a : "").localeCompare((_b = aRecord.created_date) !== null && _b !== void 0 ? _b : "");
|
|
24
|
+
if (byCreated !== 0)
|
|
25
|
+
return byCreated;
|
|
26
|
+
return ((_c = bRecord.id) !== null && _c !== void 0 ? _c : "").localeCompare((_d = aRecord.id) !== null && _d !== void 0 ? _d : "");
|
|
27
|
+
}
|
|
28
|
+
function isEmpty(value) {
|
|
29
|
+
return value === null || value === undefined;
|
|
30
|
+
}
|
|
31
|
+
/** Folds one key's rows into a single row. */
|
|
32
|
+
function foldGroup(descriptor, group) {
|
|
33
|
+
const ordered = [...group].sort((a, b) => compareNewestFirst(descriptor, a, b));
|
|
34
|
+
const merged = { ...ordered[0] };
|
|
35
|
+
for (let i = 1; i < ordered.length; i += 1) {
|
|
36
|
+
const candidate = ordered[i];
|
|
37
|
+
for (const field of Object.keys(candidate)) {
|
|
38
|
+
if (isEmpty(merged[field]) && !isEmpty(candidate[field])) {
|
|
39
|
+
merged[field] = candidate[field];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// A few columns record when something first happened, so the oldest value is
|
|
44
|
+
// the true one rather than the newest.
|
|
45
|
+
for (const field of descriptor.oldestWins) {
|
|
46
|
+
let oldest;
|
|
47
|
+
for (const row of ordered) {
|
|
48
|
+
const value = row[field];
|
|
49
|
+
if (typeof value === "number" && (oldest === undefined || value < oldest)) {
|
|
50
|
+
oldest = value;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (oldest !== undefined)
|
|
54
|
+
merged[field] = oldest;
|
|
55
|
+
}
|
|
56
|
+
return merged;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Collapses rows to one per natural key, preserving input order of first
|
|
60
|
+
* appearance.
|
|
61
|
+
*/
|
|
62
|
+
export function collapseDuplicates(descriptor, rows) {
|
|
63
|
+
const groups = new Map();
|
|
64
|
+
const order = [];
|
|
65
|
+
for (const row of rows) {
|
|
66
|
+
const key = String(row[descriptor.keyField]);
|
|
67
|
+
const existing = groups.get(key);
|
|
68
|
+
if (existing) {
|
|
69
|
+
existing.push(row);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
groups.set(key, [row]);
|
|
73
|
+
order.push(key);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
let collapsed = 0;
|
|
77
|
+
const out = [];
|
|
78
|
+
for (const key of order) {
|
|
79
|
+
const group = groups.get(key);
|
|
80
|
+
if (group.length > 1)
|
|
81
|
+
collapsed += group.length - 1;
|
|
82
|
+
out.push(group.length === 1 ? group[0] : foldGroup(descriptor, group));
|
|
83
|
+
}
|
|
84
|
+
return { rows: out, collapsed };
|
|
85
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-entity storage rules.
|
|
3
|
+
*
|
|
4
|
+
* The only place the store layer knows anything specific about the four
|
|
5
|
+
* entities. Everything else is driven off these.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
import type { IapEntityDescriptor } from "./store.types.js";
|
|
10
|
+
import type { IapConsumptionRequestRecord, IapNotificationRecord, IapSubscriptionRecord, IapTransactionRecord } from "./rows.types.js";
|
|
11
|
+
/**
|
|
12
|
+
* A purchase or renewal.
|
|
13
|
+
*
|
|
14
|
+
* `expect: "insert"` because the key is almost always new — every renewal
|
|
15
|
+
* carries a fresh `transactionId` — so trying the insert first saves a round
|
|
16
|
+
* trip on the common path.
|
|
17
|
+
*/
|
|
18
|
+
export declare const TRANSACTION_DESCRIPTOR: IapEntityDescriptor<IapTransactionRecord>;
|
|
19
|
+
/**
|
|
20
|
+
* A subscription.
|
|
21
|
+
*
|
|
22
|
+
* `expect: "update"` because after the first purchase the row exists and every
|
|
23
|
+
* later payload updates it.
|
|
24
|
+
*
|
|
25
|
+
* Two cursors, because the transaction and the renewal information arrive
|
|
26
|
+
* separately: a launch-time sync brings a transaction with no renewal
|
|
27
|
+
* information, a notification brings both. With one shared cursor a sync could
|
|
28
|
+
* advance past a later notification and silently drop a grace-period date,
|
|
29
|
+
* which would deny service to a customer Apple is still trying to bill.
|
|
30
|
+
*/
|
|
31
|
+
export declare const SUBSCRIPTION_DESCRIPTOR: IapEntityDescriptor<IapSubscriptionRecord>;
|
|
32
|
+
/**
|
|
33
|
+
* A notification from Apple.
|
|
34
|
+
*
|
|
35
|
+
* Immutable once committed, so it has no cursor: the only write after the
|
|
36
|
+
* insert is the commit patch that sets the real outcome.
|
|
37
|
+
*/
|
|
38
|
+
export declare const NOTIFICATION_DESCRIPTOR: IapEntityDescriptor<IapNotificationRecord>;
|
|
39
|
+
/**
|
|
40
|
+
* A refund-consumption request.
|
|
41
|
+
*
|
|
42
|
+
* Two cursors again: the request itself and the outcome a later notification
|
|
43
|
+
* fills in, which can arrive out of order relative to a fresh request for the
|
|
44
|
+
* same transaction.
|
|
45
|
+
*/
|
|
46
|
+
export declare const CONSUMPTION_DESCRIPTOR: IapEntityDescriptor<IapConsumptionRequestRecord>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A purchase or renewal.
|
|
3
|
+
*
|
|
4
|
+
* `expect: "insert"` because the key is almost always new — every renewal
|
|
5
|
+
* carries a fresh `transactionId` — so trying the insert first saves a round
|
|
6
|
+
* trip on the common path.
|
|
7
|
+
*/
|
|
8
|
+
export const TRANSACTION_DESCRIPTOR = {
|
|
9
|
+
name: "IapTransaction",
|
|
10
|
+
keyField: "transactionId",
|
|
11
|
+
cursors: { transaction: "signedDate" },
|
|
12
|
+
expect: "insert",
|
|
13
|
+
mergeExcluded: [
|
|
14
|
+
"transactionId",
|
|
15
|
+
// Set once, when the SDK first saw the row.
|
|
16
|
+
"recordedAt",
|
|
17
|
+
// Owned by this SDK, not by Apple's payload, and guarded separately.
|
|
18
|
+
"finishedAt",
|
|
19
|
+
],
|
|
20
|
+
oldestWins: ["recordedAt"],
|
|
21
|
+
heavyFields: ["rawJws"],
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A subscription.
|
|
25
|
+
*
|
|
26
|
+
* `expect: "update"` because after the first purchase the row exists and every
|
|
27
|
+
* later payload updates it.
|
|
28
|
+
*
|
|
29
|
+
* Two cursors, because the transaction and the renewal information arrive
|
|
30
|
+
* separately: a launch-time sync brings a transaction with no renewal
|
|
31
|
+
* information, a notification brings both. With one shared cursor a sync could
|
|
32
|
+
* advance past a later notification and silently drop a grace-period date,
|
|
33
|
+
* which would deny service to a customer Apple is still trying to bill.
|
|
34
|
+
*/
|
|
35
|
+
export const SUBSCRIPTION_DESCRIPTOR = {
|
|
36
|
+
name: "IapSubscription",
|
|
37
|
+
keyField: "originalTransactionId",
|
|
38
|
+
cursors: {
|
|
39
|
+
transaction: "latestSignedDate",
|
|
40
|
+
renewal: "latestRenewalSignedDate",
|
|
41
|
+
},
|
|
42
|
+
expect: "update",
|
|
43
|
+
mergeExcluded: ["originalTransactionId", "recordedAt"],
|
|
44
|
+
oldestWins: ["recordedAt"],
|
|
45
|
+
heavyFields: ["latestTransactionJws", "latestRenewalInfoJws"],
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A notification from Apple.
|
|
49
|
+
*
|
|
50
|
+
* Immutable once committed, so it has no cursor: the only write after the
|
|
51
|
+
* insert is the commit patch that sets the real outcome.
|
|
52
|
+
*/
|
|
53
|
+
export const NOTIFICATION_DESCRIPTOR = {
|
|
54
|
+
name: "IapNotification",
|
|
55
|
+
keyField: "notificationUUID",
|
|
56
|
+
cursors: {},
|
|
57
|
+
expect: "insert",
|
|
58
|
+
mergeExcluded: [
|
|
59
|
+
"notificationUUID",
|
|
60
|
+
"notificationType",
|
|
61
|
+
"signedDate",
|
|
62
|
+
"receivedAt",
|
|
63
|
+
"rawSignedPayload",
|
|
64
|
+
"sdkVersion",
|
|
65
|
+
],
|
|
66
|
+
oldestWins: ["receivedAt"],
|
|
67
|
+
heavyFields: ["rawSignedPayload"],
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* A refund-consumption request.
|
|
71
|
+
*
|
|
72
|
+
* Two cursors again: the request itself and the outcome a later notification
|
|
73
|
+
* fills in, which can arrive out of order relative to a fresh request for the
|
|
74
|
+
* same transaction.
|
|
75
|
+
*/
|
|
76
|
+
export const CONSUMPTION_DESCRIPTOR = {
|
|
77
|
+
name: "IapConsumptionRequest",
|
|
78
|
+
keyField: "transactionId",
|
|
79
|
+
cursors: { request: "requestSignedDate", outcome: "outcomeSignedDate" },
|
|
80
|
+
expect: "insert",
|
|
81
|
+
mergeExcluded: [
|
|
82
|
+
"transactionId",
|
|
83
|
+
// Owned by this SDK: set when it answers Apple, and guarded separately
|
|
84
|
+
// so two workers cannot both answer.
|
|
85
|
+
"respondedAt",
|
|
86
|
+
"response",
|
|
87
|
+
],
|
|
88
|
+
oldestWins: ["receivedAt"],
|
|
89
|
+
heavyFields: ["response"],
|
|
90
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The store, implemented over Base44 entities.
|
|
3
|
+
*
|
|
4
|
+
* The only file that touches the entities API, and the only one that knows
|
|
5
|
+
* about its gaps. Four of them shape everything here:
|
|
6
|
+
*
|
|
7
|
+
* 1. **No upsert.** So an insert-or-merge is two calls, and the order is
|
|
8
|
+
* chosen per entity by which outcome is likelier.
|
|
9
|
+
* 2. **No unique constraint.** So two writes can both create a row for one
|
|
10
|
+
* key. Reads collapse duplicates instead of assuming they cannot happen.
|
|
11
|
+
* 3. **No compare-and-swap.** So `updateMany`'s query is used as the guard —
|
|
12
|
+
* it is evaluated server-side in one call, which is what makes newest-wins
|
|
13
|
+
* safe under concurrency. A plain update by id is banned: it is an
|
|
14
|
+
* unconditional overwrite and would lose the newer of two racing payloads.
|
|
15
|
+
* 4. **`updated: 0` is ambiguous** between "no such row" and "the guard
|
|
16
|
+
* rejected it", so telling them apart costs an extra read.
|
|
17
|
+
*
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
import type { EntitiesModule } from "../../modules/entities.types.js";
|
|
21
|
+
import { type Clock } from "../runtime/clock.js";
|
|
22
|
+
import type { IapStore, IapStoreMode } from "./store.types.js";
|
|
23
|
+
/** Inputs to {@link createEntitiesStore}. */
|
|
24
|
+
export interface CreateEntitiesStoreOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Returns the entities module to write through.
|
|
27
|
+
*
|
|
28
|
+
* A getter rather than a value because it must be the **service-role**
|
|
29
|
+
* module — ingestion writes rows on behalf of a user whose own permissions
|
|
30
|
+
* would not allow it — and reaching for that throws when the client was
|
|
31
|
+
* built without service-role credentials. Deferring it keeps constructing an
|
|
32
|
+
* IAP client free of I/O and free of throwing, so the failure surfaces on
|
|
33
|
+
* the first write with a message that says what is missing.
|
|
34
|
+
*/
|
|
35
|
+
readonly getEntities: () => EntitiesModule;
|
|
36
|
+
/** How rows are addressed. Defaults to `"query-guard"`. */
|
|
37
|
+
readonly mode?: IapStoreMode;
|
|
38
|
+
/** The clock, for tests. */
|
|
39
|
+
readonly clock?: Clock;
|
|
40
|
+
}
|
|
41
|
+
export declare function createEntitiesStore(options: CreateEntitiesStoreOptions): IapStore;
|
|
42
|
+
/** The clock this store reads, exposed so callers stamp rows consistently. */
|
|
43
|
+
export declare function storeClock(options: CreateEntitiesStoreOptions): Clock;
|