@tansy/payments-commet 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/payments-commet`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ No changes of its own. Released beside `tansy` 0.1.1, from which every package moves on its own
9
+ version, and it now requires it: the `tansy` peer range is ^0.1.1.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
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,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/payments-commet
4
+
5
+ Commet for @tansy/payments, through better-auth's Commet plugin.
6
+
7
+ ```bash
8
+ npm install @tansy/payments-commet
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the payments plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/payments.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Commet, through better-auth's Commet plugin. Payments keeps its subscriptions as memberships. */
2
+ export declare const commet: () => import("@tansy/payments/provider").PaymentProvider;
package/index.js ADDED
@@ -0,0 +1,124 @@
1
+ import { Commet } from "@commet/node";
2
+ import { commet as commetPlugin, portal, subscriptions, webhooks } from "@commet/better-auth";
3
+ import { definePaymentProvider, isUserId, loadPlanRefs, newReference, PURCHASES, recordPurchase, recordRefund, REFERENCE, rememberCheckout, startedCheckout, str, toMinorUnits, upsertMembership } from "@tansy/payments/provider";
4
+ const keys = (settings) => settings;
5
+ const client = (settings) => new Commet({ apiKey: keys(settings).commetApiKey });
6
+ const record = (value) => (value && typeof value === "object" ? value : {});
7
+ /** better-auth's Commet plugin makes the user's id the customer's id. Payments does the same for people who signed up before. */
8
+ async function ensureCustomer(sdk, buyer) {
9
+ const { data } = await sdk.customers.list({ externalId: buyer.id });
10
+ if (!data?.length)
11
+ await sdk.customers.create({ id: buyer.id, email: buyer.email, ...(buyer.name ? { fullName: buyer.name } : {}) }).catch(async (error) => {
12
+ // Created at the same moment by another request.
13
+ if (!(await sdk.customers.list({ externalId: buyer.id })).data?.length)
14
+ throw error;
15
+ });
16
+ }
17
+ async function recordPayment(context, sdk, paymentId) {
18
+ const payment = await sdk.payments.get({ id: paymentId });
19
+ if (payment.status !== "succeeded")
20
+ return false;
21
+ const metadata = payment.metadata ?? {};
22
+ return recordPurchase(context, { provider: "commet", sessionId: str(metadata.ref), paymentRef: payment.paymentContext?.paymentLinkId ?? payment.id, metadata, amount: payment.amountTotal, currency: payment.currency });
23
+ }
24
+ /** Commet's subscription events don't carry the plan, so Payments reads the subscription back. */
25
+ async function syncSubscription(context, sdk, subscriptionId, at, plans) {
26
+ const subscription = await sdk.subscriptions.get({ id: subscriptionId });
27
+ const customerId = subscription.customerId;
28
+ const user = isUserId(customerId) && (await context.system.users.get(customerId)) ? customerId : (await sdk.customers.get({ id: customerId }).catch(() => null))?.externalId ?? null;
29
+ await upsertMembership(context, { provider: "commet", subscriptionId, user, productId: subscription.plan.id, status: subscription.status, periodEnd: subscription.currentPeriod?.end ?? null, at }, plans);
30
+ }
31
+ /** Every Commet event better-auth's plugin verified. Throwing makes Commet send it again. */
32
+ async function onEvent(context, settings, payload) {
33
+ const { event, data, timestamp } = record(payload);
34
+ if (!event || !data)
35
+ return;
36
+ const sdk = client(settings);
37
+ if (event === "payment_link.completed" && str(data.paymentId))
38
+ await recordPayment(context, sdk, str(data.paymentId));
39
+ else if (event === "payment.refunded") {
40
+ // Commet sends what was refunded. Only a refund of the whole purchase takes it back.
41
+ const ref = str(data.paymentLinkId);
42
+ if (!ref)
43
+ return;
44
+ const { items } = await context.system.records.list(PURCHASES, { filter: `paymentIntent = "${ref.replace(/[^A-Za-z0-9_-]/g, "")}"`, perPage: 1, fields: "amount,currency" });
45
+ const purchase = items[0];
46
+ const total = purchase ? toMinorUnits(purchase.amount, str(purchase.currency) || "usd") : null;
47
+ if (total !== null && Number(data.refundAmount) >= total)
48
+ await recordRefund(context, { paymentRef: ref });
49
+ }
50
+ else if (event.startsWith("subscription.") && str(data.subscriptionId)) {
51
+ await syncSubscription(context, sdk, str(data.subscriptionId), timestamp ? new Date(timestamp).getTime() : Date.now(), await loadPlanRefs(context));
52
+ }
53
+ }
54
+ /** Commet, through better-auth's Commet plugin. Payments keeps its subscriptions as memberships. */
55
+ export const commet = () => definePaymentProvider({
56
+ id: "commet",
57
+ label: "Commet",
58
+ webhookPath: "/commet/webhooks",
59
+ // Its settings in other interface languages. English is each setting's own label and description.
60
+ messages: (siteUrl) => ({
61
+ ar: { settings: {
62
+ commetApiKey: { label: "مفتاح API لـ Commet", description: "من Commet ← Developers. يبدأ بـ ck_. مفتاح sandbox للاختبار." },
63
+ commetWebhookSecret: { label: "سرّ webhook في Commet", description: `وجّه webhook من Commet إلى ${siteUrl}/api/auth/commet/webhooks، ثم الصق سرّه، الذي يبدأ بـ whsec_.` },
64
+ } },
65
+ }),
66
+ settings: (siteUrl) => [
67
+ { name: "commetApiKey", type: "secret", env: "COMMET_API_KEY", label: "Commet API key", description: "From Commet → Developers. Starts with ck_. A sandbox key tests." },
68
+ { name: "commetWebhookSecret", type: "secret", env: "COMMET_WEBHOOK_SECRET", label: "Commet webhook secret", description: `Point a Commet webhook at ${siteUrl}/api/auth/commet/webhooks, then paste its secret, which starts with whsec_.` },
69
+ ],
70
+ yearlyFromSamePlan: true,
71
+ planIdProblem: (value) => (/^[A-Za-z0-9_:.-]{1,100}$/.test(value) ? null : "Use a Commet plan id."),
72
+ ready: (settings) => Boolean(keys(settings).commetApiKey && keys(settings).commetWebhookSecret),
73
+ authPlugins: (settings, context, siteUrl) => [commetPlugin({
74
+ client: client(settings),
75
+ createCustomerOnSignUp: settings.createCustomerOnSignUp,
76
+ use: [
77
+ portal({ returnUrl: siteUrl }),
78
+ subscriptions(),
79
+ webhooks({ secret: keys(settings).commetWebhookSecret, onPayload: async (payload) => onEvent(context, settings, payload) }),
80
+ ],
81
+ })],
82
+ async checkout({ context, settings, buyer, collection, recordId, name, amount, currency, successUrl }) {
83
+ const sdk = client(settings);
84
+ await ensureCustomer(sdk, buyer);
85
+ const ref = newReference();
86
+ // A hosted payment link at the record's own price. Commet needs no product for it.
87
+ const payment = await sdk.payments.create({
88
+ amount,
89
+ currency: currency.toUpperCase(),
90
+ customerId: buyer.id,
91
+ description: name,
92
+ successUrl: `${successUrl}&session_id=${ref}`,
93
+ metadata: { tansy: "purchase", collection, recordId: String(recordId), userId: buyer.id, ref },
94
+ });
95
+ await rememberCheckout(context, ref, { id: payment.id, userId: buyer.id, collection, recordId, at: Date.now() });
96
+ if (!payment.url)
97
+ throw new Error("Commet returned no payment address.");
98
+ return payment.url;
99
+ },
100
+ isReference: (value) => REFERENCE.test(value),
101
+ async confirm(context, settings, reference, buyer) {
102
+ const started = await startedCheckout(context, reference);
103
+ if (!started || started.userId !== buyer.id)
104
+ return null;
105
+ const paid = await recordPayment(context, client(settings), started.id).catch(() => null);
106
+ if (paid === null)
107
+ return null;
108
+ context.auditTarget("record", `${started.collection}/${started.recordId}`, { paid });
109
+ return { paid };
110
+ },
111
+ async subscribe({ context, settings, buyer, plan, annual, successUrl }) {
112
+ const sdk = client(settings);
113
+ await ensureCustomer(sdk, buyer);
114
+ const created = await sdk.subscriptions.create({ customerId: buyer.id, planId: plan.productId, ...(annual ? { billingInterval: "yearly" } : {}), successUrl });
115
+ // Recorded now, so its events find whose it is.
116
+ await upsertMembership(context, { provider: "commet", subscriptionId: created.id, user: buyer.id, productId: created.plan.id, status: created.status, periodEnd: created.currentPeriod?.end ?? null, at: Date.now() }, await loadPlanRefs(context));
117
+ // A free trial without a card starts at once, with nothing to pay.
118
+ return created.checkoutUrl ?? successUrl;
119
+ },
120
+ async billing(context) {
121
+ const { url } = await context.auth.call("/commet/portal");
122
+ return url;
123
+ },
124
+ });
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@tansy/payments-commet",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Commet for @tansy/payments, through better-auth's Commet plugin.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-payments-provider"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
11
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
15
+ "directory": "plugins/payments-commet"
16
+ },
17
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.ts",
21
+ "default": "./index.js"
22
+ }
23
+ },
24
+ "peerDependencies": {
25
+ "@tansy/payments": "^0.1.1",
26
+ "tansy": "^0.1.1"
27
+ },
28
+ "dependencies": {
29
+ "@commet/better-auth": "^8.1.0",
30
+ "@commet/node": "^9.10.0"
31
+ }
32
+ }