@spondo/margin 0.3.0 → 0.4.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @spondo/margin
2
2
 
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.
3
+ The Node client for [Spondo Margin](https://margin.getspondo.com). Use it to send usage events, see what each customer's AI calls cost you, and manage customers and products. What they paid comes from your Stripe, which you connect in the dashboard.
4
4
 
5
5
  ```bash
6
6
  npm install @spondo/margin
@@ -8,16 +8,16 @@ npm install @spondo/margin
8
8
 
9
9
  It runs anywhere `fetch` does: Node 20 or later, Bun, Deno and edge runtimes. Tracing needs Node.
10
10
 
11
- ## Signals
11
+ ## Events
12
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`.
13
+ An event is one thing your product did for a customer. It gets a cost (the traces under it), and its event name and the numbers in its `data` are what value rules count.
14
14
 
15
15
  ```ts
16
16
  import { Spondo } from "@spondo/margin";
17
17
 
18
18
  const spondo = new Spondo(); // reads SPONDO_API_KEY
19
19
 
20
- await spondo.signals.send({
20
+ await spondo.events.send({
21
21
  eventName: "document_uploaded",
22
22
  customer: { externalCustomerId: account.id },
23
23
  attribution: { externalProductId: "documind" },
@@ -26,11 +26,11 @@ await spondo.signals.send({
26
26
  });
27
27
  ```
28
28
 
29
- `send` takes one signal or an array of them.
29
+ `send` takes one event or an array of them.
30
30
 
31
31
  ## Cost tracing
32
32
 
33
- Tracing puts the cost of each customer's AI calls on them. It also gives you a cost for each signal.
33
+ Tracing puts the cost of each customer's AI calls on them. It also gives you a cost for each event.
34
34
 
35
35
  Install the OpenTelemetry packages it uses (the 3.x line):
36
36
 
@@ -41,13 +41,13 @@ npm install @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/context-a
41
41
  Then wrap each unit of work in `trace()`:
42
42
 
43
43
  ```ts
44
- import { initTracing, trace, signal } from "@spondo/margin/tracing";
44
+ import { initTracing, trace, event } from "@spondo/margin/tracing";
45
45
 
46
46
  initTracing(); // once, at startup
47
47
 
48
48
  await trace({ externalCustomerId: account.id, externalProductId: "documind" }, async () => {
49
49
  const summary = await anthropic.messages.create({ ... }); // priced from its tokens
50
- await signal("document_uploaded", { pages: doc.pages }); // carries this trace's cost
50
+ await event("document_uploaded", { pages: doc.pages }); // carries this trace's cost
51
51
  });
52
52
  ```
53
53
 
@@ -56,14 +56,14 @@ LLM calls are priced from the `gen_ai.*` token counts on their spans. Register a
56
56
  ## The rest of the API
57
57
 
58
58
  ```ts
59
- const customer = await spondo.customers.create({ name: "Acme", externalId: "acme" });
59
+ // stripeCustomerId: their customer in your Stripe, so their payments count as their revenue
60
+ const customer = await spondo.customers.create({ name: "Acme", externalId: "acme", stripeCustomerId: "cus_…" });
60
61
  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
62
  ```
63
63
 
64
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`)
65
+ - `customers`, `products` and `events`
66
+ - any other `/api/v1` call, through `spondo.request(method, path, { query, body, headers })`; `headers` adds to the client's own
67
67
 
68
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
69
 
package/dist/index.d.ts CHANGED
@@ -36,31 +36,28 @@ export type CustomerRef = {
36
36
  } | {
37
37
  externalCustomerId: string;
38
38
  };
39
- export type SignalInput = {
40
- /** What happened, e.g. `document_uploaded`. Plans price usage and credits by it. */
39
+ export type EventInput = {
40
+ /** What happened, e.g. `document_uploaded`. Cost per outcome and value are worked out by it. */
41
41
  eventName: string;
42
- customer?: CustomerRef;
43
- customerUnit?: {
44
- externalCustomerUnitId: string;
45
- };
42
+ customer: CustomerRef;
46
43
  attribution?: {
47
44
  productId: string;
48
45
  } | {
49
46
  externalProductId: string;
50
47
  };
51
- /** Anything to keep with the signal; plans can price by its numbers. `trace_id` links the cost traced under it. */
48
+ /** Anything to keep with the event; value rules can count its numbers. `trace_id` links the cost traced under it. */
52
49
  data?: Json;
53
50
  /** ISO 8601; default now. */
54
51
  timestamp?: string;
55
- /** A signal sent twice with the same key is stored once. */
52
+ /** An event sent twice with the same key is stored once. */
56
53
  idempotencyKey?: string;
57
54
  };
58
- export type SignalsResult = {
55
+ export type EventsResult = {
59
56
  ingested: number;
60
57
  duplicates: number;
61
58
  failed: number;
62
59
  };
63
- export type Signal = {
60
+ export type EventRecord = {
64
61
  id: string;
65
62
  name: string;
66
63
  customerId: string | null;
@@ -74,56 +71,27 @@ export type Signal = {
74
71
  export type CustomerInput = {
75
72
  name: string;
76
73
  externalId?: string;
77
- legalName?: string;
78
74
  email?: string;
79
75
  phone?: string;
80
76
  website?: string;
81
- billingAddress?: Json;
82
- vatNumber?: string;
83
- defaultCurrency?: string;
77
+ /** Their customer in your Stripe (`cus_…`), whose payments are their revenue. */
78
+ stripeCustomerId?: string | null;
84
79
  metadata?: Json;
85
80
  };
86
81
  export type Customer = {
87
82
  id: string;
88
83
  name: string;
89
- legalName: string | null;
90
84
  email: string;
91
85
  phone: string;
92
86
  website: string;
93
87
  externalId: string | null;
94
- billingAddress: Json | null;
95
- creationState: string;
88
+ stripeCustomerId: string | null;
96
89
  status: "active" | "churned";
97
90
  churnDate: string | null;
98
- vatNumber: string | null;
99
91
  metadata: Json | null;
100
- defaultCurrency: string;
101
- connections: {
102
- stripe: {
103
- customerId: string;
104
- };
105
- };
106
92
  createdAt: string;
107
93
  updatedAt: string | null;
108
94
  };
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
95
  export declare class SpondoError extends Error {
128
96
  readonly status: number;
129
97
  readonly code: string;
@@ -136,82 +104,53 @@ export declare class Spondo {
136
104
  readonly apiKey: string;
137
105
  readonly baseUrl: string;
138
106
  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. */
107
+ /** Any /api/v1 call: `path` without the prefix, e.g. `/customers/cus_123/aliases`. `headers` can't replace the client's own. */
140
108
  request<T = Json>(method: string, path: string, { query, body, headers }?: {
141
109
  query?: Query;
142
110
  body?: unknown;
143
111
  headers?: Record<string, string>;
144
112
  }): 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>;
113
+ readonly events: {
114
+ /** One event or a batch. Retrying with the same idempotency keys is safe. */
115
+ send: (events: EventInput | EventInput[]) => Promise<EventsResult>;
148
116
  list: (q?: ListQuery & {
149
117
  customerId?: string;
150
118
  externalCustomerId?: string;
151
119
  productId?: string;
152
120
  externalProductId?: string;
153
- signalName?: string;
121
+ eventName?: string;
154
122
  createdAtFrom?: string;
155
123
  createdAtTo?: string;
156
- }) => Promise<Page<Signal>>;
157
- get: (id: string) => Promise<Signal>;
124
+ }) => Promise<Page<EventRecord>>;
125
+ get: (id: string) => Promise<EventRecord>;
158
126
  };
159
127
  readonly customers: {
160
128
  create: (body: CustomerInput) => Promise<Customer>;
161
129
  list: (q?: ListQuery) => Promise<Page<Customer>>;
162
130
  get: (ref: Ref) => Promise<Customer>;
163
- update: (ref: Ref, body: Partial<CustomerInput>) => Promise<Customer>;
131
+ /** `churnDate`: when they left (ISO 8601), or null if they're back. */
132
+ update: (ref: Ref, body: Partial<CustomerInput> & {
133
+ churnDate?: string | null;
134
+ }) => Promise<Customer>;
164
135
  delete: (ref: Ref) => Promise<void>;
165
- /** What the customer has: active orders, entitlements and credit balances. */
166
- state: (ref: Ref) => Promise<Json>;
167
136
  };
168
137
  readonly products: {
138
+ /** `externalId`: your id for it, which events and traces name. `stripeProductId`: its product in your Stripe (`prod_…`). */
169
139
  create: (body: {
170
140
  name: string;
171
141
  externalId?: string;
172
142
  description?: string;
143
+ stripeProductId?: string;
173
144
  } & Json) => Promise<Resource>;
174
145
  list: (q?: ListQuery & {
175
146
  name?: string;
176
147
  }) => Promise<Page<Resource>>;
177
148
  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>>;
149
+ update: (ref: Ref, body: {
150
+ name?: string;
151
+ externalId?: string | null;
152
+ description?: string | null;
153
+ stripeProductId?: string | null;
154
+ } & Json) => Promise<Resource>;
216
155
  };
217
156
  }
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ export class Spondo {
30
30
  this.#retries = o.maxRetries ?? 2;
31
31
  this.#fetch = o.fetch ?? globalThis.fetch;
32
32
  }
33
- /** Any /api/v1 call: `path` without the prefix, e.g. `/invoices/inv_123/lines`. `headers` can't replace the client's own. */
33
+ /** Any /api/v1 call: `path` without the prefix, e.g. `/customers/cus_123/aliases`. `headers` can't replace the client's own. */
34
34
  async request(method, path, { query, body, headers } = {}) {
35
35
  const url = new URL(`${this.baseUrl}/api/v1${path}`);
36
36
  for (const [k, v] of Object.entries(query ?? {}))
@@ -62,53 +62,25 @@ export class Spondo {
62
62
  throw new SpondoError(res.status, e.code ?? "HTTP_ERROR", e.details ?? e.error ?? (text || res.statusText), wait);
63
63
  }
64
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)}`),
65
+ events = {
66
+ /** One event or a batch. Retrying with the same idempotency keys is safe. */
67
+ send: (events) => this.request("POST", "/events/bulk", { body: { events: Array.isArray(events) ? events : [events] } }),
68
+ list: (q = {}) => this.request("GET", "/events", { query: q }),
69
+ get: (id) => this.request("GET", `/events/${encodeURIComponent(id)}`),
70
70
  };
