@akira-io/billing-js 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +274 -0
- package/dist/checkout.cjs +10 -0
- package/dist/checkout.cjs.map +1 -0
- package/dist/checkout.d.cts +3 -0
- package/dist/checkout.d.ts +3 -0
- package/dist/checkout.js +8 -0
- package/dist/checkout.js.map +1 -0
- package/dist/client-DpOXhuxx.d.cts +141 -0
- package/dist/client-DpOXhuxx.d.ts +141 -0
- package/dist/client.cjs +179 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +1 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +176 -0
- package/dist/client.js.map +1 -0
- package/dist/downloads.cjs +51 -0
- package/dist/downloads.cjs.map +1 -0
- package/dist/downloads.d.cts +34 -0
- package/dist/downloads.d.ts +34 -0
- package/dist/downloads.js +46 -0
- package/dist/downloads.js.map +1 -0
- package/dist/helpers.cjs +116 -0
- package/dist/helpers.cjs.map +1 -0
- package/dist/helpers.d.cts +55 -0
- package/dist/helpers.d.ts +55 -0
- package/dist/helpers.js +109 -0
- package/dist/helpers.js.map +1 -0
- package/dist/index.cjs +439 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +416 -0
- package/dist/index.js.map +1 -0
- package/dist/pricing.cjs +104 -0
- package/dist/pricing.cjs.map +1 -0
- package/dist/pricing.d.cts +15 -0
- package/dist/pricing.d.ts +15 -0
- package/dist/pricing.js +101 -0
- package/dist/pricing.js.map +1 -0
- package/dist/react.cjs +219 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +39 -0
- package/dist/react.d.ts +39 -0
- package/dist/react.js +215 -0
- package/dist/react.js.map +1 -0
- package/dist/types-CH4Vkivj.d.cts +59 -0
- package/dist/types-CH4Vkivj.d.ts +59 -0
- package/dist/vue.cjs +218 -0
- package/dist/vue.cjs.map +1 -0
- package/dist/vue.d.cts +32 -0
- package/dist/vue.d.ts +32 -0
- package/dist/vue.js +214 -0
- package/dist/vue.js.map +1 -0
- package/package.json +113 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// src/signature.ts
|
|
2
|
+
var HEADER_PRODUCT = "X-Akira-Product";
|
|
3
|
+
var HEADER_TIMESTAMP = "X-Akira-Timestamp";
|
|
4
|
+
var HEADER_NONCE = "X-Akira-Nonce";
|
|
5
|
+
var HEADER_SIGNATURE = "X-Akira-Signature";
|
|
6
|
+
async function sha256Hex(bytes) {
|
|
7
|
+
const digest = await getSubtle().digest("SHA-256", bytes);
|
|
8
|
+
return bufferToHex(new Uint8Array(digest));
|
|
9
|
+
}
|
|
10
|
+
function getSubtle() {
|
|
11
|
+
const subtle = globalThis.crypto?.subtle;
|
|
12
|
+
if (!subtle) {
|
|
13
|
+
throw new Error("Web Crypto SubtleCrypto API is not available in this runtime.");
|
|
14
|
+
}
|
|
15
|
+
return subtle;
|
|
16
|
+
}
|
|
17
|
+
function bufferToHex(buffer) {
|
|
18
|
+
let out = "";
|
|
19
|
+
for (const byte of buffer) {
|
|
20
|
+
out += byte.toString(16).padStart(2, "0");
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function newNonce() {
|
|
25
|
+
const buf = new Uint8Array(16);
|
|
26
|
+
if (globalThis.crypto?.getRandomValues) {
|
|
27
|
+
globalThis.crypto.getRandomValues(buf);
|
|
28
|
+
} else {
|
|
29
|
+
for (let i = 0; i < buf.length; i += 1) {
|
|
30
|
+
buf[i] = Math.floor(Math.random() * 256);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return bufferToHex(buf);
|
|
34
|
+
}
|
|
35
|
+
async function canonical(productSlug, timestamp, nonce, method, path, body) {
|
|
36
|
+
const bodyHash = await sha256Hex(body);
|
|
37
|
+
return `${productSlug}
|
|
38
|
+
${timestamp}
|
|
39
|
+
${nonce}
|
|
40
|
+
${method.toUpperCase()}
|
|
41
|
+
${path}
|
|
42
|
+
${bodyHash}`;
|
|
43
|
+
}
|
|
44
|
+
async function sign(productSecret, canonicalString) {
|
|
45
|
+
const subtle = getSubtle();
|
|
46
|
+
const keyData = new TextEncoder().encode(productSecret);
|
|
47
|
+
const key = await subtle.importKey(
|
|
48
|
+
"raw",
|
|
49
|
+
keyData,
|
|
50
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
51
|
+
false,
|
|
52
|
+
["sign"]
|
|
53
|
+
);
|
|
54
|
+
const sig = await subtle.sign("HMAC", key, new TextEncoder().encode(canonicalString));
|
|
55
|
+
return bufferToHex(new Uint8Array(sig));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/client.ts
|
|
59
|
+
var BillingApiError = class extends Error {
|
|
60
|
+
status;
|
|
61
|
+
code;
|
|
62
|
+
constructor(status, code) {
|
|
63
|
+
super(`billing api ${status}: ${code}`);
|
|
64
|
+
this.status = status;
|
|
65
|
+
this.code = code;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var BillingClient = class {
|
|
69
|
+
baseUrl;
|
|
70
|
+
productSlug;
|
|
71
|
+
productSecret;
|
|
72
|
+
customerToken;
|
|
73
|
+
fetcher;
|
|
74
|
+
constructor(config) {
|
|
75
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
76
|
+
this.productSlug = config.productSlug;
|
|
77
|
+
this.productSecret = config.productSecret;
|
|
78
|
+
this.customerToken = config.customerToken;
|
|
79
|
+
this.fetcher = config.fetcher ?? globalThis.fetch;
|
|
80
|
+
if (!this.fetcher) {
|
|
81
|
+
throw new Error("No fetch implementation available. Pass `fetcher` or use a runtime with global fetch.");
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
setCustomerToken(token) {
|
|
85
|
+
this.customerToken = token;
|
|
86
|
+
}
|
|
87
|
+
async requestOtp(payload) {
|
|
88
|
+
await this.signed("POST", "/api/auth/customer/otp/request", payload);
|
|
89
|
+
}
|
|
90
|
+
async verifyOtp(payload) {
|
|
91
|
+
const res = await this.signed("POST", "/api/auth/customer/otp/verify", payload);
|
|
92
|
+
this.setCustomerToken(res.access_token);
|
|
93
|
+
return res;
|
|
94
|
+
}
|
|
95
|
+
async customerMe() {
|
|
96
|
+
return this.signed("GET", "/api/me");
|
|
97
|
+
}
|
|
98
|
+
async licenseCheck(payload) {
|
|
99
|
+
return this.signed("POST", "/api/licenses/check", payload);
|
|
100
|
+
}
|
|
101
|
+
async licenseActivate(payload) {
|
|
102
|
+
return this.signed("POST", "/api/licenses/activate", payload);
|
|
103
|
+
}
|
|
104
|
+
async licenseRefresh(payload) {
|
|
105
|
+
return this.signed("POST", "/api/licenses/refresh", payload);
|
|
106
|
+
}
|
|
107
|
+
async entitlements() {
|
|
108
|
+
return this.signed("GET", "/api/me/entitlements");
|
|
109
|
+
}
|
|
110
|
+
async billingPortal(returnUrl) {
|
|
111
|
+
const path = `/api/billing/portal?return_url=${encodeURIComponent(returnUrl)}`;
|
|
112
|
+
return this.signed("GET", path);
|
|
113
|
+
}
|
|
114
|
+
async trackUsage(payload) {
|
|
115
|
+
return this.signed("POST", "/api/me/usage", payload);
|
|
116
|
+
}
|
|
117
|
+
async publicLicenseKeys() {
|
|
118
|
+
return this.unsigned("GET", "/api/v1/license-keys/public");
|
|
119
|
+
}
|
|
120
|
+
async signed(method, path, body) {
|
|
121
|
+
const bodyBytes = body === void 0 ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(body));
|
|
122
|
+
const timestamp = Math.floor(Date.now() / 1e3);
|
|
123
|
+
const nonce = newNonce();
|
|
124
|
+
const canonicalString = await canonical(this.productSlug, timestamp, nonce, method, path, bodyBytes);
|
|
125
|
+
const signature = await sign(this.productSecret, canonicalString);
|
|
126
|
+
const headers = {
|
|
127
|
+
Accept: "application/json",
|
|
128
|
+
[HEADER_PRODUCT]: this.productSlug,
|
|
129
|
+
[HEADER_TIMESTAMP]: String(timestamp),
|
|
130
|
+
[HEADER_NONCE]: nonce,
|
|
131
|
+
[HEADER_SIGNATURE]: signature
|
|
132
|
+
};
|
|
133
|
+
if (bodyBytes.length > 0) headers["Content-Type"] = "application/json";
|
|
134
|
+
if (this.customerToken) headers.Authorization = `Bearer ${this.customerToken}`;
|
|
135
|
+
const res = await this.fetcher(`${this.baseUrl}${path}`, {
|
|
136
|
+
method,
|
|
137
|
+
headers,
|
|
138
|
+
body: bodyBytes.length > 0 ? bodyBytes : void 0
|
|
139
|
+
});
|
|
140
|
+
return this.parseResponse(res);
|
|
141
|
+
}
|
|
142
|
+
async unsigned(method, path, body) {
|
|
143
|
+
const headers = { Accept: "application/json" };
|
|
144
|
+
let bodyInit;
|
|
145
|
+
if (body !== void 0) {
|
|
146
|
+
headers["Content-Type"] = "application/json";
|
|
147
|
+
bodyInit = JSON.stringify(body);
|
|
148
|
+
}
|
|
149
|
+
const res = await this.fetcher(`${this.baseUrl}${path}`, { method, headers, body: bodyInit });
|
|
150
|
+
return this.parseResponse(res);
|
|
151
|
+
}
|
|
152
|
+
async parseResponse(res) {
|
|
153
|
+
if (!res.ok) {
|
|
154
|
+
let code = "";
|
|
155
|
+
try {
|
|
156
|
+
const parsed = await res.json();
|
|
157
|
+
code = parsed?.error ?? "";
|
|
158
|
+
} catch {
|
|
159
|
+
try {
|
|
160
|
+
code = await res.text();
|
|
161
|
+
} catch {
|
|
162
|
+
code = "";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
throw new BillingApiError(res.status, code);
|
|
166
|
+
}
|
|
167
|
+
if (res.status === 204) {
|
|
168
|
+
return void 0;
|
|
169
|
+
}
|
|
170
|
+
return await res.json();
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// src/pricing.ts
|
|
175
|
+
var INTERVAL_SUFFIXES = ["_monthly", "_yearly", "_month", "_year", "_one_time"];
|
|
176
|
+
function tierKeyFromPlanKey(planKey) {
|
|
177
|
+
for (const suf of INTERVAL_SUFFIXES) {
|
|
178
|
+
if (planKey.endsWith(suf)) {
|
|
179
|
+
return planKey.slice(0, -suf.length);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return planKey;
|
|
183
|
+
}
|
|
184
|
+
function titleCase(s) {
|
|
185
|
+
return s.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
186
|
+
}
|
|
187
|
+
function emptyPayload(productKey) {
|
|
188
|
+
return { product: productKey, betaActive: false, tiers: [] };
|
|
189
|
+
}
|
|
190
|
+
function shapeFromApi(payload, config) {
|
|
191
|
+
const meta = config.tierMeta ?? {};
|
|
192
|
+
const monthsFree = config.yearlyMonthsFree ?? 2;
|
|
193
|
+
const tiersMap = /* @__PURE__ */ new Map();
|
|
194
|
+
for (const plan of payload.plans) {
|
|
195
|
+
const tierKey = tierKeyFromPlanKey(plan.key);
|
|
196
|
+
const m = meta[tierKey];
|
|
197
|
+
if (!tiersMap.has(tierKey)) {
|
|
198
|
+
tiersMap.set(tierKey, {
|
|
199
|
+
key: tierKey,
|
|
200
|
+
name: m?.label ?? titleCase(tierKey),
|
|
201
|
+
tagline: m?.tagline ?? plan.description ?? "",
|
|
202
|
+
highlighted: m?.highlighted ?? false,
|
|
203
|
+
monthly: null,
|
|
204
|
+
yearly: null,
|
|
205
|
+
oneTime: null,
|
|
206
|
+
isComingSoon: false,
|
|
207
|
+
features: plan.features.map(
|
|
208
|
+
(f) => ({ key: f.key, name: f.name, description: f.description })
|
|
209
|
+
)
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
const tier = tiersMap.get(tierKey);
|
|
213
|
+
if (plan.is_coming_soon === true) {
|
|
214
|
+
tier.isComingSoon = true;
|
|
215
|
+
}
|
|
216
|
+
if (tier.features.length === 0 && plan.features.length > 0) {
|
|
217
|
+
tier.features = plan.features.map((f) => ({ key: f.key, name: f.name, description: f.description }));
|
|
218
|
+
}
|
|
219
|
+
if (plan.billing_interval === "month" && plan.amount !== null && plan.currency !== null) {
|
|
220
|
+
tier.monthly = { amount: plan.amount, currency: plan.currency, planKey: plan.key };
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (plan.billing_interval === "year" && plan.amount !== null && plan.currency !== null) {
|
|
224
|
+
tier.yearly = { amount: plan.amount, currency: plan.currency, monthsFree, planKey: plan.key };
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (plan.billing_interval === null) {
|
|
228
|
+
const amount = plan.amount ?? 0;
|
|
229
|
+
const currency = plan.currency ?? "eur";
|
|
230
|
+
if (amount === 0) {
|
|
231
|
+
tier.monthly = { amount: 0, currency, planKey: plan.key };
|
|
232
|
+
} else {
|
|
233
|
+
tier.oneTime = { amount, currency, planKey: plan.key };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const tiers = Array.from(tiersMap.values()).sort((a, b) => {
|
|
238
|
+
const oa = meta[a.key]?.order ?? 999;
|
|
239
|
+
const ob = meta[b.key]?.order ?? 999;
|
|
240
|
+
return oa - ob;
|
|
241
|
+
});
|
|
242
|
+
return {
|
|
243
|
+
product: payload.product,
|
|
244
|
+
betaActive: payload.beta_active,
|
|
245
|
+
tiers
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
async function fetchPricing(config) {
|
|
249
|
+
const base = config.baseUrl?.replace(/\/$/, "");
|
|
250
|
+
if (!base) return emptyPayload(config.productKey);
|
|
251
|
+
const f = config.fetcher ?? globalThis.fetch;
|
|
252
|
+
if (!f) {
|
|
253
|
+
throw new Error("No fetch implementation available. Pass a fetcher in config or use Node 18+.");
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const res = await f(`${base}/api/v1/products/${config.productKey}/plans`, {
|
|
257
|
+
headers: { Accept: "application/json" }
|
|
258
|
+
});
|
|
259
|
+
if (!res.ok) return emptyPayload(config.productKey);
|
|
260
|
+
const data = await res.json();
|
|
261
|
+
return shapeFromApi(data, config);
|
|
262
|
+
} catch {
|
|
263
|
+
return emptyPayload(config.productKey);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function formatPrice(amountInCents, currency) {
|
|
267
|
+
const symbol = currency.toLowerCase() === "eur" ? "\u20AC" : currency.toUpperCase() + " ";
|
|
268
|
+
const major = (amountInCents / 100).toFixed(amountInCents % 100 === 0 ? 0 : 2);
|
|
269
|
+
return `${symbol}${major}`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/checkout.ts
|
|
273
|
+
function checkoutUrl(baseUrl, productKey, planKey) {
|
|
274
|
+
return `${baseUrl.replace(/\/$/, "")}/subscribe/${productKey}/${planKey}`;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/downloads.ts
|
|
278
|
+
function downloadUrl(config) {
|
|
279
|
+
const base = config.baseUrl.replace(/\/$/, "");
|
|
280
|
+
const path = `/api/v1/downloads/${config.product}/${config.channel}/${config.platform}`;
|
|
281
|
+
const params = new URLSearchParams();
|
|
282
|
+
for (const [k, v] of Object.entries(config.query ?? {})) {
|
|
283
|
+
if (v !== void 0 && v !== "") params.set(k, v);
|
|
284
|
+
}
|
|
285
|
+
const qs = params.toString();
|
|
286
|
+
return qs ? `${base}${path}?${qs}` : `${base}${path}`;
|
|
287
|
+
}
|
|
288
|
+
async function issueDownload(config) {
|
|
289
|
+
const f = config.fetcher ?? globalThis.fetch;
|
|
290
|
+
if (!f) {
|
|
291
|
+
throw new Error("No fetch implementation available. Pass a fetcher in config or use Node 18+.");
|
|
292
|
+
}
|
|
293
|
+
const url = downloadUrl(config);
|
|
294
|
+
const res = await f(url, { headers: { Accept: "application/json" } });
|
|
295
|
+
if (!res.ok) {
|
|
296
|
+
throw new Error(`download issue failed: HTTP ${res.status}`);
|
|
297
|
+
}
|
|
298
|
+
return await res.json();
|
|
299
|
+
}
|
|
300
|
+
function sendCompletionBeacon(beaconUrl) {
|
|
301
|
+
if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
|
|
302
|
+
navigator.sendBeacon(beaconUrl);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (typeof fetch !== "undefined") {
|
|
306
|
+
void fetch(beaconUrl, { method: "POST", keepalive: true }).catch(() => {
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async function triggerDownload(config) {
|
|
311
|
+
const issued = await issueDownload(config);
|
|
312
|
+
const delay = config.beaconDelayMs ?? 1500;
|
|
313
|
+
if (typeof window !== "undefined") {
|
|
314
|
+
window.location.href = issued.signedUrl;
|
|
315
|
+
setTimeout(() => sendCompletionBeacon(issued.beaconUrl), delay);
|
|
316
|
+
}
|
|
317
|
+
return issued;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/helpers.ts
|
|
321
|
+
function isFreeTier(tier) {
|
|
322
|
+
return tier.monthly?.amount === 0 && tier.yearly === null && tier.oneTime === null;
|
|
323
|
+
}
|
|
324
|
+
function isOneTimeTier(tier) {
|
|
325
|
+
return tier.oneTime !== null && tier.monthly === null;
|
|
326
|
+
}
|
|
327
|
+
function hasYearly(tier) {
|
|
328
|
+
return tier.yearly !== null && tier.monthly !== null;
|
|
329
|
+
}
|
|
330
|
+
function getCtaProps(tier, opts) {
|
|
331
|
+
const meta = opts.tierMeta;
|
|
332
|
+
const monthlyHref = tier.monthly ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.monthly.planKey) : null;
|
|
333
|
+
const yearlyHref = tier.yearly ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.yearly.planKey) : null;
|
|
334
|
+
const oneTimeHref = tier.oneTime ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.oneTime.planKey) : null;
|
|
335
|
+
if (tier.isComingSoon) {
|
|
336
|
+
return {
|
|
337
|
+
label: opts.comingSoonLabel ?? "Coming soon",
|
|
338
|
+
href: null,
|
|
339
|
+
disabled: true,
|
|
340
|
+
monthlyHref,
|
|
341
|
+
yearlyHref,
|
|
342
|
+
oneTimeHref
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
if (meta?.ctaHref) {
|
|
346
|
+
return {
|
|
347
|
+
label: meta.ctaLabel ?? "Get started",
|
|
348
|
+
href: meta.ctaHref,
|
|
349
|
+
disabled: false,
|
|
350
|
+
monthlyHref,
|
|
351
|
+
yearlyHref,
|
|
352
|
+
oneTimeHref
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
let primary;
|
|
356
|
+
let defaultLabel;
|
|
357
|
+
if (isFreeTier(tier)) {
|
|
358
|
+
primary = null;
|
|
359
|
+
defaultLabel = opts.freeLabel ?? "Get started";
|
|
360
|
+
} else if (isOneTimeTier(tier)) {
|
|
361
|
+
primary = oneTimeHref;
|
|
362
|
+
defaultLabel = opts.buyLabel ?? "Buy";
|
|
363
|
+
} else {
|
|
364
|
+
primary = opts.interval === "yearly" ? yearlyHref ?? monthlyHref : monthlyHref;
|
|
365
|
+
defaultLabel = opts.subscribeLabel ?? "Subscribe";
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
label: meta?.ctaLabel ?? defaultLabel,
|
|
369
|
+
href: primary,
|
|
370
|
+
disabled: false,
|
|
371
|
+
monthlyHref,
|
|
372
|
+
yearlyHref,
|
|
373
|
+
oneTimeHref
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function getActivePrice(tier, interval) {
|
|
377
|
+
if (interval === "yearly" && tier.yearly) {
|
|
378
|
+
return {
|
|
379
|
+
amount: formatPrice(tier.yearly.amount, tier.yearly.currency),
|
|
380
|
+
suffix: "/year",
|
|
381
|
+
raw: { amount: tier.yearly.amount, currency: tier.yearly.currency },
|
|
382
|
+
note: tier.yearly.monthsFree > 0 ? `${tier.yearly.monthsFree} months free` : void 0
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (interval === "oneTime" && tier.oneTime) {
|
|
386
|
+
return {
|
|
387
|
+
amount: formatPrice(tier.oneTime.amount, tier.oneTime.currency),
|
|
388
|
+
suffix: " one-time",
|
|
389
|
+
raw: { amount: tier.oneTime.amount, currency: tier.oneTime.currency }
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (tier.monthly) {
|
|
393
|
+
return {
|
|
394
|
+
amount: formatPrice(tier.monthly.amount, tier.monthly.currency),
|
|
395
|
+
suffix: "/month",
|
|
396
|
+
raw: { amount: tier.monthly.amount, currency: tier.monthly.currency }
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
if (tier.oneTime) {
|
|
400
|
+
return {
|
|
401
|
+
amount: formatPrice(tier.oneTime.amount, tier.oneTime.currency),
|
|
402
|
+
suffix: " one-time",
|
|
403
|
+
raw: { amount: tier.oneTime.amount, currency: tier.oneTime.currency }
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
return { amount: "\u2014", suffix: "", raw: null };
|
|
407
|
+
}
|
|
408
|
+
function defaultInterval(tiers) {
|
|
409
|
+
if (tiers.some(hasYearly)) return "monthly";
|
|
410
|
+
if (tiers.every((t) => t.monthly === null && t.oneTime !== null)) return "oneTime";
|
|
411
|
+
return "monthly";
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export { BillingApiError, BillingClient, HEADER_NONCE, HEADER_PRODUCT, HEADER_SIGNATURE, HEADER_TIMESTAMP, canonical, checkoutUrl, defaultInterval, downloadUrl, fetchPricing, formatPrice, getActivePrice, getCtaProps, hasYearly, isFreeTier, isOneTimeTier, issueDownload, newNonce, sendCompletionBeacon, sign, triggerDownload };
|
|
415
|
+
//# sourceMappingURL=index.js.map
|
|
416
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/signature.ts","../src/client.ts","../src/pricing.ts","../src/checkout.ts","../src/downloads.ts","../src/helpers.ts"],"names":[],"mappings":";AAAO,IAAM,cAAA,GAAiB;AACvB,IAAM,gBAAA,GAAmB;AACzB,IAAM,YAAA,GAAe;AACrB,IAAM,gBAAA,GAAmB;AAEhC,eAAe,UAAU,KAAA,E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,MAAA,EAAQ,QAAA;AAAA,MACR,GAAA,EAAK,EAAE,MAAA,EAAQ,IAAA,CAAK,QAAQ,MAAA,EAAQ,QAAA,EAAU,IAAA,CAAK,OAAA,CAAQ,QAAA;AAAS,KACxE;AAAA,EACJ;AAEA,EAAA,IAAI,KAAK,OAAA,EAAS;AACd,IAAA,OAAO;AAAA,MACH,QAAQ,WAAA,CAAY,IAAA,CAAK,QAAQ,MAAA,EAAQ,IAAA,CAAK,QAAQ,QAAQ,CAAA;AAAA,MAC9D,MAAA,EAAQ,WAAA;AAAA,MACR,GAAA,EAAK,EAAE,MAAA,EAAQ,IAAA,CAAK,QAAQ,MAAA,EAAQ,QAAA,EAAU,IAAA,CAAK,OAAA,CAAQ,QAAA;AAAS,KACxE;AAAA,EACJ;AAEA,EAAA,OAAO,EAAE,MAAA,EAAQ,QAAA,EAAK,MAAA,EAAQ,EAAA,EAAI,KAAK,IAAA,EAAK;AAChD;AAOO,SAAS,gBAAgB,KAAA,EAAmC;AAC/D,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA,EAAG,OAAO,SAAA;AAClC,EAAA,IAAI,KAAA,CAAM,KAAA,CAAM,CAAC,CAAA,KAAM,CAAA,CAAE,OAAA,KAAY,IAAA,IAAQ,CAAA,CAAE,OAAA,KAAY,IAAI,CAAA,EAAG,OAAO,SAAA;AACzE,EAAA,OAAO,SAAA;AACX","file":"index.js","sourcesContent":["export const HEADER_PRODUCT = 'X-Akira-Product';\nexport const HEADER_TIMESTAMP = 'X-Akira-Timestamp';\nexport const HEADER_NONCE = 'X-Akira-Nonce';\nexport const HEADER_SIGNATURE = 'X-Akira-Signature';\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n const digest = await getSubtle().digest('SHA-256', bytes as BufferSource);\n return bufferToHex(new Uint8Array(digest));\n}\n\nfunction getSubtle(): SubtleCrypto {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new Error('Web Crypto SubtleCrypto API is not available in this runtime.');\n }\n return subtle;\n}\n\nfunction bufferToHex(buffer: Uint8Array): string {\n let out = '';\n for (const byte of buffer) {\n out += byte.toString(16).padStart(2, '0');\n }\n return out;\n}\n\nexport function newNonce(): string {\n const buf = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(buf);\n } else {\n for (let i = 0; i < buf.length; i += 1) {\n buf[i] = Math.floor(Math.random() * 256);\n }\n }\n return bufferToHex(buf);\n}\n\nexport async function canonical(\n productSlug: string,\n timestamp: number,\n nonce: string,\n method: string,\n path: string,\n body: Uint8Array,\n): Promise<string> {\n const bodyHash = await sha256Hex(body);\n return `${productSlug}\\n${timestamp}\\n${nonce}\\n${method.toUpperCase()}\\n${path}\\n${bodyHash}`;\n}\n\nexport async function sign(productSecret: string, canonicalString: string): Promise<string> {\n const subtle = getSubtle();\n const keyData = new TextEncoder().encode(productSecret) as BufferSource;\n const key = await subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const sig = await subtle.sign('HMAC', key, new TextEncoder().encode(canonicalString) as BufferSource);\n return bufferToHex(new Uint8Array(sig));\n}\n","import {\n HEADER_NONCE,\n HEADER_PRODUCT,\n HEADER_SIGNATURE,\n HEADER_TIMESTAMP,\n canonical,\n newNonce,\n sign,\n} from './signature';\nimport type {\n BillingPortalResponse,\n Customer,\n EntitlementsResponse,\n LicenseActivatePayload,\n LicenseActivateResponse,\n LicenseCheckPayload,\n LicenseCheckResponse,\n LicensePublicKeysResponse,\n LicenseRefreshPayload,\n OtpRequestPayload,\n OtpVerifyPayload,\n OtpVerifyResponse,\n UsagePayload,\n UsageResponse,\n} from './client-types';\n\nexport interface BillingClientConfig {\n baseUrl: string;\n productSlug: string;\n productSecret: string;\n customerToken?: string;\n fetcher?: typeof fetch;\n}\n\nexport class BillingApiError extends Error {\n status: number;\n code: string;\n constructor(status: number, code: string) {\n super(`billing api ${status}: ${code}`);\n this.status = status;\n this.code = code;\n }\n}\n\nexport class BillingClient {\n private readonly baseUrl: string;\n private readonly productSlug: string;\n private readonly productSecret: string;\n private customerToken: string | undefined;\n private readonly fetcher: typeof fetch;\n\n constructor(config: BillingClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '');\n this.productSlug = config.productSlug;\n this.productSecret = config.productSecret;\n this.customerToken = config.customerToken;\n this.fetcher = config.fetcher ?? globalThis.fetch;\n if (!this.fetcher) {\n throw new Error('No fetch implementation available. Pass `fetcher` or use a runtime with global fetch.');\n }\n }\n\n setCustomerToken(token: string): void {\n this.customerToken = token;\n }\n\n async requestOtp(payload: OtpRequestPayload): Promise<void> {\n await this.signed('POST', '/api/auth/customer/otp/request', payload);\n }\n\n async verifyOtp(payload: OtpVerifyPayload): Promise<OtpVerifyResponse> {\n const res = await this.signed<OtpVerifyResponse>('POST', '/api/auth/customer/otp/verify', payload);\n this.setCustomerToken(res.access_token);\n return res;\n }\n\n async customerMe(): Promise<Customer> {\n return this.signed<Customer>('GET', '/api/me');\n }\n\n async licenseCheck(payload: LicenseCheckPayload): Promise<LicenseCheckResponse> {\n return this.signed<LicenseCheckResponse>('POST', '/api/licenses/check', payload);\n }\n\n async licenseActivate(payload: LicenseActivatePayload): Promise<LicenseActivateResponse> {\n return this.signed<LicenseActivateResponse>('POST', '/api/licenses/activate', payload);\n }\n\n async licenseRefresh(payload: LicenseRefreshPayload): Promise<LicenseActivateResponse> {\n return this.signed<LicenseActivateResponse>('POST', '/api/licenses/refresh', payload);\n }\n\n async entitlements(): Promise<EntitlementsResponse> {\n return this.signed<EntitlementsResponse>('GET', '/api/me/entitlements');\n }\n\n async billingPortal(returnUrl: string): Promise<BillingPortalResponse> {\n const path = `/api/billing/portal?return_url=${encodeURIComponent(returnUrl)}`;\n return this.signed<BillingPortalResponse>('GET', path);\n }\n\n async trackUsage(payload: UsagePayload): Promise<UsageResponse> {\n return this.signed<UsageResponse>('POST', '/api/me/usage', payload);\n }\n\n async publicLicenseKeys(): Promise<LicensePublicKeysResponse> {\n return this.unsigned<LicensePublicKeysResponse>('GET', '/api/v1/license-keys/public');\n }\n\n private async signed<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const bodyBytes = body === undefined ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(body));\n const timestamp = Math.floor(Date.now() / 1000);\n const nonce = newNonce();\n const canonicalString = await canonical(this.productSlug, timestamp, nonce, method, path, bodyBytes);\n const signature = await sign(this.productSecret, canonicalString);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n [HEADER_PRODUCT]: this.productSlug,\n [HEADER_TIMESTAMP]: String(timestamp),\n [HEADER_NONCE]: nonce,\n [HEADER_SIGNATURE]: signature,\n };\n if (bodyBytes.length > 0) headers['Content-Type'] = 'application/json';\n if (this.customerToken) headers.Authorization = `Bearer ${this.customerToken}`;\n\n const res = await this.fetcher(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: bodyBytes.length > 0 ? bodyBytes : undefined,\n });\n\n return this.parseResponse<T>(res);\n }\n\n private async unsigned<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n let bodyInit: BodyInit | undefined;\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n bodyInit = JSON.stringify(body);\n }\n\n const res = await this.fetcher(`${this.baseUrl}${path}`, { method, headers, body: bodyInit });\n return this.parseResponse<T>(res);\n }\n\n private async parseResponse<T>(res: Response): Promise<T> {\n if (!res.ok) {\n let code = '';\n try {\n const parsed = (await res.json()) as { error?: string };\n code = parsed?.error ?? '';\n } catch {\n try {\n code = await res.text();\n } catch {\n code = '';\n }\n }\n throw new BillingApiError(res.status, code);\n }\n\n if (res.status === 204) {\n return undefined as T;\n }\n\n return (await res.json()) as T;\n }\n}\n","import type {\n BillingInterval,\n PricingFeature,\n PricingPayload,\n PricingTier,\n TierMeta,\n} from './types';\n\nexport type FetchPricingConfig = {\n baseUrl: string;\n productKey: string;\n tierMeta?: Record<string, TierMeta>;\n yearlyMonthsFree?: number;\n /** Override the global fetch (e.g. Node 18+ or custom retry). */\n fetcher?: typeof fetch;\n};\n\ntype ApiFeature = {\n key: string;\n name: string;\n description: string | null;\n};\n\ntype ApiPlan = {\n key: string;\n name: string;\n description: string | null;\n amount: number | null;\n currency: string | null;\n billing_interval: BillingInterval | null;\n trial_period_days: number;\n is_coming_soon?: boolean;\n features: ApiFeature[];\n};\n\ntype ApiPayload = {\n product: string;\n name: string;\n description: string | null;\n beta_active: boolean;\n plans: ApiPlan[];\n};\n\nconst INTERVAL_SUFFIXES = ['_monthly', '_yearly', '_month', '_year', '_one_time'];\n\nfunction tierKeyFromPlanKey(planKey: string): string {\n for (const suf of INTERVAL_SUFFIXES) {\n if (planKey.endsWith(suf)) {\n return planKey.slice(0, -suf.length);\n }\n }\n return planKey;\n}\n\nfunction titleCase(s: string): string {\n return s.replace(/[_-]+/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\nfunction emptyPayload(productKey: string): PricingPayload {\n return { product: productKey, betaActive: false, tiers: [] };\n}\n\nfunction shapeFromApi(payload: ApiPayload, config: FetchPricingConfig): PricingPayload {\n const meta = config.tierMeta ?? {};\n const monthsFree = config.yearlyMonthsFree ?? 2;\n const tiersMap = new Map<string, PricingTier>();\n\n for (const plan of payload.plans) {\n const tierKey = tierKeyFromPlanKey(plan.key);\n const m = meta[tierKey];\n\n if (!tiersMap.has(tierKey)) {\n tiersMap.set(tierKey, {\n key: tierKey,\n name: m?.label ?? titleCase(tierKey),\n tagline: m?.tagline ?? plan.description ?? '',\n highlighted: m?.highlighted ?? false,\n monthly: null,\n yearly: null,\n oneTime: null,\n isComingSoon: false,\n features: plan.features.map(\n (f): PricingFeature => ({ key: f.key, name: f.name, description: f.description }),\n ),\n });\n }\n\n const tier = tiersMap.get(tierKey)!;\n\n if (plan.is_coming_soon === true) {\n tier.isComingSoon = true;\n }\n\n if (tier.features.length === 0 && plan.features.length > 0) {\n tier.features = plan.features.map((f) => ({ key: f.key, name: f.name, description: f.description }));\n }\n\n if (plan.billing_interval === 'month' && plan.amount !== null && plan.currency !== null) {\n tier.monthly = { amount: plan.amount, currency: plan.currency, planKey: plan.key };\n continue;\n }\n\n if (plan.billing_interval === 'year' && plan.amount !== null && plan.currency !== null) {\n tier.yearly = { amount: plan.amount, currency: plan.currency, monthsFree, planKey: plan.key };\n continue;\n }\n\n if (plan.billing_interval === null) {\n const amount = plan.amount ?? 0;\n const currency = plan.currency ?? 'eur';\n if (amount === 0) {\n tier.monthly = { amount: 0, currency, planKey: plan.key };\n } else {\n tier.oneTime = { amount, currency, planKey: plan.key };\n }\n }\n }\n\n const tiers = Array.from(tiersMap.values()).sort((a, b) => {\n const oa = meta[a.key]?.order ?? 999;\n const ob = meta[b.key]?.order ?? 999;\n return oa - ob;\n });\n\n return {\n product: payload.product,\n betaActive: payload.beta_active,\n tiers,\n };\n}\n\nexport async function fetchPricing(config: FetchPricingConfig): Promise<PricingPayload> {\n const base = config.baseUrl?.replace(/\\/$/, '');\n if (!base) return emptyPayload(config.productKey);\n\n const f = config.fetcher ?? globalThis.fetch;\n if (!f) {\n throw new Error('No fetch implementation available. Pass a fetcher in config or use Node 18+.');\n }\n\n try {\n const res = await f(`${base}/api/v1/products/${config.productKey}/plans`, {\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return emptyPayload(config.productKey);\n const data = (await res.json()) as ApiPayload;\n return shapeFromApi(data, config);\n } catch {\n return emptyPayload(config.productKey);\n }\n}\n\nexport function formatPrice(amountInCents: number, currency: string): string {\n const symbol = currency.toLowerCase() === 'eur' ? '€' : currency.toUpperCase() + ' ';\n const major = (amountInCents / 100).toFixed(amountInCents % 100 === 0 ? 0 : 2);\n return `${symbol}${major}`;\n}\n\nexport type { PricingFeature, PricingPayload, PricingTier, TierMeta };\n","export function checkoutUrl(baseUrl: string, productKey: string, planKey: string): string {\n return `${baseUrl.replace(/\\/$/, '')}/subscribe/${productKey}/${planKey}`;\n}\n","import type { AssetPlatform, IssuedDownload, ReleaseChannel } from './types';\n\nexport type DownloadConfig = {\n baseUrl: string;\n product: string;\n channel: ReleaseChannel;\n platform: AssetPlatform;\n /** Optional UTM + landing tracking. */\n query?: Record<string, string | undefined>;\n /** Delay before firing the completion beacon, ms. Default 1500. */\n beaconDelayMs?: number;\n fetcher?: typeof fetch;\n};\n\nexport function downloadUrl(config: Pick<DownloadConfig, 'baseUrl' | 'product' | 'channel' | 'platform' | 'query'>): string {\n const base = config.baseUrl.replace(/\\/$/, '');\n const path = `/api/v1/downloads/${config.product}/${config.channel}/${config.platform}`;\n const params = new URLSearchParams();\n for (const [k, v] of Object.entries(config.query ?? {})) {\n if (v !== undefined && v !== '') params.set(k, v);\n }\n const qs = params.toString();\n return qs ? `${base}${path}?${qs}` : `${base}${path}`;\n}\n\n/**\n * Issues a download via the billing API and returns the signed asset URL +\n * beacon URL without redirecting. Useful when you want full control of the\n * UX (e.g. fetch then trigger your own `<a download>` flow).\n */\nexport async function issueDownload(config: DownloadConfig): Promise<IssuedDownload> {\n const f = config.fetcher ?? globalThis.fetch;\n if (!f) {\n throw new Error('No fetch implementation available. Pass a fetcher in config or use Node 18+.');\n }\n\n const url = downloadUrl(config);\n const res = await f(url, { headers: { Accept: 'application/json' } });\n\n if (!res.ok) {\n throw new Error(`download issue failed: HTTP ${res.status}`);\n }\n\n return (await res.json()) as IssuedDownload;\n}\n\n/**\n * Fires the completion beacon for an issued download. Uses\n * `navigator.sendBeacon` when available (survives page navigation), falls\n * back to `fetch` with `keepalive: true`. Safe to call at unload time.\n */\nexport function sendCompletionBeacon(beaconUrl: string): void {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n navigator.sendBeacon(beaconUrl);\n return;\n }\n\n if (typeof fetch !== 'undefined') {\n void fetch(beaconUrl, { method: 'POST', keepalive: true }).catch(() => {});\n }\n}\n\n/**\n * One-shot helper for landing-page download CTAs: fetches a signed URL,\n * navigates the current tab to the asset, then schedules the completion\n * beacon. The function resolves once the navigation has been triggered.\n */\nexport async function triggerDownload(config: DownloadConfig): Promise<IssuedDownload> {\n const issued = await issueDownload(config);\n const delay = config.beaconDelayMs ?? 1500;\n\n if (typeof window !== 'undefined') {\n window.location.href = issued.signedUrl;\n setTimeout(() => sendCompletionBeacon(issued.beaconUrl), delay);\n }\n\n return issued;\n}\n","import { checkoutUrl } from './checkout';\nimport { formatPrice } from './pricing';\nimport type { PricingTier, TierMeta } from './types';\n\nexport type IntervalKey = 'monthly' | 'yearly' | 'oneTime';\n\nexport type CtaProps = {\n label: string;\n href: string | null;\n disabled: boolean;\n monthlyHref: string | null;\n yearlyHref: string | null;\n oneTimeHref: string | null;\n};\n\nexport type CtaOptions = {\n billingBaseUrl: string;\n productKey: string;\n tierMeta?: TierMeta;\n interval?: IntervalKey;\n freeLabel?: string;\n subscribeLabel?: string;\n buyLabel?: string;\n comingSoonLabel?: string;\n};\n\nexport function isFreeTier(tier: PricingTier): boolean {\n return tier.monthly?.amount === 0 && tier.yearly === null && tier.oneTime === null;\n}\n\nexport function isOneTimeTier(tier: PricingTier): boolean {\n return tier.oneTime !== null && tier.monthly === null;\n}\n\nexport function hasYearly(tier: PricingTier): boolean {\n return tier.yearly !== null && tier.monthly !== null;\n}\n\n/**\n * Resolves all CTA fields for a tier — label, primary href, per-interval\n * hrefs (so a UI toggle can hot-swap without re-deriving), and disabled\n * state for coming-soon plans. Replaces hand-rolled if/else trees in\n * landing pages.\n */\nexport function getCtaProps(tier: PricingTier, opts: CtaOptions): CtaProps {\n const meta = opts.tierMeta;\n const monthlyHref = tier.monthly\n ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.monthly.planKey)\n : null;\n const yearlyHref = tier.yearly\n ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.yearly.planKey)\n : null;\n const oneTimeHref = tier.oneTime\n ? checkoutUrl(opts.billingBaseUrl, opts.productKey, tier.oneTime.planKey)\n : null;\n\n if (tier.isComingSoon) {\n return {\n label: opts.comingSoonLabel ?? 'Coming soon',\n href: null,\n disabled: true,\n monthlyHref,\n yearlyHref,\n oneTimeHref,\n };\n }\n\n if (meta?.ctaHref) {\n return {\n label: meta.ctaLabel ?? 'Get started',\n href: meta.ctaHref,\n disabled: false,\n monthlyHref,\n yearlyHref,\n oneTimeHref,\n };\n }\n\n let primary: string | null;\n let defaultLabel: string;\n\n if (isFreeTier(tier)) {\n primary = null;\n defaultLabel = opts.freeLabel ?? 'Get started';\n } else if (isOneTimeTier(tier)) {\n primary = oneTimeHref;\n defaultLabel = opts.buyLabel ?? 'Buy';\n } else {\n primary = opts.interval === 'yearly' ? yearlyHref ?? monthlyHref : monthlyHref;\n defaultLabel = opts.subscribeLabel ?? 'Subscribe';\n }\n\n return {\n label: meta?.ctaLabel ?? defaultLabel,\n href: primary,\n disabled: false,\n monthlyHref,\n yearlyHref,\n oneTimeHref,\n };\n}\n\nexport type FormattedPrice = {\n amount: string;\n suffix: string;\n raw: { amount: number; currency: string } | null;\n note?: string;\n};\n\n/**\n * Returns the price + suffix to render for a tier given the active\n * interval. Falls back gracefully: a tier with only monthly always\n * shows monthly; a free tier shows €0; a one-time tier shows the amount\n * with a 'one-time' suffix.\n */\nexport function getActivePrice(tier: PricingTier, interval: IntervalKey): FormattedPrice {\n if (interval === 'yearly' && tier.yearly) {\n return {\n amount: formatPrice(tier.yearly.amount, tier.yearly.currency),\n suffix: '/year',\n raw: { amount: tier.yearly.amount, currency: tier.yearly.currency },\n note: tier.yearly.monthsFree > 0 ? `${tier.yearly.monthsFree} months free` : undefined,\n };\n }\n\n if (interval === 'oneTime' && tier.oneTime) {\n return {\n amount: formatPrice(tier.oneTime.amount, tier.oneTime.currency),\n suffix: ' one-time',\n raw: { amount: tier.oneTime.amount, currency: tier.oneTime.currency },\n };\n }\n\n if (tier.monthly) {\n return {\n amount: formatPrice(tier.monthly.amount, tier.monthly.currency),\n suffix: '/month',\n raw: { amount: tier.monthly.amount, currency: tier.monthly.currency },\n };\n }\n\n if (tier.oneTime) {\n return {\n amount: formatPrice(tier.oneTime.amount, tier.oneTime.currency),\n suffix: ' one-time',\n raw: { amount: tier.oneTime.amount, currency: tier.oneTime.currency },\n };\n }\n\n return { amount: '—', suffix: '', raw: null };\n}\n\n/**\n * Picks the natural default interval for a list of tiers: 'yearly' if\n * any tier has a yearly option, else 'monthly'. Useful as the initial\n * state for a billing-interval toggle.\n */\nexport function defaultInterval(tiers: PricingTier[]): IntervalKey {\n if (tiers.some(hasYearly)) return 'monthly';\n if (tiers.every((t) => t.monthly === null && t.oneTime !== null)) return 'oneTime';\n return 'monthly';\n}\n"]}
|
package/dist/pricing.cjs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/pricing.ts
|
|
4
|
+
var INTERVAL_SUFFIXES = ["_monthly", "_yearly", "_month", "_year", "_one_time"];
|
|
5
|
+
function tierKeyFromPlanKey(planKey) {
|
|
6
|
+
for (const suf of INTERVAL_SUFFIXES) {
|
|
7
|
+
if (planKey.endsWith(suf)) {
|
|
8
|
+
return planKey.slice(0, -suf.length);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return planKey;
|
|
12
|
+
}
|
|
13
|
+
function titleCase(s) {
|
|
14
|
+
return s.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
15
|
+
}
|
|
16
|
+
function emptyPayload(productKey) {
|
|
17
|
+
return { product: productKey, betaActive: false, tiers: [] };
|
|
18
|
+
}
|
|
19
|
+
function shapeFromApi(payload, config) {
|
|
20
|
+
const meta = config.tierMeta ?? {};
|
|
21
|
+
const monthsFree = config.yearlyMonthsFree ?? 2;
|
|
22
|
+
const tiersMap = /* @__PURE__ */ new Map();
|
|
23
|
+
for (const plan of payload.plans) {
|
|
24
|
+
const tierKey = tierKeyFromPlanKey(plan.key);
|
|
25
|
+
const m = meta[tierKey];
|
|
26
|
+
if (!tiersMap.has(tierKey)) {
|
|
27
|
+
tiersMap.set(tierKey, {
|
|
28
|
+
key: tierKey,
|
|
29
|
+
name: m?.label ?? titleCase(tierKey),
|
|
30
|
+
tagline: m?.tagline ?? plan.description ?? "",
|
|
31
|
+
highlighted: m?.highlighted ?? false,
|
|
32
|
+
monthly: null,
|
|
33
|
+
yearly: null,
|
|
34
|
+
oneTime: null,
|
|
35
|
+
isComingSoon: false,
|
|
36
|
+
features: plan.features.map(
|
|
37
|
+
(f) => ({ key: f.key, name: f.name, description: f.description })
|
|
38
|
+
)
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const tier = tiersMap.get(tierKey);
|
|
42
|
+
if (plan.is_coming_soon === true) {
|
|
43
|
+
tier.isComingSoon = true;
|
|
44
|
+
}
|
|
45
|
+
if (tier.features.length === 0 && plan.features.length > 0) {
|
|
46
|
+
tier.features = plan.features.map((f) => ({ key: f.key, name: f.name, description: f.description }));
|
|
47
|
+
}
|
|
48
|
+
if (plan.billing_interval === "month" && plan.amount !== null && plan.currency !== null) {
|
|
49
|
+
tier.monthly = { amount: plan.amount, currency: plan.currency, planKey: plan.key };
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (plan.billing_interval === "year" && plan.amount !== null && plan.currency !== null) {
|
|
53
|
+
tier.yearly = { amount: plan.amount, currency: plan.currency, monthsFree, planKey: plan.key };
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (plan.billing_interval === null) {
|
|
57
|
+
const amount = plan.amount ?? 0;
|
|
58
|
+
const currency = plan.currency ?? "eur";
|
|
59
|
+
if (amount === 0) {
|
|
60
|
+
tier.monthly = { amount: 0, currency, planKey: plan.key };
|
|
61
|
+
} else {
|
|
62
|
+
tier.oneTime = { amount, currency, planKey: plan.key };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const tiers = Array.from(tiersMap.values()).sort((a, b) => {
|
|
67
|
+
const oa = meta[a.key]?.order ?? 999;
|
|
68
|
+
const ob = meta[b.key]?.order ?? 999;
|
|
69
|
+
return oa - ob;
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
product: payload.product,
|
|
73
|
+
betaActive: payload.beta_active,
|
|
74
|
+
tiers
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
async function fetchPricing(config) {
|
|
78
|
+
const base = config.baseUrl?.replace(/\/$/, "");
|
|
79
|
+
if (!base) return emptyPayload(config.productKey);
|
|
80
|
+
const f = config.fetcher ?? globalThis.fetch;
|
|
81
|
+
if (!f) {
|
|
82
|
+
throw new Error("No fetch implementation available. Pass a fetcher in config or use Node 18+.");
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const res = await f(`${base}/api/v1/products/${config.productKey}/plans`, {
|
|
86
|
+
headers: { Accept: "application/json" }
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) return emptyPayload(config.productKey);
|
|
89
|
+
const data = await res.json();
|
|
90
|
+
return shapeFromApi(data, config);
|
|
91
|
+
} catch {
|
|
92
|
+
return emptyPayload(config.productKey);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function formatPrice(amountInCents, currency) {
|
|
96
|
+
const symbol = currency.toLowerCase() === "eur" ? "\u20AC" : currency.toUpperCase() + " ";
|
|
97
|
+
const major = (amountInCents / 100).toFixed(amountInCents % 100 === 0 ? 0 : 2);
|
|
98
|
+
return `${symbol}${major}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
exports.fetchPricing = fetchPricing;
|
|
102
|
+
exports.formatPrice = formatPrice;
|
|
103
|
+
//# sourceMappingURL=pricing.cjs.map
|
|
104
|
+
//# sourceMappingURL=pricing.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pricing.ts"],"names":[],"mappings":";;;AA2CA,IAAM,oBAAoB,CAAC,UAAA,EAAY,SAAA,EAAW,QAAA,EAAU,SAAS,WAAW,CAAA;AAEhF,SAAS,mBAAmB,OAAA,EAAyB;AACjD,EAAA,KAAA,MAAW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AA;AAC9C,EAAA,IAAI,CAAC,IAAA,EAAM,OAAO,YAAA,CAAa,OAAO,UAAU,CAAA;AAEhD,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,OAAA,IAAW,UAAA,CAAW,KAAA;AACvC,EAAA,IAAI,CAAC,CAAA,EAAG;AACJ,IAAA,MAAM,IAAI,MAAM,8EAA8E,CAAA;AAAA,EAClG;AAEA,EAAA,IAAI;AACA,IAAA,MAAM,GAAA,GAAM,MAAM,CAAA,CAAE,CAAA,EAAG,IAAI,CAAA,iBAAA,EAAoB,MAAA,CAAO,UAAU,CAAA,MAAA,CAAA,EAAU;AAAA,MACtE,OAAA,EAAS,EAAE,MAAA,EAAQ,kBAAA;AAAmB,KACzC,CAAA;AACD,IAAA,IAAI,CAAC,GAAA,CAAI,EAAA,EAAI,OAAO,YAAA,CAAa,OAAO,UAAU,CAAA;AAClD,IAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,EAAK;AAC7B,IAAA,OAAO,YAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EACpC,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,YAAA,CAAa,OAAO,UAAU,CAAA;AAAA,EACzC;AACJ;AAEO,SAAS,WAAA,CAAY,eAAuB,QAAA,EAA0B;AACzE,EAAA,MAAM,MAAA,GAAS,SAAS,WAAA,EAAY,KAAM,QAAQ,QAAA,GAAM,QAAA,CAAS,aAAY,GAAI,GAAA;AACjF,EAAA,MAAM,KAAA,GAAA,CAAS,gBAAgB,GAAA,EAAK,OAAA,CAAQ,gBAAgB,GAAA,KAAQ,CAAA,GAAI,IAAI,CAAC,CAAA;AAC7E,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,EAAG,KAAK,CAAA,CAAA;AAC5B","file":"pricing.cjs","sourcesContent":["import type {\n BillingInterval,\n PricingFeature,\n PricingPayload,\n PricingTier,\n TierMeta,\n} from './types';\n\nexport type FetchPricingConfig = {\n baseUrl: string;\n productKey: string;\n tierMeta?: Record<string, TierMeta>;\n yearlyMonthsFree?: number;\n /** Override the global fetch (e.g. Node 18+ or custom retry). */\n fetcher?: typeof fetch;\n};\n\ntype ApiFeature = {\n key: string;\n name: string;\n description: string | null;\n};\n\ntype ApiPlan = {\n key: string;\n name: string;\n description: string | null;\n amount: number | null;\n currency: string | null;\n billing_interval: BillingInterval | null;\n trial_period_days: number;\n is_coming_soon?: boolean;\n features: ApiFeature[];\n};\n\ntype ApiPayload = {\n product: string;\n name: string;\n description: string | null;\n beta_active: boolean;\n plans: ApiPlan[];\n};\n\nconst INTERVAL_SUFFIXES = ['_monthly', '_yearly', '_month', '_year', '_one_time'];\n\nfunction tierKeyFromPlanKey(planKey: string): string {\n for (const suf of INTERVAL_SUFFIXES) {\n if (planKey.endsWith(suf)) {\n return planKey.slice(0, -suf.length);\n }\n }\n return planKey;\n}\n\nfunction titleCase(s: string): string {\n return s.replace(/[_-]+/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\nfunction emptyPayload(productKey: string): PricingPayload {\n return { product: productKey, betaActive: false, tiers: [] };\n}\n\nfunction shapeFromApi(payload: ApiPayload, config: FetchPricingConfig): PricingPayload {\n const meta = config.tierMeta ?? {};\n const monthsFree = config.yearlyMonthsFree ?? 2;\n const tiersMap = new Map<string, PricingTier>();\n\n for (const plan of payload.plans) {\n const tierKey = tierKeyFromPlanKey(plan.key);\n const m = meta[tierKey];\n\n if (!tiersMap.has(tierKey)) {\n tiersMap.set(tierKey, {\n key: tierKey,\n name: m?.label ?? titleCase(tierKey),\n tagline: m?.tagline ?? plan.description ?? '',\n highlighted: m?.highlighted ?? false,\n monthly: null,\n yearly: null,\n oneTime: null,\n isComingSoon: false,\n features: plan.features.map(\n (f): PricingFeature => ({ key: f.key, name: f.name, description: f.description }),\n ),\n });\n }\n\n const tier = tiersMap.get(tierKey)!;\n\n if (plan.is_coming_soon === true) {\n tier.isComingSoon = true;\n }\n\n if (tier.features.length === 0 && plan.features.length > 0) {\n tier.features = plan.features.map((f) => ({ key: f.key, name: f.name, description: f.description }));\n }\n\n if (plan.billing_interval === 'month' && plan.amount !== null && plan.currency !== null) {\n tier.monthly = { amount: plan.amount, currency: plan.currency, planKey: plan.key };\n continue;\n }\n\n if (plan.billing_interval === 'year' && plan.amount !== null && plan.currency !== null) {\n tier.yearly = { amount: plan.amount, currency: plan.currency, monthsFree, planKey: plan.key };\n continue;\n }\n\n if (plan.billing_interval === null) {\n const amount = plan.amount ?? 0;\n const currency = plan.currency ?? 'eur';\n if (amount === 0) {\n tier.monthly = { amount: 0, currency, planKey: plan.key };\n } else {\n tier.oneTime = { amount, currency, planKey: plan.key };\n }\n }\n }\n\n const tiers = Array.from(tiersMap.values()).sort((a, b) => {\n const oa = meta[a.key]?.order ?? 999;\n const ob = meta[b.key]?.order ?? 999;\n return oa - ob;\n });\n\n return {\n product: payload.product,\n betaActive: payload.beta_active,\n tiers,\n };\n}\n\nexport async function fetchPricing(config: FetchPricingConfig): Promise<PricingPayload> {\n const base = config.baseUrl?.replace(/\\/$/, '');\n if (!base) return emptyPayload(config.productKey);\n\n const f = config.fetcher ?? globalThis.fetch;\n if (!f) {\n throw new Error('No fetch implementation available. Pass a fetcher in config or use Node 18+.');\n }\n\n try {\n const res = await f(`${base}/api/v1/products/${config.productKey}/plans`, {\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return emptyPayload(config.productKey);\n const data = (await res.json()) as ApiPayload;\n return shapeFromApi(data, config);\n } catch {\n return emptyPayload(config.productKey);\n }\n}\n\nexport function formatPrice(amountInCents: number, currency: string): string {\n const symbol = currency.toLowerCase() === 'eur' ? '€' : currency.toUpperCase() + ' ';\n const major = (amountInCents / 100).toFixed(amountInCents % 100 === 0 ? 0 : 2);\n return `${symbol}${major}`;\n}\n\nexport type { PricingFeature, PricingPayload, PricingTier, TierMeta };\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { T as TierMeta, a as PricingPayload } from './types-CH4Vkivj.cjs';
|
|
2
|
+
export { P as PricingFeature, b as PricingTier } from './types-CH4Vkivj.cjs';
|
|
3
|
+
|
|
4
|
+
type FetchPricingConfig = {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
productKey: string;
|
|
7
|
+
tierMeta?: Record<string, TierMeta>;
|
|
8
|
+
yearlyMonthsFree?: number;
|
|
9
|
+
/** Override the global fetch (e.g. Node 18+ or custom retry). */
|
|
10
|
+
fetcher?: typeof fetch;
|
|
11
|
+
};
|
|
12
|
+
declare function fetchPricing(config: FetchPricingConfig): Promise<PricingPayload>;
|
|
13
|
+
declare function formatPrice(amountInCents: number, currency: string): string;
|
|
14
|
+
|
|
15
|
+
export { type FetchPricingConfig, PricingPayload, TierMeta, fetchPricing, formatPrice };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { T as TierMeta, a as PricingPayload } from './types-CH4Vkivj.js';
|
|
2
|
+
export { P as PricingFeature, b as PricingTier } from './types-CH4Vkivj.js';
|
|
3
|
+
|
|
4
|
+
type FetchPricingConfig = {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
productKey: string;
|
|
7
|
+
tierMeta?: Record<string, TierMeta>;
|
|
8
|
+
yearlyMonthsFree?: number;
|
|
9
|
+
/** Override the global fetch (e.g. Node 18+ or custom retry). */
|
|
10
|
+
fetcher?: typeof fetch;
|
|
11
|
+
};
|
|
12
|
+
declare function fetchPricing(config: FetchPricingConfig): Promise<PricingPayload>;
|
|
13
|
+
declare function formatPrice(amountInCents: number, currency: string): string;
|
|
14
|
+
|
|
15
|
+
export { type FetchPricingConfig, PricingPayload, TierMeta, fetchPricing, formatPrice };
|