@cosmoops/connect-sdk 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.
Files changed (126) hide show
  1. package/LICENSE +34 -0
  2. package/README.md +446 -0
  3. package/dist/cjs/cli/bin.js +16 -0
  4. package/dist/cjs/cli/init.js +179 -0
  5. package/dist/cjs/client/components/account-sessions.js +112 -0
  6. package/dist/cjs/client/components/apps-grid.js +46 -0
  7. package/dist/cjs/client/components/auth-buttons.js +42 -0
  8. package/dist/cjs/client/components/feature-gate.js +61 -0
  9. package/dist/cjs/client/components/link-button.js +24 -0
  10. package/dist/cjs/client/components/logo.js +27 -0
  11. package/dist/cjs/client/components/plan-pricing.js +166 -0
  12. package/dist/cjs/client/components/plans-page.js +39 -0
  13. package/dist/cjs/client/components/plans.js +212 -0
  14. package/dist/cjs/client/components/readiness.js +117 -0
  15. package/dist/cjs/client/components/subscribe-dialog.js +60 -0
  16. package/dist/cjs/client/components/subscription.js +189 -0
  17. package/dist/cjs/client/components/usage-meter.js +68 -0
  18. package/dist/cjs/client/components/user-menu.js +172 -0
  19. package/dist/cjs/client/index.js +99 -0
  20. package/dist/cjs/client/mark.js +16 -0
  21. package/dist/cjs/client/provider.js +259 -0
  22. package/dist/cjs/client/use-checkout.js +173 -0
  23. package/dist/cjs/errors.js +74 -0
  24. package/dist/cjs/format-relative-time.js +18 -0
  25. package/dist/cjs/helpers.js +30 -0
  26. package/dist/cjs/index.js +22 -0
  27. package/dist/cjs/next/index.js +311 -0
  28. package/dist/cjs/package.json +3 -0
  29. package/dist/cjs/server/client.js +114 -0
  30. package/dist/cjs/server/handler.js +333 -0
  31. package/dist/cjs/server/http.js +160 -0
  32. package/dist/cjs/server/index.js +18 -0
  33. package/dist/cjs/server/resources/access.js +28 -0
  34. package/dist/cjs/server/resources/ai.js +36 -0
  35. package/dist/cjs/server/resources/apps.js +30 -0
  36. package/dist/cjs/server/resources/billing.js +71 -0
  37. package/dist/cjs/server/resources/drive.js +39 -0
  38. package/dist/cjs/server/resources/entitlements.js +49 -0
  39. package/dist/cjs/server/resources/identity.js +194 -0
  40. package/dist/cjs/server/resources/logs.js +41 -0
  41. package/dist/cjs/server/resources/otp.js +29 -0
  42. package/dist/cjs/server/resources/sessions.js +82 -0
  43. package/dist/cjs/types.js +15 -0
  44. package/dist/esm/cli/bin.js +13 -0
  45. package/dist/esm/cli/init.js +174 -0
  46. package/dist/esm/client/components/account-sessions.js +109 -0
  47. package/dist/esm/client/components/apps-grid.js +43 -0
  48. package/dist/esm/client/components/auth-buttons.js +38 -0
  49. package/dist/esm/client/components/feature-gate.js +57 -0
  50. package/dist/esm/client/components/link-button.js +21 -0
  51. package/dist/esm/client/components/logo.js +24 -0
  52. package/dist/esm/client/components/plan-pricing.js +156 -0
  53. package/dist/esm/client/components/plans-page.js +36 -0
  54. package/dist/esm/client/components/plans.js +209 -0
  55. package/dist/esm/client/components/readiness.js +113 -0
  56. package/dist/esm/client/components/subscribe-dialog.js +57 -0
  57. package/dist/esm/client/components/subscription.js +181 -0
  58. package/dist/esm/client/components/usage-meter.js +65 -0
  59. package/dist/esm/client/components/user-menu.js +164 -0
  60. package/dist/esm/client/index.js +47 -0
  61. package/dist/esm/client/mark.js +13 -0
  62. package/dist/esm/client/provider.js +247 -0
  63. package/dist/esm/client/use-checkout.js +168 -0
  64. package/dist/esm/errors.js +69 -0
  65. package/dist/esm/format-relative-time.js +15 -0
  66. package/dist/esm/helpers.js +26 -0
  67. package/dist/esm/index.js +15 -0
  68. package/dist/esm/next/index.js +279 -0
  69. package/dist/esm/package.json +3 -0
  70. package/dist/esm/server/client.js +110 -0
  71. package/dist/esm/server/handler.js +330 -0
  72. package/dist/esm/server/http.js +156 -0
  73. package/dist/esm/server/index.js +10 -0
  74. package/dist/esm/server/resources/access.js +24 -0
  75. package/dist/esm/server/resources/ai.js +32 -0
  76. package/dist/esm/server/resources/apps.js +26 -0
  77. package/dist/esm/server/resources/billing.js +67 -0
  78. package/dist/esm/server/resources/drive.js +35 -0
  79. package/dist/esm/server/resources/entitlements.js +45 -0
  80. package/dist/esm/server/resources/identity.js +189 -0
  81. package/dist/esm/server/resources/logs.js +37 -0
  82. package/dist/esm/server/resources/otp.js +25 -0
  83. package/dist/esm/server/resources/sessions.js +78 -0
  84. package/dist/esm/types.js +14 -0
  85. package/dist/theme.css +84 -0
  86. package/dist/types/cli/bin.d.ts +1 -0
  87. package/dist/types/cli/init.d.ts +34 -0
  88. package/dist/types/client/components/account-sessions.d.ts +25 -0
  89. package/dist/types/client/components/apps-grid.d.ts +20 -0
  90. package/dist/types/client/components/auth-buttons.d.ts +31 -0
  91. package/dist/types/client/components/feature-gate.d.ts +57 -0
  92. package/dist/types/client/components/link-button.d.ts +20 -0
  93. package/dist/types/client/components/logo.d.ts +35 -0
  94. package/dist/types/client/components/plan-pricing.d.ts +96 -0
  95. package/dist/types/client/components/plans-page.d.ts +36 -0
  96. package/dist/types/client/components/plans.d.ts +34 -0
  97. package/dist/types/client/components/readiness.d.ts +52 -0
  98. package/dist/types/client/components/subscribe-dialog.d.ts +34 -0
  99. package/dist/types/client/components/subscription.d.ts +123 -0
  100. package/dist/types/client/components/usage-meter.d.ts +24 -0
  101. package/dist/types/client/components/user-menu.d.ts +86 -0
  102. package/dist/types/client/index.d.ts +47 -0
  103. package/dist/types/client/mark.d.ts +11 -0
  104. package/dist/types/client/provider.d.ts +209 -0
  105. package/dist/types/client/use-checkout.d.ts +93 -0
  106. package/dist/types/errors.d.ts +62 -0
  107. package/dist/types/format-relative-time.d.ts +2 -0
  108. package/dist/types/helpers.d.ts +33 -0
  109. package/dist/types/index.d.ts +17 -0
  110. package/dist/types/next/index.d.ts +136 -0
  111. package/dist/types/server/client.d.ts +83 -0
  112. package/dist/types/server/handler.d.ts +67 -0
  113. package/dist/types/server/http.d.ts +52 -0
  114. package/dist/types/server/index.d.ts +15 -0
  115. package/dist/types/server/resources/access.d.ts +17 -0
  116. package/dist/types/server/resources/ai.d.ts +24 -0
  117. package/dist/types/server/resources/apps.d.ts +12 -0
  118. package/dist/types/server/resources/billing.d.ts +41 -0
  119. package/dist/types/server/resources/drive.d.ts +26 -0
  120. package/dist/types/server/resources/entitlements.d.ts +31 -0
  121. package/dist/types/server/resources/identity.d.ts +76 -0
  122. package/dist/types/server/resources/logs.d.ts +20 -0
  123. package/dist/types/server/resources/otp.d.ts +17 -0
  124. package/dist/types/server/resources/sessions.d.ts +37 -0
  125. package/dist/types/types.d.ts +434 -0
  126. package/package.json +102 -0
