@spondo/margin 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -2
- package/dist/index.d.ts +217 -0
- package/dist/index.js +114 -0
- package/dist/tracing.d.ts +20 -0
- package/dist/tracing.js +69 -0
- package/package.json +54 -4
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spondo/margin
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Node client for [Spondo Margin](https://margin.getspondo.com). Use it to send usage signals, see what each customer's AI calls cost you, and manage customers, products, plans, orders and checkouts.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @spondo/margin
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It runs anywhere `fetch` does: Node 20 or later, Bun, Deno and edge runtimes. Tracing needs Node.
|
|
10
|
+
|
|
11
|
+
## Signals
|
|
12
|
+
|
|
13
|
+
A signal is one thing your product did for a customer. Your plans price usage and credits by the signal's event name, and by the numbers in its `data`.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Spondo } from "@spondo/margin";
|
|
17
|
+
|
|
18
|
+
const spondo = new Spondo(); // reads SPONDO_API_KEY
|
|
19
|
+
|
|
20
|
+
await spondo.signals.send({
|
|
21
|
+
eventName: "document_uploaded",
|
|
22
|
+
customer: { externalCustomerId: account.id },
|
|
23
|
+
attribution: { externalProductId: "documind" },
|
|
24
|
+
data: { pages: doc.pages },
|
|
25
|
+
idempotencyKey: doc.id, // a retry with the same key is stored once
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`send` takes one signal or an array of them.
|
|
30
|
+
|
|
31
|
+
## Cost tracing
|
|
32
|
+
|
|
33
|
+
Tracing puts the cost of each customer's AI calls on them. It also gives you a cost for each signal.
|
|
34
|
+
|
|
35
|
+
Install the OpenTelemetry packages it uses (the 3.x line):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/context-async-hooks @opentelemetry/exporter-trace-otlp-http
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Then wrap each unit of work in `trace()`:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { initTracing, trace, signal } from "@spondo/margin/tracing";
|
|
45
|
+
|
|
46
|
+
initTracing(); // once, at startup
|
|
47
|
+
|
|
48
|
+
await trace({ externalCustomerId: account.id, externalProductId: "documind" }, async () => {
|
|
49
|
+
const summary = await anthropic.messages.create({ ... }); // priced from its tokens
|
|
50
|
+
await signal("document_uploaded", { pages: doc.pages }); // carries this trace's cost
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
LLM calls are priced from the `gen_ai.*` token counts on their spans. Register an OpenTelemetry instrumentation for your LLM client as you normally would: OpenLLMetry, OpenInference, and the Vercel AI SDK's `@ai-sdk/otel` all set those attributes. A span with no token counts can give its own cost in US dollars as `meter.cost`. In serverless functions, `await flush()` before returning.
|
|
55
|
+
|
|
56
|
+
## The rest of the API
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
const customer = await spondo.customers.create({ name: "Acme", externalId: "acme" });
|
|
60
|
+
await spondo.customers.get({ externalId: "acme" }); // or by Spondo Margin's id: "cus_…"
|
|
61
|
+
const { url } = await spondo.checkouts.create({ products: [{ id: "prod_…" }], externalCustomerId: "acme", successUrl: "https://example.com/welcome" });
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The client also covers:
|
|
65
|
+
- `customers`, `products`, `plans`, `orders`, `checkouts`, `invoices`, `signals` and `credits.transactions`
|
|
66
|
+
- any other `/api/v1` call, through `spondo.request(method, path, { query, body, headers })`; `headers` adds to the client's own (e.g. `Idempotency-Key` for `POST /provision`)
|
|
67
|
+
|
|
68
|
+
A failed call throws a `SpondoError`, which carries `status`, `code` and `message`. A rate-limited call (429) is retried twice, after the wait the server asks for.
|
|
69
|
+
|
|
70
|
+
## Options
|
|
71
|
+
|
|
72
|
+
| Option | Default |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `apiKey` | `SPONDO_API_KEY` |
|
|
75
|
+
| `baseUrl` | `SPONDO_BASE_URL`, then `https://margin.getspondo.com` |
|
|
76
|
+
| `maxRetries` | `2` |
|
|
77
|
+
| `fetch` | `globalThis.fetch` |
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
export declare const DEFAULT_BASE_URL = "https://margin.getspondo.com";
|
|
2
|
+
export type Json = Record<string, unknown>;
|
|
3
|
+
export type Query = Record<string, string | number | boolean | null | undefined>;
|
|
4
|
+
/** A record by its Spondo Margin id (`cus_…`, `prod_…`), or by your own id for it. */
|
|
5
|
+
export type Ref = string | {
|
|
6
|
+
externalId: string;
|
|
7
|
+
};
|
|
8
|
+
export type ListQuery = {
|
|
9
|
+
limit?: number;
|
|
10
|
+
offset?: number;
|
|
11
|
+
};
|
|
12
|
+
export type Page<T> = {
|
|
13
|
+
data: T[];
|
|
14
|
+
pagination: {
|
|
15
|
+
limit: number;
|
|
16
|
+
offset: number;
|
|
17
|
+
total: number;
|
|
18
|
+
hasMore: boolean;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
/** A record this client doesn't type in full yet: its id, and the rest as JSON. */
|
|
22
|
+
export type Resource = {
|
|
23
|
+
id: string;
|
|
24
|
+
} & Json;
|
|
25
|
+
export type ClientOptions = {
|
|
26
|
+
/** A key from Developers → API keys. Default: the SPONDO_API_KEY environment variable. */
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
/** Default: SPONDO_BASE_URL, else https://margin.getspondo.com. */
|
|
29
|
+
baseUrl?: string;
|
|
30
|
+
/** How many times a rate-limited call (429) is retried, after the wait the server asks for. Default 2. */
|
|
31
|
+
maxRetries?: number;
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
};
|
|
34
|
+
export type CustomerRef = {
|
|
35
|
+
customerId: string;
|
|
36
|
+
} | {
|
|
37
|
+
externalCustomerId: string;
|
|
38
|
+
};
|
|
39
|
+
export type SignalInput = {
|
|
40
|
+
/** What happened, e.g. `document_uploaded`. Plans price usage and credits by it. */
|
|
41
|
+
eventName: string;
|
|
42
|
+
customer?: CustomerRef;
|
|
43
|
+
customerUnit?: {
|
|
44
|
+
externalCustomerUnitId: string;
|
|
45
|
+
};
|
|
46
|
+
attribution?: {
|
|
47
|
+
productId: string;
|
|
48
|
+
} | {
|
|
49
|
+
externalProductId: string;
|
|
50
|
+
};
|
|
51
|
+
/** Anything to keep with the signal; plans can price by its numbers. `trace_id` links the cost traced under it. */
|
|
52
|
+
data?: Json;
|
|
53
|
+
/** ISO 8601; default now. */
|
|
54
|
+
timestamp?: string;
|
|
55
|
+
/** A signal sent twice with the same key is stored once. */
|
|
56
|
+
idempotencyKey?: string;
|
|
57
|
+
};
|
|
58
|
+
export type SignalsResult = {
|
|
59
|
+
ingested: number;
|
|
60
|
+
duplicates: number;
|
|
61
|
+
failed: number;
|
|
62
|
+
};
|
|
63
|
+
export type Signal = {
|
|
64
|
+
id: string;
|
|
65
|
+
name: string;
|
|
66
|
+
customerId: string | null;
|
|
67
|
+
externalCustomerId: string | null;
|
|
68
|
+
productId: string | null;
|
|
69
|
+
externalProductId: string | null;
|
|
70
|
+
traceId: string | null;
|
|
71
|
+
data: Json | null;
|
|
72
|
+
createdAt: string;
|
|
73
|
+
};
|
|
74
|
+
export type CustomerInput = {
|
|
75
|
+
name: string;
|
|
76
|
+
externalId?: string;
|
|
77
|
+
legalName?: string;
|
|
78
|
+
email?: string;
|
|
79
|
+
phone?: string;
|
|
80
|
+
website?: string;
|
|
81
|
+
billingAddress?: Json;
|
|
82
|
+
vatNumber?: string;
|
|
83
|
+
defaultCurrency?: string;
|
|
84
|
+
metadata?: Json;
|
|
85
|
+
};
|
|
86
|
+
export type Customer = {
|
|
87
|
+
id: string;
|
|
88
|
+
name: string;
|
|
89
|
+
legalName: string | null;
|
|
90
|
+
email: string;
|
|
91
|
+
phone: string;
|
|
92
|
+
website: string;
|
|
93
|
+
externalId: string | null;
|
|
94
|
+
billingAddress: Json | null;
|
|
95
|
+
creationState: string;
|
|
96
|
+
status: "active" | "churned";
|
|
97
|
+
churnDate: string | null;
|
|
98
|
+
vatNumber: string | null;
|
|
99
|
+
metadata: Json | null;
|
|
100
|
+
defaultCurrency: string;
|
|
101
|
+
connections: {
|
|
102
|
+
stripe: {
|
|
103
|
+
customerId: string;
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
createdAt: string;
|
|
107
|
+
updatedAt: string | null;
|
|
108
|
+
};
|
|
109
|
+
export type CheckoutInput = {
|
|
110
|
+
products: ({
|
|
111
|
+
id: string;
|
|
112
|
+
} & Json)[];
|
|
113
|
+
successUrl: string;
|
|
114
|
+
cancelUrl?: string;
|
|
115
|
+
currency?: string;
|
|
116
|
+
expiresAt?: string;
|
|
117
|
+
metadata?: Json;
|
|
118
|
+
} & ({
|
|
119
|
+
customerId?: string;
|
|
120
|
+
} | {
|
|
121
|
+
externalCustomerId?: string;
|
|
122
|
+
}) & Json;
|
|
123
|
+
export type Checkout = Resource & {
|
|
124
|
+
url: string;
|
|
125
|
+
status: string;
|
|
126
|
+
};
|
|
127
|
+
export declare class SpondoError extends Error {
|
|
128
|
+
readonly status: number;
|
|
129
|
+
readonly code: string;
|
|
130
|
+
/** Seconds to wait before trying again, on a 429. */
|
|
131
|
+
readonly retryAfter: number | null;
|
|
132
|
+
constructor(status: number, code: string, message: string, retryAfter?: number | null);
|
|
133
|
+
}
|
|
134
|
+
export declare class Spondo {
|
|
135
|
+
#private;
|
|
136
|
+
readonly apiKey: string;
|
|
137
|
+
readonly baseUrl: string;
|
|
138
|
+
constructor(o?: ClientOptions);
|
|
139
|
+
/** Any /api/v1 call: `path` without the prefix, e.g. `/invoices/inv_123/lines`. `headers` can't replace the client's own. */
|
|
140
|
+
request<T = Json>(method: string, path: string, { query, body, headers }?: {
|
|
141
|
+
query?: Query;
|
|
142
|
+
body?: unknown;
|
|
143
|
+
headers?: Record<string, string>;
|
|
144
|
+
}): Promise<T>;
|
|
145
|
+
readonly signals: {
|
|
146
|
+
/** Usage: one signal or a batch. Retrying with the same idempotency keys is safe. */
|
|
147
|
+
send: (signals: SignalInput | SignalInput[]) => Promise<SignalsResult>;
|
|
148
|
+
list: (q?: ListQuery & {
|
|
149
|
+
customerId?: string;
|
|
150
|
+
externalCustomerId?: string;
|
|
151
|
+
productId?: string;
|
|
152
|
+
externalProductId?: string;
|
|
153
|
+
signalName?: string;
|
|
154
|
+
createdAtFrom?: string;
|
|
155
|
+
createdAtTo?: string;
|
|
156
|
+
}) => Promise<Page<Signal>>;
|
|
157
|
+
get: (id: string) => Promise<Signal>;
|
|
158
|
+
};
|
|
159
|
+
readonly customers: {
|
|
160
|
+
create: (body: CustomerInput) => Promise<Customer>;
|
|
161
|
+
list: (q?: ListQuery) => Promise<Page<Customer>>;
|
|
162
|
+
get: (ref: Ref) => Promise<Customer>;
|
|
163
|
+
update: (ref: Ref, body: Partial<CustomerInput>) => Promise<Customer>;
|
|
164
|
+
delete: (ref: Ref) => Promise<void>;
|
|
165
|
+
/** What the customer has: active orders, entitlements and credit balances. */
|
|
166
|
+
state: (ref: Ref) => Promise<Json>;
|
|
167
|
+
};
|
|
168
|
+
readonly products: {
|
|
169
|
+
create: (body: {
|
|
170
|
+
name: string;
|
|
171
|
+
externalId?: string;
|
|
172
|
+
description?: string;
|
|
173
|
+
} & Json) => Promise<Resource>;
|
|
174
|
+
list: (q?: ListQuery & {
|
|
175
|
+
name?: string;
|
|
176
|
+
}) => Promise<Page<Resource>>;
|
|
177
|
+
get: (ref: Ref) => Promise<Resource>;
|
|
178
|
+
update: (ref: Ref, body: Json) => Promise<Resource>;
|
|
179
|
+
};
|
|
180
|
+
readonly plans: {
|
|
181
|
+
create: (body: Json) => Promise<Resource>;
|
|
182
|
+
list: (q?: ListQuery) => Promise<Page<Resource>>;
|
|
183
|
+
get: (ref: Ref) => Promise<Resource>;
|
|
184
|
+
update: (ref: Ref, body: Json) => Promise<Resource>;
|
|
185
|
+
};
|
|
186
|
+
readonly orders: {
|
|
187
|
+
create: (body: Json) => Promise<Resource>;
|
|
188
|
+
list: (q?: ListQuery & {
|
|
189
|
+
customerId?: string;
|
|
190
|
+
externalCustomerId?: string;
|
|
191
|
+
}) => Promise<Page<Resource>>;
|
|
192
|
+
get: (id: string) => Promise<Resource>;
|
|
193
|
+
update: (id: string, body: Json) => Promise<Resource>;
|
|
194
|
+
delete: (id: string) => Promise<void>;
|
|
195
|
+
};
|
|
196
|
+
readonly checkouts: {
|
|
197
|
+
/** A link to send a customer: they pick a plan and pay (Stripe), or start on an invoice. */
|
|
198
|
+
create: (body: CheckoutInput) => Promise<Checkout>;
|
|
199
|
+
list: (q?: ListQuery) => Promise<Page<Checkout>>;
|
|
200
|
+
get: (id: string) => Promise<Checkout>;
|
|
201
|
+
delete: (id: string) => Promise<void>;
|
|
202
|
+
};
|
|
203
|
+
readonly invoices: {
|
|
204
|
+
list: (q?: ListQuery & {
|
|
205
|
+
customerId?: string;
|
|
206
|
+
externalCustomerId?: string;
|
|
207
|
+
}) => Promise<Page<Resource>>;
|
|
208
|
+
get: (id: string) => Promise<Resource>;
|
|
209
|
+
lines: (id: string, q?: ListQuery) => Promise<Page<Resource>>;
|
|
210
|
+
};
|
|
211
|
+
readonly credits: {
|
|
212
|
+
transactions: (q?: ListQuery & {
|
|
213
|
+
customerId?: string;
|
|
214
|
+
externalCustomerId?: string;
|
|
215
|
+
}) => Promise<Page<Resource>>;
|
|
216
|
+
};
|
|
217
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// @spondo/margin: the client for Spondo Margin's API. A method for each call most apps make, and request() for the
|
|
2
|
+
// rest of /api/v1. Runs wherever fetch does (Node 20+, Bun, Deno, edge runtimes). Cost tracing: @spondo/margin/tracing.
|
|
3
|
+
export const DEFAULT_BASE_URL = "https://margin.getspondo.com";
|
|
4
|
+
export class SpondoError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
code;
|
|
7
|
+
/** Seconds to wait before trying again, on a 429. */
|
|
8
|
+
retryAfter;
|
|
9
|
+
constructor(status, code, message, retryAfter = null) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "SpondoError";
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.retryAfter = retryAfter;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const env = (k) => globalThis.process?.env?.[k];
|
|
18
|
+
const at = (ref) => (typeof ref === "string" ? encodeURIComponent(ref) : `external/${encodeURIComponent(ref.externalId)}`);
|
|
19
|
+
export class Spondo {
|
|
20
|
+
apiKey;
|
|
21
|
+
baseUrl;
|
|
22
|
+
#retries;
|
|
23
|
+
#fetch;
|
|
24
|
+
constructor(o = {}) {
|
|
25
|
+
const key = o.apiKey ?? env("SPONDO_API_KEY");
|
|
26
|
+
if (!key)
|
|
27
|
+
throw new Error("Spondo: pass { apiKey } or set SPONDO_API_KEY");
|
|
28
|
+
this.apiKey = key;
|
|
29
|
+
this.baseUrl = (o.baseUrl ?? env("SPONDO_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
|
|
30
|
+
this.#retries = o.maxRetries ?? 2;
|
|
31
|
+
this.#fetch = o.fetch ?? globalThis.fetch;
|
|
32
|
+
}
|
|
33
|
+
/** Any /api/v1 call: `path` without the prefix, e.g. `/invoices/inv_123/lines`. `headers` can't replace the client's own. */
|
|
34
|
+
async request(method, path, { query, body, headers } = {}) {
|
|
35
|
+
const url = new URL(`${this.baseUrl}/api/v1${path}`);
|
|
36
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
37
|
+
if (v != null)
|
|
38
|
+
url.searchParams.set(k, String(v));
|
|
39
|
+
const h = new Headers(headers);
|
|
40
|
+
h.set("authorization", `Bearer ${this.apiKey}`);
|
|
41
|
+
if (body !== undefined)
|
|
42
|
+
h.set("content-type", "application/json");
|
|
43
|
+
for (let attempt = 0;; attempt++) {
|
|
44
|
+
const res = await this.#fetch(url, {
|
|
45
|
+
method,
|
|
46
|
+
headers: h,
|
|
47
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
48
|
+
});
|
|
49
|
+
const text = await res.text();
|
|
50
|
+
if (res.ok)
|
|
51
|
+
return (text ? JSON.parse(text) : undefined);
|
|
52
|
+
const wait = res.status === 429 ? Number(res.headers.get("retry-after") ?? 1) || 0 : null;
|
|
53
|
+
if (wait !== null && attempt < this.#retries) {
|
|
54
|
+
await new Promise((ok) => setTimeout(ok, wait * 1000));
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
let e = {};
|
|
58
|
+
try {
|
|
59
|
+
e = JSON.parse(text);
|
|
60
|
+
}
|
|
61
|
+
catch { }
|
|
62
|
+
throw new SpondoError(res.status, e.code ?? "HTTP_ERROR", e.details ?? e.error ?? (text || res.statusText), wait);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
signals = {
|
|
66
|
+
/** Usage: one signal or a batch. Retrying with the same idempotency keys is safe. */
|
|
67
|
+
send: (signals) => this.request("POST", "/signals/bulk", { body: { signals: Array.isArray(signals) ? signals : [signals] } }),
|
|
68
|
+
list: (q = {}) => this.request("GET", "/signals", { query: q }),
|
|
69
|
+
get: (id) => this.request("GET", `/signals/${encodeURIComponent(id)}`),
|
|
70
|
+
};
|
|
71
|
+
customers = {
|
|
72
|
+
create: (body) => this.request("POST", "/customers", { body }),
|
|
73
|
+
list: (q = {}) => this.request("GET", "/customers", { query: q }),
|
|
74
|
+
get: (ref) => this.request("GET", `/customers/${at(ref)}`),
|
|
75
|
+
update: (ref, body) => this.request("PUT", `/customers/${at(ref)}`, { body }),
|
|
76
|
+
delete: (ref) => this.request("DELETE", `/customers/${at(ref)}`),
|
|
77
|
+
/** What the customer has: active orders, entitlements and credit balances. */
|
|
78
|
+
state: (ref) => this.request("GET", `/customers/${at(ref)}/state`),
|
|
79
|
+
};
|
|
80
|
+
products = {
|
|
81
|
+
create: (body) => this.request("POST", "/products", { body }),
|
|
82
|
+
list: (q = {}) => this.request("GET", "/products", { query: q }),
|
|
83
|
+
get: (ref) => this.request("GET", `/products/${at(ref)}`),
|
|
84
|
+
update: (ref, body) => this.request("PUT", `/products/${at(ref)}`, { body }),
|
|
85
|
+
};
|
|
86
|
+
plans = {
|
|
87
|
+
create: (body) => this.request("POST", "/plans", { body }),
|
|
88
|
+
list: (q = {}) => this.request("GET", "/plans", { query: q }),
|
|
89
|
+
get: (ref) => this.request("GET", `/plans/${at(ref)}`),
|
|
90
|
+
update: (ref, body) => this.request("PUT", `/plans/${at(ref)}`, { body }),
|
|
91
|
+
};
|
|
92
|
+
orders = {
|
|
93
|
+
create: (body) => this.request("POST", "/orders", { body }),
|
|
94
|
+
list: (q = {}) => this.request("GET", "/orders", { query: q }),
|
|
95
|
+
get: (id) => this.request("GET", `/orders/${encodeURIComponent(id)}`),
|
|
96
|
+
update: (id, body) => this.request("PUT", `/orders/${encodeURIComponent(id)}`, { body }),
|
|
97
|
+
delete: (id) => this.request("DELETE", `/orders/${encodeURIComponent(id)}`),
|
|
98
|
+
};
|
|
99
|
+
checkouts = {
|
|
100
|
+
/** A link to send a customer: they pick a plan and pay (Stripe), or start on an invoice. */
|
|
101
|
+
create: (body) => this.request("POST", "/checkouts", { body }),
|
|
102
|
+
list: (q = {}) => this.request("GET", "/checkouts", { query: q }),
|
|
103
|
+
get: (id) => this.request("GET", `/checkouts/${encodeURIComponent(id)}`),
|
|
104
|
+
delete: (id) => this.request("DELETE", `/checkouts/${encodeURIComponent(id)}`),
|
|
105
|
+
};
|
|
106
|
+
invoices = {
|
|
107
|
+
list: (q = {}) => this.request("GET", "/invoices", { query: q }),
|
|
108
|
+
get: (id) => this.request("GET", `/invoices/${encodeURIComponent(id)}`),
|
|
109
|
+
lines: (id, q = {}) => this.request("GET", `/invoices/${encodeURIComponent(id)}/lines`, { query: q }),
|
|
110
|
+
};
|
|
111
|
+
credits = {
|
|
112
|
+
transactions: (q = {}) => this.request("GET", "/credits/transactions", { query: q }),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { TracerProvider } from "@opentelemetry/sdk-trace";
|
|
2
|
+
import type { ClientOptions, Json, SignalsResult } from "./index.ts";
|
|
3
|
+
export type TraceTags = {
|
|
4
|
+
externalCustomerId: string;
|
|
5
|
+
externalProductId?: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Start sending spans; call once at startup. Takes the client's options (apiKey, baseUrl). It registers the global
|
|
9
|
+
* tracer provider and, unless the app already has one, Node's async context manager, which keeps trace()'s customer
|
|
10
|
+
* across awaits.
|
|
11
|
+
*/
|
|
12
|
+
export declare function initTracing(options?: ClientOptions): TracerProvider;
|
|
13
|
+
/** Run `fn` as one unit of work for a customer: the AI calls in it are costed to them. */
|
|
14
|
+
export declare function trace<T>(tags: TraceTags, fn: () => T | Promise<T>): Promise<T>;
|
|
15
|
+
/** Inside trace(): a signal for its customer and product that carries the trace's cost. */
|
|
16
|
+
export declare function signal(eventName: string, data?: Json, options?: {
|
|
17
|
+
idempotencyKey?: string;
|
|
18
|
+
}): Promise<SignalsResult>;
|
|
19
|
+
/** Send the spans waiting in the batch now: before a serverless function returns, or the process exits. */
|
|
20
|
+
export declare const flush: () => Promise<void>;
|
package/dist/tracing.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// @spondo/margin/tracing: what each customer's AI calls cost you. Spans go to Spondo Margin's OpenTelemetry collector
|
|
2
|
+
// (<baseUrl>/v1/traces). Every span started inside trace() carries its customer and product, and a signal() sent inside
|
|
3
|
+
// it carries that trace's cost, so you see cost per signal. LLM calls are priced from their gen_ai.* token counts, so
|
|
4
|
+
// register an OpenTelemetry instrumentation for your LLM client as usual (OpenLLMetry, OpenInference, or the Vercel AI
|
|
5
|
+
// SDK's telemetry); spans that state their own cost set `meter.cost` (USD).
|
|
6
|
+
import { SpanStatusCode, context, createContextKey, trace as otel } from "@opentelemetry/api";
|
|
7
|
+
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
|
|
8
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
9
|
+
import { BatchSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
|
|
10
|
+
import { Spondo } from "./index.js";
|
|
11
|
+
const TAGS = createContextKey("@spondo/margin tags");
|
|
12
|
+
const tags = (ctx = context.active()) => ctx.getValue(TAGS);
|
|
13
|
+
/** Copies the enclosing trace()'s customer and product onto each span as it starts. */
|
|
14
|
+
const tagger = {
|
|
15
|
+
onStart(span, ctx) {
|
|
16
|
+
const t = tags(ctx);
|
|
17
|
+
if (t)
|
|
18
|
+
span.setAttributes({ "meter.customer_id": t.externalCustomerId, ...(t.externalProductId && { "meter.product_id": t.externalProductId }) });
|
|
19
|
+
},
|
|
20
|
+
onEnd() { },
|
|
21
|
+
forceFlush: async () => { },
|
|
22
|
+
shutdown: async () => { },
|
|
23
|
+
};
|
|
24
|
+
let provider;
|
|
25
|
+
let client;
|
|
26
|
+
/**
|
|
27
|
+
* Start sending spans; call once at startup. Takes the client's options (apiKey, baseUrl). It registers the global
|
|
28
|
+
* tracer provider and, unless the app already has one, Node's async context manager, which keeps trace()'s customer
|
|
29
|
+
* across awaits.
|
|
30
|
+
*/
|
|
31
|
+
export function initTracing(options = {}) {
|
|
32
|
+
client = new Spondo(options);
|
|
33
|
+
const exporter = new OTLPTraceExporter({ url: `${client.baseUrl}/v1/traces`, headers: { authorization: `Bearer ${client.apiKey}` } });
|
|
34
|
+
provider = new TracerProvider({ spanProcessors: [tagger, new BatchSpanProcessor({ exporter })] });
|
|
35
|
+
context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
|
|
36
|
+
otel.setGlobalTracerProvider(provider);
|
|
37
|
+
return provider;
|
|
38
|
+
}
|
|
39
|
+
/** Run `fn` as one unit of work for a customer: the AI calls in it are costed to them. */
|
|
40
|
+
export function trace(tags, fn) {
|
|
41
|
+
return context.with(context.active().setValue(TAGS, tags), () => otel.getTracer("@spondo/margin").startActiveSpan("spondo.trace", async (span) => {
|
|
42
|
+
try {
|
|
43
|
+
return await fn();
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
span.recordException(e);
|
|
47
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
48
|
+
throw e;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
span.end();
|
|
52
|
+
}
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
/** Inside trace(): a signal for its customer and product that carries the trace's cost. */
|
|
56
|
+
export function signal(eventName, data = {}, options = {}) {
|
|
57
|
+
const t = tags();
|
|
58
|
+
if (!client || !t)
|
|
59
|
+
throw new Error("signal() runs inside trace(), after initTracing()");
|
|
60
|
+
return client.signals.send({
|
|
61
|
+
eventName,
|
|
62
|
+
customer: { externalCustomerId: t.externalCustomerId },
|
|
63
|
+
...(t.externalProductId && { attribution: { externalProductId: t.externalProductId } }),
|
|
64
|
+
data: { ...data, trace_id: otel.getActiveSpan()?.spanContext().traceId },
|
|
65
|
+
idempotencyKey: options.idempotencyKey,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** Send the spans waiting in the batch now: before a serverless function returns, or the process exits. */
|
|
69
|
+
export const flush = () => provider?.forceFlush() ?? Promise.resolve();
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spondo/margin",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "The client for Spondo Margin: send usage signals, trace what each customer's AI calls cost, and manage customers, plans, orders and checkouts.",
|
|
5
|
+
"homepage": "https://margin.getspondo.com",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./tracing": {
|
|
14
|
+
"types": "./dist/tracing.d.ts",
|
|
15
|
+
"default": "./dist/tracing.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc",
|
|
26
|
+
"prepublishOnly": "npm run build"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@opentelemetry/api": "^1.10.0",
|
|
30
|
+
"@opentelemetry/context-async-hooks": "^3.0.0",
|
|
31
|
+
"@opentelemetry/exporter-trace-otlp-http": ">=0.300.0",
|
|
32
|
+
"@opentelemetry/sdk-trace": "^3.0.0"
|
|
33
|
+
},
|
|
34
|
+
"peerDependenciesMeta": {
|
|
35
|
+
"@opentelemetry/api": {
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
"@opentelemetry/context-async-hooks": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
41
|
+
"@opentelemetry/exporter-trace-otlp-http": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"@opentelemetry/sdk-trace": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@opentelemetry/api": "^1.10.0",
|
|
50
|
+
"@opentelemetry/context-async-hooks": "^3.1.0",
|
|
51
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.301.0",
|
|
52
|
+
"@opentelemetry/sdk-trace": "^3.1.0",
|
|
53
|
+
"@types/node": "^26.6.6",
|
|
54
|
+
"typescript": "^7.0.2"
|
|
55
|
+
}
|
|
56
|
+
}
|