@kaperkunde/tokens 0.0.0-stage → 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 (50) hide show
  1. package/README.md +415 -2
  2. package/dist/browser-api.d.mts +56 -0
  3. package/dist/browser-api.mjs +75 -0
  4. package/dist/errors.d.mts +41 -0
  5. package/dist/errors.mjs +97 -0
  6. package/dist/index.d.mts +5 -0
  7. package/dist/index.mjs +5 -0
  8. package/dist/react/autorefill.d.mts +21 -0
  9. package/dist/react/autorefill.mjs +269 -0
  10. package/dist/react/balance.d.mts +23 -0
  11. package/dist/react/balance.mjs +116 -0
  12. package/dist/react/buy.d.mts +27 -0
  13. package/dist/react/buy.mjs +175 -0
  14. package/dist/react/history.d.mts +23 -0
  15. package/dist/react/history.mjs +102 -0
  16. package/dist/react/hooks.d.mts +52 -0
  17. package/dist/react/hooks.mjs +150 -0
  18. package/dist/react/index.d.mts +11 -0
  19. package/dist/react/index.mjs +10 -0
  20. package/dist/react/labels.d.mts +114 -0
  21. package/dist/react/labels.mjs +125 -0
  22. package/dist/react/own-model.d.mts +31 -0
  23. package/dist/react/own-model.mjs +358 -0
  24. package/dist/react/ui.d.mts +61 -0
  25. package/dist/react/ui.mjs +128 -0
  26. package/dist/react/usage.d.mts +21 -0
  27. package/dist/react/usage.mjs +137 -0
  28. package/dist/server/client.d.mts +76 -0
  29. package/dist/server/client.mjs +137 -0
  30. package/dist/server/error-of.d.mts +12 -0
  31. package/dist/server/error-of.mjs +63 -0
  32. package/dist/server/gateway.d.mts +62 -0
  33. package/dist/server/gateway.mjs +110 -0
  34. package/dist/server/index.d.mts +7 -0
  35. package/dist/server/index.mjs +7 -0
  36. package/dist/server/node.d.mts +23 -0
  37. package/dist/server/node.mjs +81 -0
  38. package/dist/server/routes.d.mts +56 -0
  39. package/dist/server/routes.mjs +257 -0
  40. package/dist/server/webhook.d.mts +47 -0
  41. package/dist/server/webhook.mjs +99 -0
  42. package/dist/styles.css +380 -0
  43. package/dist/types.d.mts +635 -0
  44. package/dist/types.mjs +142 -0
  45. package/dist/units.d.mts +37 -0
  46. package/dist/units.mjs +76 -0
  47. package/package.json +73 -4
  48. package/stub/cli.mjs +8 -0
  49. package/stub/server.d.mts +36 -0
  50. package/stub/server.mjs +1385 -0