71
71
  customers = {
72
72
  create: (body) => this.request("POST", "/customers", { body }),
73
73
  list: (q = {}) => this.request("GET", "/customers", { query: q }),
74
74
  get: (ref) => this.request("GET", `/customers/${at(ref)}`),
75
+ /** `churnDate`: when they left (ISO 8601), or null if they're back. */
75
76
  update: (ref, body) => this.request("PUT", `/customers/${at(ref)}`, { body }),
76
77
  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
78
  };
80
79
  products = {
80
+ /** `externalId`: your id for it, which events and traces name. `stripeProductId`: its product in your Stripe (`prod_…`). */
81
81
  create: (body) => this.request("POST", "/products", { body }),
82
82
  list: (q = {}) => this.request("GET", "/products", { query: q }),
83
83
  get: (ref) => this.request("GET", `/products/${at(ref)}`),
84
84
  update: (ref, body) => this.request("PUT", `/products/${at(ref)}`, { body }),
85
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
86
  }
package/dist/tracing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TracerProvider } from "@opentelemetry/sdk-trace";
2
- import type { ClientOptions, Json, SignalsResult } from "./index.ts";
2
+ import type { ClientOptions, EventsResult, Json } from "./index.ts";
3
3
  export type TraceTags = {
4
4
  externalCustomerId: string;
5
5
  externalProductId?: string;
@@ -12,9 +12,9 @@ export type TraceTags = {
12
12
  export declare function initTracing(options?: ClientOptions): TracerProvider;
13
13
  /** Run `fn` as one unit of work for a customer: the AI calls in it are costed to them. */
14
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?: {
15
+ /** Inside trace(): an event for its customer and product that carries the trace's cost. */
16
+ export declare function event(eventName: string, data?: Json, options?: {
17
17
  idempotencyKey?: string;
18
- }): Promise<SignalsResult>;
18
+ }): Promise<EventsResult>;
19
19
  /** Send the spans waiting in the batch now: before a serverless function returns, or the process exits. */
20
20
  export declare const flush: () => Promise<void>;
package/dist/tracing.js CHANGED
@@ -1,6 +1,6 @@
1
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
2
+ // (<baseUrl>/v1/traces). Every span started inside trace() carries its customer and product, and an event() sent inside
3
+ // it carries that trace's cost, so you see cost per event. LLM calls are priced from their gen_ai.* token counts, so
4
4
  // register an OpenTelemetry instrumentation for your LLM client as usual (OpenLLMetry, OpenInference, or the Vercel AI
5
5
  // SDK's telemetry); spans that state their own cost set `meter.cost` (USD).
6
6
  import { SpanStatusCode, context, createContextKey, trace as otel } from "@opentelemetry/api";
@@ -52,12 +52,12 @@ export function trace(tags, fn) {
52
52
  }
53
53
  }));
54
54
  }
55
- /** Inside trace(): a signal for its customer and product that carries the trace's cost. */
56
- export function signal(eventName, data = {}, options = {}) {
55
+ /** Inside trace(): an event for its customer and product that carries the trace's cost. */
56
+ export function event(eventName, data = {}, options = {}) {
57
57
  const t = tags();
58
58
  if (!client || !t)
59
- throw new Error("signal() runs inside trace(), after initTracing()");
60
- return client.signals.send({
59
+ throw new Error("event() runs inside trace(), after initTracing()");
60
+ return client.events.send({
61
61
  eventName,
62
62
  customer: { externalCustomerId: t.externalCustomerId },
63
63
  ...(t.externalProductId && { attribution: { externalProductId: t.externalProductId } }),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@spondo/margin",
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.",
3
+ "version": "0.4.0",
4
+ "description": "The client for Spondo Margin: send usage events, trace what each customer's AI calls cost, and manage customers and products.",
5
5
  "homepage": "https://margin.getspondo.com",
6
6
  "license": "MIT",
7
7
  "type": "module",