@baukit/purchases-core 0.0.0-stage → 0.12.1
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/LICENSE +21 -0
- package/README.md +36 -2
- package/package.json +64 -4
- package/src/entitlement.ts +39 -0
- package/src/errors.ts +26 -0
- package/src/flow.test.ts +532 -0
- package/src/flow.ts +252 -0
- package/src/index.ts +5 -0
- package/src/noop.ts +16 -0
- package/src/port.ts +40 -0
- package/src/react.test.ts +78 -0
- package/src/react.ts +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Koss
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@baukit/purchases-core`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A store-neutral purchase flow for Baukit mobile apps. It defines the `PurchasesPort` that a store adapter implements, a no-op port for builds without store keys, and a `PurchaseFlow` that gates features on the entitlement the product backend verified. It never reads store entitlements. Schlüsselbund owns entitlements, so a store receipt grants nothing until the refreshed ticket says so.
|
|
4
|
+
|
|
5
|
+
The package has no Expo, React Native or RevenueCat imports. `@baukit/purchases-revenuecat` is the RevenueCat adapter.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {
|
|
9
|
+
PurchaseFlow,
|
|
10
|
+
createNoopPurchasesPort,
|
|
11
|
+
entitlementFromTicket,
|
|
12
|
+
} from '@baukit/purchases-core';
|
|
13
|
+
|
|
14
|
+
const flow = new PurchaseFlow({
|
|
15
|
+
port: createNoopPurchasesPort(),
|
|
16
|
+
backend: {
|
|
17
|
+
refreshEntitlement: async () => entitlementFromTicket(await api.refreshEntitlementTicket()),
|
|
18
|
+
creditBalance: () => api.creditBalance(),
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
await flow.identify(suiteSubject);
|
|
23
|
+
const { current } = await flow.offerings();
|
|
24
|
+
const outcome = await flow.purchase(current!.packages[0]!);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- `identify(suiteSubject)` must finish before `purchase`, `restore` or `purchaseCreditPack`. Without it they reject with `not_identified`.
|
|
28
|
+
- `signOut()` clears the state and calls the port's `reset`.
|
|
29
|
+
- `purchase` returns `granted` once the backend serves an entitlement with a newer revision, or `pending` after `refreshAttempts` reads (default 5, 2 seconds apart).
|
|
30
|
+
- `restore` returns `granted` or `unchanged`.
|
|
31
|
+
- `purchaseCreditPack` accepts only `one_time` packages and returns `credited` once the credit balance revision advances, or `pending`.
|
|
32
|
+
- Only one purchase runs at a time. A second one rejects with `busy`.
|
|
33
|
+
- Failures are `PurchaseError` with `code` `cancelled`, `pending`, `network`, `store`, `unavailable`, `not_identified`, `identity_changed`, `subject_mismatch`, `invalid_subject`, `not_credit_pack` or `busy`.
|
|
34
|
+
|
|
35
|
+
`@baukit/purchases-core/react` has `PurchasesProvider`, `usePurchaseFlow`, `usePurchaseState`, `useEntitlement` and `useFeature(key)`.
|
|
36
|
+
|
|
37
|
+
Read Baukit's `docs/platform/mobile-purchases.md` for the full wiring.
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/purchases-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.12.1",
|
|
4
|
+
"description": "Store-neutral mobile purchases: a purchases port, a no-op client, a purchase flow that waits for suite identity and the refreshed entitlement, and feature-key gating hooks.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Patrick Koss",
|
|
7
|
+
"homepage": "https://github.com/PatrickKoss/baukit#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/PatrickKoss/baukit.git",
|
|
11
|
+
"directory": "typescript/packages/purchases-core"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/PatrickKoss/baukit/issues"
|
|
15
|
+
},
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=24.0.0"
|
|
22
|
+
},
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./react": {
|
|
31
|
+
"types": "./dist/react.d.ts",
|
|
32
|
+
"import": "./dist/react.js",
|
|
33
|
+
"default": "./dist/react.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"src",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsc -p tsconfig.json",
|
|
44
|
+
"prepare": "pnpm run build",
|
|
45
|
+
"test": "tsc -p tsconfig.test.json && vitest run --config ../../vitest.config.ts && node ../../scripts/test-packed-exports.mjs",
|
|
46
|
+
"lint": "eslint src --max-warnings=0",
|
|
47
|
+
"format:check": "prettier --check src package.json tsconfig.json tsconfig.test.json"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@testing-library/react": "16.3.3",
|
|
51
|
+
"@types/react": "19.3.0",
|
|
52
|
+
"jsdom": "30.1.1",
|
|
53
|
+
"react": "19.3.0",
|
|
54
|
+
"react-dom": "19.3.0",
|
|
55
|
+
"typescript": "6.0.3",
|
|
56
|
+
"vitest": "5.0.3"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"react": "^19.2.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"react": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Entitlement the product backend verified from the hub ticket. */
|
|
2
|
+
export interface VerifiedEntitlement {
|
|
3
|
+
readonly suiteSubject: string;
|
|
4
|
+
readonly tier: string;
|
|
5
|
+
readonly features: readonly string[];
|
|
6
|
+
readonly revision: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface CreditBalanceSnapshot {
|
|
10
|
+
readonly suiteSubject: string;
|
|
11
|
+
readonly available: number;
|
|
12
|
+
readonly revision: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Product backend calls. The backend refreshes the hub ticket with its service credentials. */
|
|
16
|
+
export interface EntitlementBackend {
|
|
17
|
+
refreshEntitlement(): Promise<VerifiedEntitlement | null>;
|
|
18
|
+
creditBalance?(): Promise<CreditBalanceSnapshot | null>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface TicketClaimsLike {
|
|
22
|
+
readonly sub: string;
|
|
23
|
+
readonly tier: string;
|
|
24
|
+
readonly features: readonly string[];
|
|
25
|
+
readonly rev: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function entitlementFromTicket(claims: TicketClaimsLike): VerifiedEntitlement {
|
|
29
|
+
return {
|
|
30
|
+
suiteSubject: claims.sub,
|
|
31
|
+
tier: claims.tier,
|
|
32
|
+
features: claims.features,
|
|
33
|
+
revision: claims.rev,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function hasFeature(entitlement: VerifiedEntitlement | null, key: string): boolean {
|
|
38
|
+
return entitlement?.features.includes(key) ?? false;
|
|
39
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type PurchaseErrorCode =
|
|
2
|
+
| 'cancelled'
|
|
3
|
+
| 'pending'
|
|
4
|
+
| 'network'
|
|
5
|
+
| 'store'
|
|
6
|
+
| 'unavailable'
|
|
7
|
+
| 'not_identified'
|
|
8
|
+
| 'identity_changed'
|
|
9
|
+
| 'subject_mismatch'
|
|
10
|
+
| 'invalid_subject'
|
|
11
|
+
| 'not_credit_pack'
|
|
12
|
+
| 'busy';
|
|
13
|
+
|
|
14
|
+
export class PurchaseError extends Error {
|
|
15
|
+
constructor(
|
|
16
|
+
readonly code: PurchaseErrorCode,
|
|
17
|
+
options?: { readonly cause?: unknown },
|
|
18
|
+
) {
|
|
19
|
+
super(code, options);
|
|
20
|
+
this.name = 'PurchaseError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isPurchaseError(error: unknown, code?: PurchaseErrorCode): error is PurchaseError {
|
|
25
|
+
return error instanceof PurchaseError && (code === undefined || error.code === code);
|
|
26
|
+
}
|
package/src/flow.test.ts
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
createNoopPurchasesPort,
|
|
5
|
+
entitlementFromTicket,
|
|
6
|
+
hasFeature,
|
|
7
|
+
PurchaseError,
|
|
8
|
+
PurchaseFlow,
|
|
9
|
+
selectOffering,
|
|
10
|
+
type CreditBalanceSnapshot,
|
|
11
|
+
type EntitlementBackend,
|
|
12
|
+
type PurchaseOfferings,
|
|
13
|
+
type PurchasePackage,
|
|
14
|
+
type PurchasesPort,
|
|
15
|
+
type VerifiedEntitlement,
|
|
16
|
+
} from './index.js';
|
|
17
|
+
|
|
18
|
+
const SUBJECT = 'suite|person-1';
|
|
19
|
+
const OTHER = 'suite|person-2';
|
|
20
|
+
|
|
21
|
+
const monthly: PurchasePackage = {
|
|
22
|
+
id: '$rc_monthly',
|
|
23
|
+
offeringId: 'default',
|
|
24
|
+
productId: 'app.product.monthly',
|
|
25
|
+
kind: 'subscription',
|
|
26
|
+
title: 'Premium',
|
|
27
|
+
description: 'Monthly',
|
|
28
|
+
priceLabel: '€4.99',
|
|
29
|
+
};
|
|
30
|
+
const pack: PurchasePackage = { ...monthly, id: 'pack_small', kind: 'one_time' };
|
|
31
|
+
|
|
32
|
+
function deferred() {
|
|
33
|
+
let resolve!: () => void;
|
|
34
|
+
const promise = new Promise<void>((onResolve) => {
|
|
35
|
+
resolve = onResolve;
|
|
36
|
+
});
|
|
37
|
+
return { promise, resolve };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
class FakePort implements PurchasesPort {
|
|
41
|
+
readonly calls: string[] = [];
|
|
42
|
+
identifyGate: Promise<void> | null = null;
|
|
43
|
+
purchaseError: Error | null = null;
|
|
44
|
+
onPurchase: () => void = () => undefined;
|
|
45
|
+
#listener: (() => void) | null = null;
|
|
46
|
+
|
|
47
|
+
async identify(subject: string): Promise<void> {
|
|
48
|
+
this.calls.push(`identify:${subject}`);
|
|
49
|
+
await this.identifyGate;
|
|
50
|
+
}
|
|
51
|
+
reset(): Promise<void> {
|
|
52
|
+
this.calls.push('reset');
|
|
53
|
+
return Promise.resolve();
|
|
54
|
+
}
|
|
55
|
+
offerings(): Promise<PurchaseOfferings> {
|
|
56
|
+
return Promise.resolve({
|
|
57
|
+
current: { id: 'default', packages: [monthly] },
|
|
58
|
+
all: { default: { id: 'default', packages: [monthly] } },
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
purchase(item: PurchasePackage): Promise<void> {
|
|
62
|
+
this.calls.push(`purchase:${item.id}`);
|
|
63
|
+
if (this.purchaseError !== null) return Promise.reject(this.purchaseError);
|
|
64
|
+
this.onPurchase();
|
|
65
|
+
return Promise.resolve();
|
|
66
|
+
}
|
|
67
|
+
restore(): Promise<void> {
|
|
68
|
+
this.calls.push('restore');
|
|
69
|
+
this.onPurchase();
|
|
70
|
+
return Promise.resolve();
|
|
71
|
+
}
|
|
72
|
+
onCustomerUpdate(listener: () => void): () => void {
|
|
73
|
+
this.#listener = listener;
|
|
74
|
+
return () => {
|
|
75
|
+
this.#listener = null;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
emitCustomerUpdate(): void {
|
|
79
|
+
this.#listener?.();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
class FakeBackend implements EntitlementBackend {
|
|
84
|
+
entitlement: VerifiedEntitlement | null = entitlement(1, []);
|
|
85
|
+
balance: CreditBalanceSnapshot | null = { suiteSubject: SUBJECT, available: 0, revision: 0 };
|
|
86
|
+
refreshes = 0;
|
|
87
|
+
failNext = false;
|
|
88
|
+
|
|
89
|
+
refreshEntitlement(): Promise<VerifiedEntitlement | null> {
|
|
90
|
+
this.refreshes += 1;
|
|
91
|
+
if (this.failNext) {
|
|
92
|
+
this.failNext = false;
|
|
93
|
+
return Promise.reject(new Error('backend offline'));
|
|
94
|
+
}
|
|
95
|
+
return Promise.resolve(this.entitlement);
|
|
96
|
+
}
|
|
97
|
+
creditBalance(): Promise<CreditBalanceSnapshot | null> {
|
|
98
|
+
return Promise.resolve(this.balance);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function entitlement(
|
|
103
|
+
revision: number,
|
|
104
|
+
features: string[],
|
|
105
|
+
suiteSubject = SUBJECT,
|
|
106
|
+
): VerifiedEntitlement {
|
|
107
|
+
return { suiteSubject, tier: features.length ? 'premium' : 'free', features, revision };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function setup(attempts = 3) {
|
|
111
|
+
const port = new FakePort();
|
|
112
|
+
const backend = new FakeBackend();
|
|
113
|
+
const sleep = vi.fn(() => Promise.resolve());
|
|
114
|
+
const flow = new PurchaseFlow({ port, backend, refreshAttempts: attempts, sleep });
|
|
115
|
+
return { port, backend, sleep, flow };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
describe('PurchaseFlow identity', () => {
|
|
119
|
+
it('refuses to purchase before identify', async () => {
|
|
120
|
+
const { port, flow } = setup();
|
|
121
|
+
|
|
122
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'not_identified' });
|
|
123
|
+
await expect(flow.restore()).rejects.toMatchObject({ code: 'not_identified' });
|
|
124
|
+
expect(port.calls).toEqual([]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('refuses to purchase while identify is still running', async () => {
|
|
128
|
+
const { port, flow } = setup();
|
|
129
|
+
const gate = deferred();
|
|
130
|
+
port.identifyGate = gate.promise;
|
|
131
|
+
|
|
132
|
+
const identifying = flow.identify(SUBJECT);
|
|
133
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'not_identified' });
|
|
134
|
+
gate.resolve();
|
|
135
|
+
await identifying;
|
|
136
|
+
|
|
137
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`]);
|
|
138
|
+
expect(flow.getState().suiteSubject).toBe(SUBJECT);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('stays signed out when the store rejects identify', async () => {
|
|
142
|
+
const { port, flow } = setup();
|
|
143
|
+
port.identify = () => Promise.reject(new PurchaseError('network'));
|
|
144
|
+
|
|
145
|
+
await expect(flow.identify(SUBJECT)).rejects.toMatchObject({ code: 'network' });
|
|
146
|
+
expect(flow.getState().suiteSubject).toBeNull();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('rejects an empty subject', async () => {
|
|
150
|
+
const { port, flow } = setup();
|
|
151
|
+
|
|
152
|
+
await expect(flow.identify(' ')).rejects.toMatchObject({ code: 'invalid_subject' });
|
|
153
|
+
expect(port.calls).toEqual([]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('drops an identify that a sign-out overtook', async () => {
|
|
157
|
+
const { port, flow } = setup();
|
|
158
|
+
const gate = deferred();
|
|
159
|
+
port.identifyGate = gate.promise;
|
|
160
|
+
|
|
161
|
+
const identifying = flow.identify(SUBJECT);
|
|
162
|
+
await flow.signOut();
|
|
163
|
+
gate.resolve();
|
|
164
|
+
|
|
165
|
+
await expect(identifying).rejects.toMatchObject({ code: 'identity_changed' });
|
|
166
|
+
expect(flow.getState().suiteSubject).toBeNull();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('resets the store and clears state on sign-out', async () => {
|
|
170
|
+
const { port, backend, flow } = setup();
|
|
171
|
+
backend.entitlement = entitlement(4, ['premium']);
|
|
172
|
+
await flow.identify(SUBJECT);
|
|
173
|
+
await flow.refreshEntitlement();
|
|
174
|
+
|
|
175
|
+
await flow.signOut();
|
|
176
|
+
|
|
177
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`, 'reset']);
|
|
178
|
+
expect(flow.getState()).toEqual({ suiteSubject: null, entitlement: null, creditBalance: null });
|
|
179
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'not_identified' });
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('rejects a purchase result when the user signed out meanwhile', async () => {
|
|
183
|
+
const { port, flow } = setup();
|
|
184
|
+
await flow.identify(SUBJECT);
|
|
185
|
+
port.onPurchase = () => {
|
|
186
|
+
void flow.signOut();
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'identity_changed' });
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
describe('PurchaseFlow purchase', () => {
|
|
194
|
+
it('identifies, purchases and shows the refreshed entitlement', async () => {
|
|
195
|
+
const { port, backend, flow, sleep } = setup();
|
|
196
|
+
await flow.identify(SUBJECT);
|
|
197
|
+
port.onPurchase = () => {
|
|
198
|
+
backend.entitlement = entitlement(2, ['premium']);
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const outcome = await flow.purchase(monthly);
|
|
202
|
+
|
|
203
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`, 'purchase:$rc_monthly']);
|
|
204
|
+
expect(outcome).toEqual({ status: 'granted', entitlement: entitlement(2, ['premium']) });
|
|
205
|
+
expect(flow.getState().entitlement).toEqual(entitlement(2, ['premium']));
|
|
206
|
+
expect(backend.refreshes).toBe(2);
|
|
207
|
+
expect(sleep).not.toHaveBeenCalled();
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('waits for the ticket revision that follows the purchase', async () => {
|
|
211
|
+
const { port, backend, flow, sleep } = setup(4);
|
|
212
|
+
await flow.identify(SUBJECT);
|
|
213
|
+
let reads = 0;
|
|
214
|
+
port.onPurchase = () => {
|
|
215
|
+
backend.refreshEntitlement = () => {
|
|
216
|
+
reads += 1;
|
|
217
|
+
if (reads === 1) return Promise.reject(new Error('backend offline'));
|
|
218
|
+
return Promise.resolve(reads < 3 ? entitlement(1, []) : entitlement(2, ['premium']));
|
|
219
|
+
};
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const outcome = await flow.purchase(monthly);
|
|
223
|
+
|
|
224
|
+
expect(outcome.status).toBe('granted');
|
|
225
|
+
expect(reads).toBe(3);
|
|
226
|
+
expect(sleep).toHaveBeenCalledTimes(2);
|
|
227
|
+
expect(sleep).toHaveBeenCalledWith(2_000);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('reports pending when the refreshed entitlement has not arrived', async () => {
|
|
231
|
+
const { backend, flow, sleep } = setup(3);
|
|
232
|
+
await flow.identify(SUBJECT);
|
|
233
|
+
|
|
234
|
+
const outcome = await flow.purchase(monthly);
|
|
235
|
+
|
|
236
|
+
expect(outcome).toEqual({ status: 'pending', entitlement: entitlement(1, []) });
|
|
237
|
+
expect(backend.refreshes).toBe(4);
|
|
238
|
+
expect(sleep).toHaveBeenCalledTimes(2);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it('reads a fresh baseline so a change that landed before the purchase does not grant it', async () => {
|
|
242
|
+
const { port, backend, flow } = setup(3);
|
|
243
|
+
await flow.identify(SUBJECT);
|
|
244
|
+
backend.entitlement = entitlement(2, ['extra']);
|
|
245
|
+
port.onPurchase = () => {
|
|
246
|
+
backend.entitlement = entitlement(3, ['premium']);
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
await expect(flow.purchase(monthly)).resolves.toEqual({
|
|
250
|
+
status: 'granted',
|
|
251
|
+
entitlement: entitlement(3, ['premium']),
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it('stays pending when only the change before the purchase arrives', async () => {
|
|
256
|
+
const { backend, flow } = setup(3);
|
|
257
|
+
await flow.identify(SUBJECT);
|
|
258
|
+
backend.entitlement = entitlement(2, ['extra']);
|
|
259
|
+
|
|
260
|
+
await expect(flow.purchase(monthly)).resolves.toEqual({
|
|
261
|
+
status: 'pending',
|
|
262
|
+
entitlement: entitlement(2, ['extra']),
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it('rejects before the store call when the baseline read fails', async () => {
|
|
267
|
+
const { port, backend, flow } = setup();
|
|
268
|
+
await flow.identify(SUBJECT);
|
|
269
|
+
backend.failNext = true;
|
|
270
|
+
|
|
271
|
+
await expect(flow.purchase(monthly)).rejects.toThrow('backend offline');
|
|
272
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`]);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it('passes a cancelled purchase through without refreshing', async () => {
|
|
276
|
+
const { port, backend, flow } = setup();
|
|
277
|
+
await flow.identify(SUBJECT);
|
|
278
|
+
port.purchaseError = new PurchaseError('cancelled');
|
|
279
|
+
|
|
280
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'cancelled' });
|
|
281
|
+
expect(backend.refreshes).toBe(1);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it('passes a store-pending purchase through', async () => {
|
|
285
|
+
const { port, flow } = setup();
|
|
286
|
+
await flow.identify(SUBJECT);
|
|
287
|
+
port.purchaseError = new PurchaseError('pending');
|
|
288
|
+
|
|
289
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'pending' });
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it('wraps unknown store failures', async () => {
|
|
293
|
+
const { port, flow } = setup();
|
|
294
|
+
await flow.identify(SUBJECT);
|
|
295
|
+
const cause = new Error('boom');
|
|
296
|
+
port.purchaseError = cause;
|
|
297
|
+
|
|
298
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'store', cause });
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it('refuses a second purchase while one runs', async () => {
|
|
302
|
+
const { port, flow } = setup(1);
|
|
303
|
+
await flow.identify(SUBJECT);
|
|
304
|
+
const gate = deferred();
|
|
305
|
+
port.purchase = async () => {
|
|
306
|
+
await gate.promise;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const first = flow.purchase(monthly);
|
|
310
|
+
await Promise.resolve();
|
|
311
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'busy' });
|
|
312
|
+
gate.resolve();
|
|
313
|
+
await expect(first).resolves.toMatchObject({ status: 'pending' });
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('rejects an entitlement for another subject', async () => {
|
|
317
|
+
const { backend, flow } = setup();
|
|
318
|
+
await flow.identify(SUBJECT);
|
|
319
|
+
backend.entitlement = entitlement(3, ['premium'], OTHER);
|
|
320
|
+
|
|
321
|
+
await expect(flow.refreshEntitlement()).rejects.toMatchObject({ code: 'subject_mismatch' });
|
|
322
|
+
expect(flow.getState().entitlement).toBeNull();
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it('keeps a newer entitlement over a late older one', async () => {
|
|
326
|
+
const { backend, flow } = setup();
|
|
327
|
+
await flow.identify(SUBJECT);
|
|
328
|
+
backend.entitlement = entitlement(5, ['premium']);
|
|
329
|
+
await flow.refreshEntitlement();
|
|
330
|
+
backend.entitlement = entitlement(4, []);
|
|
331
|
+
|
|
332
|
+
await expect(flow.refreshEntitlement()).resolves.toEqual(entitlement(5, ['premium']));
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it('restores and reports unchanged when nothing new arrives', async () => {
|
|
336
|
+
const { port, backend, flow } = setup(2);
|
|
337
|
+
await flow.identify(SUBJECT);
|
|
338
|
+
|
|
339
|
+
await expect(flow.restore()).resolves.toEqual({
|
|
340
|
+
status: 'unchanged',
|
|
341
|
+
entitlement: entitlement(1, []),
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
port.onPurchase = () => {
|
|
345
|
+
backend.entitlement = entitlement(2, ['premium']);
|
|
346
|
+
};
|
|
347
|
+
await expect(flow.restore()).resolves.toEqual({
|
|
348
|
+
status: 'granted',
|
|
349
|
+
entitlement: entitlement(2, ['premium']),
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
it('refreshes the entitlement on a customer update', async () => {
|
|
354
|
+
const { port, backend, flow } = setup();
|
|
355
|
+
port.emitCustomerUpdate();
|
|
356
|
+
expect(backend.refreshes).toBe(0);
|
|
357
|
+
await flow.identify(SUBJECT);
|
|
358
|
+
backend.entitlement = entitlement(2, ['premium']);
|
|
359
|
+
|
|
360
|
+
port.emitCustomerUpdate();
|
|
361
|
+
await vi.waitFor(() => {
|
|
362
|
+
expect(flow.getState().entitlement?.revision).toBe(2);
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
backend.failNext = true;
|
|
366
|
+
port.emitCustomerUpdate();
|
|
367
|
+
await vi.waitFor(() => {
|
|
368
|
+
expect(backend.refreshes).toBe(2);
|
|
369
|
+
});
|
|
370
|
+
flow.dispose();
|
|
371
|
+
port.emitCustomerUpdate();
|
|
372
|
+
expect(backend.refreshes).toBe(2);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it('notifies subscribers until they unsubscribe', async () => {
|
|
376
|
+
const { flow } = setup();
|
|
377
|
+
const listener = vi.fn();
|
|
378
|
+
const unsubscribe = flow.subscribe(listener);
|
|
379
|
+
|
|
380
|
+
await flow.identify(SUBJECT);
|
|
381
|
+
unsubscribe();
|
|
382
|
+
await flow.refreshEntitlement();
|
|
383
|
+
|
|
384
|
+
expect(listener).toHaveBeenCalledTimes(2);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
describe('PurchaseFlow credit packs', () => {
|
|
389
|
+
it('purchases a pack and reports the credited balance', async () => {
|
|
390
|
+
const { port, backend, flow } = setup();
|
|
391
|
+
await flow.identify(SUBJECT);
|
|
392
|
+
port.onPurchase = () => {
|
|
393
|
+
backend.balance = { suiteSubject: SUBJECT, available: 1_000, revision: 1 };
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
const outcome = await flow.purchaseCreditPack(pack);
|
|
397
|
+
|
|
398
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`, 'purchase:pack_small']);
|
|
399
|
+
expect(outcome).toEqual({
|
|
400
|
+
status: 'credited',
|
|
401
|
+
balance: { suiteSubject: SUBJECT, available: 1_000, revision: 1 },
|
|
402
|
+
});
|
|
403
|
+
expect(flow.getState().creditBalance?.available).toBe(1_000);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it('reports a pack as pending until the balance revision moves', async () => {
|
|
407
|
+
const { flow } = setup(2);
|
|
408
|
+
await flow.identify(SUBJECT);
|
|
409
|
+
|
|
410
|
+
await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
|
|
411
|
+
status: 'pending',
|
|
412
|
+
balance: { suiteSubject: SUBJECT, available: 0, revision: 0 },
|
|
413
|
+
});
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it('reads a fresh balance baseline before buying a pack', async () => {
|
|
417
|
+
const { port, backend, flow } = setup(3);
|
|
418
|
+
await flow.identify(SUBJECT);
|
|
419
|
+
await flow.refreshCreditBalance();
|
|
420
|
+
backend.balance = { suiteSubject: SUBJECT, available: 500, revision: 1 };
|
|
421
|
+
port.onPurchase = () => {
|
|
422
|
+
backend.balance = { suiteSubject: SUBJECT, available: 1_500, revision: 2 };
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
|
|
426
|
+
status: 'credited',
|
|
427
|
+
balance: { suiteSubject: SUBJECT, available: 1_500, revision: 2 },
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
it('keeps a pack pending when only the earlier balance change arrives', async () => {
|
|
432
|
+
const { backend, flow } = setup(3);
|
|
433
|
+
await flow.identify(SUBJECT);
|
|
434
|
+
await flow.refreshCreditBalance();
|
|
435
|
+
backend.balance = { suiteSubject: SUBJECT, available: 500, revision: 1 };
|
|
436
|
+
|
|
437
|
+
await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
|
|
438
|
+
status: 'pending',
|
|
439
|
+
balance: { suiteSubject: SUBJECT, available: 500, revision: 1 },
|
|
440
|
+
});
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
it('rejects a pack before the store call when the balance read fails', async () => {
|
|
444
|
+
const { port, backend, flow } = setup();
|
|
445
|
+
await flow.identify(SUBJECT);
|
|
446
|
+
backend.creditBalance = () => Promise.reject(new Error('backend offline'));
|
|
447
|
+
|
|
448
|
+
await expect(flow.purchaseCreditPack(pack)).rejects.toThrow('backend offline');
|
|
449
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`]);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it('treats a missing balance as no revision yet', async () => {
|
|
453
|
+
const { port, backend, flow } = setup(1);
|
|
454
|
+
await flow.identify(SUBJECT);
|
|
455
|
+
backend.balance = null;
|
|
456
|
+
port.onPurchase = () => {
|
|
457
|
+
backend.balance = { suiteSubject: SUBJECT, available: 3_000, revision: 0 };
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
await expect(flow.purchaseCreditPack(pack)).resolves.toMatchObject({ status: 'credited' });
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it('refuses subscriptions and packs without identity or a balance source', async () => {
|
|
464
|
+
const port = new FakePort();
|
|
465
|
+
const flow = new PurchaseFlow({
|
|
466
|
+
port,
|
|
467
|
+
backend: { refreshEntitlement: () => Promise.resolve(null) },
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
await expect(flow.purchaseCreditPack(monthly)).rejects.toMatchObject({
|
|
471
|
+
code: 'not_credit_pack',
|
|
472
|
+
});
|
|
473
|
+
await expect(flow.purchaseCreditPack(pack)).rejects.toMatchObject({ code: 'not_identified' });
|
|
474
|
+
await flow.identify(SUBJECT);
|
|
475
|
+
await expect(flow.purchaseCreditPack(pack)).rejects.toMatchObject({ code: 'unavailable' });
|
|
476
|
+
expect(port.calls).toEqual([`identify:${SUBJECT}`]);
|
|
477
|
+
});
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
describe('no-op purchases', () => {
|
|
481
|
+
it('identifies, sells nothing and keeps gating on the backend entitlement', async () => {
|
|
482
|
+
const backend = new FakeBackend();
|
|
483
|
+
backend.entitlement = entitlement(3, ['premium']);
|
|
484
|
+
const flow = new PurchaseFlow({ port: createNoopPurchasesPort(), backend });
|
|
485
|
+
|
|
486
|
+
await flow.identify(SUBJECT);
|
|
487
|
+
await flow.refreshEntitlement();
|
|
488
|
+
await expect(flow.offerings()).resolves.toEqual({ current: null, all: {} });
|
|
489
|
+
await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'unavailable' });
|
|
490
|
+
await expect(flow.restore()).rejects.toMatchObject({ code: 'unavailable' });
|
|
491
|
+
expect(hasFeature(flow.getState().entitlement, 'premium')).toBe(true);
|
|
492
|
+
await flow.signOut();
|
|
493
|
+
expect(flow.getState().entitlement).toBeNull();
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
describe('helpers', () => {
|
|
498
|
+
it('selects the configured offering or the current one', async () => {
|
|
499
|
+
const offerings = await new FakePort().offerings();
|
|
500
|
+
|
|
501
|
+
expect(selectOffering(offerings)?.id).toBe('default');
|
|
502
|
+
expect(selectOffering(offerings, 'default')?.id).toBe('default');
|
|
503
|
+
expect(selectOffering(offerings, 'missing')).toBeNull();
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
it('maps verified ticket claims and gates on feature keys', () => {
|
|
507
|
+
const verified = entitlementFromTicket({
|
|
508
|
+
sub: SUBJECT,
|
|
509
|
+
tier: 'premium',
|
|
510
|
+
features: ['export'],
|
|
511
|
+
rev: 7,
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
expect(verified).toEqual({
|
|
515
|
+
suiteSubject: SUBJECT,
|
|
516
|
+
tier: 'premium',
|
|
517
|
+
features: ['export'],
|
|
518
|
+
revision: 7,
|
|
519
|
+
});
|
|
520
|
+
expect(hasFeature(verified, 'export')).toBe(true);
|
|
521
|
+
expect(hasFeature(verified, 'sync')).toBe(false);
|
|
522
|
+
expect(hasFeature(null, 'export')).toBe(false);
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it('names its errors', () => {
|
|
526
|
+
const error = new PurchaseError('network');
|
|
527
|
+
|
|
528
|
+
expect(error).toBeInstanceOf(Error);
|
|
529
|
+
expect(error.name).toBe('PurchaseError');
|
|
530
|
+
expect(error.message).toBe('network');
|
|
531
|
+
});
|
|
532
|
+
});
|
package/src/flow.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CreditBalanceSnapshot,
|
|
3
|
+
EntitlementBackend,
|
|
4
|
+
VerifiedEntitlement,
|
|
5
|
+
} from './entitlement.js';
|
|
6
|
+
import { isPurchaseError, PurchaseError } from './errors.js';
|
|
7
|
+
import type { PurchaseOfferings, PurchasePackage, PurchasesPort } from './port.js';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_REFRESH_ATTEMPTS = 5;
|
|
10
|
+
export const DEFAULT_REFRESH_INTERVAL_MS = 2_000;
|
|
11
|
+
const NO_REVISION = -1;
|
|
12
|
+
|
|
13
|
+
export interface PurchaseState {
|
|
14
|
+
readonly suiteSubject: string | null;
|
|
15
|
+
readonly entitlement: VerifiedEntitlement | null;
|
|
16
|
+
readonly creditBalance: CreditBalanceSnapshot | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type PurchaseOutcome =
|
|
20
|
+
| { readonly status: 'granted'; readonly entitlement: VerifiedEntitlement }
|
|
21
|
+
| { readonly status: 'pending'; readonly entitlement: VerifiedEntitlement | null };
|
|
22
|
+
|
|
23
|
+
export type RestoreOutcome =
|
|
24
|
+
| { readonly status: 'granted'; readonly entitlement: VerifiedEntitlement }
|
|
25
|
+
| { readonly status: 'unchanged'; readonly entitlement: VerifiedEntitlement | null };
|
|
26
|
+
|
|
27
|
+
export type CreditPackOutcome =
|
|
28
|
+
| { readonly status: 'credited'; readonly balance: CreditBalanceSnapshot }
|
|
29
|
+
| { readonly status: 'pending'; readonly balance: CreditBalanceSnapshot | null };
|
|
30
|
+
|
|
31
|
+
export interface PurchaseFlowOptions {
|
|
32
|
+
readonly port: PurchasesPort;
|
|
33
|
+
readonly backend: EntitlementBackend;
|
|
34
|
+
/** Backend reads after a purchase before the outcome is reported as pending. */
|
|
35
|
+
readonly refreshAttempts?: number;
|
|
36
|
+
readonly refreshIntervalMs?: number;
|
|
37
|
+
readonly sleep?: (milliseconds: number) => Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Identity {
|
|
41
|
+
readonly generation: number;
|
|
42
|
+
readonly suiteSubject: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface Revisioned {
|
|
46
|
+
readonly revision: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const SIGNED_OUT: PurchaseState = { suiteSubject: null, entitlement: null, creditBalance: null };
|
|
50
|
+
|
|
51
|
+
function wait(milliseconds: number): Promise<void> {
|
|
52
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function storeError(error: unknown): PurchaseError {
|
|
56
|
+
return isPurchaseError(error) ? error : new PurchaseError('store', { cause: error });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class PurchaseFlow {
|
|
60
|
+
readonly #port: PurchasesPort;
|
|
61
|
+
readonly #backend: EntitlementBackend;
|
|
62
|
+
readonly #attempts: number;
|
|
63
|
+
readonly #interval: number;
|
|
64
|
+
readonly #sleep: (milliseconds: number) => Promise<void>;
|
|
65
|
+
readonly #listeners = new Set<() => void>();
|
|
66
|
+
readonly #stopCustomerUpdates: () => void;
|
|
67
|
+
#state: PurchaseState = SIGNED_OUT;
|
|
68
|
+
#generation = 0;
|
|
69
|
+
#busy = false;
|
|
70
|
+
|
|
71
|
+
constructor(options: PurchaseFlowOptions) {
|
|
72
|
+
this.#port = options.port;
|
|
73
|
+
this.#backend = options.backend;
|
|
74
|
+
this.#attempts = Math.max(1, options.refreshAttempts ?? DEFAULT_REFRESH_ATTEMPTS);
|
|
75
|
+
this.#interval = options.refreshIntervalMs ?? DEFAULT_REFRESH_INTERVAL_MS;
|
|
76
|
+
this.#sleep = options.sleep ?? wait;
|
|
77
|
+
this.#stopCustomerUpdates = this.#port.onCustomerUpdate(() => {
|
|
78
|
+
this.#refreshQuietly();
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
readonly getState = (): PurchaseState => this.#state;
|
|
83
|
+
|
|
84
|
+
readonly subscribe = (listener: () => void): (() => void) => {
|
|
85
|
+
this.#listeners.add(listener);
|
|
86
|
+
return () => {
|
|
87
|
+
this.#listeners.delete(listener);
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Purchases stay refused until the store has finished identifying this suite subject. */
|
|
92
|
+
async identify(suiteSubject: string): Promise<void> {
|
|
93
|
+
if (suiteSubject.trim() === '') throw new PurchaseError('invalid_subject');
|
|
94
|
+
const generation = this.#restart();
|
|
95
|
+
await this.#port.identify(suiteSubject);
|
|
96
|
+
this.#assertGeneration(generation);
|
|
97
|
+
this.#setState({ ...SIGNED_OUT, suiteSubject });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async signOut(): Promise<void> {
|
|
101
|
+
this.#restart();
|
|
102
|
+
await this.#port.reset();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
offerings(): Promise<PurchaseOfferings> {
|
|
106
|
+
return this.#port.offerings();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async refreshEntitlement(): Promise<VerifiedEntitlement | null> {
|
|
110
|
+
const identity = this.#identity();
|
|
111
|
+
const entitlement = await this.#backend.refreshEntitlement();
|
|
112
|
+
this.#accept(identity, entitlement, 'entitlement');
|
|
113
|
+
return this.#state.entitlement;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async refreshCreditBalance(): Promise<CreditBalanceSnapshot | null> {
|
|
117
|
+
const identity = this.#identity();
|
|
118
|
+
const read = this.#backend.creditBalance?.bind(this.#backend);
|
|
119
|
+
if (read === undefined) throw new PurchaseError('unavailable');
|
|
120
|
+
const balance = await read();
|
|
121
|
+
this.#accept(identity, balance, 'creditBalance');
|
|
122
|
+
return this.#state.creditBalance;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
purchase(item: PurchasePackage): Promise<PurchaseOutcome> {
|
|
126
|
+
return this.#exclusive(async (identity) => {
|
|
127
|
+
const baseline = await this.#entitlementBaseline();
|
|
128
|
+
await this.#storeCall(identity, () => this.#port.purchase(item));
|
|
129
|
+
const entitlement = await this.#poll(identity, baseline, () => this.refreshEntitlement());
|
|
130
|
+
return entitlement
|
|
131
|
+
? { status: 'granted', entitlement }
|
|
132
|
+
: { status: 'pending', entitlement: this.#state.entitlement };
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
restore(): Promise<RestoreOutcome> {
|
|
137
|
+
return this.#exclusive(async (identity) => {
|
|
138
|
+
const baseline = await this.#entitlementBaseline();
|
|
139
|
+
await this.#storeCall(identity, () => this.#port.restore());
|
|
140
|
+
const entitlement = await this.#poll(identity, baseline, () => this.refreshEntitlement());
|
|
141
|
+
return entitlement
|
|
142
|
+
? { status: 'granted', entitlement }
|
|
143
|
+
: { status: 'unchanged', entitlement: this.#state.entitlement };
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
purchaseCreditPack(item: PurchasePackage): Promise<CreditPackOutcome> {
|
|
148
|
+
if (item.kind !== 'one_time') return Promise.reject(new PurchaseError('not_credit_pack'));
|
|
149
|
+
return this.#exclusive(async (identity) => {
|
|
150
|
+
const baseline = (await this.refreshCreditBalance())?.revision;
|
|
151
|
+
await this.#storeCall(identity, () => this.#port.purchase(item));
|
|
152
|
+
const balance = await this.#poll(identity, baseline ?? NO_REVISION, () =>
|
|
153
|
+
this.refreshCreditBalance(),
|
|
154
|
+
);
|
|
155
|
+
return balance
|
|
156
|
+
? { status: 'credited', balance }
|
|
157
|
+
: { status: 'pending', balance: this.#state.creditBalance };
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
dispose(): void {
|
|
162
|
+
this.#stopCustomerUpdates();
|
|
163
|
+
this.#listeners.clear();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async #entitlementBaseline(): Promise<number> {
|
|
167
|
+
const entitlement = await this.refreshEntitlement();
|
|
168
|
+
return entitlement?.revision ?? NO_REVISION;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async #storeCall(identity: Identity, call: () => Promise<void>): Promise<void> {
|
|
172
|
+
try {
|
|
173
|
+
await call();
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw storeError(error);
|
|
176
|
+
}
|
|
177
|
+
this.#assertGeneration(identity.generation);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async #poll<T extends Revisioned>(
|
|
181
|
+
identity: Identity,
|
|
182
|
+
baseline: number,
|
|
183
|
+
read: () => Promise<T | null>,
|
|
184
|
+
): Promise<T | null> {
|
|
185
|
+
for (let attempt = 0; attempt < this.#attempts; attempt += 1) {
|
|
186
|
+
if (attempt > 0) await this.#sleep(this.#interval);
|
|
187
|
+
this.#assertGeneration(identity.generation);
|
|
188
|
+
const value = await this.#readTolerantly(read);
|
|
189
|
+
if (value !== null && value.revision > baseline) return value;
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async #readTolerantly<T>(read: () => Promise<T | null>): Promise<T | null> {
|
|
195
|
+
try {
|
|
196
|
+
return await read();
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (isPurchaseError(error)) throw error;
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async #exclusive<T>(operation: (identity: Identity) => Promise<T>): Promise<T> {
|
|
204
|
+
const identity = this.#identity();
|
|
205
|
+
if (this.#busy) throw new PurchaseError('busy');
|
|
206
|
+
this.#busy = true;
|
|
207
|
+
try {
|
|
208
|
+
return await operation(identity);
|
|
209
|
+
} finally {
|
|
210
|
+
this.#busy = false;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
#accept<K extends 'entitlement' | 'creditBalance'>(
|
|
215
|
+
identity: Identity,
|
|
216
|
+
value: PurchaseState[K],
|
|
217
|
+
key: K,
|
|
218
|
+
): void {
|
|
219
|
+
this.#assertGeneration(identity.generation);
|
|
220
|
+
if (value === null) return;
|
|
221
|
+
if (value.suiteSubject !== identity.suiteSubject) throw new PurchaseError('subject_mismatch');
|
|
222
|
+
const current = this.#state[key];
|
|
223
|
+
if (current !== null && value.revision < current.revision) return;
|
|
224
|
+
this.#setState({ ...this.#state, [key]: value });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
#identity(): Identity {
|
|
228
|
+
const { suiteSubject } = this.#state;
|
|
229
|
+
if (suiteSubject === null) throw new PurchaseError('not_identified');
|
|
230
|
+
return { generation: this.#generation, suiteSubject };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
#restart(): number {
|
|
234
|
+
this.#generation += 1;
|
|
235
|
+
this.#setState(SIGNED_OUT);
|
|
236
|
+
return this.#generation;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
#assertGeneration(generation: number): void {
|
|
240
|
+
if (generation !== this.#generation) throw new PurchaseError('identity_changed');
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
#refreshQuietly(): void {
|
|
244
|
+
if (this.#state.suiteSubject === null) return;
|
|
245
|
+
this.refreshEntitlement().catch(() => undefined);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
#setState(state: PurchaseState): void {
|
|
249
|
+
this.#state = state;
|
|
250
|
+
for (const listener of this.#listeners) listener();
|
|
251
|
+
}
|
|
252
|
+
}
|
package/src/index.ts
ADDED
package/src/noop.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { PurchaseError } from './errors.js';
|
|
2
|
+
import type { PurchaseOfferings, PurchasesPort } from './port.js';
|
|
3
|
+
|
|
4
|
+
const EMPTY_OFFERINGS: PurchaseOfferings = { current: null, all: {} };
|
|
5
|
+
|
|
6
|
+
/** Port for builds without store keys: identity succeeds, nothing is for sale. */
|
|
7
|
+
export function createNoopPurchasesPort(): PurchasesPort {
|
|
8
|
+
return {
|
|
9
|
+
identify: () => Promise.resolve(),
|
|
10
|
+
reset: () => Promise.resolve(),
|
|
11
|
+
offerings: () => Promise.resolve(EMPTY_OFFERINGS),
|
|
12
|
+
purchase: () => Promise.reject(new PurchaseError('unavailable')),
|
|
13
|
+
restore: () => Promise.reject(new PurchaseError('unavailable')),
|
|
14
|
+
onCustomerUpdate: () => () => undefined,
|
|
15
|
+
};
|
|
16
|
+
}
|
package/src/port.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type PurchaseProductKind = 'subscription' | 'one_time';
|
|
2
|
+
|
|
3
|
+
export interface PurchasePackage {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly offeringId: string;
|
|
6
|
+
readonly productId: string;
|
|
7
|
+
readonly kind: PurchaseProductKind;
|
|
8
|
+
readonly title: string;
|
|
9
|
+
readonly description: string;
|
|
10
|
+
readonly priceLabel: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PurchaseOffering {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly packages: readonly PurchasePackage[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PurchaseOfferings {
|
|
19
|
+
readonly current: PurchaseOffering | null;
|
|
20
|
+
readonly all: Readonly<Record<string, PurchaseOffering>>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Store boundary. Implementations throw `PurchaseError` with a store-neutral code. */
|
|
24
|
+
export interface PurchasesPort {
|
|
25
|
+
identify(suiteSubject: string): Promise<void>;
|
|
26
|
+
reset(): Promise<void>;
|
|
27
|
+
offerings(): Promise<PurchaseOfferings>;
|
|
28
|
+
purchase(item: PurchasePackage): Promise<void>;
|
|
29
|
+
restore(): Promise<void>;
|
|
30
|
+
onCustomerUpdate(listener: () => void): () => void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Returns the configured offering when it exists, otherwise the store's current offering. */
|
|
34
|
+
export function selectOffering(
|
|
35
|
+
offerings: PurchaseOfferings,
|
|
36
|
+
configuredId?: string,
|
|
37
|
+
): PurchaseOffering | null {
|
|
38
|
+
if (configuredId) return offerings.all[configuredId] ?? null;
|
|
39
|
+
return offerings.current;
|
|
40
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act, cleanup, renderHook } from '@testing-library/react';
|
|
3
|
+
import { createElement, type ReactNode } from 'react';
|
|
4
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { createNoopPurchasesPort, PurchaseFlow, type VerifiedEntitlement } from './index.js';
|
|
7
|
+
import {
|
|
8
|
+
PurchasesProvider,
|
|
9
|
+
useEntitlement,
|
|
10
|
+
useFeature,
|
|
11
|
+
usePurchaseFlow,
|
|
12
|
+
usePurchaseState,
|
|
13
|
+
} from './react.js';
|
|
14
|
+
|
|
15
|
+
const SUBJECT = 'suite|person-1';
|
|
16
|
+
|
|
17
|
+
afterEach(() => {
|
|
18
|
+
cleanup();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
function setup() {
|
|
22
|
+
let current: VerifiedEntitlement | null = null;
|
|
23
|
+
const flow = new PurchaseFlow({
|
|
24
|
+
port: createNoopPurchasesPort(),
|
|
25
|
+
backend: { refreshEntitlement: () => Promise.resolve(current) },
|
|
26
|
+
});
|
|
27
|
+
const wrapper = ({ children }: { children: ReactNode }) =>
|
|
28
|
+
createElement(PurchasesProvider, { flow }, children);
|
|
29
|
+
const grant = (features: string[], revision: number) => {
|
|
30
|
+
current = { suiteSubject: SUBJECT, tier: 'premium', features, revision };
|
|
31
|
+
};
|
|
32
|
+
return { flow, wrapper, grant };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('purchase hooks', () => {
|
|
36
|
+
it('gates on the refreshed entitlement feature keys', async () => {
|
|
37
|
+
const { flow, wrapper, grant } = setup();
|
|
38
|
+
const view = renderHook(
|
|
39
|
+
() => ({ exports: useFeature('export'), entitlement: useEntitlement() }),
|
|
40
|
+
{
|
|
41
|
+
wrapper,
|
|
42
|
+
},
|
|
43
|
+
);
|
|
44
|
+
expect(view.result.current.exports).toBe(false);
|
|
45
|
+
|
|
46
|
+
await act(async () => {
|
|
47
|
+
await flow.identify(SUBJECT);
|
|
48
|
+
grant(['export'], 2);
|
|
49
|
+
await flow.refreshEntitlement();
|
|
50
|
+
});
|
|
51
|
+
expect(view.result.current.exports).toBe(true);
|
|
52
|
+
expect(view.result.current.entitlement?.revision).toBe(2);
|
|
53
|
+
|
|
54
|
+
await act(async () => {
|
|
55
|
+
await flow.signOut();
|
|
56
|
+
});
|
|
57
|
+
expect(view.result.current.exports).toBe(false);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('exposes the flow and its state', async () => {
|
|
61
|
+
const { flow, wrapper } = setup();
|
|
62
|
+
const view = renderHook(() => ({ flow: usePurchaseFlow(), state: usePurchaseState() }), {
|
|
63
|
+
wrapper,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
expect(view.result.current.flow).toBe(flow);
|
|
67
|
+
await act(async () => {
|
|
68
|
+
await flow.identify(SUBJECT);
|
|
69
|
+
});
|
|
70
|
+
expect(view.result.current.state.suiteSubject).toBe(SUBJECT);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('requires a provider', () => {
|
|
74
|
+
expect(() => renderHook(() => usePurchaseFlow())).toThrow(
|
|
75
|
+
'usePurchaseFlow requires a PurchasesProvider',
|
|
76
|
+
);
|
|
77
|
+
});
|
|
78
|
+
});
|
package/src/react.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, useSyncExternalStore } from 'react';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
import { hasFeature, type VerifiedEntitlement } from './entitlement.js';
|
|
5
|
+
import type { PurchaseFlow, PurchaseState } from './flow.js';
|
|
6
|
+
|
|
7
|
+
const PurchaseFlowContext = createContext<PurchaseFlow | null>(null);
|
|
8
|
+
|
|
9
|
+
export interface PurchasesProviderProps {
|
|
10
|
+
readonly flow: PurchaseFlow;
|
|
11
|
+
readonly children?: ReactNode;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function PurchasesProvider({ flow, children }: PurchasesProviderProps): ReactNode {
|
|
15
|
+
return createElement(PurchaseFlowContext.Provider, { value: flow }, children);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function usePurchaseFlow(): PurchaseFlow {
|
|
19
|
+
const flow = useContext(PurchaseFlowContext);
|
|
20
|
+
if (flow === null) throw new Error('usePurchaseFlow requires a PurchasesProvider');
|
|
21
|
+
return flow;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function usePurchaseState(): PurchaseState {
|
|
25
|
+
const flow = usePurchaseFlow();
|
|
26
|
+
return useSyncExternalStore(flow.subscribe, flow.getState, flow.getState);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function useEntitlement(): VerifiedEntitlement | null {
|
|
30
|
+
return usePurchaseState().entitlement;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** True only when the backend-verified entitlement grants the feature key. */
|
|
34
|
+
export function useFeature(key: string): boolean {
|
|
35
|
+
return hasFeature(useEntitlement(), key);
|
|
36
|
+
}
|