@@ -0,0 +1,97 @@
1
+ import { ERROR_CODES, ERROR_STATUS } from "./types.mjs";
2
+ // src/errors.ts
3
+ /**
4
+ * An error the Token Center answered with (or that the client synthesised for
5
+ * it: `center_unavailable` when it cannot be reached). `code` is the contract's
6
+ * stable code, `status` the HTTP status, `detail` the whole body the center
7
+ * sent (`action`, `capability`, `minimumCents`, `retryAfterSeconds` …).
8
+ *
9
+ * `message` is an English sentence safe to show a user.
10
+ */
11
+ var TokenCenterError = class extends Error {
12
+ code;
13
+ status;
14
+ detail;
15
+ constructor(detail, status = ERROR_STATUS[detail.code], options) {
16
+ super(detail.message, options);
17
+ this.name = "TokenCenterError";
18
+ this.code = detail.code;
19
+ this.status = status;
20
+ this.detail = detail;
21
+ }
22
+ /** The center's call this error belongs to (`x-token-call-id`), when it does: a failed or refused call. */
23
+ get callId() {
24
+ return this.detail.callId;
25
+ }
26
+ /** `invalid_request`: the JSON path of the offending field or header (`amountCents`, `tools[0].type`, `body`). */
27
+ get path() {
28
+ return this.detail.path;
29
+ }
30
+ /** What the app should offer the user: buy tokens, set up an own model, wait. */
31
+ get action() {
32
+ return this.detail.action;
33
+ }
34
+ };
35
+ const isErrorCode = (value) => typeof value === "string" && ERROR_CODES.includes(value);
36
+ /** Whether `error` is a `TokenCenterError`, optionally of one of `codes`. */
37
+ function isTokenError(error, ...codes) {
38
+ return error instanceof TokenCenterError && (codes.length === 0 || codes.includes(error.code));
39
+ }
40
+ /** `center_unavailable`: nothing answered, or only a 5xx with no contract body. Apps fail closed. */
41
+ function centerUnavailable(cause, message = "The token center is unavailable.") {
42
+ return new TokenCenterError({
43
+ code: "center_unavailable",
44
+ message
45
+ }, 503, cause === void 0 ? void 0 : { cause });
46
+ }
47
+ const asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
48
+ /** A `TokenErrorDetail` out of anything shaped like one, or null. */
49
+ function detailOf(value) {
50
+ const record = asRecord(value);
51
+ if (!record || !isErrorCode(record.code)) return null;
52
+ return {
53
+ ...record,
54
+ code: record.code,
55
+ message: typeof record.message === "string" && record.message ? record.message : defaultMessage(record.code)
56
+ };
57
+ }
58
+ function defaultMessage(code) {
59
+ return code === "center_unavailable" ? "The token center is unavailable." : `The token center answered ${code}.`;
60
+ }
61
+ const STATUS_CODE = {
62
+ 400: "invalid_request",
63
+ 401: "unauthenticated",
64
+ 402: "insufficient_balance",
65
+ 403: "forbidden",
66
+ 404: "not_found",
67
+ 409: "conflict",
68
+ 429: "rate_limited"
69
+ };
70
+ /**
71
+ * The error for a non-2xx answer. Reads, in order: the app API body
72
+ * (`{ error: {code, …} }`), the gateway body (`{ …, token_center: {code, …} }`),
73
+ * the `x-token-error` header; with none of them a 5xx is `center_unavailable`
74
+ * (a proxy's error page, a crash) and anything else is mapped by status.
75
+ */
76
+ function errorFromResponse(status, body, headers) {
77
+ const record = asRecord(body);
78
+ const detail = detailOf(record?.token_center) ?? detailOf(record?.error) ?? (isErrorCode(headers?.code) ? {
79
+ code: headers.code,
80
+ message: typeof asRecord(record?.error)?.message === "string" ? asRecord(record?.error)?.message : defaultMessage(headers.code)
81
+ } : null);
82
+ const retry = Number(headers?.retryAfter);
83
+ const callId = headers?.callId || void 0;
84
+ if (detail) {
85
+ if (detail.callId === void 0 && callId) detail.callId = callId;
86
+ if (detail.retryAfterSeconds === void 0 && Number.isFinite(retry) && retry > 0) detail.retryAfterSeconds = retry;
87
+ return new TokenCenterError(detail, status);
88
+ }
89
+ if (status >= 500) return centerUnavailable(void 0, `The token center answered ${status}.`);
90
+ return new TokenCenterError({
91
+ code: STATUS_CODE[status] ?? "internal_error",
92
+ message: `The token center answered ${status}.`,
93
+ ...callId ? { callId } : {},
94
+ ...Number.isFinite(retry) && retry > 0 ? { retryAfterSeconds: retry } : {}
95
+ }, status);
96
+ }
97
+ export { TokenCenterError, centerUnavailable, detailOf, errorFromResponse, isErrorCode, isTokenError };
@@ -0,0 +1,5 @@
1
+ import { APP_KEY_HEADERS, APP_KEY_PATTERN, AnthropicMessagesRequest, AppInfo, AppUnit, AppUser, Attribution, AutoRefill, AutoRefillFailedEvent, AutoRefillInput, BackendOrder, BackendOrderInput, Balance, BalanceEmptyEvent, BalanceLowEvent, BalanceSummary, CONTRACT_VERSION, CallCharge, CallEndpoint, CallRecord, CallStatus, CallUsage, CallsPage, CallsQuery, Capability, CardSetupRequest, CardSetupSession, Cents, ChatCompletionsRequest, CheckoutRequest, CheckoutSession, Currency, ERROR_CODES, ERROR_STATUS, ErrorCode, GatewayAnthropicError, GatewayModelList, GatewayOpenAIError, GrantExpiredEvent, GrantLot, GrantReceivedEvent, HeaderCharge, HistoryEntry, HistoryPage, IsoTime, Micros, ModelInfo, ModelPrice, OwnEndpoint, OwnEndpointInput, OwnEndpointResponse, OwnEndpointTest, Protocol, ProviderId, Purchase, PurchaseCompletedEvent, PurchaseOptions, PurchaseStatus, RouteDecision, RouteRequest, SalePrice, SalePrices, Source, SpeechRequest, TOKEN_HEADERS, TokenErrorBody, TokenErrorDetail, ToolChoice, UpsertUserRequest, VoiceInfo, WEBHOOK_EVENT_TYPES, WEBHOOK_RETRY_SECONDS, WEBHOOK_TOLERANCE_SECONDS, WebhookEnvelope, WebhookEvent, WebhookEventType } from "./types.mjs";
2
+ import { TokenCenterError, centerUnavailable, detailOf, errorFromResponse, isErrorCode, isTokenError } from "./errors.mjs";
3
+ import { FormatUnitsOptions, MICROS_PER_DOLLAR, creditFor, formatCompact, formatMoney, formatUnits, microsOf, microsToUsd, unitsOf } from "./units.mjs";
4
+ import { CardInput, CheckoutInput, TokenApi, TokenApiOptions, createTokenApi } from "./browser-api.mjs";
5
+ export { APP_KEY_HEADERS, APP_KEY_PATTERN, AnthropicMessagesRequest, AppInfo, AppUnit, AppUser, Attribution, AutoRefill, AutoRefillFailedEvent, AutoRefillInput, BackendOrder, BackendOrderInput, Balance, BalanceEmptyEvent, BalanceLowEvent, BalanceSummary, CONTRACT_VERSION, CallCharge, CallEndpoint, CallRecord, CallStatus, CallUsage, CallsPage, CallsQuery, Capability, CardInput, CardSetupRequest, CardSetupSession, Cents, ChatCompletionsRequest, CheckoutInput, CheckoutRequest, CheckoutSession, Currency, ERROR_CODES, ERROR_STATUS, ErrorCode, FormatUnitsOptions, GatewayAnthropicError, GatewayModelList, GatewayOpenAIError, GrantExpiredEvent, GrantLot, GrantReceivedEvent, HeaderCharge, HistoryEntry, HistoryPage, IsoTime, MICROS_PER_DOLLAR, Micros, ModelInfo, ModelPrice, OwnEndpoint, OwnEndpointInput, OwnEndpointResponse, OwnEndpointTest, Protocol, ProviderId, Purchase, PurchaseCompletedEvent, PurchaseOptions, PurchaseStatus, RouteDecision, RouteRequest, SalePrice, SalePrices, Source, SpeechRequest, TOKEN_HEADERS, TokenApi, TokenApiOptions, TokenCenterError, TokenErrorBody, TokenErrorDetail, ToolChoice, UpsertUserRequest, VoiceInfo, WEBHOOK_EVENT_TYPES, WEBHOOK_RETRY_SECONDS, WEBHOOK_TOLERANCE_SECONDS, WebhookEnvelope, WebhookEvent, WebhookEventType, centerUnavailable, createTokenApi, creditFor, detailOf, errorFromResponse, formatCompact, formatMoney, formatUnits, isErrorCode, isTokenError, microsOf, microsToUsd, unitsOf };
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import { APP_KEY_HEADERS, APP_KEY_PATTERN, CONTRACT_VERSION, ERROR_CODES, ERROR_STATUS, TOKEN_HEADERS, WEBHOOK_EVENT_TYPES, WEBHOOK_RETRY_SECONDS, WEBHOOK_TOLERANCE_SECONDS } from "./types.mjs";
2
+ import { TokenCenterError, centerUnavailable, detailOf, errorFromResponse, isErrorCode, isTokenError } from "./errors.mjs";
3
+ import { MICROS_PER_DOLLAR, creditFor, formatCompact, formatMoney, formatUnits, microsOf, microsToUsd, unitsOf } from "./units.mjs";
4
+ import { createTokenApi } from "./browser-api.mjs";
5
+ export { APP_KEY_HEADERS, APP_KEY_PATTERN, CONTRACT_VERSION, ERROR_CODES, ERROR_STATUS, MICROS_PER_DOLLAR, TOKEN_HEADERS, TokenCenterError, WEBHOOK_EVENT_TYPES, WEBHOOK_RETRY_SECONDS, WEBHOOK_TOLERANCE_SECONDS, centerUnavailable, createTokenApi, creditFor, detailOf, errorFromResponse, formatCompact, formatMoney, formatUnits, isErrorCode, isTokenError, microsOf, microsToUsd, unitsOf };
@@ -0,0 +1,21 @@
1
+ import { AppUnit, AutoRefill as AutoRefill$1, AutoRefillInput, Currency } from "../types.mjs";
2
+ import { LabelOverrides } from "./labels.mjs";
3
+ import { Styling } from "./ui.mjs";
4
+ export type AutoRefillProps = Styling & {
5
+ /** Current settings; loaded when not given. */
6
+ value?: AutoRefill$1;
7
+ unit?: AppUnit;
8
+ /** Save yourself; default `PUT`s to the app's route. */
9
+ onSave?: (input: AutoRefillInput) => Promise<unknown>;
10
+ /** Open the card form; default asks the app's route for a Stripe setup session and goes there. */
11
+ onAddCard?: () => Promise<unknown>;
12
+ onRemoveCard?: () => Promise<unknown>;
13
+ /** A path on the app to come back to after saving a card. */
14
+ returnPath?: string;
15
+ onRedirect?: (url: string) => void;
16
+ currencies?: Currency[];
17
+ labels?: LabelOverrides;
18
+ basePath?: string;
19
+ };
20
+ /** Auto-refill: a switch, the threshold, the amount, the monthly maximum, and the card on file. */
21
+ export declare function AutoRefill(props: AutoRefillProps): import("react").JSX.Element;
@@ -0,0 +1,269 @@
1
+ "use client";
2
+ import { formatMoney, microsOf, unitsOf } from "../units.mjs";
3
+ import { refreshTokens, useAppInfo, useAutoRefill, useLabels, useLocale, useTokenApi } from "./hooks.mjs";
4
+ import { Field, Notice, Panel, Segmented, part, stillNeeded, useAction } from "./ui.mjs";
5
+ import { useEffect, useState } from "react";
6
+ import { jsx, jsxs } from "react/jsx-runtime";
7
+ // src/react/autorefill.tsx
8
+ const major = (cents) => (cents / 100).toString();
9
+ const toCents = (text) => Math.round(Number(text.replace(",", ".")) * 100);
10
+ /** Auto-refill: a switch, the threshold, the amount, the monthly maximum, and the card on file. */
11
+ function AutoRefill(props) {
12
+ const labels = useLabels(props.labels);
13
+ const locale = useLocale();
14
+ const api = useTokenApi(props.basePath);
15
+ const styling = props;
16
+ const loaded = useAutoRefill({
17
+ basePath: props.basePath,
18
+ skip: props.value !== void 0
19
+ });
20
+ const app = useAppInfo({
21
+ basePath: props.basePath,
22
+ skip: props.unit !== void 0
23
+ });
24
+ const value = props.value ?? loaded.data;
25
+ const unit = props.unit ?? app.data?.unit ?? {
26
+ one: "token",
27
+ many: "tokens",
28
+ perDollar: 1e6
29
+ };
30
+ const [enabled, setEnabled] = useState(false);
31
+ const [threshold, setThreshold] = useState("");
32
+ const [amount, setAmount] = useState("");
33
+ const [currency, setCurrency] = useState("eur");
34
+ const [monthly, setMonthly] = useState("");
35
+ const [seeded, setSeeded] = useState();
36
+ const [problem, setProblem] = useState(null);
37
+ const [done, setDone] = useState(false);
38
+ const save = useAction(labels);
39
+ const card = useAction(labels);
40
+ useEffect(() => {
41
+ if (!value || value === seeded) return;
42
+ setSeeded(value);
43
+ setEnabled(value.enabled);
44
+ setThreshold(String(unitsOf(value.thresholdMicros, unit)));
45
+ setAmount(major(value.amountCents));
46
+ setCurrency(value.currency);
47
+ setMonthly(major(value.monthlyMaxCents));
48
+ }, [
49
+ value,
50
+ seeded,
51
+ unit
52
+ ]);
53
+ if (!value) return /* @__PURE__ */ jsx(Panel, {
54
+ title: labels.autoRefillTitle,
55
+ styling,
56
+ children: loaded.error ? /* @__PURE__ */ jsx(Notice, {
57
+ styling,
58
+ children: labels.unavailable
59
+ }) : /* @__PURE__ */ jsx("p", {
60
+ className: "tk-muted",
61
+ children: labels.loading
62
+ })
63
+ });
64
+ async function submit(event) {
65
+ event.preventDefault();
66
+ setDone(false);
67
+ setProblem(null);
68
+ const need = stillNeeded(labels, [
69
+ {
70
+ label: labels.threshold,
71
+ filled: threshold.trim() !== "" && Number(threshold) >= 0
72
+ },
73
+ {
74
+ label: labels.refillAmount,
75
+ filled: toCents(amount) > 0
76
+ },
77
+ {
78
+ label: labels.monthlyMax,
79
+ filled: toCents(monthly) > 0
80
+ }
81
+ ]);
82
+ if (need) return setProblem(need);
83
+ if (enabled && !value.card) return setProblem(labels.needCardFirst);
84
+ const input = {
85
+ enabled,
86
+ thresholdMicros: microsOf(Number(threshold), unit),
87
+ amountCents: toCents(amount),
88
+ currency,
89
+ monthlyMaxCents: toCents(monthly)
90
+ };
91
+ if (await save.run(() => props.onSave ? props.onSave(input) : api.setAutoRefill(input)) !== void 0) {
92
+ setDone(true);
93
+ loaded.refresh();
94
+ refreshTokens();
95
+ }
96
+ }
97
+ async function addCard() {
98
+ await card.run(async () => {
99
+ if (props.onAddCard) return void await props.onAddCard();
100
+ const session = await api.setupCard({
101
+ currency,
102
+ ...props.returnPath ? { returnPath: props.returnPath } : {}
103
+ });
104
+ if (props.onRedirect) props.onRedirect(session.url);
105
+ else window.location.assign(session.url);
106
+ });
107
+ }
108
+ async function removeCard() {
109
+ if (await card.run(async () => {
110
+ await (props.onRemoveCard ? props.onRemoveCard() : api.removeCard());
111
+ return true;
112
+ })) {
113
+ loaded.refresh();
114
+ refreshTokens();
115
+ }
116
+ }
117
+ const currencies = props.currencies ?? ["eur", "usd"];
118
+ return /* @__PURE__ */ jsxs(Panel, {
119
+ title: labels.autoRefillTitle,
120
+ styling,
121
+ children: [
122
+ /* @__PURE__ */ jsx("p", {
123
+ className: "tk-muted",
124
+ children: labels.autoRefillHelp
125
+ }),
126
+ value.failedAt && !value.enabled ? /* @__PURE__ */ jsx(Notice, {
127
+ styling,
128
+ children: labels.autoRefillFailed
129
+ }) : null,
130
+ /* @__PURE__ */ jsxs("form", {
131
+ className: part(styling, "form"),
132
+ onSubmit: submit,
133
+ noValidate: true,
134
+ children: [
135
+ /* @__PURE__ */ jsxs("label", {
136
+ className: part(styling, "switch"),
137
+ children: [
138
+ /* @__PURE__ */ jsx("input", {
139
+ type: "checkbox",
140
+ role: "switch",
141
+ checked: enabled,
142
+ onChange: (e) => setEnabled(e.target.checked)
143
+ }),
144
+ " ",
145
+ labels.autoRefillOn
146
+ ]
147
+ }),
148
+ /* @__PURE__ */ jsx(Field, {
149
+ label: labels.threshold,
150
+ required: true,
151
+ styling,
152
+ children: (p) => /* @__PURE__ */ jsx("input", {
153
+ ...p,
154
+ className: part(styling, "input"),
155
+ type: "number",
156
+ inputMode: "numeric",
157
+ min: "0",
158
+ step: "1",
159
+ value: threshold,
160
+ onChange: (e) => setThreshold(e.target.value)
161
+ })
162
+ }),
163
+ currencies.length > 1 ? /* @__PURE__ */ jsx(Segmented, {
164
+ label: labels.currency,
165
+ value: currency,
166
+ options: currencies.map((c) => ({
167
+ value: c,
168
+ label: c.toUpperCase()
169
+ })),
170
+ onChange: setCurrency,
171
+ styling
172
+ }) : null,
173
+ /* @__PURE__ */ jsx(Field, {
174
+ label: `${labels.refillAmount} (${currency.toUpperCase()})`,
175
+ required: true,
176
+ styling,
177
+ children: (p) => /* @__PURE__ */ jsx("input", {
178
+ ...p,
179
+ className: part(styling, "input"),
180
+ type: "text",
181
+ inputMode: "decimal",
182
+ value: amount,
183
+ onChange: (e) => setAmount(e.target.value)
184
+ })
185
+ }),
186
+ /* @__PURE__ */ jsx(Field, {
187
+ label: `${labels.monthlyMax} (${currency.toUpperCase()})`,
188
+ required: true,
189
+ styling,
190
+ children: (p) => /* @__PURE__ */ jsx("input", {
191
+ ...p,
192
+ className: part(styling, "input"),
193
+ type: "text",
194
+ inputMode: "decimal",
195
+ value: monthly,
196
+ onChange: (e) => setMonthly(e.target.value)
197
+ })
198
+ }),
199
+ /* @__PURE__ */ jsxs("div", {
200
+ className: part(styling, "field"),
201
+ children: [
202
+ /* @__PURE__ */ jsx("span", {
203
+ className: part(styling, "label"),
204
+ children: labels.card
205
+ }),
206
+ /* @__PURE__ */ jsx("p", {
207
+ className: "tk-card",
208
+ children: value.card ? value.card.label : labels.noCard
209
+ }),
210
+ /* @__PURE__ */ jsxs("div", {
211
+ className: part(styling, "actions"),
212
+ children: [/* @__PURE__ */ jsx("button", {
213
+ type: "button",
214
+ className: part(styling, "button"),
215
+ onClick: addCard,
216
+ "aria-busy": card.pending,
217
+ children: value.card ? labels.replaceCard : labels.addCard
218
+ }), value.card ? /* @__PURE__ */ jsx("button", {
219
+ type: "button",
220
+ className: part(styling, "button", "tk-button--quiet"),
221
+ onClick: removeCard,
222
+ "aria-busy": card.pending,
223
+ children: labels.removeCard
224
+ }) : null]
225
+ }),
226
+ card.error ? /* @__PURE__ */ jsx(Notice, {
227
+ styling,
228
+ children: card.error
229
+ }) : null
230
+ ]
231
+ }),
232
+ value.card ? /* @__PURE__ */ jsxs("p", {
233
+ className: "tk-muted",
234
+ children: [
235
+ formatMoney(toCents(amount) || 0, currency, locale),
236
+ " /",
237
+ " ",
238
+ formatMoney(toCents(monthly) || 0, currency, locale)
239
+ ]
240
+ }) : null,
241
+ problem ? /* @__PURE__ */ jsx(Notice, {
242
+ styling,
243
+ children: problem
244
+ }) : null,
245
+ save.error ? /* @__PURE__ */ jsx(Notice, {
246
+ styling,
247
+ children: save.error
248
+ }) : null,
249
+ done ? /* @__PURE__ */ jsx(Notice, {
250
+ kind: "ok",
251
+ styling,
252
+ children: labels.saved
253
+ }) : null,
254
+ /* @__PURE__ */ jsx("div", {
255
+ className: part(styling, "actions"),
256
+ children: /* @__PURE__ */ jsx("button", {
257
+ type: "submit",
258
+ className: part(styling, "button", "tk-button--primary"),
259
+ "aria-busy": save.pending,
260
+ disabled: save.pending,
261
+ children: save.pending ? labels.saving : labels.save
262
+ })
263
+ })
264
+ ]
265
+ })
266
+ ]
267
+ });
268
+ }
269
+ export { AutoRefill };
@@ -0,0 +1,23 @@
1
+ import { Balance } from "../types.mjs";
2
+ import { LabelOverrides } from "./labels.mjs";
3
+ import { Styling } from "./ui.mjs";
4
+ export type TokenBalanceProps = Styling & {
5
+ /** `pill`: one short line for a header ("84k credits"). `full`: the breakdown. */
6
+ variant?: "pill" | "full";
7
+ /** A balance you already hold; otherwise it is loaded and polled. */
8
+ balance?: Balance;
9
+ /** Poll interval in ms for the loaded balance. Default 30 s. */
10
+ refreshMs?: number;
11
+ /** Where the pill goes when pressed (the page that buys). */
12
+ href?: string;
13
+ /** Shown beside the full balance: a link or button to buy. */
14
+ action?: React.ReactNode;
15
+ labels?: LabelOverrides;
16
+ /** Where the app mounted its routes, if not `/api/tokens`. */
17
+ basePath?: string;
18
+ };
19
+ /**
20
+ * The balance: a compact pill for the header or the full breakdown. Colours
21
+ * come from `--tk-*`; the unit's name from the app's registration.
22
+ */
23
+ export declare function TokenBalance(props: TokenBalanceProps): import("react").JSX.Element;
@@ -0,0 +1,116 @@
1
+ "use client";
2
+ import { formatCompact, formatUnits, unitsOf } from "../units.mjs";
3
+ import { useBalance, useLabels, useLocale } from "./hooks.mjs";
4
+ import { fill } from "./labels.mjs";
5
+ import { Notice, Panel, cx, dateText, part } from "./ui.mjs";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
+ // src/react/balance.tsx
8
+ /**
9
+ * The balance: a compact pill for the header or the full breakdown. Colours
10
+ * come from `--tk-*`; the unit's name from the app's registration.
11
+ */
12
+ function TokenBalance(props) {
13
+ const labels = useLabels(props.labels);
14
+ const locale = useLocale();
15
+ const loaded = useBalance({
16
+ basePath: props.basePath,
17
+ refreshMs: props.refreshMs,
18
+ skip: props.balance !== void 0
19
+ });
20
+ const balance = props.balance ?? loaded.data;
21
+ const variant = props.variant ?? "pill";
22
+ const styling = props;
23
+ if (variant === "pill") {
24
+ const content = balance ? /* @__PURE__ */ jsxs(Fragment, { children: [
25
+ /* @__PURE__ */ jsx("span", {
26
+ className: "tk-balance__amount",
27
+ children: formatCompact(unitsOf(balance.availableMicros, balance.unit))
28
+ }),
29
+ " ",
30
+ /* @__PURE__ */ jsx("span", {
31
+ className: "tk-balance__unit tk-hide-narrow",
32
+ children: balance.unit.many
33
+ })
34
+ ] }) : loaded.error ? /* @__PURE__ */ jsx("span", {
35
+ title: labels.balanceUnknown,
36
+ children: "—"
37
+ }) : /* @__PURE__ */ jsx("span", {
38
+ "aria-label": labels.loading,
39
+ children: "…"
40
+ });
41
+ const empty = balance !== void 0 && balance.availableMicros <= 0;
42
+ const classes = cx(part(styling, "balance", "tk-balance--pill", empty && "tk-balance--empty", styling.className));
43
+ const title = balance ? formatUnits(balance.availableMicros, balance.unit, { locale }) : void 0;
44
+ return props.href ? /* @__PURE__ */ jsx("a", {
45
+ className: classes,
46
+ href: props.href,
47
+ title,
48
+ children: content
49
+ }) : /* @__PURE__ */ jsx("span", {
50
+ className: classes,
51
+ role: "status",
52
+ title,
53
+ children: content
54
+ });
55
+ }
56
+ return /* @__PURE__ */ jsx(Panel, {
57
+ title: labels.balance,
58
+ styling,
59
+ children: !balance ? loaded.error ? /* @__PURE__ */ jsx(Notice, {
60
+ styling,
61
+ children: labels.unavailable
62
+ }) : /* @__PURE__ */ jsx("p", {
63
+ className: "tk-muted",
64
+ children: labels.loading
65
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
66
+ /* @__PURE__ */ jsxs("p", {
67
+ className: part(styling, "balance", "tk-balance--full"),
68
+ role: "status",
69
+ children: [
70
+ /* @__PURE__ */ jsx("span", {
71
+ className: "tk-balance__amount",
72
+ children: formatUnits(balance.availableMicros, balance.unit, {
73
+ locale,
74
+ bare: true
75
+ })
76
+ }),
77
+ " ",
78
+ /* @__PURE__ */ jsx("span", {
79
+ className: "tk-balance__unit",
80
+ children: balance.unit.many
81
+ })
82
+ ]
83
+ }),
84
+ balance.availableMicros <= 0 ? /* @__PURE__ */ jsx("p", {
85
+ className: "tk-muted",
86
+ children: labels.empty
87
+ }) : null,
88
+ /* @__PURE__ */ jsxs("dl", {
89
+ className: part(styling, "breakdown"),
90
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("dt", { children: labels.purchased }), /* @__PURE__ */ jsx("dd", { children: formatUnits(balance.purchasedMicros, balance.unit, {
91
+ locale,
92
+ bare: true
93
+ }) })] }), balance.grantsMicros > 0 ? /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("dt", { children: labels.fromGrants }), /* @__PURE__ */ jsx("dd", { children: formatUnits(balance.grantsMicros, balance.unit, {
94
+ locale,
95
+ bare: true
96
+ }) })] }) : null]
97
+ }),
98
+ balance.nextExpiry ? /* @__PURE__ */ jsx("p", {
99
+ className: "tk-muted",
100
+ children: fill(labels.expiring, {
101
+ amount: formatUnits(balance.nextExpiry.micros, balance.unit, { locale }),
102
+ date: dateText(balance.nextExpiry.at, locale)
103
+ })
104
+ }) : null,
105
+ balance.purchasedMicros < 0 ? /* @__PURE__ */ jsx("p", {
106
+ className: "tk-muted",
107
+ children: fill(labels.shortfall, { amount: formatUnits(-balance.purchasedMicros, balance.unit, { locale }) })
108
+ }) : null,
109
+ props.action ? /* @__PURE__ */ jsx("div", {
110
+ className: part(styling, "actions"),
111
+ children: props.action
112
+ }) : null
113
+ ] })
114
+ });
115
+ }
116
+ export { TokenBalance };
@@ -0,0 +1,27 @@
1
+ import { CheckoutInput } from "../browser-api.mjs";
2
+ import { AppUnit, CheckoutSession, Currency } from "../types.mjs";
3
+ import { LabelOverrides } from "./labels.mjs";
4
+ import { Styling } from "./ui.mjs";
5
+ export type BuyTokensProps = Styling & {
6
+ /** The packs on offer, in cents of the chosen currency. Default 5, 10, 25, 50. */
7
+ amounts?: number[];
8
+ /** Offer a free amount as well. Default true. */
9
+ allowOther?: boolean;
10
+ /** Currencies on offer (those the center has a price for). Default: all of them. */
11
+ currencies?: Currency[];
12
+ defaultCurrency?: Currency;
13
+ /** A path on the app to come back to after paying (default `/`). */
14
+ returnPath?: string;
15
+ /** Offer "save my card for auto-refill". Default true. */
16
+ offerSaveCard?: boolean;
17
+ /** The app's unit, to say what an amount buys; read from the center if not given. */
18
+ unit?: AppUnit;
19
+ /** Start the checkout yourself; default posts to the app's mounted route. */
20
+ onCheckout?: (input: CheckoutInput) => Promise<Pick<CheckoutSession, "url">>;
21
+ /** Where to send the browser; default `location.assign`. */
22
+ onRedirect?: (url: string) => void;
23
+ labels?: LabelOverrides;
24
+ basePath?: string;
25
+ };
26
+ /** Choose an amount and a currency, start Stripe Checkout through the app's route, and go there. */
27
+ export declare function BuyTokens(props: BuyTokensProps): import("react").JSX.Element;