@ai-billing/nextjs 0.0.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 (93) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +50 -0
  3. package/dist/index.cjs +36 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +4 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +10 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/polar/CreditTopUpPolar.cjs +278 -0
  10. package/dist/polar/CreditTopUpPolar.cjs.map +1 -0
  11. package/dist/polar/CreditTopUpPolar.d.cts +9 -0
  12. package/dist/polar/CreditTopUpPolar.d.ts +9 -0
  13. package/dist/polar/CreditTopUpPolar.js +244 -0
  14. package/dist/polar/CreditTopUpPolar.js.map +1 -0
  15. package/dist/polar/CreditUsagePolar.cjs +133 -0
  16. package/dist/polar/CreditUsagePolar.cjs.map +1 -0
  17. package/dist/polar/CreditUsagePolar.d.cts +10 -0
  18. package/dist/polar/CreditUsagePolar.d.ts +10 -0
  19. package/dist/polar/CreditUsagePolar.js +107 -0
  20. package/dist/polar/CreditUsagePolar.js.map +1 -0
  21. package/dist/polar/createCheckout.cjs +47 -0
  22. package/dist/polar/createCheckout.cjs.map +1 -0
  23. package/dist/polar/createCheckout.d.cts +9 -0
  24. package/dist/polar/createCheckout.d.ts +9 -0
  25. package/dist/polar/createCheckout.js +23 -0
  26. package/dist/polar/createCheckout.js.map +1 -0
  27. package/dist/polar/fetchPolarConfig.cjs +52 -0
  28. package/dist/polar/fetchPolarConfig.cjs.map +1 -0
  29. package/dist/polar/fetchPolarConfig.d.cts +6 -0
  30. package/dist/polar/fetchPolarConfig.d.ts +6 -0
  31. package/dist/polar/fetchPolarConfig.js +28 -0
  32. package/dist/polar/fetchPolarConfig.js.map +1 -0
  33. package/dist/polar/fetchPolarUsage.cjs +64 -0
  34. package/dist/polar/fetchPolarUsage.cjs.map +1 -0
  35. package/dist/polar/fetchPolarUsage.d.cts +9 -0
  36. package/dist/polar/fetchPolarUsage.d.ts +9 -0
  37. package/dist/polar/fetchPolarUsage.js +40 -0
  38. package/dist/polar/fetchPolarUsage.js.map +1 -0
  39. package/dist/polar/fetchTopUpConfig.cjs +55 -0
  40. package/dist/polar/fetchTopUpConfig.cjs.map +1 -0
  41. package/dist/polar/fetchTopUpConfig.d.cts +10 -0
  42. package/dist/polar/fetchTopUpConfig.d.ts +10 -0
  43. package/dist/polar/fetchTopUpConfig.js +31 -0
  44. package/dist/polar/fetchTopUpConfig.js.map +1 -0
  45. package/dist/polar/types.cjs +17 -0
  46. package/dist/polar/types.cjs.map +1 -0
  47. package/dist/polar/types.d.cts +18 -0
  48. package/dist/polar/types.d.ts +18 -0
  49. package/dist/polar/types.js +1 -0
  50. package/dist/polar/types.js.map +1 -0
  51. package/dist/server.cjs +44 -0
  52. package/dist/server.cjs.map +1 -0
  53. package/dist/server.d.cts +8 -0
  54. package/dist/server.d.ts +8 -0
  55. package/dist/server.js +15 -0
  56. package/dist/server.js.map +1 -0
  57. package/dist/stripe/CreditUsageStripe.cjs +158 -0
  58. package/dist/stripe/CreditUsageStripe.cjs.map +1 -0
  59. package/dist/stripe/CreditUsageStripe.d.cts +11 -0
  60. package/dist/stripe/CreditUsageStripe.d.ts +11 -0
  61. package/dist/stripe/CreditUsageStripe.js +132 -0
  62. package/dist/stripe/CreditUsageStripe.js.map +1 -0
  63. package/dist/stripe/fetchStripeConfig.cjs +52 -0
  64. package/dist/stripe/fetchStripeConfig.cjs.map +1 -0
  65. package/dist/stripe/fetchStripeConfig.d.cts +6 -0
  66. package/dist/stripe/fetchStripeConfig.d.ts +6 -0
  67. package/dist/stripe/fetchStripeConfig.js +28 -0
  68. package/dist/stripe/fetchStripeConfig.js.map +1 -0
  69. package/dist/stripe/fetchStripeUsage.cjs +67 -0
  70. package/dist/stripe/fetchStripeUsage.cjs.map +1 -0
  71. package/dist/stripe/fetchStripeUsage.d.cts +9 -0
  72. package/dist/stripe/fetchStripeUsage.d.ts +9 -0
  73. package/dist/stripe/fetchStripeUsage.js +33 -0
  74. package/dist/stripe/fetchStripeUsage.js.map +1 -0
  75. package/dist/stripe/types.cjs +17 -0
  76. package/dist/stripe/types.cjs.map +1 -0
  77. package/dist/stripe/types.d.cts +9 -0
  78. package/dist/stripe/types.d.ts +9 -0
  79. package/dist/stripe/types.js +1 -0
  80. package/dist/stripe/types.js.map +1 -0
  81. package/dist/styles.cjs +83 -0
  82. package/dist/styles.cjs.map +1 -0
  83. package/dist/styles.d.cts +11 -0
  84. package/dist/styles.d.ts +11 -0
  85. package/dist/styles.js +53 -0
  86. package/dist/styles.js.map +1 -0
  87. package/dist/utils.cjs +53 -0
  88. package/dist/utils.cjs.map +1 -0
  89. package/dist/utils.d.cts +20 -0
  90. package/dist/utils.d.ts +20 -0
  91. package/dist/utils.js +26 -0
  92. package/dist/utils.js.map +1 -0
  93. package/package.json +82 -0
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var CreditUsageStripe_exports = {};
31
+ __export(CreditUsageStripe_exports, {
32
+ CreditUsageStripe: () => CreditUsageStripe
33
+ });
34
+ module.exports = __toCommonJS(CreditUsageStripe_exports);
35
+ var import_jsx_runtime = require("react/jsx-runtime");
36
+ var import_react = __toESM(require("react"), 1);
37
+ var import_styles = require("../styles.js");
38
+ var import_utils = require("../utils.js");
39
+ var import_fetchStripeUsage = require("./fetchStripeUsage.js");
40
+ function monthLabel(d) {
41
+ return d.toLocaleDateString("en-US", {
42
+ month: "long",
43
+ year: "numeric",
44
+ timeZone: "UTC"
45
+ });
46
+ }
47
+ const CreditUsageStripe = import_react.default.forwardRef(
48
+ ({ stripeCustomerId, budget, label, unit = "$", className, style, ...props }, ref) => {
49
+ const cls = (className ?? "").trim();
50
+ const [data, setData] = (0, import_react.useState)(null);
51
+ const [loading, setLoading] = (0, import_react.useState)(true);
52
+ (0, import_react.useEffect)(() => {
53
+ let cancelled = false;
54
+ setLoading(true);
55
+ (async () => {
56
+ try {
57
+ const result = await (0, import_fetchStripeUsage.fetchStripeUsage)(stripeCustomerId);
58
+ if (!cancelled) setData(result);
59
+ } catch {
60
+ if (!cancelled) setData(null);
61
+ } finally {
62
+ if (!cancelled) setLoading(false);
63
+ }
64
+ })();
65
+ return () => {
66
+ cancelled = true;
67
+ };
68
+ }, [stripeCustomerId]);
69
+ if (loading) {
70
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
71
+ "div",
72
+ {
73
+ ref,
74
+ className: cls,
75
+ style: { ...import_styles.cardBase, height: 120, opacity: 0.5, ...style },
76
+ ...props
77
+ }
78
+ );
79
+ }
80
+ if (!data?.found) {
81
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
82
+ "div",
83
+ {
84
+ ref,
85
+ className: cls,
86
+ style: { ...import_styles.cardBase, ...style },
87
+ ...props,
88
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { style: import_styles.mutedText, children: "No usage data available." })
89
+ }
90
+ );
91
+ }
92
+ const cardLabel = label ?? `${monthLabel(/* @__PURE__ */ new Date())} usage`;
93
+ const showBar = budget !== void 0;
94
+ const pct = budget && budget > 0 ? data.aggregatedValue / budget * 100 : 0;
95
+ const barPct = Math.min(pct, 100);
96
+ const color = (0, import_utils.barColor)(barPct);
97
+ const remaining = budget - data.aggregatedValue;
98
+ const over = remaining < 0;
99
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
100
+ "div",
101
+ {
102
+ ref,
103
+ className: cls,
104
+ style: { ...import_styles.cardBase, ...style },
105
+ ...props,
106
+ children: [
107
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { style: import_styles.heading, children: cardLabel }),
108
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
109
+ "div",
110
+ {
111
+ style: {
112
+ display: "flex",
113
+ alignItems: "baseline",
114
+ gap: 6,
115
+ margin: "0 0 14px"
116
+ },
117
+ children: [
118
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: import_styles.bigNumber, children: (0, import_utils.fmt)(data.aggregatedValue, unit) }),
119
+ showBar && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { style: import_styles.subLabel, children: [
120
+ "/ ",
121
+ (0, import_utils.fmt)(budget, unit)
122
+ ] })
123
+ ]
124
+ }
125
+ ),
126
+ showBar && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
127
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: import_styles.barTrack, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
128
+ "div",
129
+ {
130
+ style: {
131
+ height: "100%",
132
+ width: `${barPct}%`,
133
+ borderRadius: 3,
134
+ background: color,
135
+ transition: "width 0.3s ease"
136
+ }
137
+ }
138
+ ) }),
139
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: import_styles.barLabels, children: [
140
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
141
+ pct.toFixed(0),
142
+ "% used",
143
+ over ? " (over)" : ""
144
+ ] }),
145
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: over ? `${(0, import_utils.fmt)(Math.abs(remaining), unit)} over` : `${(0, import_utils.fmt)(remaining, unit)} remaining` })
146
+ ] })
147
+ ] })
148
+ ]
149
+ }
150
+ );
151
+ }
152
+ );
153
+ CreditUsageStripe.displayName = "CreditUsageStripe";
154
+ // Annotate the CommonJS export names for ESM import in node:
155
+ 0 && (module.exports = {
156
+ CreditUsageStripe
157
+ });
158
+ //# sourceMappingURL=CreditUsageStripe.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/CreditUsageStripe.tsx"],"sourcesContent":["'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport {\n cardBase,\n heading,\n mutedText,\n bigNumber,\n subLabel,\n barTrack,\n barLabels,\n} from '../styles.js';\nimport { barColor, fmt } from '../utils.js';\nimport { fetchStripeUsage } from './fetchStripeUsage.js';\nimport type { StripeUsageData } from './types.js';\n\nexport interface CreditUsageStripeProps extends React.HTMLAttributes<HTMLDivElement> {\n stripeCustomerId: string;\n budget?: number;\n label?: string;\n unit?: string;\n}\n\nfunction monthLabel(d: Date): string {\n return d.toLocaleDateString('en-US', {\n month: 'long',\n year: 'numeric',\n timeZone: 'UTC',\n });\n}\n\nexport const CreditUsageStripe = React.forwardRef<\n HTMLDivElement,\n CreditUsageStripeProps\n>(\n (\n { stripeCustomerId, budget, label, unit = '$', className, style, ...props },\n ref,\n ) => {\n const cls = (className ?? '').trim();\n const [data, setData] = useState<StripeUsageData | null>(null);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n (async () => {\n try {\n const result = await fetchStripeUsage(stripeCustomerId);\n if (!cancelled) setData(result);\n } catch {\n if (!cancelled) setData(null);\n } finally {\n if (!cancelled) setLoading(false);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [stripeCustomerId]);\n\n if (loading) {\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, height: 120, opacity: 0.5, ...style }}\n {...props}\n />\n );\n }\n\n if (!data?.found) {\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, ...style }}\n {...props}\n >\n <p style={mutedText}>No usage data available.</p>\n </div>\n );\n }\n\n const cardLabel = label ?? `${monthLabel(new Date())} usage`;\n const showBar = budget !== undefined;\n const pct =\n budget && budget > 0 ? (data.aggregatedValue / budget) * 100 : 0;\n const barPct = Math.min(pct, 100);\n const color = barColor(barPct);\n const remaining = budget! - data.aggregatedValue;\n const over = remaining < 0;\n\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, ...style }}\n {...props}\n >\n <p style={heading}>{cardLabel}</p>\n <div\n style={{\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n margin: '0 0 14px',\n }}\n >\n <span style={bigNumber}>{fmt(data.aggregatedValue, unit)}</span>\n {showBar && <span style={subLabel}>/ {fmt(budget!, unit)}</span>}\n </div>\n {showBar && (\n <>\n <div style={barTrack}>\n <div\n style={{\n height: '100%',\n width: `${barPct}%`,\n borderRadius: 3,\n background: color,\n transition: 'width 0.3s ease',\n }}\n />\n </div>\n <div style={barLabels}>\n <span>\n {pct.toFixed(0)}% used{over ? ' (over)' : ''}\n </span>\n <span>\n {over\n ? `${fmt(Math.abs(remaining), unit)} over`\n : `${fmt(remaining, unit)} remaining`}\n </span>\n </div>\n </>\n )}\n </div>\n );\n },\n);\nCreditUsageStripe.displayName = 'CreditUsageStripe';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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AAC,UACE,iBACG,OAAG,kBAAI,KAAK,IAAI,SAAS,GAAG,IAAI,CAAC,UACjC,OAAG,kBAAI,WAAW,IAAI,CAAC,cAC7B;AAAA,eACF;AAAA,aACF;AAAA;AAAA;AAAA,IAEJ;AAAA,EAEJ;AACF;AACA,kBAAkB,cAAc;","names":["React"]}
@@ -0,0 +1,11 @@
1
+ import React from 'react';
2
+
3
+ interface CreditUsageStripeProps extends React.HTMLAttributes<HTMLDivElement> {
4
+ stripeCustomerId: string;
5
+ budget?: number;
6
+ label?: string;
7
+ unit?: string;
8
+ }
9
+ declare const CreditUsageStripe: React.ForwardRefExoticComponent<CreditUsageStripeProps & React.RefAttributes<HTMLDivElement>>;
10
+
11
+ export { CreditUsageStripe, type CreditUsageStripeProps };
@@ -0,0 +1,11 @@
1
+ import React from 'react';
2
+
3
+ interface CreditUsageStripeProps extends React.HTMLAttributes<HTMLDivElement> {
4
+ stripeCustomerId: string;
5
+ budget?: number;
6
+ label?: string;
7
+ unit?: string;
8
+ }
9
+ declare const CreditUsageStripe: React.ForwardRefExoticComponent<CreditUsageStripeProps & React.RefAttributes<HTMLDivElement>>;
10
+
11
+ export { CreditUsageStripe, type CreditUsageStripeProps };
@@ -0,0 +1,132 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import React, { useState, useEffect } from "react";
4
+ import {
5
+ cardBase,
6
+ heading,
7
+ mutedText,
8
+ bigNumber,
9
+ subLabel,
10
+ barTrack,
11
+ barLabels
12
+ } from "../styles.js";
13
+ import { barColor, fmt } from "../utils.js";
14
+ import { fetchStripeUsage } from "./fetchStripeUsage.js";
15
+ function monthLabel(d) {
16
+ return d.toLocaleDateString("en-US", {
17
+ month: "long",
18
+ year: "numeric",
19
+ timeZone: "UTC"
20
+ });
21
+ }
22
+ const CreditUsageStripe = React.forwardRef(
23
+ ({ stripeCustomerId, budget, label, unit = "$", className, style, ...props }, ref) => {
24
+ const cls = (className ?? "").trim();
25
+ const [data, setData] = useState(null);
26
+ const [loading, setLoading] = useState(true);
27
+ useEffect(() => {
28
+ let cancelled = false;
29
+ setLoading(true);
30
+ (async () => {
31
+ try {
32
+ const result = await fetchStripeUsage(stripeCustomerId);
33
+ if (!cancelled) setData(result);
34
+ } catch {
35
+ if (!cancelled) setData(null);
36
+ } finally {
37
+ if (!cancelled) setLoading(false);
38
+ }
39
+ })();
40
+ return () => {
41
+ cancelled = true;
42
+ };
43
+ }, [stripeCustomerId]);
44
+ if (loading) {
45
+ return /* @__PURE__ */ jsx(
46
+ "div",
47
+ {
48
+ ref,
49
+ className: cls,
50
+ style: { ...cardBase, height: 120, opacity: 0.5, ...style },
51
+ ...props
52
+ }
53
+ );
54
+ }
55
+ if (!data?.found) {
56
+ return /* @__PURE__ */ jsx(
57
+ "div",
58
+ {
59
+ ref,
60
+ className: cls,
61
+ style: { ...cardBase, ...style },
62
+ ...props,
63
+ children: /* @__PURE__ */ jsx("p", { style: mutedText, children: "No usage data available." })
64
+ }
65
+ );
66
+ }
67
+ const cardLabel = label ?? `${monthLabel(/* @__PURE__ */ new Date())} usage`;
68
+ const showBar = budget !== void 0;
69
+ const pct = budget && budget > 0 ? data.aggregatedValue / budget * 100 : 0;
70
+ const barPct = Math.min(pct, 100);
71
+ const color = barColor(barPct);
72
+ const remaining = budget - data.aggregatedValue;
73
+ const over = remaining < 0;
74
+ return /* @__PURE__ */ jsxs(
75
+ "div",
76
+ {
77
+ ref,
78
+ className: cls,
79
+ style: { ...cardBase, ...style },
80
+ ...props,
81
+ children: [
82
+ /* @__PURE__ */ jsx("p", { style: heading, children: cardLabel }),
83
+ /* @__PURE__ */ jsxs(
84
+ "div",
85
+ {
86
+ style: {
87
+ display: "flex",
88
+ alignItems: "baseline",
89
+ gap: 6,
90
+ margin: "0 0 14px"
91
+ },
92
+ children: [
93
+ /* @__PURE__ */ jsx("span", { style: bigNumber, children: fmt(data.aggregatedValue, unit) }),
94
+ showBar && /* @__PURE__ */ jsxs("span", { style: subLabel, children: [
95
+ "/ ",
96
+ fmt(budget, unit)
97
+ ] })
98
+ ]
99
+ }
100
+ ),
101
+ showBar && /* @__PURE__ */ jsxs(Fragment, { children: [
102
+ /* @__PURE__ */ jsx("div", { style: barTrack, children: /* @__PURE__ */ jsx(
103
+ "div",
104
+ {
105
+ style: {
106
+ height: "100%",
107
+ width: `${barPct}%`,
108
+ borderRadius: 3,
109
+ background: color,
110
+ transition: "width 0.3s ease"
111
+ }
112
+ }
113
+ ) }),
114
+ /* @__PURE__ */ jsxs("div", { style: barLabels, children: [
115
+ /* @__PURE__ */ jsxs("span", { children: [
116
+ pct.toFixed(0),
117
+ "% used",
118
+ over ? " (over)" : ""
119
+ ] }),
120
+ /* @__PURE__ */ jsx("span", { children: over ? `${fmt(Math.abs(remaining), unit)} over` : `${fmt(remaining, unit)} remaining` })
121
+ ] })
122
+ ] })
123
+ ]
124
+ }
125
+ );
126
+ }
127
+ );
128
+ CreditUsageStripe.displayName = "CreditUsageStripe";
129
+ export {
130
+ CreditUsageStripe
131
+ };
132
+ //# sourceMappingURL=CreditUsageStripe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/CreditUsageStripe.tsx"],"sourcesContent":["'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport {\n cardBase,\n heading,\n mutedText,\n bigNumber,\n subLabel,\n barTrack,\n barLabels,\n} from '../styles.js';\nimport { barColor, fmt } from '../utils.js';\nimport { fetchStripeUsage } from './fetchStripeUsage.js';\nimport type { StripeUsageData } from './types.js';\n\nexport interface CreditUsageStripeProps extends React.HTMLAttributes<HTMLDivElement> {\n stripeCustomerId: string;\n budget?: number;\n label?: string;\n unit?: string;\n}\n\nfunction monthLabel(d: Date): string {\n return d.toLocaleDateString('en-US', {\n month: 'long',\n year: 'numeric',\n timeZone: 'UTC',\n });\n}\n\nexport const CreditUsageStripe = React.forwardRef<\n HTMLDivElement,\n CreditUsageStripeProps\n>(\n (\n { stripeCustomerId, budget, label, unit = '$', className, style, ...props },\n ref,\n ) => {\n const cls = (className ?? '').trim();\n const [data, setData] = useState<StripeUsageData | null>(null);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n (async () => {\n try {\n const result = await fetchStripeUsage(stripeCustomerId);\n if (!cancelled) setData(result);\n } catch {\n if (!cancelled) setData(null);\n } finally {\n if (!cancelled) setLoading(false);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [stripeCustomerId]);\n\n if (loading) {\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, height: 120, opacity: 0.5, ...style }}\n {...props}\n />\n );\n }\n\n if (!data?.found) {\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, ...style }}\n {...props}\n >\n <p style={mutedText}>No usage data available.</p>\n </div>\n );\n }\n\n const cardLabel = label ?? `${monthLabel(new Date())} usage`;\n const showBar = budget !== undefined;\n const pct =\n budget && budget > 0 ? (data.aggregatedValue / budget) * 100 : 0;\n const barPct = Math.min(pct, 100);\n const color = barColor(barPct);\n const remaining = budget! - data.aggregatedValue;\n const over = remaining < 0;\n\n return (\n <div\n ref={ref}\n className={cls}\n style={{ ...cardBase, ...style }}\n {...props}\n >\n <p style={heading}>{cardLabel}</p>\n <div\n style={{\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n margin: '0 0 14px',\n }}\n >\n <span style={bigNumber}>{fmt(data.aggregatedValue, unit)}</span>\n {showBar && <span style={subLabel}>/ {fmt(budget!, unit)}</span>}\n </div>\n {showBar && (\n <>\n <div style={barTrack}>\n <div\n style={{\n height: '100%',\n width: `${barPct}%`,\n borderRadius: 3,\n background: color,\n transition: 'width 0.3s ease',\n }}\n />\n </div>\n <div style={barLabels}>\n <span>\n {pct.toFixed(0)}% used{over ? ' (over)' : ''}\n </span>\n <span>\n {over\n ? `${fmt(Math.abs(remaining), unit)} over`\n : `${fmt(remaining, unit)} remaining`}\n </span>\n </div>\n </>\n )}\n </div>\n );\n },\n);\nCreditUsageStrip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AI,OAAO,WACV;AAAA,mCAAC,UACE;AAAA,oBAAI,QAAQ,CAAC;AAAA,gBAAE;AAAA,gBAAO,OAAO,YAAY;AAAA,iBAC5C;AAAA,cACA,oBAAC,UACE,iBACG,GAAG,IAAI,KAAK,IAAI,SAAS,GAAG,IAAI,CAAC,UACjC,GAAG,IAAI,WAAW,IAAI,CAAC,cAC7B;AAAA,eACF;AAAA,aACF;AAAA;AAAA;AAAA,IAEJ;AAAA,EAEJ;AACF;AACA,kBAAkB,cAAc;","names":[]}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ "use server";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var fetchStripeConfig_exports = {};
21
+ __export(fetchStripeConfig_exports, {
22
+ fetchStripeConfig: () => fetchStripeConfig
23
+ });
24
+ module.exports = __toCommonJS(fetchStripeConfig_exports);
25
+ async function fetchStripeConfig() {
26
+ try {
27
+ const key = process.env.NAREV_API_KEY;
28
+ if (!key) {
29
+ console.error("fetchStripeConfig: NAREV_API_KEY is not set");
30
+ return null;
31
+ }
32
+ const res = await fetch("https://www.narev.ai/api/billing-target/stripe", {
33
+ headers: { Authorization: `Bearer ${key}` }
34
+ });
35
+ if (!res.ok) {
36
+ console.error(
37
+ `fetchStripeConfig: Narev returned ${res.status} ${res.statusText}`
38
+ );
39
+ return null;
40
+ }
41
+ const json = await res.json();
42
+ return json.data;
43
+ } catch (error) {
44
+ console.error("fetchStripeConfig:", error);
45
+ return null;
46
+ }
47
+ }
48
+ // Annotate the CommonJS export names for ESM import in node:
49
+ 0 && (module.exports = {
50
+ fetchStripeConfig
51
+ });
52
+ //# sourceMappingURL=fetchStripeConfig.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/fetchStripeConfig.ts"],"sourcesContent":["'use server';\n\nimport type { StripeConfig } from './types.js';\n\n/** Fetches Stripe billing configuration from the Narev API */\nexport async function fetchStripeConfig(): Promise<StripeConfig | null> {\n try {\n const key = process.env.NAREV_API_KEY;\n if (!key) {\n console.error('fetchStripeConfig: NAREV_API_KEY is not set');\n return null;\n }\n\n const res = await fetch('https://www.narev.ai/api/billing-target/stripe', {\n headers: { Authorization: `Bearer ${key}` },\n });\n if (!res.ok) {\n console.error(\n `fetchStripeConfig: Narev returned ${res.status} ${res.statusText}`,\n );\n return null;\n }\n const json = await res.json();\n return json.data as StripeConfig;\n } catch (error) {\n console.error('fetchStripeConfig:', error);\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,eAAsB,oBAAkD;AACtE,MAAI;AACF,UAAM,MAAM,QAAQ,IAAI;AACxB,QAAI,CAAC,KAAK;AACR,cAAQ,MAAM,6CAA6C;AAC3D,aAAO;AAAA,IACT;AAEA,UAAM,MAAM,MAAM,MAAM,kDAAkD;AAAA,MACxE,SAAS,EAAE,eAAe,UAAU,GAAG,GAAG;AAAA,IAC5C,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ;AAAA,QACN,qCAAqC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,MACnE;AACA,aAAO;AAAA,IACT;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,WAAO,KAAK;AAAA,EACd,SAAS,OAAO;AACd,YAAQ,MAAM,sBAAsB,KAAK;AACzC,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,6 @@
1
+ import { StripeConfig } from './types.cjs';
2
+
3
+ /** Fetches Stripe billing configuration from the Narev API */
4
+ declare function fetchStripeConfig(): Promise<StripeConfig | null>;
5
+
6
+ export { fetchStripeConfig };
@@ -0,0 +1,6 @@
1
+ import { StripeConfig } from './types.js';
2
+
3
+ /** Fetches Stripe billing configuration from the Narev API */
4
+ declare function fetchStripeConfig(): Promise<StripeConfig | null>;
5
+
6
+ export { fetchStripeConfig };
@@ -0,0 +1,28 @@
1
+ "use server";
2
+ async function fetchStripeConfig() {
3
+ try {
4
+ const key = process.env.NAREV_API_KEY;
5
+ if (!key) {
6
+ console.error("fetchStripeConfig: NAREV_API_KEY is not set");
7
+ return null;
8
+ }
9
+ const res = await fetch("https://www.narev.ai/api/billing-target/stripe", {
10
+ headers: { Authorization: `Bearer ${key}` }
11
+ });
12
+ if (!res.ok) {
13
+ console.error(
14
+ `fetchStripeConfig: Narev returned ${res.status} ${res.statusText}`
15
+ );
16
+ return null;
17
+ }
18
+ const json = await res.json();
19
+ return json.data;
20
+ } catch (error) {
21
+ console.error("fetchStripeConfig:", error);
22
+ return null;
23
+ }
24
+ }
25
+ export {
26
+ fetchStripeConfig
27
+ };
28
+ //# sourceMappingURL=fetchStripeConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/fetchStripeConfig.ts"],"sourcesContent":["'use server';\n\nimport type { StripeConfig } from './types.js';\n\n/** Fetches Stripe billing configuration from the Narev API */\nexport async function fetchStripeConfig(): Promise<StripeConfig | null> {\n try {\n const key = process.env.NAREV_API_KEY;\n if (!key) {\n console.error('fetchStripeConfig: NAREV_API_KEY is not set');\n return null;\n }\n\n const res = await fetch('https://www.narev.ai/api/billing-target/stripe', {\n headers: { Authorization: `Bearer ${key}` },\n });\n if (!res.ok) {\n console.error(\n `fetchStripeConfig: Narev returned ${res.status} ${res.statusText}`,\n );\n return null;\n }\n const json = await res.json();\n return json.data as StripeConfig;\n } catch (error) {\n console.error('fetchStripeConfig:', error);\n return null;\n }\n}\n"],"mappings":";AAKA,eAAsB,oBAAkD;AACtE,MAAI;AACF,UAAM,MAAM,QAAQ,IAAI;AACxB,QAAI,CAAC,KAAK;AACR,cAAQ,MAAM,6CAA6C;AAC3D,aAAO;AAAA,IACT;AAEA,UAAM,MAAM,MAAM,MAAM,kDAAkD;AAAA,MACxE,SAAS,EAAE,eAAe,UAAU,GAAG,GAAG;AAAA,IAC5C,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ;AAAA,QACN,qCAAqC,IAAI,MAAM,IAAI,IAAI,UAAU;AAAA,MACnE;AACA,aAAO;AAAA,IACT;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,WAAO,KAAK;AAAA,EACd,SAAS,OAAO;AACd,YAAQ,MAAM,sBAAsB,KAAK;AACzC,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ "use server";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var fetchStripeUsage_exports = {};
31
+ __export(fetchStripeUsage_exports, {
32
+ fetchStripeUsage: () => fetchStripeUsage
33
+ });
34
+ module.exports = __toCommonJS(fetchStripeUsage_exports);
35
+ var import_fetchStripeConfig = require("./fetchStripeConfig.js");
36
+ var import_stripe = __toESM(require("stripe"), 1);
37
+ async function fetchStripeUsage(stripeCustomerId) {
38
+ const empty = { aggregatedValue: 0, found: false };
39
+ const config = await (0, import_fetchStripeConfig.fetchStripeConfig)();
40
+ if (!config || !config.meterId) return empty;
41
+ const stripe = new import_stripe.default(process.env.STRIPE_SECRET_KEY);
42
+ const start = new Date(
43
+ Date.UTC((/* @__PURE__ */ new Date()).getUTCFullYear(), (/* @__PURE__ */ new Date()).getUTCMonth(), 1)
44
+ );
45
+ const end = /* @__PURE__ */ new Date();
46
+ try {
47
+ const summaries = await stripe.billing.meters.listEventSummaries(
48
+ config.meterId,
49
+ {
50
+ customer: stripeCustomerId,
51
+ start_time: Math.floor(start.getTime() / 1e3),
52
+ end_time: Math.floor(end.getTime() / 1e3)
53
+ }
54
+ );
55
+ let aggregatedValue = 0;
56
+ for (const s of summaries.data) aggregatedValue += s.aggregated_value;
57
+ return { aggregatedValue: aggregatedValue / 1e9, found: true };
58
+ } catch (error) {
59
+ console.error("fetchStripeUsage:", error);
60
+ }
61
+ return empty;
62
+ }
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ fetchStripeUsage
66
+ });
67
+ //# sourceMappingURL=fetchStripeUsage.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/fetchStripeUsage.ts"],"sourcesContent":["'use server';\n\nimport { fetchStripeConfig } from './fetchStripeConfig.js';\nimport Stripe from 'stripe';\nimport type { StripeUsageData } from './types.js';\n\n/**\n * Fetches usage data from Stripe for a given customer, converting nano-units to dollars.\n * @param stripeCustomerId - the Stripe customer ID\n */\nexport async function fetchStripeUsage(\n stripeCustomerId: string,\n): Promise<StripeUsageData> {\n const empty = { aggregatedValue: 0, found: false };\n\n const config = await fetchStripeConfig();\n if (!config || !config.meterId) return empty;\n\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const start = new Date(\n Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1),\n );\n const end = new Date();\n\n try {\n const summaries = await stripe.billing.meters.listEventSummaries(\n config.meterId,\n {\n customer: stripeCustomerId,\n start_time: Math.floor(start.getTime() / 1000),\n end_time: Math.floor(end.getTime() / 1000),\n },\n );\n let aggregatedValue = 0;\n for (const s of summaries.data) aggregatedValue += s.aggregated_value;\n return { aggregatedValue: aggregatedValue / 1_000_000_000, found: true };\n } catch (error) {\n console.error('fetchStripeUsage:', error);\n }\n\n return empty;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,+BAAkC;AAClC,oBAAmB;AAOnB,eAAsB,iBACpB,kBAC0B;AAC1B,QAAM,QAAQ,EAAE,iBAAiB,GAAG,OAAO,MAAM;AAEjD,QAAM,SAAS,UAAM,4CAAkB;AACvC,MAAI,CAAC,UAAU,CAAC,OAAO,QAAS,QAAO;AAEvC,QAAM,SAAS,IAAI,cAAAA,QAAO,QAAQ,IAAI,iBAAkB;AACxD,QAAM,QAAQ,IAAI;AAAA,IAChB,KAAK,KAAI,oBAAI,KAAK,GAAE,eAAe,IAAG,oBAAI,KAAK,GAAE,YAAY,GAAG,CAAC;AAAA,EACnE;AACA,QAAM,MAAM,oBAAI,KAAK;AAErB,MAAI;AACF,UAAM,YAAY,MAAM,OAAO,QAAQ,OAAO;AAAA,MAC5C,OAAO;AAAA,MACP;AAAA,QACE,UAAU;AAAA,QACV,YAAY,KAAK,MAAM,MAAM,QAAQ,IAAI,GAAI;AAAA,QAC7C,UAAU,KAAK,MAAM,IAAI,QAAQ,IAAI,GAAI;AAAA,MAC3C;AAAA,IACF;AACA,QAAI,kBAAkB;AACtB,eAAW,KAAK,UAAU,KAAM,oBAAmB,EAAE;AACrD,WAAO,EAAE,iBAAiB,kBAAkB,KAAe,OAAO,KAAK;AAAA,EACzE,SAAS,OAAO;AACd,YAAQ,MAAM,qBAAqB,KAAK;AAAA,EAC1C;AAEA,SAAO;AACT;","names":["Stripe"]}
@@ -0,0 +1,9 @@
1
+ import { StripeUsageData } from './types.cjs';
2
+
3
+ /**
4
+ * Fetches usage data from Stripe for a given customer, converting nano-units to dollars.
5
+ * @param stripeCustomerId - the Stripe customer ID
6
+ */
7
+ declare function fetchStripeUsage(stripeCustomerId: string): Promise<StripeUsageData>;
8
+
9
+ export { fetchStripeUsage };
@@ -0,0 +1,9 @@
1
+ import { StripeUsageData } from './types.js';
2
+
3
+ /**
4
+ * Fetches usage data from Stripe for a given customer, converting nano-units to dollars.
5
+ * @param stripeCustomerId - the Stripe customer ID
6
+ */
7
+ declare function fetchStripeUsage(stripeCustomerId: string): Promise<StripeUsageData>;
8
+
9
+ export { fetchStripeUsage };
@@ -0,0 +1,33 @@
1
+ "use server";
2
+ import { fetchStripeConfig } from "./fetchStripeConfig.js";
3
+ import Stripe from "stripe";
4
+ async function fetchStripeUsage(stripeCustomerId) {
5
+ const empty = { aggregatedValue: 0, found: false };
6
+ const config = await fetchStripeConfig();
7
+ if (!config || !config.meterId) return empty;
8
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
9
+ const start = new Date(
10
+ Date.UTC((/* @__PURE__ */ new Date()).getUTCFullYear(), (/* @__PURE__ */ new Date()).getUTCMonth(), 1)
11
+ );
12
+ const end = /* @__PURE__ */ new Date();
13
+ try {
14
+ const summaries = await stripe.billing.meters.listEventSummaries(
15
+ config.meterId,
16
+ {
17
+ customer: stripeCustomerId,
18
+ start_time: Math.floor(start.getTime() / 1e3),
19
+ end_time: Math.floor(end.getTime() / 1e3)
20
+ }
21
+ );
22
+ let aggregatedValue = 0;
23
+ for (const s of summaries.data) aggregatedValue += s.aggregated_value;
24
+ return { aggregatedValue: aggregatedValue / 1e9, found: true };
25
+ } catch (error) {
26
+ console.error("fetchStripeUsage:", error);
27
+ }
28
+ return empty;
29
+ }
30
+ export {
31
+ fetchStripeUsage
32
+ };
33
+ //# sourceMappingURL=fetchStripeUsage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/fetchStripeUsage.ts"],"sourcesContent":["'use server';\n\nimport { fetchStripeConfig } from './fetchStripeConfig.js';\nimport Stripe from 'stripe';\nimport type { StripeUsageData } from './types.js';\n\n/**\n * Fetches usage data from Stripe for a given customer, converting nano-units to dollars.\n * @param stripeCustomerId - the Stripe customer ID\n */\nexport async function fetchStripeUsage(\n stripeCustomerId: string,\n): Promise<StripeUsageData> {\n const empty = { aggregatedValue: 0, found: false };\n\n const config = await fetchStripeConfig();\n if (!config || !config.meterId) return empty;\n\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const start = new Date(\n Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1),\n );\n const end = new Date();\n\n try {\n const summaries = await stripe.billing.meters.listEventSummaries(\n config.meterId,\n {\n customer: stripeCustomerId,\n start_time: Math.floor(start.getTime() / 1000),\n end_time: Math.floor(end.getTime() / 1000),\n },\n );\n let aggregatedValue = 0;\n for (const s of summaries.data) aggregatedValue += s.aggregated_value;\n return { aggregatedValue: aggregatedValue / 1_000_000_000, found: true };\n } catch (error) {\n console.error('fetchStripeUsage:', error);\n }\n\n return empty;\n}\n"],"mappings":";AAEA,SAAS,yBAAyB;AAClC,OAAO,YAAY;AAOnB,eAAsB,iBACpB,kBAC0B;AAC1B,QAAM,QAAQ,EAAE,iBAAiB,GAAG,OAAO,MAAM;AAEjD,QAAM,SAAS,MAAM,kBAAkB;AACvC,MAAI,CAAC,UAAU,CAAC,OAAO,QAAS,QAAO;AAEvC,QAAM,SAAS,IAAI,OAAO,QAAQ,IAAI,iBAAkB;AACxD,QAAM,QAAQ,IAAI;AAAA,IAChB,KAAK,KAAI,oBAAI,KAAK,GAAE,eAAe,IAAG,oBAAI,KAAK,GAAE,YAAY,GAAG,CAAC;AAAA,EACnE;AACA,QAAM,MAAM,oBAAI,KAAK;AAErB,MAAI;AACF,UAAM,YAAY,MAAM,OAAO,QAAQ,OAAO;AAAA,MAC5C,OAAO;AAAA,MACP;AAAA,QACE,UAAU;AAAA,QACV,YAAY,KAAK,MAAM,MAAM,QAAQ,IAAI,GAAI;AAAA,QAC7C,UAAU,KAAK,MAAM,IAAI,QAAQ,IAAI,GAAI;AAAA,MAC3C;AAAA,IACF;AACA,QAAI,kBAAkB;AACtB,eAAW,KAAK,UAAU,KAAM,oBAAmB,EAAE;AACrD,WAAO,EAAE,iBAAiB,kBAAkB,KAAe,OAAO,KAAK;AAAA,EACzE,SAAS,OAAO;AACd,YAAQ,MAAM,qBAAqB,KAAK;AAAA,EAC1C;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var types_exports = {};
16
+ module.exports = __toCommonJS(types_exports);
17
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stripe/types.ts"],"sourcesContent":["export interface StripeConfig {\n meterId: string;\n}\n\nexport interface StripeUsageData {\n aggregatedValue: number;\n found: boolean;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -0,0 +1,9 @@
1
+ interface StripeConfig {
2
+ meterId: string;
3
+ }
4
+ interface StripeUsageData {
5
+ aggregatedValue: number;
6
+ found: boolean;
7
+ }
8
+
9
+ export type { StripeConfig, StripeUsageData };
@@ -0,0 +1,9 @@
1
+ interface StripeConfig {
2
+ meterId: string;
3
+ }
4
+ interface StripeUsageData {
5
+ aggregatedValue: number;
6
+ found: boolean;
7
+ }
8
+
9
+ export type { StripeConfig, StripeUsageData };
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}