@onemrr/node 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris McCaw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @onemrr/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-side activity tracking for [OneMRR](https://app.onemrr.dev) Churn Signals. Tell OneMRR which of your customer accounts are using your product, so it can spot paying customers whose usage drops before they cancel.
4
+
5
+ No dependencies. Node 20 or later.
6
+
7
+ ```sh
8
+ npm install @onemrr/node
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```ts
14
+ import { OneMRR } from "@onemrr/node";
15
+
16
+ const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
17
+
18
+ // Once per account (and whenever its billing changes): link your account ID to the
19
+ // customer in your billing source.
20
+ await onemrr.identify({
21
+ accountId: "merchant_123",
22
+ email: "merchant@example.com", // optional
23
+ source: "shopify",
24
+ externalCustomerId: "merchant-123.myshopify.com",
25
+ });
26
+
27
+ // Whenever something meaningful happens. Queued and sent in batches.
28
+ onemrr.track({ accountId: "merchant_123", event: "event_published" });
29
+
30
+ // In serverless functions, before returning:
31
+ await onemrr.flush();
32
+ ```
33
+
34
+ Create a secret key in OneMRR under **Settings → API keys**. A key limited to tracking can only identify accounts and track events. Keep it on your server: the SDK refuses to run in a browser, and OneMRR refuses secret keys sent from one.
35
+
36
+ ## What is sent
37
+
38
+ Only your account ID, the event name and its time. No properties, page URLs, IP addresses or user details. Each event carries a generated ID, so retries are counted once.
39
+
40
+ ## API
41
+
42
+ - `identify({ accountId, name?, email?, links?, source?, sourceId?, externalCustomerId? })`: creates or updates the account and its billing links. Resolves the result, including each link's status (`linked`, `pending_customer`, `conflict`), or `null` if it couldn't be sent.
43
+ - `identifyMany(inputs)`: the same for up to 500 accounts per request.
44
+ - `track({ accountId, event, timestamp?, id? })`: queues an event. Never throws.
45
+ - `flush()`: sends the queue now.
46
+ - `verify()`: checks the key and reports the last event OneMRR received.
47
+ - `shutdown()`: flushes before your process exits.
48
+
49
+ Options: `baseUrl`, `flushAt` (default 50), `flushInterval` (default 5000 ms), `timeout` (default 10000 ms), `maxRetries` (default 3), `onError`, `disabled`.
50
+
51
+ The REST API is documented at <https://app.onemrr.dev/api/v1/openapi.json>.
@@ -0,0 +1,138 @@
1
+ /**
2
+ * @onemrr/node — tell OneMRR which accounts use your product, from your server.
3
+ *
4
+ * import { OneMRR } from "@onemrr/node";
5
+ * const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
6
+ * await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
7
+ * onemrr.track({ accountId: "merchant_123", event: "event_published" });
8
+ * await onemrr.flush(); // before a serverless function returns
9
+ *
10
+ * Events are queued and sent in batches, each with a unique id, so a retry never counts
11
+ * twice. Tracking never throws: problems go to `onError`. No dependencies; Node 20+.
12
+ */
13
+ export type BillingSource = "stripe" | "shopify" | "wix" | "paddle" | "lemonsqueezy" | "csv" | "custom";
14
+ export interface OneMRROptions {
15
+ /** A secret key (sk_live_…) from OneMRR Settings → API keys. Keep it on your server. */
16
+ apiKey: string;
17
+ /** Defaults to https://app.onemrr.dev. */
18
+ baseUrl?: string;
19
+ /** Send once this many events are queued (default 50, at most 500). */
20
+ flushAt?: number;
21
+ /** And at least this often, in milliseconds (default 5000). */
22
+ flushInterval?: number;
23
+ /** Per request, in milliseconds (default 10000). */
24
+ timeout?: number;
25
+ /** Retries for network errors, 429 and 5xx (default 3). */
26
+ maxRetries?: number;
27
+ /** Called with every failure. Defaults to console.warn. */
28
+ onError?: (error: OneMRRError) => void;
29
+ /** Don't send anything (tests, local development). */
30
+ disabled?: boolean;
31
+ /** A fetch implementation (defaults to the global one). */
32
+ fetch?: typeof fetch;
33
+ }
34
+ export interface Link {
35
+ /** The billing source kind, when you have one source of that kind. */
36
+ source?: BillingSource;
37
+ /** Or the source's ID, from OneMRR's Sources page. */
38
+ sourceId?: number;
39
+ /** The customer's ID in that source: Stripe customer ID, myshopify domain, Wix instance ID. */
40
+ externalCustomerId: string;
41
+ }
42
+ export interface IdentifyInput {
43
+ /** Your own ID for the customer account. */
44
+ accountId: string;
45
+ name?: string | null;
46
+ /** Optional. Used only for retention emails when billing has no email. */
47
+ email?: string | null;
48
+ /** The billing customers this account pays through. */
49
+ links?: Link[];
50
+ /** Shorthand for a single link. */
51
+ source?: BillingSource;
52
+ sourceId?: number;
53
+ externalCustomerId?: string;
54
+ }
55
+ export interface TrackInput {
56
+ accountId: string;
57
+ /** A short name such as "event_published": letters, numbers, _ . : or -. */
58
+ event: string;
59
+ /** When it happened; defaults to now. */
60
+ timestamp?: string | Date;
61
+ /** A unique event ID; generated when left out. */
62
+ id?: string;
63
+ }
64
+ export interface IdentifyResult {
65
+ account_id: string;
66
+ status: "created" | "updated" | "unchanged";
67
+ links: {
68
+ source_id: number | null;
69
+ external_customer_id: string;
70
+ status: "linked" | "unchanged" | "pending_customer" | "conflict" | "error";
71
+ linked_to?: string;
72
+ error?: string;
73
+ }[];
74
+ }
75
+ export interface FlushResult {
76
+ sent: number;
77
+ accepted: number;
78
+ duplicates: number;
79
+ rejected: {
80
+ id: string;
81
+ event: string;
82
+ reason: string;
83
+ error: string;
84
+ }[];
85
+ failed: number;
86
+ }
87
+ export declare class OneMRRError extends Error {
88
+ readonly status?: number | undefined;
89
+ readonly type?: string | undefined;
90
+ constructor(message: string, status?: number | undefined, type?: string | undefined);
91
+ }
92
+ export declare const VERSION = "0.1.0";
93
+ /** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
94
+ export declare function eventId(now?: number): string;
95
+ export declare class OneMRR {
96
+ private readonly key;
97
+ private readonly base;
98
+ private readonly flushAt;
99
+ private readonly interval;
100
+ private readonly timeout;
101
+ private readonly retries;
102
+ private readonly onError;
103
+ private readonly disabled;
104
+ private readonly fetchImpl;
105
+ private queue;
106
+ private timer;
107
+ private inflight;
108
+ private totals;
109
+ constructor(opts: OneMRROptions);
110
+ /** Creates or updates an account and its billing links. Resolves null if it couldn't be sent. */
111
+ identify(input: IdentifyInput): Promise<IdentifyResult | null>;
112
+ /** Identifies up to 500 accounts per request (for a backfill). */
113
+ identifyMany(inputs: IdentifyInput[]): Promise<{
114
+ results: IdentifyResult[];
115
+ } | null>;
116
+ /** Queues an event. Never throws; invalid events are reported to onError and dropped. */
117
+ track(input: TrackInput): void;
118
+ /**
119
+ * Sends everything queued. Call before a short-lived process or function exits. Reports
120
+ * every event sent since the last flush() returned, including automatic batches.
121
+ */
122
+ flush(): Promise<FlushResult>;
123
+ private send;
124
+ /** Checks the key and reports when OneMRR last received an event. */
125
+ verify(): Promise<{
126
+ ok: boolean;
127
+ lastEventAt: string | null;
128
+ message: string;
129
+ }>;
130
+ /** Flushes and stops the timer. */
131
+ shutdown(): Promise<FlushResult>;
132
+ /** Starts sending in the background; results are reported by the next flush(). */
133
+ private kick;
134
+ private schedule;
135
+ private fail;
136
+ /** JSON request with retries on network errors, 429 and 5xx. Resolves null after reporting a failure. */
137
+ private request;
138
+ }
package/dist/index.js ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * @onemrr/node — tell OneMRR which accounts use your product, from your server.
3
+ *
4
+ * import { OneMRR } from "@onemrr/node";
5
+ * const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
6
+ * await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
7
+ * onemrr.track({ accountId: "merchant_123", event: "event_published" });
8
+ * await onemrr.flush(); // before a serverless function returns
9
+ *
10
+ * Events are queued and sent in batches, each with a unique id, so a retry never counts
11
+ * twice. Tracking never throws: problems go to `onError`. No dependencies; Node 20+.
12
+ */
13
+ export class OneMRRError extends Error {
14
+ status;
15
+ type;
16
+ constructor(message, status, type) {
17
+ super(message);
18
+ this.status = status;
19
+ this.type = type;
20
+ this.name = "OneMRRError";
21
+ }
22
+ }
23
+ const EVENT_RE = /^[a-z0-9][a-z0-9_.:-]{0,63}$/i;
24
+ const MAX_QUEUE = 10_000;
25
+ const BATCH = 500;
26
+ export const VERSION = "0.1.0";
27
+ /** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
28
+ export function eventId(now = Date.now()) {
29
+ const b = new Uint8Array(16);
30
+ crypto.getRandomValues(b);
31
+ let t = now;
32
+ for (let i = 5; i >= 0; i--) {
33
+ b[i] = t & 0xff;
34
+ t = Math.floor(t / 256);
35
+ }
36
+ b[6] = (b[6] & 0x0f) | 0x70;
37
+ b[8] = (b[8] & 0x3f) | 0x80;
38
+ const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
39
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
40
+ }
41
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
42
+ export class OneMRR {
43
+ key;
44
+ base;
45
+ flushAt;
46
+ interval;
47
+ timeout;
48
+ retries;
49
+ onError;
50
+ disabled;
51
+ fetchImpl;
52
+ queue = [];
53
+ timer = null;
54
+ inflight = null;
55
+ totals = { sent: 0, accepted: 0, duplicates: 0, rejected: [], failed: 0 };
56
+ constructor(opts) {
57
+ if (!opts?.apiKey && !opts?.disabled)
58
+ throw new OneMRRError("OneMRR: apiKey is required (sk_live_…)");
59
+ if (opts.apiKey?.startsWith("pk_"))
60
+ throw new OneMRRError("OneMRR: that's a publishable key. @onemrr/node needs a secret key (sk_live_…) from Settings → API keys.");
61
+ const g = globalThis;
62
+ if (g.window !== undefined && g.document !== undefined)
63
+ throw new OneMRRError("OneMRR: @onemrr/node runs on your server. Never put a secret key in browser code.");
64
+ this.key = opts.apiKey;
65
+ this.base = (opts.baseUrl ?? "https://app.onemrr.dev").replace(/\/$/, "");
66
+ this.flushAt = Math.min(BATCH, Math.max(1, opts.flushAt ?? 50));
67
+ this.interval = Math.max(100, opts.flushInterval ?? 5000);
68
+ this.timeout = opts.timeout ?? 10_000;
69
+ this.retries = Math.max(0, opts.maxRetries ?? 3);
70
+ this.onError = opts.onError ?? ((e) => console.warn(`[onemrr] ${e.message}`));
71
+ this.disabled = Boolean(opts.disabled);
72
+ this.fetchImpl = opts.fetch ?? fetch;
73
+ }
74
+ /** Creates or updates an account and its billing links. Resolves null if it couldn't be sent. */
75
+ async identify(input) {
76
+ if (this.disabled)
77
+ return null;
78
+ const body = toIdentify(input);
79
+ if (!body) {
80
+ this.fail(new OneMRRError("identify needs accountId"));
81
+ return null;
82
+ }
83
+ const r = await this.request("POST", "/api/v1/identify", body);
84
+ for (const l of r?.links ?? []) {
85
+ if (l.status === "conflict")
86
+ this.fail(new OneMRRError(`${l.external_customer_id} is already linked to account ${l.linked_to}; resolve it in OneMRR (Churn → Activity).`, 409, "conflict"));
87
+ if (l.status === "error")
88
+ this.fail(new OneMRRError(l.error ?? "Link failed", 422, "invalid_request"));
89
+ }
90
+ return r;
91
+ }
92
+ /** Identifies up to 500 accounts per request (for a backfill). */
93
+ async identifyMany(inputs) {
94
+ if (this.disabled)
95
+ return null;
96
+ const out = [];
97
+ for (let i = 0; i < inputs.length; i += BATCH) {
98
+ const identities = inputs.slice(i, i + BATCH).map(toIdentify).filter(Boolean);
99
+ const r = await this.request("POST", "/api/v1/identify/batch", { identities });
100
+ if (!r)
101
+ return null;
102
+ out.push(...r.results);
103
+ }
104
+ return { results: out };
105
+ }
106
+ /** Queues an event. Never throws; invalid events are reported to onError and dropped. */
107
+ track(input) {
108
+ if (this.disabled)
109
+ return;
110
+ const accountId = input?.accountId == null ? "" : String(input.accountId).trim();
111
+ if (!accountId || accountId.length > 200)
112
+ return this.fail(new OneMRRError("track needs accountId (up to 200 characters)"));
113
+ if (typeof input.event !== "string" || !EVENT_RE.test(input.event))
114
+ return this.fail(new OneMRRError(`Invalid event name "${String(input.event)}": use 1–64 letters, numbers, _ . : or -`));
115
+ const at = input.timestamp == null ? new Date() : new Date(input.timestamp);
116
+ if (Number.isNaN(at.getTime()))
117
+ return this.fail(new OneMRRError(`Invalid timestamp for ${input.event}`));
118
+ if (this.queue.length >= MAX_QUEUE) {
119
+ this.queue.shift();
120
+ this.fail(new OneMRRError("Queue full; dropped the oldest event. Is OneMRR reachable?"));
121
+ }
122
+ this.queue.push({ id: input.id ?? eventId(), account_id: accountId, event: input.event.toLowerCase(), timestamp: at.toISOString() });
123
+ if (this.queue.length >= this.flushAt)
124
+ this.kick();
125
+ else
126
+ this.schedule();
127
+ }
128
+ /**
129
+ * Sends everything queued. Call before a short-lived process or function exits. Reports
130
+ * every event sent since the last flush() returned, including automatic batches.
131
+ */
132
+ async flush() {
133
+ if (this.timer)
134
+ clearTimeout(this.timer);
135
+ this.timer = null;
136
+ while (this.inflight)
137
+ await this.inflight;
138
+ if (this.queue.length) {
139
+ this.inflight = this.send().finally(() => (this.inflight = null));
140
+ await this.inflight;
141
+ }
142
+ const out = this.totals;
143
+ this.totals = { sent: 0, accepted: 0, duplicates: 0, rejected: [], failed: 0 };
144
+ return out;
145
+ }
146
+ async send() {
147
+ const total = this.totals;
148
+ while (this.queue.length) {
149
+ const batch = this.queue.splice(0, BATCH);
150
+ const r = await this.request("POST", "/api/v1/track", { events: batch }, true);
151
+ total.sent += batch.length;
152
+ if (!r) {
153
+ total.failed += batch.length;
154
+ continue;
155
+ }
156
+ total.accepted += r.accepted;
157
+ total.duplicates += r.duplicates;
158
+ for (const x of r.rejected ?? []) {
159
+ const e = batch[x.index];
160
+ total.rejected.push({ id: e?.id ?? "", event: e?.event ?? "", reason: x.reason, error: x.error });
161
+ this.fail(new OneMRRError(`Event ${e?.event ?? x.index} rejected: ${x.error}`, 400, x.reason));
162
+ }
163
+ }
164
+ }
165
+ /** Checks the key and reports when OneMRR last received an event. */
166
+ async verify() {
167
+ const r = await this.request("GET", "/api/v1/tracking/status");
168
+ if (!r)
169
+ return { ok: false, lastEventAt: null, message: "Couldn't reach OneMRR with this key; see onError for the reason." };
170
+ return { ok: true, lastEventAt: r.last_event_at, message: r.last_event_at ? `Connected. Last event ${r.last_event_at}, ${r.events.today} today.` : "Connected. No events yet." };
171
+ }
172
+ /** Flushes and stops the timer. */
173
+ async shutdown() {
174
+ return this.flush();
175
+ }
176
+ /** Starts sending in the background; results are reported by the next flush(). */
177
+ kick() {
178
+ if (this.timer)
179
+ clearTimeout(this.timer);
180
+ this.timer = null;
181
+ if (this.inflight || !this.queue.length)
182
+ return;
183
+ this.inflight = this.send().finally(() => {
184
+ this.inflight = null;
185
+ if (this.queue.length)
186
+ this.schedule();
187
+ });
188
+ }
189
+ schedule() {
190
+ if (this.timer)
191
+ return;
192
+ this.timer = setTimeout(() => {
193
+ this.timer = null;
194
+ this.kick();
195
+ }, this.interval);
196
+ this.timer.unref?.();
197
+ }
198
+ fail(e) {
199
+ try {
200
+ this.onError(e);
201
+ }
202
+ catch {
203
+ /* an onError that throws must not break the caller */
204
+ }
205
+ }
206
+ /** JSON request with retries on network errors, 429 and 5xx. Resolves null after reporting a failure. */
207
+ async request(method, path, body, acceptPartial = false) {
208
+ let last = null;
209
+ for (let attempt = 0; attempt <= this.retries; attempt++) {
210
+ if (attempt)
211
+ await sleep(Math.min(8000, 500 * 2 ** (attempt - 1)) * (0.75 + Math.random() / 2));
212
+ const ctl = new AbortController();
213
+ const t = setTimeout(() => ctl.abort(), this.timeout);
214
+ try {
215
+ const res = await this.fetchImpl(this.base + path, {
216
+ method,
217
+ headers: { Authorization: `Bearer ${this.key}`, "Content-Type": "application/json", "User-Agent": `onemrr-node/${VERSION}` },
218
+ body: body === undefined ? undefined : JSON.stringify(body),
219
+ signal: ctl.signal,
220
+ });
221
+ const json = (await res.json().catch(() => null));
222
+ if (res.ok)
223
+ return json;
224
+ const msg = json?.error?.message ?? `HTTP ${res.status}`;
225
+ last = new OneMRRError(msg, res.status, json?.error?.type);
226
+ if (res.status === 429) {
227
+ const wait = Number(res.headers.get("retry-after"));
228
+ if (wait > 0 && attempt < this.retries)
229
+ await sleep(Math.min(60, wait) * 1000);
230
+ continue;
231
+ }
232
+ if (res.status >= 500)
233
+ continue;
234
+ // A track request where every event was refused is a 400 with per-event issues.
235
+ if (acceptPartial && res.status === 400 && json?.error && "issues" in json.error) {
236
+ const issues = json.error.issues ?? [];
237
+ return { accepted: 0, duplicates: 0, rejected: issues.map((i) => ({ index: Number(i.path.split(".")[1]), reason: "invalid", error: i.message })) };
238
+ }
239
+ break;
240
+ }
241
+ catch (err) {
242
+ last = new OneMRRError(err instanceof Error && err.name === "AbortError" ? `Timed out after ${this.timeout} ms` : `Network error: ${err instanceof Error ? err.message : String(err)}`);
243
+ }
244
+ finally {
245
+ clearTimeout(t);
246
+ }
247
+ }
248
+ if (last)
249
+ this.fail(last);
250
+ return null;
251
+ }
252
+ }
253
+ function toIdentify(i) {
254
+ if (!i?.accountId)
255
+ return null;
256
+ const link = (l) => ({ ...(l.sourceId != null ? { source_id: l.sourceId } : {}), ...(l.source ? { source: l.source } : {}), external_customer_id: l.externalCustomerId });
257
+ const links = [...(i.links ?? [])];
258
+ if (i.externalCustomerId)
259
+ links.push({ source: i.source, sourceId: i.sourceId, externalCustomerId: i.externalCustomerId });
260
+ return {
261
+ account_id: String(i.accountId),
262
+ ...(i.name !== undefined ? { name: i.name } : {}),
263
+ ...(i.email !== undefined ? { email: i.email } : {}),
264
+ ...(links.length ? { links: links.map(link) } : {}),
265
+ };
266
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@onemrr/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Server-side activity tracking for OneMRR Churn Signals: identify accounts, track key events.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "sideEffects": false,
23
+ "license": "MIT",
24
+ "homepage": "https://app.onemrr.dev/api/v1/openapi.json",
25
+ "keywords": [
26
+ "onemrr",
27
+ "churn",
28
+ "mrr",
29
+ "analytics",
30
+ "saas"
31
+ ],
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json",
34
+ "prepublishOnly": "tsc -p tsconfig.build.json"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/chrismccaw/OneMRR.git",
39
+ "directory": "packages/node"
40
+ }
41
+ }