@referalli/sdk 0.0.0-stage → 0.3.21
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/CHANGELOG.md +132 -0
- package/LICENSE +21 -0
- package/README.md +236 -2
- package/dist/cjs/attribution.d.ts +105 -0
- package/dist/cjs/attribution.js +200 -0
- package/dist/cjs/browser.d.ts +41 -0
- package/dist/cjs/browser.js +88 -0
- package/dist/cjs/client.d.ts +97 -0
- package/dist/cjs/client.js +301 -0
- package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/cjs/consent/adapters/cookiebot.js +49 -0
- package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
- package/dist/cjs/consent/adapters/custom.d.ts +8 -0
- package/dist/cjs/consent/adapters/custom.js +39 -0
- package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
- package/dist/cjs/consent/adapters/didomi.js +67 -0
- package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
- package/dist/cjs/consent/adapters/gcm.js +78 -0
- package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
- package/dist/cjs/consent/adapters/gpp.js +92 -0
- package/dist/cjs/consent/adapters/none.d.ts +3 -0
- package/dist/cjs/consent/adapters/none.js +30 -0
- package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
- package/dist/cjs/consent/adapters/onetrust.js +71 -0
- package/dist/cjs/consent/adapters/osano.d.ts +9 -0
- package/dist/cjs/consent/adapters/osano.js +71 -0
- package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
- package/dist/cjs/consent/adapters/tcf.js +79 -0
- package/dist/cjs/consent/adapters/termly.d.ts +10 -0
- package/dist/cjs/consent/adapters/termly.js +61 -0
- package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/cjs/consent/adapters/usercentrics.js +106 -0
- package/dist/cjs/consent/conformance.d.ts +22 -0
- package/dist/cjs/consent/conformance.js +33 -0
- package/dist/cjs/consent/gate.d.ts +23 -0
- package/dist/cjs/consent/gate.js +220 -0
- package/dist/cjs/consent/port.d.ts +105 -0
- package/dist/cjs/consent/port.js +72 -0
- package/dist/cjs/consent/registry.d.ts +17 -0
- package/dist/cjs/consent/registry.js +61 -0
- package/dist/cjs/consent/served.d.ts +15 -0
- package/dist/cjs/consent/served.js +26 -0
- package/dist/cjs/core.d.ts +77 -0
- package/dist/cjs/core.js +64 -0
- package/dist/cjs/errors.d.ts +42 -0
- package/dist/cjs/errors.generated.d.ts +183 -0
- package/dist/cjs/errors.generated.js +279 -0
- package/dist/cjs/errors.js +47 -0
- package/dist/cjs/generated.d.ts +15151 -0
- package/dist/cjs/generated.js +625 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +93 -0
- package/dist/cjs/mobile.d.ts +66 -0
- package/dist/cjs/mobile.js +69 -0
- package/dist/cjs/node.d.ts +209 -0
- package/dist/cjs/node.js +140 -0
- package/dist/cjs/outbox.d.ts +186 -0
- package/dist/cjs/outbox.js +324 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/resources.generated.d.ts +6002 -0
- package/dist/cjs/resources.generated.js +2090 -0
- package/dist/cjs/served.d.ts +25 -0
- package/dist/cjs/served.js +214 -0
- package/dist/cjs/sha256.d.ts +2 -0
- package/dist/cjs/sha256.js +86 -0
- package/dist/cjs/snippet.d.ts +99 -0
- package/dist/cjs/snippet.js +213 -0
- package/dist/cjs/stripe-events.d.ts +25 -0
- package/dist/cjs/stripe-events.js +117 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +76 -0
- package/dist/cjs/webhooks.js +159 -0
- package/dist/esm/attribution.d.ts +105 -0
- package/dist/esm/attribution.js +186 -0
- package/dist/esm/browser.d.ts +41 -0
- package/dist/esm/browser.js +68 -0
- package/dist/esm/client.d.ts +97 -0
- package/dist/esm/client.js +297 -0
- package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/esm/consent/adapters/cookiebot.js +46 -0
- package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/esm/consent/adapters/cookiemunch.js +53 -0
- package/dist/esm/consent/adapters/custom.d.ts +8 -0
- package/dist/esm/consent/adapters/custom.js +36 -0
- package/dist/esm/consent/adapters/didomi.d.ts +9 -0
- package/dist/esm/consent/adapters/didomi.js +64 -0
- package/dist/esm/consent/adapters/gcm.d.ts +10 -0
- package/dist/esm/consent/adapters/gcm.js +75 -0
- package/dist/esm/consent/adapters/gpp.d.ts +9 -0
- package/dist/esm/consent/adapters/gpp.js +89 -0
- package/dist/esm/consent/adapters/none.d.ts +3 -0
- package/dist/esm/consent/adapters/none.js +27 -0
- package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
- package/dist/esm/consent/adapters/onetrust.js +68 -0
- package/dist/esm/consent/adapters/osano.d.ts +9 -0
- package/dist/esm/consent/adapters/osano.js +68 -0
- package/dist/esm/consent/adapters/tcf.d.ts +8 -0
- package/dist/esm/consent/adapters/tcf.js +76 -0
- package/dist/esm/consent/adapters/termly.d.ts +10 -0
- package/dist/esm/consent/adapters/termly.js +58 -0
- package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/esm/consent/adapters/usercentrics.js +103 -0
- package/dist/esm/consent/conformance.d.ts +22 -0
- package/dist/esm/consent/conformance.js +30 -0
- package/dist/esm/consent/gate.d.ts +23 -0
- package/dist/esm/consent/gate.js +217 -0
- package/dist/esm/consent/port.d.ts +105 -0
- package/dist/esm/consent/port.js +67 -0
- package/dist/esm/consent/registry.d.ts +17 -0
- package/dist/esm/consent/registry.js +55 -0
- package/dist/esm/consent/served.d.ts +15 -0
- package/dist/esm/consent/served.js +22 -0
- package/dist/esm/core.d.ts +77 -0
- package/dist/esm/core.js +60 -0
- package/dist/esm/errors.d.ts +42 -0
- package/dist/esm/errors.generated.d.ts +183 -0
- package/dist/esm/errors.generated.js +231 -0
- package/dist/esm/errors.js +40 -0
- package/dist/esm/generated.d.ts +15151 -0
- package/dist/esm/generated.js +622 -0
- package/dist/esm/index.d.ts +22 -0
- package/dist/esm/index.js +22 -0
- package/dist/esm/mobile.d.ts +66 -0
- package/dist/esm/mobile.js +64 -0
- package/dist/esm/node.d.ts +209 -0
- package/dist/esm/node.js +135 -0
- package/dist/esm/outbox.d.ts +186 -0
- package/dist/esm/outbox.js +316 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/resources.generated.d.ts +6002 -0
- package/dist/esm/resources.generated.js +2086 -0
- package/dist/esm/served.d.ts +25 -0
- package/dist/esm/served.js +207 -0
- package/dist/esm/sha256.d.ts +2 -0
- package/dist/esm/sha256.js +82 -0
- package/dist/esm/snippet.d.ts +99 -0
- package/dist/esm/snippet.js +210 -0
- package/dist/esm/stripe-events.d.ts +25 -0
- package/dist/esm/stripe-events.js +114 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +76 -0
- package/dist/esm/webhooks.js +153 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/package.json +105 -4
- package/src/attribution.ts +216 -0
- package/src/browser.ts +107 -0
- package/src/client.ts +351 -0
- package/src/codegen.ts +130 -0
- package/src/consent/adapters/cookiebot.ts +42 -0
- package/src/consent/adapters/cookiemunch.ts +49 -0
- package/src/consent/adapters/custom.ts +37 -0
- package/src/consent/adapters/didomi.ts +59 -0
- package/src/consent/adapters/gcm.ts +68 -0
- package/src/consent/adapters/gpp.ts +81 -0
- package/src/consent/adapters/none.ts +28 -0
- package/src/consent/adapters/onetrust.ts +64 -0
- package/src/consent/adapters/osano.ts +63 -0
- package/src/consent/adapters/tcf.ts +67 -0
- package/src/consent/adapters/termly.ts +54 -0
- package/src/consent/adapters/usercentrics.ts +97 -0
- package/src/consent/conformance.ts +47 -0
- package/src/consent/gate.ts +216 -0
- package/src/consent/port.ts +148 -0
- package/src/consent/registry.ts +60 -0
- package/src/consent/served.ts +24 -0
- package/src/core.ts +127 -0
- package/src/errors.generated.ts +277 -0
- package/src/errors.ts +57 -0
- package/src/generated.ts +14545 -0
- package/src/index.ts +100 -0
- package/src/mobile.ts +96 -0
- package/src/node.ts +291 -0
- package/src/outbox.ts +452 -0
- package/src/resources.generated.ts +2097 -0
- package/src/served.ts +229 -0
- package/src/sha256.ts +82 -0
- package/src/snippet.ts +305 -0
- package/src/stripe-events.ts +130 -0
- package/src/version.ts +2 -0
- package/src/webhooks.ts +207 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The first-party referral context, shared by the browser tracker (`aff.js`,
|
|
3
|
+
* `referalli/browser`) and the server kits (`@referalli/next`,
|
|
4
|
+
* `@referalli/express`): what it is, how a landing URL updates it, and how it
|
|
5
|
+
* is stored in a cookie on the merchant's own domain. Isomorphic and
|
|
6
|
+
* dependency-free.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Cookie (and localStorage key) holding the context. A wire name shared with every `aff.js` install; don't change it. */
|
|
10
|
+
export const REFERRAL_COOKIE = 'referalli_ctx';
|
|
11
|
+
/**
|
|
12
|
+
* The pre-rename name of the same context. The browser tracker (`aff.js`,
|
|
13
|
+
* `referalli/browser`) writes the context under BOTH names, with the same
|
|
14
|
+
* value, attributes and expiry, and reads either.
|
|
15
|
+
*
|
|
16
|
+
* Why: integrations that read the cookie themselves may still read the pre-rename
|
|
17
|
+
* name. Atlas's connector and Cookie Munch's preset both read `referalli_ctx` now.
|
|
18
|
+
* The twin is written until 2027-01-31, announced in the changelog and on
|
|
19
|
+
* /docs/renamed-from-referally, then dropped (reading stays tolerant).
|
|
20
|
+
*
|
|
21
|
+
* TODO(legacy-ctx, 2027-01-31): stop writing the legacy name; keep reading it for
|
|
22
|
+
* one more cookie window after that.
|
|
23
|
+
*/
|
|
24
|
+
export const LEGACY_REFERRAL_COOKIE = 'referally_ctx';
|
|
25
|
+
/** Every name the context is written and read under, current first. */
|
|
26
|
+
export const REFERRAL_COOKIE_NAMES: readonly string[] = [REFERRAL_COOKIE, LEGACY_REFERRAL_COOKIE];
|
|
27
|
+
/** Query parameters that carry a partner's referral code, in priority order. */
|
|
28
|
+
export const REFERRAL_PARAMS: readonly string[] = ['via', 'ref', 'aff'];
|
|
29
|
+
/** Query parameter carrying a click id from a Referalli redirect link (`/go/...`). */
|
|
30
|
+
export const CLICK_ID_PARAM = 'ref_click_id';
|
|
31
|
+
export const DEFAULT_COOKIE_DAYS = 60;
|
|
32
|
+
const DAY_MS = 86_400_000;
|
|
33
|
+
|
|
34
|
+
export interface ReferralContext {
|
|
35
|
+
/** This browser's anonymous id (`a_…`). */
|
|
36
|
+
anonId: string;
|
|
37
|
+
/** The partner's referral code from `?via=` / `?ref=` / `?aff=`. */
|
|
38
|
+
code: string | null;
|
|
39
|
+
/** The click id from a redirect link. */
|
|
40
|
+
clickId: string | null;
|
|
41
|
+
/** When the context was first created (epoch ms). */
|
|
42
|
+
ts: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The stored shape: the context plus when it expires (epoch ms). */
|
|
46
|
+
export type StoredReferral = ReferralContext & { exp?: number };
|
|
47
|
+
|
|
48
|
+
export interface MergeOptions {
|
|
49
|
+
now?: number;
|
|
50
|
+
/** Lifetime, 1–400 days. Default 60. */
|
|
51
|
+
cookieDays?: number;
|
|
52
|
+
/** Keep an unexpired first referral instead of replacing it. */
|
|
53
|
+
firstTouch?: boolean;
|
|
54
|
+
randomId?: () => string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const clampDays = (days: number | undefined): number => Math.max(1, Math.min(400, Math.round(days ?? DEFAULT_COOKIE_DAYS)));
|
|
58
|
+
|
|
59
|
+
/** A fresh anonymous id: `a_` + 20 random base-36 characters. */
|
|
60
|
+
export function newAnonId(): string {
|
|
61
|
+
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
|
62
|
+
const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;
|
|
63
|
+
const bytes = new Uint8Array(20);
|
|
64
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
65
|
+
else for (let i = 0; i < 20; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
66
|
+
let out = 'a_';
|
|
67
|
+
for (const b of bytes) out += chars[b % chars.length];
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The referral a URL carries: the first of `params` that is set, and `ref_click_id`. */
|
|
72
|
+
export function referralFromUrl(url: string | URL, params: readonly string[] = REFERRAL_PARAMS): { code: string | null; clickId: string | null } {
|
|
73
|
+
let u: URL;
|
|
74
|
+
try {
|
|
75
|
+
u = typeof url === 'string' ? new URL(url, 'http://localhost') : url;
|
|
76
|
+
} catch {
|
|
77
|
+
return { code: null, clickId: null };
|
|
78
|
+
}
|
|
79
|
+
let code: string | null = null;
|
|
80
|
+
for (const p of params) {
|
|
81
|
+
const v = u.searchParams.get(p);
|
|
82
|
+
if (v) {
|
|
83
|
+
code = v.slice(0, 120);
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const clickId = u.searchParams.get(CLICK_ID_PARAM)?.slice(0, 80) || null;
|
|
88
|
+
return { code, clickId };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Parse a stored context (the cookie's or localStorage's value, URI-encoded or not). Expired or malformed → null. */
|
|
92
|
+
export function parseReferral(raw: string | null | undefined, now: number = Date.now()): StoredReferral | null {
|
|
93
|
+
if (!raw) return null;
|
|
94
|
+
let text = raw;
|
|
95
|
+
try {
|
|
96
|
+
if (raw.startsWith('%7B') || raw.startsWith('%7b')) text = decodeURIComponent(raw);
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(text) as StoredReferral;
|
|
102
|
+
if (!parsed || typeof parsed.anonId !== 'string') return null;
|
|
103
|
+
if (parsed.exp && parsed.exp < now) return null;
|
|
104
|
+
return {
|
|
105
|
+
anonId: parsed.anonId,
|
|
106
|
+
code: typeof parsed.code === 'string' ? parsed.code : null,
|
|
107
|
+
clickId: typeof parsed.clickId === 'string' ? parsed.clickId : null,
|
|
108
|
+
ts: typeof parsed.ts === 'number' ? parsed.ts : now,
|
|
109
|
+
...(typeof parsed.exp === 'number' ? { exp: parsed.exp } : {}),
|
|
110
|
+
};
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The context from a `Cookie` request header. `names` are tried in order
|
|
118
|
+
* (default: `REFERRAL_COOKIE_NAMES`, the current name then the legacy one);
|
|
119
|
+
* add an older cookie name to keep reading contexts saved under it.
|
|
120
|
+
*/
|
|
121
|
+
export function referralFromCookieHeader(
|
|
122
|
+
cookieHeader: string | null | undefined,
|
|
123
|
+
now: number = Date.now(),
|
|
124
|
+
names: readonly string[] = REFERRAL_COOKIE_NAMES,
|
|
125
|
+
): StoredReferral | null {
|
|
126
|
+
if (!cookieHeader) return null;
|
|
127
|
+
const jar = new Map<string, string>();
|
|
128
|
+
for (const part of cookieHeader.split(';')) {
|
|
129
|
+
const i = part.indexOf('=');
|
|
130
|
+
if (i > 0) jar.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
|
|
131
|
+
}
|
|
132
|
+
for (const name of names) {
|
|
133
|
+
const raw = jar.get(name);
|
|
134
|
+
if (raw === undefined) continue;
|
|
135
|
+
try {
|
|
136
|
+
const ctx = parseReferral(decodeURIComponent(raw), now);
|
|
137
|
+
if (ctx) return ctx;
|
|
138
|
+
} catch {
|
|
139
|
+
/* malformed: try the next name */
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The context after a page view: a new referral in the URL replaces the
|
|
147
|
+
* stored one (unless `firstTouch` keeps an unexpired one), and a referral
|
|
148
|
+
* restarts the expiry window. Same rules as `aff.js`.
|
|
149
|
+
*/
|
|
150
|
+
export function mergeReferral(stored: StoredReferral | null, fromUrl: { code: string | null; clickId: string | null }, opts: MergeOptions = {}): StoredReferral {
|
|
151
|
+
const now = opts.now ?? Date.now();
|
|
152
|
+
const days = clampDays(opts.cookieDays);
|
|
153
|
+
const referred = Boolean(fromUrl.code || fromUrl.clickId);
|
|
154
|
+
const keep = Boolean(opts.firstTouch && (stored?.code || stored?.clickId));
|
|
155
|
+
return {
|
|
156
|
+
anonId: stored?.anonId ?? (opts.randomId ?? newAnonId)(),
|
|
157
|
+
code: keep ? (stored?.code ?? null) : (fromUrl.code ?? stored?.code ?? null),
|
|
158
|
+
clickId: keep ? (stored?.clickId ?? null) : (fromUrl.clickId ?? stored?.clickId ?? null),
|
|
159
|
+
ts: stored?.ts ?? now,
|
|
160
|
+
exp: keep && stored?.exp ? stored.exp : referred || !stored?.exp ? now + days * DAY_MS : stored.exp,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface CookieOptions {
|
|
165
|
+
cookieDays?: number;
|
|
166
|
+
/** Share with subdomains, e.g. `.example.com`. */
|
|
167
|
+
domain?: string;
|
|
168
|
+
/** Default true. Turn off only for plain-http local development. */
|
|
169
|
+
secure?: boolean;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* A `Set-Cookie` header value for the context. Not HttpOnly on purpose: the
|
|
174
|
+
* browser tracker reads the same cookie.
|
|
175
|
+
*/
|
|
176
|
+
export function serializeReferralCookie(ctx: StoredReferral, opts: CookieOptions = {}): string {
|
|
177
|
+
const days = clampDays(opts.cookieDays);
|
|
178
|
+
const domain = opts.domain && /^\.?[a-z0-9.-]+$/i.test(opts.domain) ? `; Domain=${opts.domain}` : '';
|
|
179
|
+
const secure = opts.secure === false ? '' : '; Secure';
|
|
180
|
+
return `${REFERRAL_COOKIE}=${encodeURIComponent(JSON.stringify(ctx))}; Path=/; Max-Age=${days * 86_400}; SameSite=Lax${domain}${secure}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* `Set-Cookie` values for the context under every name: `referalli_ctx` and
|
|
185
|
+
* its legacy twin `referally_ctx`, same value, attributes and expiry (see
|
|
186
|
+
* LEGACY_REFERRAL_COOKIE). Server kits append each one.
|
|
187
|
+
*/
|
|
188
|
+
export function serializeReferralCookies(ctx: StoredReferral, opts: CookieOptions = {}): string[] {
|
|
189
|
+
const value = serializeReferralCookie(ctx, opts);
|
|
190
|
+
const tail = value.slice(REFERRAL_COOKIE.length);
|
|
191
|
+
return REFERRAL_COOKIE_NAMES.map((name) => `${name}${tail}`);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** `Set-Cookie` values that delete the context under every name (consent denied or withdrawn). */
|
|
195
|
+
export function clearReferralCookies(opts: Pick<CookieOptions, 'domain' | 'secure'> = {}): string[] {
|
|
196
|
+
const domain = opts.domain && /^\.?[a-z0-9.-]+$/i.test(opts.domain) ? `; Domain=${opts.domain}` : '';
|
|
197
|
+
const secure = opts.secure === false ? '' : '; Secure';
|
|
198
|
+
return REFERRAL_COOKIE_NAMES.map((name) => `${name}=; Path=/; Max-Age=0; SameSite=Lax${domain}${secure}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Fields for `associate` (server-side attribution at signup) from a context. */
|
|
202
|
+
export function associateFields(ctx: ReferralContext | null | undefined): { anonId?: string; referralToken?: string; couponCode?: string } {
|
|
203
|
+
if (!ctx) return {};
|
|
204
|
+
return {
|
|
205
|
+
...(ctx.anonId ? { anonId: ctx.anonId } : {}),
|
|
206
|
+
...(ctx.clickId ? { referralToken: ctx.clickId } : {}),
|
|
207
|
+
...(ctx.code ? { couponCode: ctx.code } : {}),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** SHA-256 hex of a normalised (trimmed, lower-cased) email, for `emailHash` (WebCrypto). */
|
|
212
|
+
export async function hashEmail(email: string): Promise<string> {
|
|
213
|
+
const data = new TextEncoder().encode(email.trim().toLowerCase());
|
|
214
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', data);
|
|
215
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
216
|
+
}
|
package/src/browser.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `referalli/browser`: the referral tracker for your own pages. It reads
|
|
3
|
+
* `?via=` / `?ref=` / `?aff=` and `ref_click_id` from the landing URL, keeps
|
|
4
|
+
* the context in a first-party cookie (and localStorage) on your domain,
|
|
5
|
+
* records the visit, and attributes the visitor when they sign up.
|
|
6
|
+
*
|
|
7
|
+
* import { createTracker } from '@referalli/sdk/browser';
|
|
8
|
+
* const tracker = await createTracker({ publishableKey: 'tk_...' });
|
|
9
|
+
* // after signup:
|
|
10
|
+
* await tracker.trackSignup({ customerRef: user.id, email: user.email });
|
|
11
|
+
*
|
|
12
|
+
* Consent: pass `consent: 'auto'` (or a CMP id such as `'onetrust'`) and
|
|
13
|
+
* nothing is stored or sent until the visitor's CMP grants it; the referral
|
|
14
|
+
* still reaches `signupMetadata()` from memory. Without a CMP, call
|
|
15
|
+
* `tracker.consent(true | false)`. The default, `'none'`, always stores.
|
|
16
|
+
*
|
|
17
|
+
* Only your public tracking token goes in the browser, never an `rk_` key.
|
|
18
|
+
* Tree-shakeable and dependency-free.
|
|
19
|
+
*/
|
|
20
|
+
import { hashEmail, parseReferral, REFERRAL_COOKIE_NAMES, referralFromCookieHeader, type ReferralContext, type StoredReferral } from './attribution.js';
|
|
21
|
+
import { initSnippet, type AffApi, type SnippetConfig } from './snippet.js';
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
associateFields,
|
|
25
|
+
hashEmail,
|
|
26
|
+
mergeReferral,
|
|
27
|
+
parseReferral,
|
|
28
|
+
LEGACY_REFERRAL_COOKIE,
|
|
29
|
+
REFERRAL_COOKIE,
|
|
30
|
+
REFERRAL_COOKIE_NAMES,
|
|
31
|
+
REFERRAL_PARAMS,
|
|
32
|
+
referralFromCookieHeader,
|
|
33
|
+
referralFromUrl,
|
|
34
|
+
serializeReferralCookie,
|
|
35
|
+
serializeReferralCookies,
|
|
36
|
+
clearReferralCookies,
|
|
37
|
+
type ReferralContext,
|
|
38
|
+
type StoredReferral,
|
|
39
|
+
} from './attribution.js';
|
|
40
|
+
export type { AffApi } from './snippet.js';
|
|
41
|
+
export {
|
|
42
|
+
AUTO_ORDER,
|
|
43
|
+
CONSENT_ADAPTER_IDS,
|
|
44
|
+
type ConsentAdapterId,
|
|
45
|
+
type ConsentConfig,
|
|
46
|
+
type ConsentEvidence,
|
|
47
|
+
type ConsentMode,
|
|
48
|
+
type ConsentOptions,
|
|
49
|
+
type ConsentState,
|
|
50
|
+
} from './consent/port.js';
|
|
51
|
+
|
|
52
|
+
export interface TrackerOptions extends Omit<SnippetConfig, 'token' | 'baseUrl'> {
|
|
53
|
+
/** Your org's public tracking token (Settings → Tracking). Safe to ship to browsers. */
|
|
54
|
+
publishableKey: string;
|
|
55
|
+
/** Default `https://referalli.com` (or your tracking domain). */
|
|
56
|
+
baseUrl?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface Tracker extends AffApi {
|
|
60
|
+
/** Attribute this visitor to the customer they just became (hashes `email` in the browser). */
|
|
61
|
+
trackSignup(input: { customerRef?: string; email?: string }): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Start tracking this page view. Resolves once the visit beacon is sent (it never rejects for network errors). */
|
|
65
|
+
export async function createTracker(opts: TrackerOptions): Promise<Tracker> {
|
|
66
|
+
if (typeof window === 'undefined') throw new Error('referalli/browser: createTracker runs in the browser only');
|
|
67
|
+
const { publishableKey, baseUrl, ...rest } = opts;
|
|
68
|
+
let storage: Storage | null = null;
|
|
69
|
+
try {
|
|
70
|
+
storage = window.localStorage;
|
|
71
|
+
} catch {
|
|
72
|
+
/* blocked (privacy mode) */
|
|
73
|
+
}
|
|
74
|
+
const api = await initSnippet(
|
|
75
|
+
{
|
|
76
|
+
win: window,
|
|
77
|
+
doc: document,
|
|
78
|
+
storage,
|
|
79
|
+
fetchFn: (url, init) => fetch(url, { ...init, keepalive: true }),
|
|
80
|
+
consentWindow: window,
|
|
81
|
+
},
|
|
82
|
+
{ ...rest, token: publishableKey, baseUrl: (baseUrl ?? 'https://referalli.com').replace(/\/+$/, '') },
|
|
83
|
+
);
|
|
84
|
+
return {
|
|
85
|
+
...api,
|
|
86
|
+
trackSignup: async ({ customerRef, email }) =>
|
|
87
|
+
api.identify({ customerRef, emailHash: email ? await hashEmail(email) : undefined }),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The stored referral context without starting a tracker (no network). Null on the server or when there is none. */
|
|
92
|
+
export function getReferral(): ReferralContext | null {
|
|
93
|
+
if (typeof document === 'undefined') return null;
|
|
94
|
+
// Either name: `referalli_ctx`, or its legacy twin `referally_ctx`.
|
|
95
|
+
let stored: StoredReferral | null = null;
|
|
96
|
+
for (const key of REFERRAL_COOKIE_NAMES) {
|
|
97
|
+
try {
|
|
98
|
+
stored = parseReferral(window.localStorage.getItem(key));
|
|
99
|
+
} catch {
|
|
100
|
+
/* storage may be blocked */
|
|
101
|
+
}
|
|
102
|
+
if (stored) break;
|
|
103
|
+
}
|
|
104
|
+
stored ??= referralFromCookieHeader(document.cookie);
|
|
105
|
+
if (!stored) return null;
|
|
106
|
+
return { anonId: stored.anonId, code: stored.code, clickId: stored.clickId, ts: stored.ts };
|
|
107
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { ListPromise, type ListEnvelope, type OperationInput, type QueryValue, type RequestOptions, type Transport } from './core.js';
|
|
2
|
+
import { ApiConnectionError, ApiError, ApiTimeoutError, ReferalliError } from './errors.js';
|
|
3
|
+
import { errorClasses } from './errors.generated.js';
|
|
4
|
+
import type * as T from './generated.js';
|
|
5
|
+
import { API_VERSION, buildResources, operations, type OperationId, type Resources } from './resources.generated.js';
|
|
6
|
+
import { SDK_VERSION } from './version.js';
|
|
7
|
+
|
|
8
|
+
const OPTION_KEYS = new Set(['idempotencyKey', 'timeout', 'maxRetries', 'signal', 'headers', 'apiVersion']);
|
|
9
|
+
|
|
10
|
+
/** A method that gained a query parameter keeps its old `(id, options)` call working: request options in the query slot move back. */
|
|
11
|
+
function splitOptions<I extends OperationInput>(queryNames: readonly string[], input: I, options: RequestOptions): { input: I; options: RequestOptions } {
|
|
12
|
+
const q = input.query as Record<string, unknown> | undefined;
|
|
13
|
+
if (!q || Object.keys(q).length === 0 || !Object.keys(q).every((k) => OPTION_KEYS.has(k) && !queryNames.includes(k))) return { input, options };
|
|
14
|
+
return { input: { ...input, query: undefined }, options: { ...(q as RequestOptions), ...options } };
|
|
15
|
+
}
|
|
16
|
+
import { webhooks, type Webhooks } from './webhooks.js';
|
|
17
|
+
|
|
18
|
+
/** Production API. */
|
|
19
|
+
export const DEFAULT_BASE_URL = 'https://referalli.com';
|
|
20
|
+
|
|
21
|
+
type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
22
|
+
|
|
23
|
+
export interface ReferalliOptions {
|
|
24
|
+
/** Your secret `rk_` key. Defaults to the `REFERALLI_API_KEY` environment variable. Keep it on your server. */
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
/** Default `https://referalli.com` (or `REFERALLI_BASE_URL`). */
|
|
27
|
+
baseUrl?: string;
|
|
28
|
+
/**
|
|
29
|
+
* The `referalli-version` to send. Defaults to the version this SDK was
|
|
30
|
+
* generated against; `null` sends none (your key's pinned version applies).
|
|
31
|
+
*/
|
|
32
|
+
apiVersion?: string | null;
|
|
33
|
+
/**
|
|
34
|
+
* Sent as `referalli-mode`. Only needed for session auth; an API key's mode
|
|
35
|
+
* is fixed, and a mismatching header is refused with `mode_mismatch`.
|
|
36
|
+
*/
|
|
37
|
+
mode?: 'live' | 'test';
|
|
38
|
+
/** Milliseconds per attempt. Default 60 000. */
|
|
39
|
+
timeout?: number;
|
|
40
|
+
/** Retries after the first attempt (network errors, timeouts, 408, 429, 5xx). Default 2. */
|
|
41
|
+
maxRetries?: number;
|
|
42
|
+
/** First backoff in milliseconds; doubles per retry, with jitter, up to 8 s. Default 500. */
|
|
43
|
+
retryBaseDelay?: number;
|
|
44
|
+
/** A custom fetch (tests, proxies, instrumentation). Defaults to the global fetch. */
|
|
45
|
+
fetch?: FetchLike;
|
|
46
|
+
/** Headers sent with every request. */
|
|
47
|
+
headers?: Record<string, string>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
51
|
+
const IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);
|
|
52
|
+
const MAX_BACKOFF_MS = 8_000;
|
|
53
|
+
const MAX_RETRY_AFTER_MS = 60_000;
|
|
54
|
+
|
|
55
|
+
/** One raw request. `kind` says how to read a success: JSON, text, or nothing. */
|
|
56
|
+
export interface RawRequest extends RequestOptions {
|
|
57
|
+
method: string;
|
|
58
|
+
path: string;
|
|
59
|
+
query?: object;
|
|
60
|
+
body?: unknown;
|
|
61
|
+
kind?: 'json' | 'list' | 'text' | 'empty';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const env = (name: string): string | undefined => {
|
|
65
|
+
try {
|
|
66
|
+
return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.[name];
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The Referalli API client. Every operation is a typed method, grouped by
|
|
74
|
+
* resource:
|
|
75
|
+
*
|
|
76
|
+
* const referalli = new Referalli({ apiKey: process.env.REFERALLI_API_KEY });
|
|
77
|
+
* const link = await referalli.links.create({ programId, partnerId, destinationUrl });
|
|
78
|
+
* for await (const r of referalli.referrals.list({ status: 'active' })) console.log(r.id);
|
|
79
|
+
*
|
|
80
|
+
* POSTs carry an idempotency key (generated unless you pass one) that is
|
|
81
|
+
* reused across retries. Idempotent and keyed requests are retried on network
|
|
82
|
+
* errors, timeouts, 408, 429 and 5xx with exponential backoff and jitter,
|
|
83
|
+
* honouring `Retry-After`. Errors are typed per code (`NotFoundError`, …).
|
|
84
|
+
*/
|
|
85
|
+
// The resource namespaces are assigned in the constructor; the interface declares them.
|
|
86
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/no-empty-object-type
|
|
87
|
+
export interface Referalli extends Resources {}
|
|
88
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
|
89
|
+
export class Referalli {
|
|
90
|
+
readonly baseUrl: string;
|
|
91
|
+
readonly apiVersion: string | null;
|
|
92
|
+
readonly mode: 'live' | 'test' | undefined;
|
|
93
|
+
readonly timeout: number;
|
|
94
|
+
readonly maxRetries: number;
|
|
95
|
+
readonly retryBaseDelay: number;
|
|
96
|
+
/** Webhook verification (`await referalli.webhooks.constructEvent(body, headers, secret)`). */
|
|
97
|
+
readonly webhooks: Webhooks = webhooks;
|
|
98
|
+
private readonly apiKey: string | undefined;
|
|
99
|
+
private readonly fetchFn: FetchLike;
|
|
100
|
+
private readonly headers: Record<string, string>;
|
|
101
|
+
|
|
102
|
+
constructor(options: ReferalliOptions = {}) {
|
|
103
|
+
this.apiKey = options.apiKey ?? env('REFERALLI_API_KEY');
|
|
104
|
+
this.baseUrl = (options.baseUrl ?? env('REFERALLI_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
105
|
+
this.apiVersion = options.apiVersion === undefined ? API_VERSION : options.apiVersion;
|
|
106
|
+
this.mode = options.mode;
|
|
107
|
+
this.timeout = options.timeout ?? 60_000;
|
|
108
|
+
this.maxRetries = Math.max(0, options.maxRetries ?? 2);
|
|
109
|
+
this.retryBaseDelay = options.retryBaseDelay ?? 500;
|
|
110
|
+
this.fetchFn = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
111
|
+
this.headers = { ...(options.headers ?? {}) };
|
|
112
|
+
const transport: Transport = {
|
|
113
|
+
op: (id, input, opts) => this.call(id as OperationId, input, opts) as Promise<never>,
|
|
114
|
+
list: <Item, Page extends ListEnvelope<Item>>(id: string, input: OperationInput, opts?: RequestOptions) =>
|
|
115
|
+
this.listPages<Item, Page>(id as OperationId, input, opts),
|
|
116
|
+
};
|
|
117
|
+
Object.assign(this, buildResources(transport));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Call any operation by its id (`postPartners`, `getReferralsId`, … see `operations`). */
|
|
121
|
+
async call<R = unknown>(id: OperationId, input: OperationInput & { idempotencyKey?: string } = {}, options: RequestOptions = {}): Promise<R> {
|
|
122
|
+
const spec = operations[id];
|
|
123
|
+
if (!spec) throw new ReferalliError(`unknown operation ${String(id)}`);
|
|
124
|
+
({ input, options } = splitOptions(spec.query, input, options));
|
|
125
|
+
const path = spec.path.replace(/\{(\w+)\}/g, (_, name: string) => {
|
|
126
|
+
const value = input.path?.[name];
|
|
127
|
+
if (value === undefined || value === null || value === '') throw new ReferalliError(`${id}: missing path parameter "${name}"`);
|
|
128
|
+
return encodeURIComponent(String(value));
|
|
129
|
+
});
|
|
130
|
+
return this.request<R>({
|
|
131
|
+
...options,
|
|
132
|
+
idempotencyKey: options.idempotencyKey ?? input.idempotencyKey,
|
|
133
|
+
method: spec.method,
|
|
134
|
+
path,
|
|
135
|
+
query: input.query,
|
|
136
|
+
body: spec.body ? input.body : undefined,
|
|
137
|
+
kind: spec.kind,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Every item of a list operation, following `next_cursor`: `for await (const p of referalli.listAll('getPartners'))`. */
|
|
142
|
+
listAll<Item = unknown>(id: OperationId, input: OperationInput = {}, options: RequestOptions = {}): ListPromise<Item, ListEnvelope<Item>> {
|
|
143
|
+
return this.listPages<Item, ListEnvelope<Item>>(id, input, options);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private listPages<Item, Page extends ListEnvelope<Item>>(id: OperationId, input: OperationInput, options: RequestOptions = {}): ListPromise<Item, Page> {
|
|
147
|
+
({ input, options } = splitOptions(operations[id]?.query ?? [], input, options));
|
|
148
|
+
return new ListPromise<Item, Page>((cursor) =>
|
|
149
|
+
this.call<Page>(id, cursor ? { ...input, query: { ...(input.query ?? {}), starting_after: cursor } } : input, options),
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A raw request to any path (`/v1/...`), with the client's auth, retries and error mapping. */
|
|
154
|
+
async request<R = unknown>(req: RawRequest): Promise<R> {
|
|
155
|
+
const method = req.method.toUpperCase();
|
|
156
|
+
const url = this.baseUrl + req.path + encodeQuery(req.query);
|
|
157
|
+
const version = req.apiVersion === undefined ? this.apiVersion : req.apiVersion;
|
|
158
|
+
const headers: Record<string, string> = { accept: 'application/json', ...this.headers };
|
|
159
|
+
if (version) headers['referalli-version'] = version;
|
|
160
|
+
if (this.mode) headers['referalli-mode'] = this.mode;
|
|
161
|
+
if (this.apiKey) headers.authorization = `Bearer ${this.apiKey}`;
|
|
162
|
+
if (typeof (globalThis as { window?: unknown }).window === 'undefined') headers['user-agent'] = `referalli-js/${SDK_VERSION}`;
|
|
163
|
+
const hasBody = req.body !== undefined;
|
|
164
|
+
if (hasBody) headers['content-type'] = 'application/json';
|
|
165
|
+
const key = req.idempotencyKey ?? (method === 'POST' ? await newIdempotencyKey() : undefined);
|
|
166
|
+
if (key) headers['idempotency-key'] = key;
|
|
167
|
+
Object.assign(headers, req.headers ?? {});
|
|
168
|
+
const body = hasBody ? JSON.stringify(req.body) : undefined;
|
|
169
|
+
const retryable = IDEMPOTENT.has(method) || Boolean(key);
|
|
170
|
+
const maxRetries = retryable ? Math.max(0, req.maxRetries ?? this.maxRetries) : 0;
|
|
171
|
+
const timeout = req.timeout ?? this.timeout;
|
|
172
|
+
|
|
173
|
+
for (let attempt = 0; ; attempt++) {
|
|
174
|
+
let res: Response;
|
|
175
|
+
const { signal, cancel, timedOut } = withTimeout(timeout, req.signal);
|
|
176
|
+
try {
|
|
177
|
+
res = await this.fetchFn(url, { method, headers, body, signal });
|
|
178
|
+
} catch (err) {
|
|
179
|
+
cancel();
|
|
180
|
+
if (req.signal?.aborted) throw req.signal.reason ?? err;
|
|
181
|
+
if (attempt < maxRetries) {
|
|
182
|
+
await sleep(this.backoff(attempt), req.signal);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (timedOut()) throw new ApiTimeoutError(`${method} ${req.path} timed out after ${timeout} ms`, { cause: err });
|
|
186
|
+
throw new ApiConnectionError(`${method} ${req.path} failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
if (res.ok) {
|
|
190
|
+
if (req.kind === 'text') return (await res.text()) as R;
|
|
191
|
+
const raw = await res.text();
|
|
192
|
+
if (req.kind === 'empty' || raw === '') return undefined as R;
|
|
193
|
+
return JSON.parse(raw) as R;
|
|
194
|
+
}
|
|
195
|
+
const raw = await res.text().catch(() => '');
|
|
196
|
+
const resHeaders = headerRecord(res.headers);
|
|
197
|
+
const retryAfterMs = parseRetryAfter(resHeaders);
|
|
198
|
+
if (RETRY_STATUSES.has(res.status) && attempt < maxRetries && resHeaders['x-should-retry'] !== 'false') {
|
|
199
|
+
await sleep(retryAfterMs ?? this.backoff(attempt), req.signal);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
throw toApiError(res.status, raw, resHeaders, retryAfterMs);
|
|
203
|
+
} catch (err) {
|
|
204
|
+
if (err instanceof ReferalliError || req.signal?.aborted) throw err;
|
|
205
|
+
if (timedOut()) {
|
|
206
|
+
if (attempt < maxRetries) continue;
|
|
207
|
+
throw new ApiTimeoutError(`${method} ${req.path} timed out after ${timeout} ms`, { cause: err });
|
|
208
|
+
}
|
|
209
|
+
throw new ApiConnectionError(`${method} ${req.path}: could not read the response`, { cause: err });
|
|
210
|
+
} finally {
|
|
211
|
+
cancel();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private backoff(attempt: number): number {
|
|
217
|
+
const base = Math.min(this.retryBaseDelay * 2 ** attempt, MAX_BACKOFF_MS);
|
|
218
|
+
return base * (0.75 + Math.random() * 0.25);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// --- Helpers kept from the hand-written SDK -----------------------------------------
|
|
222
|
+
|
|
223
|
+
/** Attribute a new customer to the partner who referred them: the key server-side call at signup. */
|
|
224
|
+
associate(body: T.PostReferralsAssociateBody, options?: RequestOptions): Promise<T.PostReferralsAssociateResponse> {
|
|
225
|
+
return this.referrals.associate(body, { idempotencyKey: body.idempotencyKey, ...options });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Report a customer's product event (`activation` or a custom name) that can pay a bounty. */
|
|
229
|
+
trackEvent(
|
|
230
|
+
body: { programId: string; customerRef: string; event: string; occurredAt?: string; idempotencyKey?: string },
|
|
231
|
+
options?: RequestOptions,
|
|
232
|
+
): Promise<T.PostTrackEventsResponse> {
|
|
233
|
+
return this.track.events({ type: 'event', ...body }, { idempotencyKey: body.idempotencyKey, ...options });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Report value facts (payments, credit, costs). Up to 500 per call, each idempotent by `externalId`. */
|
|
237
|
+
reportValueEvents(events: T.PostValueEventsBody['events'], options?: RequestOptions): Promise<T.PostValueEventsResponse> {
|
|
238
|
+
return this.value.events({ events }, options);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** A payment, with the cash received and any store credit or discount that paid part of it. */
|
|
242
|
+
reportPayment(input: ValueFact, options?: RequestOptions): Promise<T.PostValueEventsResponse> {
|
|
243
|
+
return this.reportValueEvents([{ ...input, kind: 'payment' } as ValueEvent], options);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
type ValueEvent = T.PostValueEventsBody['events'][number];
|
|
248
|
+
type ValueFact = Omit<ValueEvent, 'kind'>;
|
|
249
|
+
|
|
250
|
+
function encodeQuery(query: object | undefined): string {
|
|
251
|
+
if (!query) return '';
|
|
252
|
+
const qs = new URLSearchParams();
|
|
253
|
+
for (const [k, v] of Object.entries(query as Record<string, QueryValue>)) {
|
|
254
|
+
if (v === undefined || v === null) continue;
|
|
255
|
+
if (Array.isArray(v)) for (const x of v) qs.append(k, String(x));
|
|
256
|
+
else qs.append(k, v instanceof Date ? v.toISOString() : String(v));
|
|
257
|
+
}
|
|
258
|
+
const s = qs.toString();
|
|
259
|
+
return s ? `?${s}` : '';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function headerRecord(h: Headers): Record<string, string> {
|
|
263
|
+
const out: Record<string, string> = {};
|
|
264
|
+
h.forEach((v, k) => (out[k.toLowerCase()] = v));
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Milliseconds from `retry-after-ms` / `retry-after` (seconds or an HTTP date), capped at 60 s. */
|
|
269
|
+
function parseRetryAfter(h: Record<string, string>): number | null {
|
|
270
|
+
const ms = Number(h['retry-after-ms']);
|
|
271
|
+
if (h['retry-after-ms'] && Number.isFinite(ms)) return Math.min(Math.max(0, ms), MAX_RETRY_AFTER_MS);
|
|
272
|
+
const v = h['retry-after'];
|
|
273
|
+
if (!v) return null;
|
|
274
|
+
const secs = Number(v);
|
|
275
|
+
if (Number.isFinite(secs)) return Math.min(Math.max(0, secs * 1000), MAX_RETRY_AFTER_MS);
|
|
276
|
+
const at = Date.parse(v);
|
|
277
|
+
return Number.isNaN(at) ? null : Math.min(Math.max(0, at - Date.now()), MAX_RETRY_AFTER_MS);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function toApiError(status: number, raw: string, headers: Record<string, string>, retryAfterMs: number | null): ApiError {
|
|
281
|
+
let err: { code?: unknown; message?: unknown; requestId?: unknown; docs_url?: unknown; details?: unknown } = {};
|
|
282
|
+
try {
|
|
283
|
+
const parsed = JSON.parse(raw) as { error?: typeof err };
|
|
284
|
+
if (parsed && typeof parsed.error === 'object' && parsed.error) err = parsed.error;
|
|
285
|
+
} catch {
|
|
286
|
+
/* not JSON */
|
|
287
|
+
}
|
|
288
|
+
const code = typeof err.code === 'string' && err.code ? err.code : 'http_error';
|
|
289
|
+
const Cls = errorClasses[code] ?? ApiError;
|
|
290
|
+
return new Cls({
|
|
291
|
+
status,
|
|
292
|
+
code,
|
|
293
|
+
message: typeof err.message === 'string' ? err.message : raw.slice(0, 500) || `HTTP ${status}`,
|
|
294
|
+
requestId: (typeof err.requestId === 'string' ? err.requestId : undefined) ?? headers['x-request-id'] ?? null,
|
|
295
|
+
docsUrl: typeof err.docs_url === 'string' ? err.docs_url : null,
|
|
296
|
+
details: err.details,
|
|
297
|
+
retryAfter: retryAfterMs === null ? null : retryAfterMs / 1000,
|
|
298
|
+
headers,
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** An AbortSignal that fires on `timeout` ms or when `parent` aborts (no `AbortSignal.any`: Node 18). */
|
|
303
|
+
function withTimeout(timeout: number, parent?: AbortSignal): { signal: AbortSignal; cancel: () => void; timedOut: () => boolean } {
|
|
304
|
+
const controller = new AbortController();
|
|
305
|
+
let fired = false;
|
|
306
|
+
const timer = timeout > 0 && Number.isFinite(timeout) ? setTimeout(() => ((fired = true), controller.abort()), timeout) : undefined;
|
|
307
|
+
const onAbort = () => controller.abort(parent?.reason);
|
|
308
|
+
if (parent) {
|
|
309
|
+
if (parent.aborted) controller.abort(parent.reason);
|
|
310
|
+
else parent.addEventListener('abort', onAbort, { once: true });
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
signal: controller.signal,
|
|
314
|
+
cancel: () => {
|
|
315
|
+
if (timer) clearTimeout(timer);
|
|
316
|
+
parent?.removeEventListener('abort', onAbort);
|
|
317
|
+
},
|
|
318
|
+
timedOut: () => fired,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
323
|
+
return new Promise((resolve, reject) => {
|
|
324
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
325
|
+
const t = setTimeout(() => {
|
|
326
|
+
signal?.removeEventListener('abort', onAbort);
|
|
327
|
+
resolve();
|
|
328
|
+
}, ms);
|
|
329
|
+
const onAbort = () => {
|
|
330
|
+
clearTimeout(t);
|
|
331
|
+
reject(signal?.reason);
|
|
332
|
+
};
|
|
333
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function newIdempotencyKey(): Promise<string> {
|
|
338
|
+
const c = (globalThis as { crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;
|
|
339
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
340
|
+
let bytes = new Uint8Array(16);
|
|
341
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
342
|
+
else {
|
|
343
|
+
const mod = 'node:crypto';
|
|
344
|
+
const nodeCrypto = (await import(/* webpackIgnore: true */ /* @vite-ignore */ mod)) as { randomBytes(n: number): Uint8Array };
|
|
345
|
+
bytes = new Uint8Array(nodeCrypto.randomBytes(16));
|
|
346
|
+
}
|
|
347
|
+
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
|
|
348
|
+
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
|
|
349
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
350
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
351
|
+
}
|