@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.
Files changed (184) hide show
  1. package/CHANGELOG.md +132 -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 +15151 -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 +15151 -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 +14545 -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
package/src/index.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * `referalli`: the official Referalli SDK for JavaScript and TypeScript.
3
+ * Server-side client (`Referalli`), typed errors, webhook verification and the
4
+ * referral-context helpers. The browser tracker is `referalli/browser`.
5
+ */
6
+ export { Referalli, Referalli as default, DEFAULT_BASE_URL, type RawRequest, type ReferalliOptions } from './client.js';
7
+ export {
8
+ ListPromise,
9
+ type HttpMethod,
10
+ type ListEnvelope,
11
+ type OperationInput,
12
+ type OperationSpec,
13
+ type PageParams,
14
+ type QueryValue,
15
+ type RequestOptions,
16
+ } from './core.js';
17
+ export { ApiConnectionError, ApiError, ApiTimeoutError, ReferalliError, type ApiErrorInit } from './errors.js';
18
+ export * from './errors.generated.js';
19
+ export { API_VERSION, operations, type OperationId, type Resources } from './resources.generated.js';
20
+ export { SDK_VERSION } from './version.js';
21
+ export {
22
+ constructWebhookEvent,
23
+ verifyWebhook,
24
+ webhooks,
25
+ WebhookVerificationError,
26
+ WEBHOOK_TOLERANCE_SEC,
27
+ type VerifyOptions,
28
+ type WebhookEnvelope,
29
+ type WebhookEvent,
30
+ type WebhookEventOf,
31
+ type WebhookFailure,
32
+ type WebhookHeaders,
33
+ type Webhooks,
34
+ type WebhookTopic,
35
+ } from './webhooks.js';
36
+ export {
37
+ associateFields,
38
+ hashEmail,
39
+ mergeReferral,
40
+ newAnonId,
41
+ parseReferral,
42
+ LEGACY_REFERRAL_COOKIE,
43
+ REFERRAL_COOKIE,
44
+ REFERRAL_COOKIE_NAMES,
45
+ REFERRAL_PARAMS,
46
+ referralFromCookieHeader,
47
+ referralFromUrl,
48
+ serializeReferralCookie,
49
+ serializeReferralCookies,
50
+ clearReferralCookies,
51
+ type CookieOptions,
52
+ type ReferralContext,
53
+ type StoredReferral,
54
+ } from './attribution.js';
55
+ // Every API type (`Program`, `Partner`, `PostLinksBody`, `GetReferralsResponse`, …).
56
+ export type * from './generated.js';
57
+
58
+ // Kept for existing integrations and the API server.
59
+ export { initSnippet, type AffApi, type SnippetConfig, type SnippetEnv } from './snippet.js';
60
+ export { renderBarJs, renderCallsJs, renderSnippetJs, snippetCookieDays, type SnippetOptions } from './served.js';
61
+ export {
62
+ AUTO_ORDER,
63
+ CONSENT_ADAPTER_IDS,
64
+ CONSENT_MODES,
65
+ consentConfig,
66
+ type ConsentAdapterId,
67
+ type ConsentConfig,
68
+ type ConsentEvidence,
69
+ type ConsentMode,
70
+ type ConsentOptions,
71
+ type ConsentSource,
72
+ type ConsentState,
73
+ } from './consent/port.js';
74
+ export { CONSENT_SOURCES, adapterOf, isConsentAdapterId } from './consent/registry.js';
75
+ export {
76
+ ReferalliClient,
77
+ referalliAuthEvents,
78
+ SDK_API_VERSION,
79
+ type Associates,
80
+ type AuthEventsOptions,
81
+ type ListPage,
82
+ type ReferalliClientOptions,
83
+ } from './node.js';
84
+ export {
85
+ buildBillingEvent,
86
+ createOutbox,
87
+ memoryOutboxStore,
88
+ pgOutboxStore,
89
+ sqliteOutboxStore,
90
+ type FlushResult,
91
+ type GenericBillingEvent,
92
+ type Outbox,
93
+ type OutboxEntry,
94
+ type OutboxOptions,
95
+ type OutboxStore,
96
+ type PgQuery,
97
+ type SqlExecute,
98
+ } from './outbox.js';
99
+ export { stripeEventToBillingEvents, type StripeEventLike, type StripeEventMapOptions } from './stripe-events.js';
100
+ export { createMobileClient, MobileApiError, type MobileClientOptions } from './mobile.js';
package/src/mobile.ts ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Mobile-app attribution client (works in React Native and any JS mobile runtime;
3
+ * the native iOS/Android SDKs wrap the same HTTP calls).
4
+ *
5
+ * Flow:
6
+ * 1. On first launch, capture `ref_click_id` from the deep link if present
7
+ * (Android: Play Install Referrer; iOS: Universal Link). If absent, call
8
+ * `resolveDeferred()` to recover it + the destination by device fingerprint.
9
+ * 2. Record the app visit with `trackVisit(anonId, { clickId })`, and after
10
+ * signup call `identify(anonId, { customerRef })` and
11
+ * `attributeInstall(customerRef, clickId)`.
12
+ * 3. In-app purchases are NOT reported from the app: send the receipt to your
13
+ * backend, validate it, then call `ReferalliClient.trackMobilePurchase(...)`
14
+ * there with your API key. (The app only holds the public tracking token,
15
+ * which can't be trusted to create commissions.)
16
+ *
17
+ * Every method rejects with `MobileApiError` when the API answers non-2xx
18
+ * (`status` set) or can't be reached (`status: null`).
19
+ */
20
+ export interface MobileClientOptions {
21
+ /** Base URL of the Referalli API (e.g. https://track.yourapp.com). */
22
+ endpoint: string;
23
+ /** Your org's public tracking token, or a live publishable key (`rk_pub_…`). */
24
+ trackingToken: string;
25
+ /** The program these installs belong to. */
26
+ programId: string;
27
+ fetchImpl?: typeof fetch;
28
+ }
29
+
30
+ /** A mobile tracking call failed: `status` is the HTTP status, or null for a network error; `code` is the API's error code. */
31
+ export class MobileApiError extends Error {
32
+ constructor(
33
+ message: string,
34
+ readonly status: number | null,
35
+ readonly code: string | null = null,
36
+ ) {
37
+ super(message);
38
+ this.name = 'MobileApiError';
39
+ }
40
+ }
41
+
42
+ export function createMobileClient(opts: MobileClientOptions) {
43
+ const f = opts.fetchImpl ?? fetch;
44
+ const root = `${opts.endpoint.replace(/\/+$/, '')}/t/${encodeURIComponent(opts.trackingToken)}`;
45
+ const base = `${root}/mobile`;
46
+
47
+ async function call<T>(url: string, init?: RequestInit): Promise<T> {
48
+ let res: Response;
49
+ try {
50
+ res = await f(url, init);
51
+ } catch (e) {
52
+ throw new MobileApiError(`could not reach Referalli: ${(e as Error).message}`, null);
53
+ }
54
+ const body = (await res.json().catch(() => ({}))) as T & { error?: { code?: string; message?: string } };
55
+ if (!res.ok) {
56
+ const path = new URL(url).pathname;
57
+ throw new MobileApiError(body?.error?.message ?? `Referalli answered ${res.status} for ${path}`, res.status, body?.error?.code ?? null);
58
+ }
59
+ return body;
60
+ }
61
+ const post = <T>(url: string, payload: Record<string, unknown>) =>
62
+ call<T>(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
63
+
64
+ return {
65
+ /** Deferred deep link: recover the click id + destination by fingerprint. */
66
+ async resolveDeferred(): Promise<{ matched: boolean; clickId?: string; destination?: string; code?: string; programId?: string }> {
67
+ return call<{ matched: boolean; clickId?: string; destination?: string; code?: string; programId?: string }>(`${base}/resolve`);
68
+ },
69
+ /** Attribute a newly-signed-up user to the referring partner. */
70
+ async attributeInstall(customerRef: string, clickId?: string, deviceId?: string) {
71
+ return post<{ attributed: boolean; referralId: string | null; partnerId: string | null }>(`${base}/install`, {
72
+ programId: opts.programId,
73
+ customerRef,
74
+ clickId,
75
+ deviceId,
76
+ });
77
+ },
78
+ /** Record an app visit (a referral link opened in the app); returns the click id recorded or echoed. */
79
+ async trackVisit(anonId: string, visit: { code?: string | null; clickId?: string | null; url?: string } = {}): Promise<{ ok: true; clickId: string | null }> {
80
+ return post<{ ok: true; clickId: string | null }>(`${root}/visit`, {
81
+ anonId,
82
+ ...(visit.code ? { code: visit.code } : {}),
83
+ ...(visit.clickId ? { clickId: visit.clickId } : {}),
84
+ ...(visit.url ? { url: visit.url.slice(0, 2048) } : {}),
85
+ });
86
+ },
87
+ /** Tie this install's anonymous id to the customer (or a hashed email). */
88
+ async identify(anonId: string, who: { customerRef?: string; emailHash?: string } = {}): Promise<{ ok: true }> {
89
+ return post<{ ok: true }>(`${root}/identify`, {
90
+ anonId,
91
+ ...(who.customerRef ? { customerRef: who.customerRef } : {}),
92
+ ...(who.emailHash ? { emailHash: who.emailHash } : {}),
93
+ });
94
+ },
95
+ };
96
+ }
package/src/node.ts ADDED
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The original hand-written client, kept for existing integrations. New code
3
+ * should use `Referalli` (every operation, typed, with retries and typed errors).
4
+ */
5
+
6
+ type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
7
+
8
+ export interface ReferalliClientOptions {
9
+ apiKey: string;
10
+ /** Default `https://referalli.com`. */
11
+ baseUrl?: string;
12
+ fetchFn?: FetchLike;
13
+ /**
14
+ * The API version to send as `referalli-version`. Defaults to the version
15
+ * this SDK was written against; pass `null` to send none and use the key's
16
+ * pinned version.
17
+ */
18
+ apiVersion?: string | null;
19
+ }
20
+
21
+ /** The API version this SDK speaks (paginated list envelopes). */
22
+ export const SDK_API_VERSION = '2026-11-05';
23
+
24
+ /** One page of a list endpoint (referalli-version 2026-11-01 and later). */
25
+ export interface ListPage<T> {
26
+ object: 'list';
27
+ data: T[];
28
+ has_more: boolean;
29
+ next_cursor: string | null;
30
+ }
31
+
32
+ /** One value fact for POST /v1/value/events (amounts in integer minor units). */
33
+ export interface ValueEventReport {
34
+ kind: 'payment' | 'refund' | 'credit_granted' | 'credit_redeemed' | 'credit_expired' | 'credit_revoked' | 'cost' | 'adjustment';
35
+ /** Needed: at least one of customerRef, partnerId, partnerExternalRef. */
36
+ customerRef?: string;
37
+ partnerId?: string;
38
+ partnerExternalRef?: string;
39
+ creditGrantId?: string;
40
+ referralId?: string;
41
+ programId?: string;
42
+ productRef?: string;
43
+ currency: string;
44
+ cashMinor?: number;
45
+ creditAppliedMinor?: number;
46
+ discountMinor?: number;
47
+ taxMinor?: number;
48
+ feesMinor?: number;
49
+ costMinor?: number;
50
+ faceMinor?: number;
51
+ /** Your id for this fact; reporting it again is a no-op. */
52
+ externalId: string;
53
+ invoiceRef?: string;
54
+ provider?: string;
55
+ /** ISO 8601 instant or date. */
56
+ occurredAt: string | Date;
57
+ role?: 'referee' | 'referrer';
58
+ metadata?: Record<string, unknown>;
59
+ }
60
+
61
+ export interface ValueEventsResult {
62
+ results: Array<{ index: number; id: string; created: boolean; superseded: string[] }>;
63
+ errors: Array<{ index: number; message: string }>;
64
+ }
65
+
66
+ type Without<K extends keyof ValueEventReport> = Omit<ValueEventReport, 'kind' | K>;
67
+ export type ReportPaymentInput = Without<'role' | 'faceMinor' | 'costMinor'>;
68
+ export type ReportCreditGrantedInput = Without<'costMinor' | 'cashMinor'> & { role: 'referee' | 'referrer'; faceMinor: number };
69
+ export type ReportCreditUsedInput = Without<'role' | 'costMinor'> & { creditAppliedMinor: number };
70
+ export type ReportCostInput = Without<'role' | 'faceMinor' | 'cashMinor'> & { costMinor: number };
71
+
72
+ /** @deprecated Use `Referalli`. */
73
+ export class ReferalliClient {
74
+ private readonly fetchFn: FetchLike;
75
+
76
+ private readonly version: string | null;
77
+
78
+ constructor(private readonly opts: ReferalliClientOptions) {
79
+ this.fetchFn = opts.fetchFn ?? ((url, init) => fetch(url, init));
80
+ this.version = opts.apiVersion === undefined ? SDK_API_VERSION : opts.apiVersion;
81
+ }
82
+
83
+ /** One page of a list endpoint. `query` adds filters; `limit` is 1–100. */
84
+ listPage<T = Record<string, unknown>>(
85
+ path: string,
86
+ query: Record<string, string | number | undefined> = {},
87
+ ): Promise<ListPage<T>> {
88
+ const qs = new URLSearchParams();
89
+ for (const [k, v] of Object.entries(query)) if (v !== undefined) qs.set(k, String(v));
90
+ const sep = path.includes('?') ? '&' : '?';
91
+ const q = qs.toString();
92
+ return this.request('GET', q ? `${path}${sep}${q}` : path);
93
+ }
94
+
95
+ /**
96
+ * Every item of a list endpoint, fetching pages as you iterate:
97
+ * `for await (const r of client.list('/v1/referrals', { status: 'active' }))`.
98
+ */
99
+ async *list<T = Record<string, unknown>>(
100
+ path: string,
101
+ query: Record<string, string | number | undefined> = {},
102
+ ): AsyncGenerator<T, void, undefined> {
103
+ let cursor: string | undefined;
104
+ do {
105
+ const page = await this.listPage<T>(path, { limit: 100, ...query, starting_after: cursor });
106
+ if (!page || !Array.isArray(page.data)) {
107
+ throw new Error(`referalli api GET ${path} did not return a list page (send referalli-version ${SDK_API_VERSION})`);
108
+ }
109
+ yield* page.data;
110
+ cursor = page.has_more && page.next_cursor ? page.next_cursor : undefined;
111
+ } while (cursor);
112
+ }
113
+
114
+ private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
115
+ const res = await this.fetchFn(`${(this.opts.baseUrl ?? 'https://referalli.com').replace(/\/+$/, '')}${path}`, {
116
+ method,
117
+ headers: {
118
+ authorization: `Bearer ${this.opts.apiKey}`,
119
+ 'content-type': 'application/json',
120
+ ...(this.version ? { 'referalli-version': this.version } : {}),
121
+ },
122
+ body: body === undefined ? undefined : JSON.stringify(body),
123
+ });
124
+ if (!res.ok) {
125
+ const text = await res.text().catch(() => '');
126
+ throw new Error(`referalli api ${method} ${path} failed (${res.status}): ${text}`);
127
+ }
128
+ return res.json() as Promise<T>;
129
+ }
130
+
131
+ associate(input: {
132
+ programId: string;
133
+ customerRef: string;
134
+ anonId?: string;
135
+ referralToken?: string;
136
+ couponCode?: string;
137
+ /** From `aff.getHandoffToken()` / `POST /v1/referrals/handoff-tokens`: fills anonId, referralToken and couponCode when not sent. */
138
+ handoffToken?: string;
139
+ emailHash?: string;
140
+ ip?: string;
141
+ ua?: string;
142
+ idempotencyKey?: string;
143
+ }): Promise<{ referral: Record<string, unknown> | null }> {
144
+ return this.request('POST', '/v1/referrals/associate', input);
145
+ }
146
+
147
+ trackClick(input: {
148
+ programId: string;
149
+ partnerId: string;
150
+ linkId?: string;
151
+ url?: string;
152
+ anonId?: string;
153
+ ip?: string;
154
+ ua?: string;
155
+ }): Promise<{ clickId: string }> {
156
+ return this.request('POST', '/v1/track/events', { type: 'click', url: '', ...input });
157
+ }
158
+
159
+ /**
160
+ * Report an in-app purchase (or refund) for commissioning. Call it from your
161
+ * server after validating the App Store / Play receipt — never from the app.
162
+ * Idempotent per `eventId`.
163
+ */
164
+ trackMobilePurchase(input: {
165
+ eventId: string;
166
+ customerRef: string;
167
+ amountMinor: number;
168
+ currency?: string;
169
+ productRef?: string;
170
+ type?: 'purchase' | 'refund';
171
+ }): Promise<{ conversions: number; linesCreated: number; reversals: number }> {
172
+ return this.request('POST', '/v1/mobile/purchases', { currency: 'usd', type: 'purchase', ...input });
173
+ }
174
+
175
+ /**
176
+ * Report value facts (payments, credit, costs) directly. Up to 500 per call; each
177
+ * is idempotent by `externalId`, and invalid ones come back in `errors` while the
178
+ * rest are recorded.
179
+ */
180
+ reportValueEvents(events: ValueEventReport[]): Promise<ValueEventsResult> {
181
+ return this.request('POST', '/v1/value/events', { events });
182
+ }
183
+
184
+ /** A payment, with the cash received and any store credit or discount that paid part of it. */
185
+ reportPayment(input: ReportPaymentInput): Promise<ValueEventsResult> {
186
+ return this.reportValueEvents([{ kind: 'payment', ...input }]);
187
+ }
188
+
189
+ /** Credit you granted to a customer (`referee`) or a partner (`referrer`). */
190
+ reportCreditGranted(input: ReportCreditGrantedInput): Promise<ValueEventsResult> {
191
+ return this.reportValueEvents([{ kind: 'credit_granted', ...input }]);
192
+ }
193
+
194
+ /** Credit used up against a purchase. */
195
+ reportCreditUsed(input: ReportCreditUsedInput): Promise<ValueEventsResult> {
196
+ return this.reportValueEvents([{ kind: 'credit_redeemed', ...input }]);
197
+ }
198
+
199
+ /** What serving a customer or partner cost you. */
200
+ reportCost(input: ReportCostInput): Promise<ValueEventsResult> {
201
+ return this.reportValueEvents([{ kind: 'cost', ...input }]);
202
+ }
203
+
204
+ listReferrals(query: { programId?: string; partnerId?: string; status?: string } = {}): Promise<
205
+ Array<Record<string, unknown>>
206
+ > {
207
+ const qs = new URLSearchParams(
208
+ Object.entries(query).filter(([, v]) => v !== undefined) as [string, string][],
209
+ ).toString();
210
+ return this.request('GET', `/v1/referrals${qs ? `?${qs}` : ''}`);
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Auth.js / NextAuth adapter. Callback-based auth platforms run inside the
216
+ * merchant's own server, so instead of a webhook we hand them a `createUser`
217
+ * event handler that attributes each new user. The referral context comes from
218
+ * the client (window.aff.getReferral()) — pass a resolver that reads it from
219
+ * wherever you stashed it (a cookie, the user's metadata, the pending sign-up).
220
+ *
221
+ * import { Referalli, referalliAuthEvents, referralFromCookieHeader } from "@referalli/sdk";
222
+ * const events = referalliAuthEvents(new Referalli(), {
223
+ * programId: "prg_...",
224
+ * // Sync or async. Reads referalli_ctx, falling back to the pre-rename referally_ctx.
225
+ * getReferral: async () => referralFromCookieHeader((await headers()).get("cookie")),
226
+ * });
227
+ * // Auth.js config: events: { createUser: events.createUser }
228
+ */
229
+ /** What `getReferral` returns: the visitor's referral context, or nothing. */
230
+ export type ReferralLookup = {
231
+ anonId?: string | null;
232
+ clickId?: string | null;
233
+ code?: string | null;
234
+ coupon?: string | null;
235
+ /** A hand-off token you kept in your own session (`aff.getHandoffToken()`), for sign-ups without the cookie. */
236
+ handoffToken?: string | null;
237
+ } | null | undefined;
238
+
239
+ export interface AuthEventsOptions {
240
+ programId: string;
241
+ getReferral?: (user: { id?: string; email?: string }) => ReferralLookup | Promise<ReferralLookup>;
242
+ }
243
+
244
+ /** Anything with an `associate` call: `Referalli` or `ReferalliClient`. */
245
+ export interface Associates {
246
+ associate(input: {
247
+ programId: string;
248
+ customerRef: string;
249
+ anonId?: string;
250
+ referralToken?: string;
251
+ couponCode?: string;
252
+ handoffToken?: string;
253
+ emailHash?: string;
254
+ idempotencyKey?: string;
255
+ }): Promise<unknown>;
256
+ }
257
+
258
+ export function referalliAuthEvents(client: Associates, opts: AuthEventsOptions) {
259
+ return {
260
+ /** Wire into Auth.js `events.createUser` (or call from any signup handler). */
261
+ createUser: async (message: { user: { id?: string; email?: string } }): Promise<void> => {
262
+ const user = message.user;
263
+ const customerRef = user.id ?? user.email;
264
+ if (!customerRef) return;
265
+ const ref = (await opts.getReferral?.(user)) ?? {};
266
+ const emailHash = user.email ? await sha256Hex(user.email.toLowerCase()) : undefined;
267
+ if (!ref.anonId && !ref.clickId && !ref.coupon && !ref.handoffToken && !emailHash) return;
268
+ await client
269
+ .associate({
270
+ programId: opts.programId,
271
+ customerRef,
272
+ anonId: ref.anonId ?? undefined,
273
+ referralToken: ref.clickId ?? undefined,
274
+ couponCode: ref.coupon ?? undefined,
275
+ handoffToken: ref.handoffToken ?? undefined,
276
+ emailHash,
277
+ idempotencyKey: `authjs:${customerRef}`,
278
+ })
279
+ .catch(() => {
280
+ /* attribution is best-effort; never block signup */
281
+ });
282
+ },
283
+ };
284
+ }
285
+
286
+ async function sha256Hex(input: string): Promise<string> {
287
+ // Works in Node 18+ and edge runtimes via the Web Crypto API.
288
+ const data = new TextEncoder().encode(input);
289
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', data);
290
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
291
+ }