@referalli/sdk 0.0.0-stage → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/README.md +236 -2
  4. package/dist/cjs/attribution.d.ts +105 -0
  5. package/dist/cjs/attribution.js +200 -0
  6. package/dist/cjs/browser.d.ts +41 -0
  7. package/dist/cjs/browser.js +88 -0
  8. package/dist/cjs/client.d.ts +97 -0
  9. package/dist/cjs/client.js +301 -0
  10. package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
  11. package/dist/cjs/consent/adapters/cookiebot.js +49 -0
  12. package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
  13. package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
  14. package/dist/cjs/consent/adapters/custom.d.ts +8 -0
  15. package/dist/cjs/consent/adapters/custom.js +39 -0
  16. package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
  17. package/dist/cjs/consent/adapters/didomi.js +67 -0
  18. package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
  19. package/dist/cjs/consent/adapters/gcm.js +78 -0
  20. package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
  21. package/dist/cjs/consent/adapters/gpp.js +92 -0
  22. package/dist/cjs/consent/adapters/none.d.ts +3 -0
  23. package/dist/cjs/consent/adapters/none.js +30 -0
  24. package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
  25. package/dist/cjs/consent/adapters/onetrust.js +71 -0
  26. package/dist/cjs/consent/adapters/osano.d.ts +9 -0
  27. package/dist/cjs/consent/adapters/osano.js +71 -0
  28. package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
  29. package/dist/cjs/consent/adapters/tcf.js +79 -0
  30. package/dist/cjs/consent/adapters/termly.d.ts +10 -0
  31. package/dist/cjs/consent/adapters/termly.js +61 -0
  32. package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
  33. package/dist/cjs/consent/adapters/usercentrics.js +106 -0
  34. package/dist/cjs/consent/conformance.d.ts +22 -0
  35. package/dist/cjs/consent/conformance.js +33 -0
  36. package/dist/cjs/consent/gate.d.ts +23 -0
  37. package/dist/cjs/consent/gate.js +220 -0
  38. package/dist/cjs/consent/port.d.ts +105 -0
  39. package/dist/cjs/consent/port.js +72 -0
  40. package/dist/cjs/consent/registry.d.ts +17 -0
  41. package/dist/cjs/consent/registry.js +61 -0
  42. package/dist/cjs/consent/served.d.ts +15 -0
  43. package/dist/cjs/consent/served.js +26 -0
  44. package/dist/cjs/core.d.ts +77 -0
  45. package/dist/cjs/core.js +64 -0
  46. package/dist/cjs/errors.d.ts +42 -0
  47. package/dist/cjs/errors.generated.d.ts +183 -0
  48. package/dist/cjs/errors.generated.js +279 -0
  49. package/dist/cjs/errors.js +47 -0
  50. package/dist/cjs/generated.d.ts +15146 -0
  51. package/dist/cjs/generated.js +625 -0
  52. package/dist/cjs/index.d.ts +22 -0
  53. package/dist/cjs/index.js +93 -0
  54. package/dist/cjs/mobile.d.ts +66 -0
  55. package/dist/cjs/mobile.js +69 -0
  56. package/dist/cjs/node.d.ts +209 -0
  57. package/dist/cjs/node.js +140 -0
  58. package/dist/cjs/outbox.d.ts +186 -0
  59. package/dist/cjs/outbox.js +324 -0
  60. package/dist/cjs/package.json +3 -0
  61. package/dist/cjs/resources.generated.d.ts +6002 -0
  62. package/dist/cjs/resources.generated.js +2090 -0
  63. package/dist/cjs/served.d.ts +25 -0
  64. package/dist/cjs/served.js +214 -0
  65. package/dist/cjs/sha256.d.ts +2 -0
  66. package/dist/cjs/sha256.js +86 -0
  67. package/dist/cjs/snippet.d.ts +99 -0
  68. package/dist/cjs/snippet.js +213 -0
  69. package/dist/cjs/stripe-events.d.ts +25 -0
  70. package/dist/cjs/stripe-events.js +117 -0
  71. package/dist/cjs/version.d.ts +2 -0
  72. package/dist/cjs/version.js +5 -0
  73. package/dist/cjs/webhooks.d.ts +76 -0
  74. package/dist/cjs/webhooks.js +159 -0
  75. package/dist/esm/attribution.d.ts +105 -0
  76. package/dist/esm/attribution.js +186 -0
  77. package/dist/esm/browser.d.ts +41 -0
  78. package/dist/esm/browser.js +68 -0
  79. package/dist/esm/client.d.ts +97 -0
  80. package/dist/esm/client.js +297 -0
  81. package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
  82. package/dist/esm/consent/adapters/cookiebot.js +46 -0
  83. package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
  84. package/dist/esm/consent/adapters/cookiemunch.js +53 -0
  85. package/dist/esm/consent/adapters/custom.d.ts +8 -0
  86. package/dist/esm/consent/adapters/custom.js +36 -0
  87. package/dist/esm/consent/adapters/didomi.d.ts +9 -0
  88. package/dist/esm/consent/adapters/didomi.js +64 -0
  89. package/dist/esm/consent/adapters/gcm.d.ts +10 -0
  90. package/dist/esm/consent/adapters/gcm.js +75 -0
  91. package/dist/esm/consent/adapters/gpp.d.ts +9 -0
  92. package/dist/esm/consent/adapters/gpp.js +89 -0
  93. package/dist/esm/consent/adapters/none.d.ts +3 -0
  94. package/dist/esm/consent/adapters/none.js +27 -0
  95. package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
  96. package/dist/esm/consent/adapters/onetrust.js +68 -0
  97. package/dist/esm/consent/adapters/osano.d.ts +9 -0
  98. package/dist/esm/consent/adapters/osano.js +68 -0
  99. package/dist/esm/consent/adapters/tcf.d.ts +8 -0
  100. package/dist/esm/consent/adapters/tcf.js +76 -0
  101. package/dist/esm/consent/adapters/termly.d.ts +10 -0
  102. package/dist/esm/consent/adapters/termly.js +58 -0
  103. package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
  104. package/dist/esm/consent/adapters/usercentrics.js +103 -0
  105. package/dist/esm/consent/conformance.d.ts +22 -0
  106. package/dist/esm/consent/conformance.js +30 -0
  107. package/dist/esm/consent/gate.d.ts +23 -0
  108. package/dist/esm/consent/gate.js +217 -0
  109. package/dist/esm/consent/port.d.ts +105 -0
  110. package/dist/esm/consent/port.js +67 -0
  111. package/dist/esm/consent/registry.d.ts +17 -0
  112. package/dist/esm/consent/registry.js +55 -0
  113. package/dist/esm/consent/served.d.ts +15 -0
  114. package/dist/esm/consent/served.js +22 -0
  115. package/dist/esm/core.d.ts +77 -0
  116. package/dist/esm/core.js +60 -0
  117. package/dist/esm/errors.d.ts +42 -0
  118. package/dist/esm/errors.generated.d.ts +183 -0
  119. package/dist/esm/errors.generated.js +231 -0
  120. package/dist/esm/errors.js +40 -0
  121. package/dist/esm/generated.d.ts +15146 -0
  122. package/dist/esm/generated.js +622 -0
  123. package/dist/esm/index.d.ts +22 -0
  124. package/dist/esm/index.js +22 -0
  125. package/dist/esm/mobile.d.ts +66 -0
  126. package/dist/esm/mobile.js +64 -0
  127. package/dist/esm/node.d.ts +209 -0
  128. package/dist/esm/node.js +135 -0
  129. package/dist/esm/outbox.d.ts +186 -0
  130. package/dist/esm/outbox.js +316 -0
  131. package/dist/esm/package.json +3 -0
  132. package/dist/esm/resources.generated.d.ts +6002 -0
  133. package/dist/esm/resources.generated.js +2086 -0
  134. package/dist/esm/served.d.ts +25 -0
  135. package/dist/esm/served.js +207 -0
  136. package/dist/esm/sha256.d.ts +2 -0
  137. package/dist/esm/sha256.js +82 -0
  138. package/dist/esm/snippet.d.ts +99 -0
  139. package/dist/esm/snippet.js +210 -0
  140. package/dist/esm/stripe-events.d.ts +25 -0
  141. package/dist/esm/stripe-events.js +114 -0
  142. package/dist/esm/version.d.ts +2 -0
  143. package/dist/esm/version.js +2 -0
  144. package/dist/esm/webhooks.d.ts +76 -0
  145. package/dist/esm/webhooks.js +153 -0
  146. package/dist/tsconfig.build.tsbuildinfo +1 -0
  147. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  148. package/package.json +105 -4
  149. package/src/attribution.ts +216 -0
  150. package/src/browser.ts +107 -0
  151. package/src/client.ts +351 -0
  152. package/src/codegen.ts +130 -0
  153. package/src/consent/adapters/cookiebot.ts +42 -0
  154. package/src/consent/adapters/cookiemunch.ts +49 -0
  155. package/src/consent/adapters/custom.ts +37 -0
  156. package/src/consent/adapters/didomi.ts +59 -0
  157. package/src/consent/adapters/gcm.ts +68 -0
  158. package/src/consent/adapters/gpp.ts +81 -0
  159. package/src/consent/adapters/none.ts +28 -0
  160. package/src/consent/adapters/onetrust.ts +64 -0
  161. package/src/consent/adapters/osano.ts +63 -0
  162. package/src/consent/adapters/tcf.ts +67 -0
  163. package/src/consent/adapters/termly.ts +54 -0
  164. package/src/consent/adapters/usercentrics.ts +97 -0
  165. package/src/consent/conformance.ts +47 -0
  166. package/src/consent/gate.ts +216 -0
  167. package/src/consent/port.ts +148 -0
  168. package/src/consent/registry.ts +60 -0
  169. package/src/consent/served.ts +24 -0
  170. package/src/core.ts +127 -0
  171. package/src/errors.generated.ts +277 -0
  172. package/src/errors.ts +57 -0
  173. package/src/generated.ts +14540 -0
  174. package/src/index.ts +100 -0
  175. package/src/mobile.ts +96 -0
  176. package/src/node.ts +291 -0
  177. package/src/outbox.ts +452 -0
  178. package/src/resources.generated.ts +2097 -0
  179. package/src/served.ts +229 -0
  180. package/src/sha256.ts +82 -0
  181. package/src/snippet.ts +305 -0
  182. package/src/stripe-events.ts +130 -0
  183. package/src/version.ts +2 -0
  184. package/src/webhooks.ts +207 -0