@@ -0,0 +1,65 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Card, Skeleton } from "@heroui/react";
4
+ import { AlertTriangle } from "lucide-react";
5
+ import { useConnect, useConnectAddonUsage } from "../provider.js";
6
+ import { formatPrice } from "./plan-pricing.js";
7
+ function formatUnits(value, unit) {
8
+ return `${value.toLocaleString("en-IN")} ${unit}`;
9
+ }
10
+ function formatDate(iso) {
11
+ return new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short" });
12
+ }
13
+ /**
14
+ * How much of each consumable add-on this workspace has left.
15
+ *
16
+ * Reads the balance Connect actually debits, so the number here and the number
17
+ * `consumeAddon` enforces cannot disagree. Before the `addons:read` endpoint
18
+ * existed this component was impossible to write honestly: a service could
19
+ * spend an allowance down on every request and the only thing the API exposed
20
+ * was the list of add-on *ids* on the subscription.
21
+ *
22
+ * **It shows `balance` against `includedPerCycle`, and never a "used" figure.**
23
+ * With `carryForward` an unspent balance survives the cycle boundary, so
24
+ * `included - balance` can go negative - a meter that runs backwards. Real
25
+ * consumption for a cycle is a ledger question, and computing it from a
26
+ * balance would be a guess rendered as a fact.
27
+ */
28
+ export function ConnectUsageMeter({ addonIds, hideWhenEmpty = true, title = "Usage this cycle", className, }) {
29
+ const { session } = useConnect();
30
+ const { data, isLoading, error } = useConnectAddonUsage();
31
+ if (!session?.user)
32
+ return null;
33
+ if (isLoading)
34
+ return _jsx(Skeleton, { className: `h-40 rounded-xl ${className ?? ""}` });
35
+ if (error || !data)
36
+ return null;
37
+ // Defended here as well as in `billing.getAddonUsage`, and deliberately so:
38
+ // `data` is whatever the host app's bridge returned, which a partner can
39
+ // route, wrap or proxy. This component's contract is that it renders nothing
40
+ // when there is nothing to meter, and it should hold for a malformed body as
41
+ // much as for an empty list.
42
+ const available = data.addons ?? [];
43
+ const addons = addonIds
44
+ ? addonIds
45
+ .map((id) => available.find((addon) => addon.addonId === id))
46
+ .filter((addon) => !!addon)
47
+ : available;
48
+ if (addons.length === 0) {
49
+ if (hideWhenEmpty)
50
+ return null;
51
+ return (_jsx(Card, { className: className, children: _jsxs(Card.Header, { children: [_jsx(Card.Title, { children: title }), _jsx(Card.Description, { children: "No metered add-ons on this plan." })] }) }));
52
+ }
53
+ return (_jsxs(Card, { className: className, children: [_jsxs(Card.Header, { children: [_jsx(Card.Title, { children: title }), data.resetsAt && _jsxs(Card.Description, { children: ["Resets on ", formatDate(data.resetsAt), "."] })] }), _jsx(Card.Content, { className: "flex flex-col gap-4", children: addons.map((addon) => (_jsx(AddonRow, { addon: addon }, addon.addonId))) })] }));
54
+ }
55
+ function AddonRow({ addon }) {
56
+ const overdrawn = addon.balance < 0;
57
+ // Carried-forward balance can exceed the grant, so the bar is clamped at
58
+ // both ends rather than assuming `0 <= balance <= includedPerCycle`. An
59
+ // unclamped width renders as a bar overflowing its own track.
60
+ const fraction = addon.includedPerCycle > 0 ? Math.min(1, Math.max(0, addon.balance / addon.includedPerCycle)) : 0;
61
+ const carried = addon.balance > addon.includedPerCycle ? addon.balance - addon.includedPerCycle : 0;
62
+ return (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("div", { className: "flex flex-wrap items-baseline justify-between gap-2 text-sm", children: [_jsx("span", { className: "font-medium text-foreground", children: addon.name }), _jsxs("span", { className: overdrawn ? "text-danger" : "text-muted", children: [overdrawn
63
+ ? `${formatUnits(Math.abs(addon.balance), addon.unit)} over`
64
+ : `${formatUnits(addon.balance, addon.unit)} left`, _jsxs("span", { className: "text-muted", children: [" of ", formatUnits(addon.includedPerCycle, addon.unit)] })] })] }), _jsx("div", { className: "h-1.5 w-full overflow-hidden rounded-full bg-surface", role: "meter", "aria-label": `${addon.name} remaining`, "aria-valuenow": addon.balance, "aria-valuemin": 0, "aria-valuemax": addon.includedPerCycle, children: _jsx("div", { className: `h-full rounded-full ${overdrawn ? "bg-danger" : "bg-accent"}`, style: { width: `${overdrawn ? 100 : fraction * 100}%` } }) }), carried > 0 && (_jsxs("p", { className: "text-xs text-muted", children: ["Includes ", formatUnits(carried, addon.unit), " carried over from last cycle."] })), overdrawn && addon.overagePricePerUnit !== null && (_jsxs("p", { className: "flex items-center gap-1.5 text-xs text-danger", children: [_jsx(AlertTriangle, { className: "size-3.5 shrink-0", "aria-hidden": "true" }), "Billed at ", formatPrice(addon.overagePricePerUnit), " per ", addon.unit, " beyond your allowance."] })), !overdrawn && addon.overagePolicy === "reject" && addon.balance === 0 && (_jsxs("p", { className: "flex items-center gap-1.5 text-xs text-danger", children: [_jsx(AlertTriangle, { className: "size-3.5 shrink-0", "aria-hidden": "true" }), "Nothing left this cycle - further use is blocked until it resets."] }))] }));
65
+ }
@@ -0,0 +1,164 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Avatar, Button, Chip, Modal, Separator, Skeleton, ToggleButton, ToggleButtonGroup, } from "@heroui/react";
4
+ import { CreditCard, ExternalLink, Laptop, LogOut, Moon, ReceiptText, Sun, UserRound, } from "lucide-react";
5
+ import { useConnect } from "../provider.js";
6
+ import { ConnectMark } from "../mark.js";
7
+ import { ConnectAccountSessions } from "./account-sessions.js";
8
+ const THEME_OPTIONS = [
9
+ { value: "light", label: "Light", icon: Sun },
10
+ { value: "dark", label: "Dark", icon: Moon },
11
+ { value: "system", label: "System", icon: Laptop },
12
+ ];
13
+ function initials(name, email) {
14
+ const source = name?.trim() || email?.trim() || "";
15
+ const parts = source.split(/[\s@._-]+/).filter(Boolean);
16
+ return (parts.slice(0, 2).map((part) => part[0]).join("") || "?").toUpperCase();
17
+ }
18
+ function openExternal(url) {
19
+ window.open(url, "_blank", "noopener,noreferrer");
20
+ }
21
+ /** `dispatch_admin` / `billing-viewer` -> `Dispatch admin`. */
22
+ function humanizeRole(role) {
23
+ const words = role.replace(/[_-]+/g, " ").trim();
24
+ return words.charAt(0).toUpperCase() + words.slice(1);
25
+ }
26
+ /**
27
+ * The subscription chip, and only when there is something to say.
28
+ *
29
+ * A plain "Active" badge is noise - it restates the default. A trial that is
30
+ * running out, a subscription paused mid-dunning, or one already cancelled
31
+ * are the three states where the account modal is exactly where a user goes
32
+ * looking, and the chip is what points them at Billing.
33
+ */
34
+ function subscriptionChip(subscription) {
35
+ if (!subscription)
36
+ return null;
37
+ if (subscription.isTrialing) {
38
+ return (_jsx(Chip, { size: "sm", variant: "soft", color: "warning", children: "Trial" }));
39
+ }
40
+ if (subscription.status === "paused") {
41
+ return (_jsx(Chip, { size: "sm", variant: "soft", color: "warning", children: "Paused" }));
42
+ }
43
+ if (subscription.status === "cancelled") {
44
+ return (_jsx(Chip, { size: "sm", variant: "soft", color: "danger", children: "Cancelled" }));
45
+ }
46
+ return null;
47
+ }
48
+ /**
49
+ * One of the three Connect destinations, as a tile rather than a menu row.
50
+ *
51
+ * These are not sibling actions of "Sign out" and should not queue up in the
52
+ * same vertical list as it - they are three places to *go*, all at another
53
+ * origin, and a row of equal-weight tiles says that at a glance where four
54
+ * stacked text buttons said "pick one of four unrelated things". The
55
+ * external-link mark stays on every one of them: they open in a new tab, and
56
+ * that is a promise the affordance has to make before the click, not after.
57
+ *
58
+ * `w-full` is load-bearing, not decoration: HeroUI's `.button` base is
59
+ * `w-fit`, so a tile dropped into a grid cell shrinks to its own label and
60
+ * the three of them come out ragged and unequal.
61
+ */
62
+ function DestinationTile({ icon, label, url, }) {
63
+ return (_jsxs(Button, { variant: "tertiary", "aria-label": `${label} (opens in a new tab)`, className: "relative h-auto w-full flex-col items-center justify-center gap-2 rounded-xl border border-border bg-surface px-2 py-4 hover:bg-surface-secondary", onPress: () => openExternal(url), children: [_jsx(ExternalLink, { className: "absolute end-2 top-2 size-3 text-muted", "aria-hidden": "true" }), _jsx("span", { className: "flex size-9 items-center justify-center rounded-full bg-surface-secondary text-muted", children: icon }), _jsx("span", { className: "text-xs font-medium text-foreground", children: label })] }));
64
+ }
65
+ /**
66
+ * Avatar and name in the trigger; an identity card, the three Connect
67
+ * destinations (Profile, Billing, Connect), an optional appearance control,
68
+ * this account's active sessions, and sign-out in the modal it opens.
69
+ *
70
+ * Profile/Billing/Connect open in a **new tab**, each marked with an
71
+ * external-link icon. They are a different application at a different
72
+ * origin, and navigating the host app away to reach them would lose
73
+ * whatever the user was doing here. Sign out is the only action that acts
74
+ * in place, which is why it sits alone in the footer rather than as a fourth
75
+ * item in the same list as three navigations.
76
+ *
77
+ * The session list is account-wide, not scoped to this service - see
78
+ * `ConnectUserSession`'s doc comment in `types.ts`. Appearance only renders
79
+ * when both `theme` and `onThemeChange` are supplied.
80
+ *
81
+ * Renders nothing when signed out - pair it with `<ConnectLoginButton>`, which
82
+ * renders nothing when signed *in*, and the two swap cleanly with no branch in
83
+ * your own layout.
84
+ *
85
+ * On the HeroUI shape: the trigger is a plain `<Button>` as a **direct child**
86
+ * of `<Modal>`, not wrapped in `<Modal.Trigger>`. `Dropdown.Trigger` (and by
87
+ * the same construction, `Modal.Trigger`) is itself a React Aria `Button`, so
88
+ * wrapping one produces a button inside a button - invalid markup, and press
89
+ * handling stops working. Kept uncontrolled (no `isOpen`/`onOpenChange`),
90
+ * matching `<ConnectAppsGrid>`'s own `<Modal>` - nothing here needs to close
91
+ * the modal programmatically; sign-out uses `slot="close"` instead.
92
+ */
93
+ export function ConnectUserMenu({ compact = false, onSignOut, className, theme, onThemeChange, }) {
94
+ const { session, isLoading, signOut, appUrl } = useConnect();
95
+ if (isLoading) {
96
+ return (_jsxs("div", { className: `flex items-center gap-2 ${className ?? ""}`, children: [_jsx(Skeleton, { className: "size-8 shrink-0 rounded-full" }), !compact && _jsx(Skeleton, { className: "h-4 w-24" })] }));
97
+ }
98
+ const user = session?.user;
99
+ if (!user)
100
+ return null;
101
+ const label = user.displayName ?? user.email ?? "Account";
102
+ const role = session?.serviceRole?.role;
103
+ const planChip = subscriptionChip(session?.subscription ?? null);
104
+ return (_jsxs(Modal, { children: [_jsxs(Button, { variant: "tertiary", "aria-label": `Account: ${label}`, className: `gap-1 pl-1 ${className ?? ""}`, children: [_jsx(Avatar, { size: "sm", color: "accent", variant: "soft", children: _jsx(Avatar.Fallback, { children: initials(user.displayName, user.email) }) }), !compact && _jsx("span", { className: "text-sm font-medium text-foreground", children: label })] }), _jsx(Modal.Backdrop, { children: _jsx(Modal.Container, { size: "md", scroll: "inside", children: _jsxs(Modal.Dialog, { children: [_jsx(Modal.CloseTrigger, {}), _jsx(Modal.Header, { children: _jsx(Modal.Heading, { children: "Account" }) }), _jsxs(Modal.Body, { className: "flex flex-col gap-5", children: [_jsxs("div", { className: "flex items-start gap-3 rounded-xl border border-border bg-surface-secondary p-4", children: [_jsx(Avatar, { size: "lg", color: "accent", variant: "soft", children: _jsx(Avatar.Fallback, { children: initials(user.displayName, user.email) }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "truncate text-sm font-semibold text-foreground", children: label }), user.email && _jsx("p", { className: "truncate text-xs text-muted", children: user.email }), _jsxs("div", { className: "mt-2 flex flex-wrap items-center gap-1.5", children: [_jsx(Chip, { size: "sm", variant: "soft", children: user.organizationName }), role && (_jsx(Chip, { size: "sm", variant: "soft", color: "accent", children: humanizeRole(role) })), planChip, !user.emailVerified && (_jsx(Chip, { size: "sm", variant: "soft", color: "warning", children: "Email unverified" }))] })] })] }), _jsxs("div", { className: "grid grid-cols-3 gap-2", children: [_jsx(DestinationTile, { icon: _jsx(UserRound, { className: "size-4", "aria-hidden": "true" }), label: "Profile", url: `${appUrl}/profile` }), _jsx(DestinationTile, { icon: _jsx(CreditCard, { className: "size-4", "aria-hidden": "true" }), label: "Billing", url: `${appUrl}/billing` }), _jsx(DestinationTile, { icon: _jsx(ConnectMark, { className: "size-4" }), label: "Connect", url: appUrl })] }), theme && onThemeChange && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("p", { className: "text-sm font-medium text-foreground", children: "Appearance" }), _jsx(ToggleButtonGroup, { fullWidth: true, "aria-label": "Theme", selectionMode: "single", disallowEmptySelection: true, selectedKeys: [theme], onSelectionChange: (keys) => {
105
+ const [next] = [...keys];
106
+ if (typeof next === "string")
107
+ onThemeChange(next);
108
+ }, children: THEME_OPTIONS.map(({ value, label: optionLabel, icon: Icon }, index) => (_jsxs(ToggleButton, { id: value, children: [index > 0 && _jsx(ToggleButtonGroup.Separator, {}), _jsx(Icon, { className: "size-4", "aria-hidden": "true" }), optionLabel] }, value))) })] })), _jsx(Separator, {}), _jsx(ConnectAccountSessions, {})] }), _jsx(Modal.Footer, { children: _jsxs(Button, { slot: "close", fullWidth: true, variant: "tertiary", className: "text-danger", onPress: () => {
109
+ void signOut().then(onSignOut);
110
+ }, children: [_jsx(LogOut, { className: "size-4 shrink-0" }), "Sign out"] }) })] }) }) })] }));
111
+ }
112
+ /**
113
+ * The "Manage subscription" action on its own, for layouts that want it
114
+ * visible rather than buried in the account menu - a billing banner, an empty
115
+ * state, a settings page.
116
+ */
117
+ export function ConnectManageSubscriptionButton({ className }) {
118
+ const { appUrl } = useConnect();
119
+ return (_jsxs(Button, { variant: "secondary", className: className, onPress: () => openExternal(`${appUrl}/billing`), children: [_jsx(CreditCard, { className: "size-4 shrink-0" }), "Manage subscription", _jsx(ExternalLink, { className: "size-3.5 shrink-0 text-muted" })] }));
120
+ }
121
+ /**
122
+ * Invoices and payment history, on Connect.
123
+ *
124
+ * A deep link rather than a component that lists them, and that is not a
125
+ * placeholder: nothing in `/api/v1/service/*` exposes invoices, so an SDK-side
126
+ * list would have nothing to read. It is also the right answer regardless -
127
+ * a GST tax invoice is a legal document with a fixed format, downloadable and
128
+ * emailed from one place, and a partner-rendered copy of one would be a second
129
+ * version of a record that must have exactly one.
130
+ */
131
+ export function ConnectInvoicesButton({ className }) {
132
+ const { session, appUrl } = useConnect();
133
+ if (!session?.user)
134
+ return null;
135
+ return (_jsxs(Button, { variant: "tertiary", className: className, onPress: () => openExternal(`${appUrl}/billing/invoices`), children: [_jsx(ReceiptText, { className: "size-4 shrink-0" }), "Invoices", _jsx(ExternalLink, { className: "size-3.5 shrink-0 text-muted" })] }));
136
+ }
137
+ /**
138
+ * The "Profile" action on its own - the third of the three Connect
139
+ * destinations, alongside `ConnectManageSubscriptionButton` (Billing) and
140
+ * `ConnectHomeButton`.
141
+ *
142
+ * It was reachable only from inside `ConnectUserMenu`, which meant an app that
143
+ * builds its own account menu had to hardcode `${appUrl}/profile` to offer it.
144
+ */
145
+ export function ConnectProfileButton({ className }) {
146
+ const { session, appUrl } = useConnect();
147
+ if (!session?.user)
148
+ return null;
149
+ return (_jsxs(Button, { variant: "tertiary", className: className, onPress: () => openExternal(`${appUrl}/profile`), children: [_jsx(UserRound, { className: "size-4 shrink-0" }), "Profile", _jsx(ExternalLink, { className: "size-3.5 shrink-0 text-muted" })] }));
150
+ }
151
+ /** A plain "Open Connect" button, for a footer or a help menu. */
152
+ export function ConnectHomeButton({ className }) {
153
+ const { appUrl } = useConnect();
154
+ return (_jsxs(Button, { variant: "tertiary", className: className, onPress: () => openExternal(appUrl), children: [_jsx(ConnectMark, { className: "size-4 shrink-0" }), "Connect", _jsx(ExternalLink, { className: "size-3.5 shrink-0 text-muted" })] }));
155
+ }
156
+ /** Sign out on its own, for a settings page that wants it as a destructive row. */
157
+ export function ConnectSignOutButton({ onSignOut, className, }) {
158
+ const { session, signOut } = useConnect();
159
+ if (!session?.user)
160
+ return null;
161
+ return (_jsxs(Button, { variant: "tertiary", className: className, onPress: () => {
162
+ void signOut().then(onSignOut);
163
+ }, children: [_jsx(LogOut, { className: "size-4 shrink-0" }), "Sign out"] }));
164
+ }
@@ -0,0 +1,47 @@
1
+ "use client";
2
+ /**
3
+ * Browser half of `@cosmoops/connect-sdk` - React components and hooks.
4
+ *
5
+ * Holds no credential. Everything here talks to your own origin, where
6
+ * `createConnectHandler` from `@cosmoops/connect-sdk/server` holds the API key
7
+ * and reaches Connect.
8
+ *
9
+ * Styling is HeroUI v3 semantic tokens only (`accent`, `muted`, `surface`,
10
+ * `separator`, ...), never a hardcoded colour - so these components inherit
11
+ * whatever theme the host service platform already configured, and one theme
12
+ * change lands identically in all of them.
13
+ */
14
+ export { ConnectProvider, useConnect, useConnectUser, useConnectEntitlements, useConnectPlans, useConnectApps, useConnectAddonUsage, useConnectSessions, useConnectResource, CONNECT_APP_URL, } from "./provider.js";
15
+ // Re-exported from the root entry rather than kept there alone: it is a pure
16
+ // helper, but every caller is UI code, and making a component file reach two
17
+ // entry points for one function is friction with nothing behind it.
18
+ export { blockingBlockers, normalizePlanFeatures } from "../helpers.js";
19
+ export { ConnectError, isConnectError } from "../errors.js";
20
+ export { ConnectMark } from "./mark.js";
21
+ export { ConnectLogo } from "./components/logo.js";
22
+ export { ConnectLoginButton, ConnectRegisterButton } from "./components/auth-buttons.js";
23
+ export { ConnectUserMenu, ConnectManageSubscriptionButton, ConnectInvoicesButton, ConnectProfileButton, ConnectHomeButton, ConnectSignOutButton, } from "./components/user-menu.js";
24
+ // Built, compiled into `dist/`, and reachable from no entry point until now -
25
+ // `ConnectUserMenu` was the only thing that could render it.
26
+ export { ConnectAccountSessions } from "./components/account-sessions.js";
27
+ export { ConnectAppsGrid } from "./components/apps-grid.js";
28
+ export { ConnectPlans } from "./components/plans.js";
29
+ export { ConnectSubscribeDialog } from "./components/subscribe-dialog.js";
30
+ // The subscribe / upgrade / downgrade flow's two moving parts, exported so a
31
+ // partner can drive the same hand-off from its own pricing page instead of
32
+ // `<ConnectPlans>` - the pricing table is one presentation of the flow, not
33
+ // the flow itself.
34
+ // Subscription state, gates and the surfaces around the plan grid.
35
+ export { ConnectSubscriptionGate, ConnectNoSubscriptionCard, ConnectSubscriptionCard, ConnectTrialBanner, ConnectSeatUsage, resolveSubscriptionState, } from "./components/subscription.js";
36
+ export { ConnectReadinessBanner, ConnectReadinessGate } from "./components/readiness.js";
37
+ export { ConnectFeatureGate, useConnectFeature } from "./components/feature-gate.js";
38
+ export { ConnectUsageMeter } from "./components/usage-meter.js";
39
+ export { ConnectPlansPage } from "./components/plans-page.js";
40
+ export { useConnectCheckout, buildCheckoutUrl } from "./use-checkout.js";
41
+ export { formatPrice, monthlyOf, resolveAction, annualSaving, discountLabel, ACTION_LABEL,
42
+ // The tier model, exported because a partner writing its own pricing grid
43
+ // needs the same pairing `ConnectPlans` uses. Grouping a flat plan list by
44
+ // hand means matching on `name`, which Connect neither enforces unique nor
45
+ // keeps stable across a rename - `planGroup` is the field that exists to
46
+ // answer this, and `groupPlansByTier` is how to read it.
47
+ groupPlansByTier, resolvePlanGroup, } from "./components/plan-pricing.js";
@@ -0,0 +1,13 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /**
4
+ * The Connect mark - concentric rings on a solid accent badge.
5
+ *
6
+ * Painted from `--accent` / `--accent-foreground`, the same HeroUI tokens the
7
+ * host app themes, so the badge tracks whatever palette a service platform has
8
+ * configured rather than carrying a hardcoded CosmoOps green into someone
9
+ * else's brand.
10
+ */
11
+ export function ConnectMark({ className = "size-5" }) {
12
+ return (_jsxs("svg", { viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true", className: className, children: [_jsx("rect", { width: "32", height: "32", rx: "9", fill: "var(--accent)" }), _jsxs("g", { stroke: "var(--accent-foreground)", strokeWidth: "2", fill: "none", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("circle", { cx: "16", cy: "16", r: "2.5" }), _jsx("circle", { cx: "16", cy: "16", r: "6" }), _jsx("circle", { cx: "16", cy: "16", r: "9.5" })] })] }));
13
+ }
@@ -0,0 +1,247 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
4
+ export const CONNECT_APP_URL = "https://connect.cosmoops.com";
5
+ const ConnectContext = createContext(null);
6
+ /**
7
+ * Wraps the part of your app that shows Connect UI.
8
+ *
9
+ * Holds one session read, shared by every component below it, so a page with a
10
+ * user menu, an apps grid and a plan table makes one request rather than three.
11
+ * There is no API key here and there cannot be: everything goes to your own
12
+ * origin, where `createConnectHandler` holds the credential.
13
+ *
14
+ * ```tsx
15
+ * // Next.js - clientId comes from NEXT_PUBLIC_CONNECT_CLIENT_ID
16
+ * <ConnectProvider>
17
+ * <App />
18
+ * </ConnectProvider>
19
+ * ```
20
+ */
21
+ export function ConnectProvider({ clientId = process.env.NEXT_PUBLIC_CONNECT_CLIENT_ID ?? "", basePath = "/api/connect", redirectUri, appUrl = CONNECT_APP_URL, fetch: fetchImpl, children, }) {
22
+ // One state cell, not three. `isLoading` is *derived* from "no result yet"
23
+ // rather than set - a `setIsLoading(true)` at the top of an effect is a
24
+ // synchronous setState inside that effect, which cascades an extra render
25
+ // and is what `react-hooks/set-state-in-effect` flags. Everything below
26
+ // writes state only from an async callback.
27
+ const [result, setResult] = useState(null);
28
+ const isLoading = result === null;
29
+ const session = result?.session ?? null;
30
+ const error = result?.error ?? null;
31
+ // One entry per path. Held in a ref, not state, because a cache write must
32
+ // not re-render every consumer of this context - only the component awaiting
33
+ // that promise cares.
34
+ const cache = useRef(new Map());
35
+ const fetchResource = useCallback((path) => {
36
+ const key = `${basePath}${path}`;
37
+ const existing = cache.current.get(key);
38
+ if (existing)
39
+ return existing;
40
+ const pending = (fetchImpl ?? globalThis.fetch)(key, {
41
+ credentials: "same-origin",
42
+ headers: { accept: "application/json" },
43
+ })
44
+ .then(async (response) => {
45
+ const body = await response.json().catch(() => null);
46
+ if (!response.ok) {
47
+ throw new Error(body?.error?.message ?? `Connect bridge returned ${response.status}`);
48
+ }
49
+ return body;
50
+ })
51
+ .catch((cause) => {
52
+ // A failed read must not be cached, or the UI can never recover
53
+ // without a reload.
54
+ cache.current.delete(key);
55
+ throw cause;
56
+ });
57
+ cache.current.set(key, pending);
58
+ return pending;
59
+ }, [basePath, fetchImpl]);
60
+ const mutateResource = useCallback(async (path, body) => {
61
+ const response = await (fetchImpl ?? globalThis.fetch)(`${basePath}${path}`, {
62
+ method: "POST",
63
+ credentials: "same-origin",
64
+ headers: {
65
+ accept: "application/json",
66
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
67
+ },
68
+ body: body !== undefined ? JSON.stringify(body) : undefined,
69
+ });
70
+ const responseBody = await response.json().catch(() => null);
71
+ if (!response.ok) {
72
+ throw new Error(responseBody?.error?.message ?? `Connect bridge returned ${response.status}`);
73
+ }
74
+ // Only this path's own entry - see this method's doc comment for why
75
+ // a blunt full-cache clear (like `refresh()`/`signOut()` use) is wrong
76
+ // here.
77
+ cache.current.delete(`${basePath}${path}`);
78
+ return responseBody;
79
+ }, [basePath, fetchImpl]);
80
+ const invalidateResource = useCallback((path) => {
81
+ cache.current.delete(`${basePath}${path}`);
82
+ }, [basePath]);
83
+ const refresh = useCallback(async () => {
84
+ cache.current.clear();
85
+ try {
86
+ const session = await fetchResource("/session");
87
+ setResult({ session, error: null });
88
+ }
89
+ catch (cause) {
90
+ // A bridge that cannot be reached is reported as signed out *with* an
91
+ // error, so a Login button still renders rather than the UI hanging on
92
+ // skeletons forever.
93
+ setResult({
94
+ session: { user: null, subscription: null, serviceRole: null },
95
+ error: cause instanceof Error ? cause.message : "Could not reach Connect",
96
+ });
97
+ }
98
+ }, [fetchResource]);
99
+ useEffect(() => {
100
+ // A documented false positive: `refresh` writes state only after awaiting
101
+ // the bridge, so nothing here is synchronous - but the rule cannot follow
102
+ // an await boundary across a `useCallback` and reports the reachable
103
+ // `setResult`. Fetching on mount is the sanctioned pattern; the rule
104
+ // targets the synchronous case, which this is not.
105
+ // eslint-disable-next-line react-hooks/set-state-in-effect
106
+ void refresh();
107
+ }, [refresh]);
108
+ const signIn = useCallback((options = {}) => {
109
+ const url = new URL("/sso/authorize", appUrl);
110
+ url.searchParams.set("client_id", clientId);
111
+ url.searchParams.set("response_type", "code");
112
+ url.searchParams.set("scope", "openid");
113
+ if (redirectUri)
114
+ url.searchParams.set("redirect_uri", redirectUri);
115
+ if (options.prompt)
116
+ url.searchParams.set("prompt", options.prompt);
117
+ // `state` is deliberately absent: it must be generated and stored
118
+ // server-side to be worth anything, so the redirect goes through your own
119
+ // start route, which mints one and forwards. See `ConnectLoginButton`.
120
+ window.location.href = redirectUri ? url.toString() : `${basePath}/signin${options.prompt ? "?prompt=create" : ""}`;
121
+ }, [appUrl, basePath, clientId, redirectUri]);
122
+ const signOut = useCallback(async () => {
123
+ await (fetchImpl ?? globalThis.fetch)(`${basePath}/logout`, {
124
+ method: "POST",
125
+ credentials: "same-origin",
126
+ }).catch(() => { });
127
+ cache.current.clear();
128
+ setResult({ session: { user: null, subscription: null, serviceRole: null }, error: null });
129
+ }, [basePath, fetchImpl]);
130
+ const value = useMemo(() => ({
131
+ clientId,
132
+ appUrl,
133
+ session,
134
+ isLoading,
135
+ error,
136
+ signIn,
137
+ signOut,
138
+ refresh,
139
+ fetchResource,
140
+ mutateResource,
141
+ invalidateResource,
142
+ }), [
143
+ clientId,
144
+ appUrl,
145
+ session,
146
+ isLoading,
147
+ error,
148
+ signIn,
149
+ signOut,
150
+ refresh,
151
+ fetchResource,
152
+ mutateResource,
153
+ invalidateResource,
154
+ ]);
155
+ return _jsx(ConnectContext.Provider, { value: value, children: children });
156
+ }
157
+ export function useConnect() {
158
+ const value = useContext(ConnectContext);
159
+ if (!value) {
160
+ throw new Error("useConnect must be used inside <ConnectProvider>. Wrap your app once, near the root.");
161
+ }
162
+ return value;
163
+ }
164
+ /** The signed-in user, or `null`. Sugar over `useConnect().session`. */
165
+ export function useConnectUser() {
166
+ return useConnect().session?.user ?? null;
167
+ }
168
+ /** Readiness gates and the live subscription, fetched on first use. */
169
+ export function useConnectEntitlements() {
170
+ return useConnectResource("/entitlements");
171
+ }
172
+ /**
173
+ * What is left of every consumable add-on on this workspace's subscription.
174
+ *
175
+ * The read half of `client.billing.consumeAddon` - a service that meters its
176
+ * own end users had no way to show them what remained until this existed.
177
+ * Empty `addons` means there is nothing to meter, which is not an error.
178
+ */
179
+ export function useConnectAddonUsage() {
180
+ return useConnectResource("/addons");
181
+ }
182
+ /** This service's plan catalog. */
183
+ export function useConnectPlans() {
184
+ return useConnectResource("/plans");
185
+ }
186
+ /** The apps this organization can open. */
187
+ export function useConnectApps() {
188
+ return useConnectResource("/apps");
189
+ }
190
+ /**
191
+ * This Connect account's own login sessions - account-wide, not scoped to
192
+ * this service, see `SessionsListResponse`'s doc comment. The component
193
+ * that calls this is also the one that must own any revoke actions and call
194
+ * the returned `refetch()` afterward - see `mutateResource`'s doc comment
195
+ * for why nothing does that automatically.
196
+ */
197
+ export function useConnectSessions() {
198
+ return useConnectResource("/sessions");
199
+ }
200
+ /**
201
+ * One bridge read, shared through the provider's cache.
202
+ *
203
+ * Only fetches once a user is known: every resource route needs a session, so
204
+ * firing before one exists just buys a guaranteed 401.
205
+ */
206
+ export function useConnectResource(path) {
207
+ const { fetchResource, session, isLoading: sessionLoading } = useConnect();
208
+ // Stamped with the `path` it belongs to, so switching paths reports loading
209
+ // without a synchronous `setIsLoading(true)` - and, more usefully, so a
210
+ // resolved response for a previous path can never be read as this one's.
211
+ const [entry, setEntry] = useState(null);
212
+ const [version, setVersion] = useState(0);
213
+ useEffect(() => {
214
+ // Signed out is handled by derivation below rather than by writing state
215
+ // here - a synchronous setState inside an effect costs an extra render pass
216
+ // and is what `react-hooks/set-state-in-effect` exists to catch.
217
+ if (sessionLoading || !session?.user)
218
+ return;
219
+ let active = true;
220
+ fetchResource(path)
221
+ .then((data) => {
222
+ if (active)
223
+ setEntry({ path, data, error: null });
224
+ })
225
+ .catch((cause) => {
226
+ if (active) {
227
+ setEntry({ path, data: null, error: cause instanceof Error ? cause.message : "Request failed" });
228
+ }
229
+ });
230
+ return () => {
231
+ active = false;
232
+ };
233
+ // `version` is otherwise unread - it exists purely to force this effect
234
+ // to re-run on `refetch()`, after the caller has already evicted this
235
+ // path's cache entry via `mutateResource`.
236
+ }, [fetchResource, path, session?.user, sessionLoading, version]);
237
+ const signedOut = !sessionLoading && !session?.user;
238
+ const loaded = entry?.path === path ? entry : null;
239
+ return {
240
+ data: loaded?.data ?? null,
241
+ // Signed out is a settled answer, not a pending one - a gated component
242
+ // should render its signed-out state, not skeletons forever.
243
+ isLoading: !signedOut && !loaded,
244
+ error: loaded?.error ?? null,
245
+ refetch: () => setVersion((v) => v + 1),
246
+ };
247
+ }