@@ -0,0 +1,186 @@
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
+ /** Cookie (and localStorage key) holding the context. A wire name shared with every `aff.js` install; don't change it. */
9
+ export const REFERRAL_COOKIE = 'referalli_ctx';
10
+ /**
11
+ * The pre-rename name of the same context. The browser tracker (`aff.js`,
12
+ * `referalli/browser`) writes the context under BOTH names, with the same
13
+ * value, attributes and expiry, and reads either.
14
+ *
15
+ * Why: integrations that read the cookie themselves may still read the pre-rename
16
+ * name. Atlas's connector and Cookie Munch's preset both read `referalli_ctx` now.
17
+ * The twin is written until 2027-01-31, announced in the changelog and on
18
+ * /docs/renamed-from-referally, then dropped (reading stays tolerant).
19
+ *
20
+ * TODO(legacy-ctx, 2027-01-31): stop writing the legacy name; keep reading it for
21
+ * one more cookie window after that.
22
+ */
23
+ export const LEGACY_REFERRAL_COOKIE = 'referally_ctx';
24
+ /** Every name the context is written and read under, current first. */
25
+ export const REFERRAL_COOKIE_NAMES = [REFERRAL_COOKIE, LEGACY_REFERRAL_COOKIE];
26
+ /** Query parameters that carry a partner's referral code, in priority order. */
27
+ export const REFERRAL_PARAMS = ['via', 'ref', 'aff'];
28
+ /** Query parameter carrying a click id from a Referalli redirect link (`/go/...`). */
29
+ export const CLICK_ID_PARAM = 'ref_click_id';
30
+ export const DEFAULT_COOKIE_DAYS = 60;
31
+ const DAY_MS = 86_400_000;
32
+ export const clampDays = (days) => Math.max(1, Math.min(400, Math.round(days ?? DEFAULT_COOKIE_DAYS)));
33
+ /** A fresh anonymous id: `a_` + 20 random base-36 characters. */
34
+ export function newAnonId() {
35
+ const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
36
+ const c = globalThis.crypto;
37
+ const bytes = new Uint8Array(20);
38
+ if (c?.getRandomValues)
39
+ c.getRandomValues(bytes);
40
+ else
41
+ for (let i = 0; i < 20; i++)
42
+ bytes[i] = Math.floor(Math.random() * 256);
43
+ let out = 'a_';
44
+ for (const b of bytes)
45
+ out += chars[b % chars.length];
46
+ return out;
47
+ }
48
+ /** The referral a URL carries: the first of `params` that is set, and `ref_click_id`. */
49
+ export function referralFromUrl(url, params = REFERRAL_PARAMS) {
50
+ let u;
51
+ try {
52
+ u = typeof url === 'string' ? new URL(url, 'http://localhost') : url;
53
+ }
54
+ catch {
55
+ return { code: null, clickId: null };
56
+ }
57
+ let code = null;
58
+ for (const p of params) {
59
+ const v = u.searchParams.get(p);
60
+ if (v) {
61
+ code = v.slice(0, 120);
62
+ break;
63
+ }
64
+ }
65
+ const clickId = u.searchParams.get(CLICK_ID_PARAM)?.slice(0, 80) || null;
66
+ return { code, clickId };
67
+ }
68
+ /** Parse a stored context (the cookie's or localStorage's value, URI-encoded or not). Expired or malformed → null. */
69
+ export function parseReferral(raw, now = Date.now()) {
70
+ if (!raw)
71
+ return null;
72
+ let text = raw;
73
+ try {
74
+ if (raw.startsWith('%7B') || raw.startsWith('%7b'))
75
+ text = decodeURIComponent(raw);
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ try {
81
+ const parsed = JSON.parse(text);
82
+ if (!parsed || typeof parsed.anonId !== 'string')
83
+ return null;
84
+ if (parsed.exp && parsed.exp < now)
85
+ return null;
86
+ return {
87
+ anonId: parsed.anonId,
88
+ code: typeof parsed.code === 'string' ? parsed.code : null,
89
+ clickId: typeof parsed.clickId === 'string' ? parsed.clickId : null,
90
+ ts: typeof parsed.ts === 'number' ? parsed.ts : now,
91
+ ...(typeof parsed.exp === 'number' ? { exp: parsed.exp } : {}),
92
+ };
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ /**
99
+ * The context from a `Cookie` request header. `names` are tried in order
100
+ * (default: `REFERRAL_COOKIE_NAMES`, the current name then the legacy one);
101
+ * add an older cookie name to keep reading contexts saved under it.
102
+ */
103
+ export function referralFromCookieHeader(cookieHeader, now = Date.now(), names = REFERRAL_COOKIE_NAMES) {
104
+ if (!cookieHeader)
105
+ return null;
106
+ const jar = new Map();
107
+ for (const part of cookieHeader.split(';')) {
108
+ const i = part.indexOf('=');
109
+ if (i > 0)
110
+ jar.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
111
+ }
112
+ for (const name of names) {
113
+ const raw = jar.get(name);
114
+ if (raw === undefined)
115
+ continue;
116
+ try {
117
+ const ctx = parseReferral(decodeURIComponent(raw), now);
118
+ if (ctx)
119
+ return ctx;
120
+ }
121
+ catch {
122
+ /* malformed: try the next name */
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+ /**
128
+ * The context after a page view: a new referral in the URL replaces the
129
+ * stored one (unless `firstTouch` keeps an unexpired one), and a referral
130
+ * restarts the expiry window. Same rules as `aff.js`.
131
+ */
132
+ export function mergeReferral(stored, fromUrl, opts = {}) {
133
+ const now = opts.now ?? Date.now();
134
+ const days = clampDays(opts.cookieDays);
135
+ const referred = Boolean(fromUrl.code || fromUrl.clickId);
136
+ const keep = Boolean(opts.firstTouch && (stored?.code || stored?.clickId));
137
+ return {
138
+ anonId: stored?.anonId ?? (opts.randomId ?? newAnonId)(),
139
+ code: keep ? (stored?.code ?? null) : (fromUrl.code ?? stored?.code ?? null),
140
+ clickId: keep ? (stored?.clickId ?? null) : (fromUrl.clickId ?? stored?.clickId ?? null),
141
+ ts: stored?.ts ?? now,
142
+ exp: keep && stored?.exp ? stored.exp : referred || !stored?.exp ? now + days * DAY_MS : stored.exp,
143
+ };
144
+ }
145
+ /**
146
+ * A `Set-Cookie` header value for the context. Not HttpOnly on purpose: the
147
+ * browser tracker reads the same cookie.
148
+ */
149
+ export function serializeReferralCookie(ctx, opts = {}) {
150
+ const days = clampDays(opts.cookieDays);
151
+ const domain = opts.domain && /^\.?[a-z0-9.-]+$/i.test(opts.domain) ? `; Domain=${opts.domain}` : '';
152
+ const secure = opts.secure === false ? '' : '; Secure';
153
+ return `${REFERRAL_COOKIE}=${encodeURIComponent(JSON.stringify(ctx))}; Path=/; Max-Age=${days * 86_400}; SameSite=Lax${domain}${secure}`;
154
+ }
155
+ /**
156
+ * `Set-Cookie` values for the context under every name: `referalli_ctx` and
157
+ * its legacy twin `referally_ctx`, same value, attributes and expiry (see
158
+ * LEGACY_REFERRAL_COOKIE). Server kits append each one.
159
+ */
160
+ export function serializeReferralCookies(ctx, opts = {}) {
161
+ const value = serializeReferralCookie(ctx, opts);
162
+ const tail = value.slice(REFERRAL_COOKIE.length);
163
+ return REFERRAL_COOKIE_NAMES.map((name) => `${name}${tail}`);
164
+ }
165
+ /** `Set-Cookie` values that delete the context under every name (consent denied or withdrawn). */
166
+ export function clearReferralCookies(opts = {}) {
167
+ const domain = opts.domain && /^\.?[a-z0-9.-]+$/i.test(opts.domain) ? `; Domain=${opts.domain}` : '';
168
+ const secure = opts.secure === false ? '' : '; Secure';
169
+ return REFERRAL_COOKIE_NAMES.map((name) => `${name}=; Path=/; Max-Age=0; SameSite=Lax${domain}${secure}`);
170
+ }
171
+ /** Fields for `associate` (server-side attribution at signup) from a context. */
172
+ export function associateFields(ctx) {
173
+ if (!ctx)
174
+ return {};
175
+ return {
176
+ ...(ctx.anonId ? { anonId: ctx.anonId } : {}),
177
+ ...(ctx.clickId ? { referralToken: ctx.clickId } : {}),
178
+ ...(ctx.code ? { couponCode: ctx.code } : {}),
179
+ };
180
+ }
181
+ /** SHA-256 hex of a normalised (trimmed, lower-cased) email, for `emailHash` (WebCrypto). */
182
+ export async function hashEmail(email) {
183
+ const data = new TextEncoder().encode(email.trim().toLowerCase());
184
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', data);
185
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
186
+ }
@@ -0,0 +1,41 @@
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 { type ReferralContext } from './attribution.js';
21
+ import { type AffApi, type SnippetConfig } from './snippet.js';
22
+ export { associateFields, hashEmail, mergeReferral, parseReferral, LEGACY_REFERRAL_COOKIE, REFERRAL_COOKIE, REFERRAL_COOKIE_NAMES, REFERRAL_PARAMS, referralFromCookieHeader, referralFromUrl, serializeReferralCookie, serializeReferralCookies, clearReferralCookies, type ReferralContext, type StoredReferral, } from './attribution.js';
23
+ export type { AffApi } from './snippet.js';
24
+ export { AUTO_ORDER, CONSENT_ADAPTER_IDS, type ConsentAdapterId, type ConsentConfig, type ConsentEvidence, type ConsentMode, type ConsentOptions, type ConsentState, } from './consent/port.js';
25
+ export interface TrackerOptions extends Omit<SnippetConfig, 'token' | 'baseUrl'> {
26
+ /** Your org's public tracking token (Settings → Tracking). Safe to ship to browsers. */
27
+ publishableKey: string;
28
+ /** Default `https://referalli.com` (or your tracking domain). */
29
+ baseUrl?: string;
30
+ }
31
+ export interface Tracker extends AffApi {
32
+ /** Attribute this visitor to the customer they just became (hashes `email` in the browser). */
33
+ trackSignup(input: {
34
+ customerRef?: string;
35
+ email?: string;
36
+ }): Promise<void>;
37
+ }
38
+ /** Start tracking this page view. Resolves once the visit beacon is sent (it never rejects for network errors). */
39
+ export declare function createTracker(opts: TrackerOptions): Promise<Tracker>;
40
+ /** The stored referral context without starting a tracker (no network). Null on the server or when there is none. */
41
+ export declare function getReferral(): ReferralContext | null;
@@ -0,0 +1,68 @@
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 } from './attribution.js';
21
+ import { initSnippet } from './snippet.js';
22
+ export { associateFields, hashEmail, mergeReferral, parseReferral, LEGACY_REFERRAL_COOKIE, REFERRAL_COOKIE, REFERRAL_COOKIE_NAMES, REFERRAL_PARAMS, referralFromCookieHeader, referralFromUrl, serializeReferralCookie, serializeReferralCookies, clearReferralCookies, } from './attribution.js';
23
+ export { AUTO_ORDER, CONSENT_ADAPTER_IDS, } from './consent/port.js';
24
+ /** Start tracking this page view. Resolves once the visit beacon is sent (it never rejects for network errors). */
25
+ export async function createTracker(opts) {
26
+ if (typeof window === 'undefined')
27
+ throw new Error('referalli/browser: createTracker runs in the browser only');
28
+ const { publishableKey, baseUrl, ...rest } = opts;
29
+ let storage = null;
30
+ try {
31
+ storage = window.localStorage;
32
+ }
33
+ catch {
34
+ /* blocked (privacy mode) */
35
+ }
36
+ const api = await initSnippet({
37
+ win: window,
38
+ doc: document,
39
+ storage,
40
+ fetchFn: (url, init) => fetch(url, { ...init, keepalive: true }),
41
+ consentWindow: window,
42
+ }, { ...rest, token: publishableKey, baseUrl: (baseUrl ?? 'https://referalli.com').replace(/\/+$/, '') });
43
+ return {
44
+ ...api,
45
+ trackSignup: async ({ customerRef, email }) => api.identify({ customerRef, emailHash: email ? await hashEmail(email) : undefined }),
46
+ };
47
+ }
48
+ /** The stored referral context without starting a tracker (no network). Null on the server or when there is none. */
49
+ export function getReferral() {
50
+ if (typeof document === 'undefined')
51
+ return null;
52
+ // Either name: `referalli_ctx`, or its legacy twin `referally_ctx`.
53
+ let stored = null;
54
+ for (const key of REFERRAL_COOKIE_NAMES) {
55
+ try {
56
+ stored = parseReferral(window.localStorage.getItem(key));
57
+ }
58
+ catch {
59
+ /* storage may be blocked */
60
+ }
61
+ if (stored)
62
+ break;
63
+ }
64
+ stored ??= referralFromCookieHeader(document.cookie);
65
+ if (!stored)
66
+ return null;
67
+ return { anonId: stored.anonId, code: stored.code, clickId: stored.clickId, ts: stored.ts };
68
+ }
@@ -0,0 +1,97 @@
1
+ import { ListPromise, type ListEnvelope, type OperationInput, type RequestOptions } from './core.js';
2
+ import type * as T from './generated.js';
3
+ import { type OperationId, type Resources } from './resources.generated.js';
4
+ import { type Webhooks } from './webhooks.js';
5
+ /** Production API. */
6
+ export declare const DEFAULT_BASE_URL = "https://referalli.com";
7
+ type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
8
+ export interface ReferalliOptions {
9
+ /** Your secret `rk_` key. Defaults to the `REFERALLI_API_KEY` environment variable. Keep it on your server. */
10
+ apiKey?: string;
11
+ /** Default `https://referalli.com` (or `REFERALLI_BASE_URL`). */
12
+ baseUrl?: string;
13
+ /**
14
+ * The `referalli-version` to send. Defaults to the version this SDK was
15
+ * generated against; `null` sends none (your key's pinned version applies).
16
+ */
17
+ apiVersion?: string | null;
18
+ /**
19
+ * Sent as `referalli-mode`. Only needed for session auth; an API key's mode
20
+ * is fixed, and a mismatching header is refused with `mode_mismatch`.
21
+ */
22
+ mode?: 'live' | 'test';
23
+ /** Milliseconds per attempt. Default 60 000. */
24
+ timeout?: number;
25
+ /** Retries after the first attempt (network errors, timeouts, 408, 429, 5xx). Default 2. */
26
+ maxRetries?: number;
27
+ /** First backoff in milliseconds; doubles per retry, with jitter, up to 8 s. Default 500. */
28
+ retryBaseDelay?: number;
29
+ /** A custom fetch (tests, proxies, instrumentation). Defaults to the global fetch. */
30
+ fetch?: FetchLike;
31
+ /** Headers sent with every request. */
32
+ headers?: Record<string, string>;
33
+ }
34
+ /** One raw request. `kind` says how to read a success: JSON, text, or nothing. */
35
+ export interface RawRequest extends RequestOptions {
36
+ method: string;
37
+ path: string;
38
+ query?: object;
39
+ body?: unknown;
40
+ kind?: 'json' | 'list' | 'text' | 'empty';
41
+ }
42
+ /**
43
+ * The Referalli API client. Every operation is a typed method, grouped by
44
+ * resource:
45
+ *
46
+ * const referalli = new Referalli({ apiKey: process.env.REFERALLI_API_KEY });
47
+ * const link = await referalli.links.create({ programId, partnerId, destinationUrl });
48
+ * for await (const r of referalli.referrals.list({ status: 'active' })) console.log(r.id);
49
+ *
50
+ * POSTs carry an idempotency key (generated unless you pass one) that is
51
+ * reused across retries. Idempotent and keyed requests are retried on network
52
+ * errors, timeouts, 408, 429 and 5xx with exponential backoff and jitter,
53
+ * honouring `Retry-After`. Errors are typed per code (`NotFoundError`, …).
54
+ */
55
+ export interface Referalli extends Resources {
56
+ }
57
+ export declare class Referalli {
58
+ readonly baseUrl: string;
59
+ readonly apiVersion: string | null;
60
+ readonly mode: 'live' | 'test' | undefined;
61
+ readonly timeout: number;
62
+ readonly maxRetries: number;
63
+ readonly retryBaseDelay: number;
64
+ /** Webhook verification (`await referalli.webhooks.constructEvent(body, headers, secret)`). */
65
+ readonly webhooks: Webhooks;
66
+ private readonly apiKey;
67
+ private readonly fetchFn;
68
+ private readonly headers;
69
+ constructor(options?: ReferalliOptions);
70
+ /** Call any operation by its id (`postPartners`, `getReferralsId`, … see `operations`). */
71
+ call<R = unknown>(id: OperationId, input?: OperationInput & {
72
+ idempotencyKey?: string;
73
+ }, options?: RequestOptions): Promise<R>;
74
+ /** Every item of a list operation, following `next_cursor`: `for await (const p of referalli.listAll('getPartners'))`. */
75
+ listAll<Item = unknown>(id: OperationId, input?: OperationInput, options?: RequestOptions): ListPromise<Item, ListEnvelope<Item>>;
76
+ private listPages;
77
+ /** A raw request to any path (`/v1/...`), with the client's auth, retries and error mapping. */
78
+ request<R = unknown>(req: RawRequest): Promise<R>;
79
+ private backoff;
80
+ /** Attribute a new customer to the partner who referred them: the key server-side call at signup. */
81
+ associate(body: T.PostReferralsAssociateBody, options?: RequestOptions): Promise<T.PostReferralsAssociateResponse>;
82
+ /** Report a customer's product event (`activation` or a custom name) that can pay a bounty. */
83
+ trackEvent(body: {
84
+ programId: string;
85
+ customerRef: string;
86
+ event: string;
87
+ occurredAt?: string;
88
+ idempotencyKey?: string;
89
+ }, options?: RequestOptions): Promise<T.PostTrackEventsResponse>;
90
+ /** Report value facts (payments, credit, costs). Up to 500 per call, each idempotent by `externalId`. */
91
+ reportValueEvents(events: T.PostValueEventsBody['events'], options?: RequestOptions): Promise<T.PostValueEventsResponse>;
92
+ /** A payment, with the cash received and any store credit or discount that paid part of it. */
93
+ reportPayment(input: ValueFact, options?: RequestOptions): Promise<T.PostValueEventsResponse>;
94
+ }
95
+ type ValueEvent = T.PostValueEventsBody['events'][number];
96
+ type ValueFact = Omit<ValueEvent, 'kind'>;
97
+ export {};