@clikgate/node 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/LICENSE +21 -0
  3. package/README.md +300 -2
  4. package/SECURITY.md +34 -0
  5. package/dist/cjs/ads-hashing.d.ts +37 -0
  6. package/dist/cjs/ads-hashing.js +67 -0
  7. package/dist/cjs/click-ids.d.ts +184 -0
  8. package/dist/cjs/click-ids.js +535 -0
  9. package/dist/cjs/client.d.ts +175 -0
  10. package/dist/cjs/client.js +266 -0
  11. package/dist/cjs/config.d.ts +12 -0
  12. package/dist/cjs/config.js +87 -0
  13. package/dist/cjs/core.d.ts +15 -0
  14. package/dist/cjs/core.js +100 -0
  15. package/dist/cjs/enums.d.ts +48 -0
  16. package/dist/cjs/enums.js +47 -0
  17. package/dist/cjs/errors.d.ts +117 -0
  18. package/dist/cjs/errors.js +257 -0
  19. package/dist/cjs/express.d.ts +49 -0
  20. package/dist/cjs/express.js +44 -0
  21. package/dist/cjs/fastify.d.ts +47 -0
  22. package/dist/cjs/fastify.js +35 -0
  23. package/dist/cjs/generated/index.d.ts +17534 -0
  24. package/dist/cjs/generated/index.js +8816 -0
  25. package/dist/cjs/goals.d.ts +116 -0
  26. package/dist/cjs/goals.js +381 -0
  27. package/dist/cjs/guard.d.ts +17 -0
  28. package/dist/cjs/guard.js +40 -0
  29. package/dist/cjs/http.d.ts +16 -0
  30. package/dist/cjs/http.js +148 -0
  31. package/dist/cjs/identity.d.ts +32 -0
  32. package/dist/cjs/identity.js +99 -0
  33. package/dist/cjs/index.d.ts +32 -0
  34. package/dist/cjs/index.js +64 -0
  35. package/dist/cjs/logger.d.ts +9 -0
  36. package/dist/cjs/logger.js +8 -0
  37. package/dist/cjs/money.d.ts +16 -0
  38. package/dist/cjs/money.js +51 -0
  39. package/dist/cjs/next.d.ts +81 -0
  40. package/dist/cjs/next.js +103 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payments.d.ts +174 -0
  43. package/dist/cjs/payments.js +485 -0
  44. package/dist/cjs/resources.d.ts +109 -0
  45. package/dist/cjs/resources.js +189 -0
  46. package/dist/cjs/shutdown.d.ts +2 -0
  47. package/dist/cjs/shutdown.js +51 -0
  48. package/dist/cjs/transport.d.ts +14 -0
  49. package/dist/cjs/transport.js +204 -0
  50. package/dist/cjs/types.d.ts +218 -0
  51. package/dist/cjs/types.js +2 -0
  52. package/dist/cjs/user-agent.d.ts +1 -0
  53. package/dist/cjs/user-agent.js +53 -0
  54. package/dist/cjs/version.d.ts +2 -0
  55. package/dist/cjs/version.js +5 -0
  56. package/dist/cjs/webhooks.d.ts +36 -0
  57. package/dist/cjs/webhooks.js +108 -0
  58. package/dist/esm/ads-hashing.d.ts +37 -0
  59. package/dist/esm/ads-hashing.js +62 -0
  60. package/dist/esm/click-ids.d.ts +184 -0
  61. package/dist/esm/click-ids.js +526 -0
  62. package/dist/esm/client.d.ts +175 -0
  63. package/dist/esm/client.js +262 -0
  64. package/dist/esm/config.d.ts +12 -0
  65. package/dist/esm/config.js +82 -0
  66. package/dist/esm/core.d.ts +15 -0
  67. package/dist/esm/core.js +96 -0
  68. package/dist/esm/enums.d.ts +48 -0
  69. package/dist/esm/enums.js +44 -0
  70. package/dist/esm/errors.d.ts +117 -0
  71. package/dist/esm/errors.js +234 -0
  72. package/dist/esm/express.d.ts +49 -0
  73. package/dist/esm/express.js +40 -0
  74. package/dist/esm/fastify.d.ts +47 -0
  75. package/dist/esm/fastify.js +32 -0
  76. package/dist/esm/generated/index.d.ts +17534 -0
  77. package/dist/esm/generated/index.js +8754 -0
  78. package/dist/esm/goals.d.ts +116 -0
  79. package/dist/esm/goals.js +371 -0
  80. package/dist/esm/guard.d.ts +17 -0
  81. package/dist/esm/guard.js +36 -0
  82. package/dist/esm/http.d.ts +16 -0
  83. package/dist/esm/http.js +138 -0
  84. package/dist/esm/identity.d.ts +32 -0
  85. package/dist/esm/identity.js +92 -0
  86. package/dist/esm/index.d.ts +32 -0
  87. package/dist/esm/index.js +21 -0
  88. package/dist/esm/logger.d.ts +9 -0
  89. package/dist/esm/logger.js +5 -0
  90. package/dist/esm/money.d.ts +16 -0
  91. package/dist/esm/money.js +48 -0
  92. package/dist/esm/next.d.ts +81 -0
  93. package/dist/esm/next.js +96 -0
  94. package/dist/esm/package.json +1 -0
  95. package/dist/esm/payments.d.ts +174 -0
  96. package/dist/esm/payments.js +476 -0
  97. package/dist/esm/resources.d.ts +109 -0
  98. package/dist/esm/resources.js +183 -0
  99. package/dist/esm/shutdown.d.ts +2 -0
  100. package/dist/esm/shutdown.js +47 -0
  101. package/dist/esm/transport.d.ts +14 -0
  102. package/dist/esm/transport.js +166 -0
  103. package/dist/esm/types.d.ts +218 -0
  104. package/dist/esm/types.js +1 -0
  105. package/dist/esm/user-agent.d.ts +1 -0
  106. package/dist/esm/user-agent.js +16 -0
  107. package/dist/esm/version.d.ts +2 -0
  108. package/dist/esm/version.js +2 -0
  109. package/dist/esm/webhooks.d.ts +36 -0
  110. package/dist/esm/webhooks.js +105 -0
  111. package/package.json +128 -4
@@ -0,0 +1,116 @@
1
+ import { type RequestOptions } from './http.js';
2
+ import type { Provider } from './enums.js';
3
+ import { type BrowserEngine, type KeptBy, type Platform } from './click-ids.js';
4
+ import { type MoneyInput } from './money.js';
5
+ import type { GoalBatchResult, GoalEvent } from './types.js';
6
+ /** Options for a goal event. Only `reference` is required. */
7
+ export interface GoalOptions {
8
+ /** Your own unique ID for this event (application number, order ID, transaction reference), 1–128 characters. */
9
+ reference: string;
10
+ /** The Clikgate click ID you kept (`clk_…`), e.g. from `clickIds.fromRequest(req)`. */
11
+ clickId?: string | null;
12
+ /** An offline or creator code, instead of a click ID. */
13
+ code?: string | null;
14
+ /** The value in normal units (₦2,000,000 is `'2000000'`). Prefer a decimal string. */
15
+ value?: MoneyInput | null;
16
+ /** ISO 4217; defaults to the goal's default currency. */
17
+ currency?: string | null;
18
+ /**
19
+ * The payment provider of a Payment goal, e.g. `Provider.Paystack` (with `reference` = the payment reference).
20
+ * A provider key string works too, for a gateway added after this SDK release; the API checks it.
21
+ */
22
+ provider?: Provider | (string & {}) | null;
23
+ /** Your statement that this is the customer's first such event (from your server, this is what counts a new customer). */
24
+ isFirst?: boolean | null;
25
+ /**
26
+ * The person's label your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and up).
27
+ * In private mode only when the organisation allows labels there. Don't put information in labels that your
28
+ * customers wouldn't expect you to keep.
29
+ */
30
+ label?: string | null;
31
+ /** How the click ID was kept (`clickIds.context(req)` sets it). Allowed in private mode. */
32
+ keptBy?: KeptBy | null;
33
+ /** The visitor's browser engine (`clickIds.context(req)` sets it). Allowed in private mode. */
34
+ browserEngine?: BrowserEngine | null;
35
+ /** The visitor's platform (`clickIds.context(req)` sets it). Allowed in private mode. */
36
+ platform?: Platform | null;
37
+ /**
38
+ * Ad network matching: your own SHA-256 of the customer's email, trimmed and lowercased, as 64
39
+ * lowercase hex characters. Make it with `hashForAds({ email })`. Used only when the business turned on matching
40
+ * by hashed email or phone for a destination. In private mode, hash on your own server: Clikgate never hashes
41
+ * for you there.
42
+ */
43
+ hashedEmail?: string | null;
44
+ /** SHA-256 of the phone in E.164 with the `+` (`hashForAds({ phone })`). See `hashedEmail`. */
45
+ hashedPhoneE164?: string | null;
46
+ /** SHA-256 of the phone digits with the country code, no `+` (`hashForAds({ phone })`). See `hashedEmail`. */
47
+ hashedPhoneDigits?: string | null;
48
+ /** When it happened (defaults to now on the server). */
49
+ occurredAt?: Date | string | null;
50
+ /** Up to 8 KB of your own data. Refused in private mode. */
51
+ metadata?: Record<string, unknown> | null;
52
+ /** Consent signals (`analytics`, `attribution`, `ad_user_data`, `ad_personalization`). Allowed in private mode. */
53
+ consent?: Record<string, unknown> | null;
54
+ /** Extra wire fields, sent as is (forward compatibility). Checked by the private-mode guard. */
55
+ extra?: Record<string, unknown>;
56
+ }
57
+ /** One event of `goals.sendBatch`: the goal key plus its options. */
58
+ export interface GoalBatchEvent extends GoalOptions {
59
+ goal: string;
60
+ }
61
+ /** Options for `goals.reverse`. */
62
+ export interface ReverseOptions {
63
+ /** A partial reversal amount; omit for a full reversal. */
64
+ value?: MoneyInput | null;
65
+ /** Why (free text). Refused in private mode. */
66
+ reason?: string | null;
67
+ }
68
+ /**
69
+ * Goal events: the outcomes your business cares about (`account_opened`, `loan_disbursed`, `order_paid`).
70
+ * `goals.send` waits for the API and throws on failure; `clikgate.goal()` is the fire-and-forget version.
71
+ */
72
+ export declare class Goals {
73
+ private readonly core;
74
+ /**
75
+ * Send one goal event and wait for the result. Each call sends a random `Idempotency-Key`, reused
76
+ * across that call's retries; the API itself ignores a second event with the same goal and
77
+ * reference, so a resend never counts twice.
78
+ *
79
+ * @returns the goal event: `status` (`GoalStatus`: counted, waiting or refused), `reason`, `goal_kind`,
80
+ * `attributed_to`, `first_for_click`, … `waiting` and `refused` are results, not errors.
81
+ * @throws {InvalidRequestError} local validation or a 4xx; {@link PrivateModeFieldRejectedError} in private mode.
82
+ * @example
83
+ * const event = await clikgate.goals.send('account_opened', {
84
+ * clickId: application.clickId, // kept since the visitor landed
85
+ * reference: 'APP-55231',
86
+ * value: '2000000', // ₦2,000,000 in normal units, as a string
87
+ * currency: 'NGN',
88
+ * });
89
+ * if (event.status === GoalStatus.Counted) console.log('attributed to', event.attributed_to?.link_id);
90
+ *
91
+ * // A Payment goal, right after your server verified the payment with the gateway:
92
+ * await clikgate.goals.send('order_paid', { reference: 'T123456', provider: Provider.Paystack, value: '7500', currency: 'NGN', clickId });
93
+ */
94
+ send(key: string, options: GoalOptions, requestOptions?: RequestOptions): Promise<GoalEvent>;
95
+ /**
96
+ * Send up to 500 goal events in one request. Per-event failures are returned, not thrown.
97
+ *
98
+ * @throws {InvalidRequestError} when an event fails local validation (with `index`), or the batch is empty or too large.
99
+ * @example
100
+ * const result = await clikgate.goals.sendBatch([
101
+ * { goal: 'order_paid', reference: 'ORD-1001', clickId, value: '1500.50', currency: 'NGN' },
102
+ * { goal: 'order_paid', reference: 'ORD-1002', value: '99.90' },
103
+ * ]);
104
+ * for (const item of result.data) if (!item.ok) console.warn(item.index, item.error?.code);
105
+ */
106
+ sendBatch(events: GoalBatchEvent[], requestOptions?: RequestOptions): Promise<GoalBatchResult>;
107
+ /**
108
+ * Reverse a goal event, fully (no value) or partly (a refund, a cancelled loan, a chargeback).
109
+ * The completion still counts; reported value drops by the reversed amount.
110
+ *
111
+ * @example
112
+ * await clikgate.goals.reverse('loan_disbursed', 'LN-2201'); // full
113
+ * await clikgate.goals.reverse('order_paid', 'ORD-1001', { value: '500' }); // partial
114
+ */
115
+ reverse(key: string, reference: string, options?: ReverseOptions, requestOptions?: RequestOptions): Promise<GoalEvent>;
116
+ }
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Goals = exports.GoalQueue = void 0;
4
+ exports.buildGoalWire = buildGoalWire;
5
+ exports.goalWarnings = goalWarnings;
6
+ exports.checkBeforeSend = checkBeforeSend;
7
+ exports.asClikgateError = asClikgateError;
8
+ exports.withTimeout = withTimeout;
9
+ const errors_js_1 = require("./errors.js");
10
+ const guard_js_1 = require("./guard.js");
11
+ const http_js_1 = require("./http.js");
12
+ const click_ids_js_1 = require("./click-ids.js");
13
+ const money_js_1 = require("./money.js");
14
+ const ads_hashing_js_1 = require("./ads-hashing.js");
15
+ const GOAL_KEY = /^[a-z][a-z0-9_]{1,39}$/;
16
+ const PROVIDER_KEY = /^[a-z][a-z0-9_]{1,29}$/;
17
+ const compact = (o) => {
18
+ for (const k of Object.keys(o))
19
+ if (o[k] === undefined || o[k] === null)
20
+ delete o[k];
21
+ return o;
22
+ };
23
+ function checkKey(key) {
24
+ if (typeof key !== 'string' || !GOAL_KEY.test(key)) {
25
+ throw (0, errors_js_1.localError)('invalid_goal_key', 'Goal keys are snake_case, 2-40 characters, starting with a letter (e.g. "account_opened").', 'goal');
26
+ }
27
+ return key;
28
+ }
29
+ function checkReference(reference) {
30
+ if (typeof reference !== 'string' || reference.length < 1 || reference.length > 128) {
31
+ throw (0, errors_js_1.localError)('invalid_reference', 'reference is required: your own unique ID for this event, 1-128 characters.', 'reference');
32
+ }
33
+ return reference;
34
+ }
35
+ function checkEnum(field, value, allowed) {
36
+ if (value == null)
37
+ return;
38
+ if (typeof value !== 'string' || !allowed.includes(value)) {
39
+ throw (0, errors_js_1.localError)('invalid_argument', `${field} must be one of ${allowed.join(', ')}.`, field);
40
+ }
41
+ }
42
+ /** @internal Validate goal options and build the wire object (SPEC 9.1 step 1). */
43
+ function buildGoalWire(core, key, options) {
44
+ const goal = checkKey(key);
45
+ const o = (options ?? {});
46
+ const reference = checkReference(o.reference);
47
+ if (o.clickId != null && o.code != null)
48
+ throw (0, errors_js_1.localError)('click_id_and_code', 'Send either clickId or code, not both.', 'code');
49
+ if (o.provider != null && (typeof o.provider !== 'string' || !PROVIDER_KEY.test(o.provider))) {
50
+ throw (0, errors_js_1.localError)('invalid_provider', 'provider must be a provider key such as "paystack" or "stripe" (lower case; see Provider).', 'provider');
51
+ }
52
+ checkEnum('kept_by', o.keptBy, click_ids_js_1.KEPT_BY);
53
+ checkEnum('browser_engine', o.browserEngine, click_ids_js_1.BROWSER_ENGINES);
54
+ checkEnum('platform', o.platform, click_ids_js_1.PLATFORMS);
55
+ const wire = {
56
+ goal,
57
+ reference,
58
+ click_id: o.clickId,
59
+ code: o.code,
60
+ value: o.value === undefined || o.value === null ? undefined : (0, money_js_1.formatValue)(o.value, (m) => core.warn('inexact_number', m)),
61
+ currency: o.currency,
62
+ provider: o.provider,
63
+ is_first: o.isFirst,
64
+ label: o.label,
65
+ kept_by: o.keptBy,
66
+ browser_engine: o.browserEngine,
67
+ platform: o.platform,
68
+ hashed_email: o.hashedEmail,
69
+ hashed_phone_e164: o.hashedPhoneE164,
70
+ hashed_phone_digits: o.hashedPhoneDigits,
71
+ occurred_at: o.occurredAt == null ? undefined : (0, http_js_1.formatDate)(o.occurredAt),
72
+ metadata: o.metadata,
73
+ consent: o.consent,
74
+ ...(o.extra ?? {}),
75
+ };
76
+ (0, ads_hashing_js_1.checkHashedFields)(wire);
77
+ return compact(wire);
78
+ }
79
+ /** @internal Config-based warnings (SPEC 12.3); warn-only. */
80
+ function goalWarnings(core, state, wire) {
81
+ if (!state.config || core.privateMode !== 'auto')
82
+ return;
83
+ const goal = state.config.goals?.find((g) => g.key === wire.goal);
84
+ if (!goal) {
85
+ core.warn('unknown_goal', `The goal "${wire.goal}" isn't defined for your organisation (it will be sent; the API decides).`, wire.goal);
86
+ return;
87
+ }
88
+ if (goal.value_mode === 'none' && wire.value !== undefined)
89
+ core.warn('value_not_allowed', `The goal "${wire.goal}" takes no value.`, wire.goal);
90
+ if (goal.value_mode === 'required' && wire.value === undefined)
91
+ core.warn('value_required', `The goal "${wire.goal}" needs a value.`, wire.goal);
92
+ }
93
+ /** @internal Steps 2 and 3 of SPEC 9.1 for one wire event. Throws PrivateModeFieldRejectedError. */
94
+ function checkBeforeSend(core, state, wire) {
95
+ goalWarnings(core, state, wire);
96
+ if (state.guard)
97
+ (0, guard_js_1.guardPayload)('goal', wire);
98
+ }
99
+ const MAX_FAILED_ROUNDS = 3;
100
+ /** @internal The background queue (SPEC 9.3): one batch in flight at a time, in queue order. */
101
+ class GoalQueue {
102
+ core;
103
+ settings;
104
+ items = [];
105
+ chain = Promise.resolve();
106
+ sizeJobPending = false;
107
+ timer = null;
108
+ pendingSync = new Set();
109
+ constructor(core, settings) {
110
+ this.core = core;
111
+ this.settings = settings;
112
+ }
113
+ get size() {
114
+ return this.items.length;
115
+ }
116
+ /** Whether anything is queued or in flight. */
117
+ get busy() {
118
+ return this.items.length > 0 || this.pendingSync.size > 0;
119
+ }
120
+ enqueue(wire) {
121
+ if (this.items.length >= this.settings.maxQueueSize) {
122
+ const dropped = this.items.shift();
123
+ if (dropped) {
124
+ this.core.warn('queue_full_dropped', `The Clikgate queue is full (${this.settings.maxQueueSize} events); the oldest event was dropped.`);
125
+ this.core.report((0, errors_js_1.localError)('queue_full', 'The background queue was full; this event was dropped.'), { operation: 'goal', events: [this.shown(dropped.wire)], dropped: true });
126
+ }
127
+ }
128
+ this.items.push({ wire, rounds: 0 });
129
+ this.startTimer();
130
+ if (this.items.length >= this.settings.batchSize && !this.sizeJobPending) {
131
+ this.sizeJobPending = true;
132
+ this.schedule(async () => {
133
+ this.sizeJobPending = false;
134
+ while (this.items.length >= this.settings.batchSize) {
135
+ const requeue = await this.sendBatch(this.items.splice(0, this.settings.batchSize));
136
+ this.items.unshift(...requeue);
137
+ if (requeue.length)
138
+ break;
139
+ }
140
+ });
141
+ }
142
+ }
143
+ /** Hold on to a sync-mode send so flush() waits for it. */
144
+ holdSend(p) {
145
+ this.pendingSync.add(p);
146
+ void p.finally(() => this.pendingSync.delete(p));
147
+ }
148
+ /** Send everything queued now (and wait for in-flight sends). Resolves true when done before the timeout. Never rejects. */
149
+ flush(timeoutMs) {
150
+ const work = this.schedule(() => this.drainOnce()).then(() => Promise.allSettled([...this.pendingSync]));
151
+ return withTimeout(work, timeoutMs);
152
+ }
153
+ stop() {
154
+ if (this.timer)
155
+ clearInterval(this.timer);
156
+ this.timer = null;
157
+ }
158
+ startTimer() {
159
+ if (this.timer || this.settings.flushIntervalMs <= 0)
160
+ return;
161
+ this.timer = setInterval(() => {
162
+ if (this.items.length)
163
+ void this.schedule(() => this.drainOnce());
164
+ }, this.settings.flushIntervalMs);
165
+ this.timer.unref?.();
166
+ }
167
+ schedule(job) {
168
+ this.chain = this.chain.then(job).catch(() => undefined);
169
+ return this.chain;
170
+ }
171
+ /** Attempt every event queued at this moment once; failed retryable ones go back to the front. */
172
+ async drainOnce() {
173
+ let remaining = this.items.length;
174
+ const requeue = [];
175
+ while (remaining > 0 && this.items.length > 0) {
176
+ const batch = this.items.splice(0, Math.min(this.settings.batchSize, remaining));
177
+ remaining -= batch.length;
178
+ requeue.push(...(await this.sendBatch(batch)));
179
+ }
180
+ this.items.unshift(...requeue);
181
+ }
182
+ shown(wire) {
183
+ return { goal: wire.goal, reference: this.core.shownReference(wire.reference) };
184
+ }
185
+ /** Send one batch. Returns the events to re-queue. */
186
+ async sendBatch(batch) {
187
+ let state;
188
+ try {
189
+ state = await this.core.guardState();
190
+ }
191
+ catch {
192
+ state = { guard: true, config: null };
193
+ }
194
+ const sendable = [];
195
+ for (const q of batch) {
196
+ try {
197
+ checkBeforeSend(this.core, state, q.wire);
198
+ sendable.push(q);
199
+ }
200
+ catch (err) {
201
+ this.core.report(asClikgateError(err), { operation: 'goal', events: [this.shown(q.wire)], dropped: true });
202
+ }
203
+ }
204
+ if (sendable.length === 0)
205
+ return [];
206
+ try {
207
+ const { data } = await this.core.requester.request({
208
+ method: 'POST',
209
+ path: '/v1/goals/events/batch',
210
+ body: { events: sendable.map((q) => q.wire) },
211
+ });
212
+ for (const item of data?.data ?? []) {
213
+ const q = sendable[item.index];
214
+ if (!q)
215
+ continue;
216
+ if (item.ok) {
217
+ this.core.noteRefusedGoal(q.wire.goal, item.goal_event?.reason);
218
+ continue;
219
+ }
220
+ const error = (0, errors_js_1.errorFromBatchItem)(item.status, item.error);
221
+ this.core.noteRefusedGoal(q.wire.goal, error.code);
222
+ this.core.report(error, { operation: 'goal', events: [this.shown(q.wire)], dropped: true });
223
+ }
224
+ return [];
225
+ }
226
+ catch (err) {
227
+ const error = asClikgateError(err);
228
+ for (const q of sendable)
229
+ this.core.noteRefusedGoal(q.wire.goal, error.code);
230
+ if ((0, http_js_1.isRetryable)(error)) {
231
+ const keep = [];
232
+ const drop = [];
233
+ for (const q of sendable) {
234
+ q.rounds += 1;
235
+ (q.rounds >= MAX_FAILED_ROUNDS ? drop : keep).push(q);
236
+ }
237
+ if (drop.length)
238
+ this.core.report(error, { operation: 'goals.batch', events: drop.map((q) => this.shown(q.wire)), dropped: true });
239
+ return keep;
240
+ }
241
+ this.core.report(error, { operation: 'goals.batch', events: sendable.map((q) => this.shown(q.wire)), dropped: true });
242
+ return [];
243
+ }
244
+ }
245
+ }
246
+ exports.GoalQueue = GoalQueue;
247
+ /** @internal */
248
+ function asClikgateError(err) {
249
+ if (err instanceof errors_js_1.ClikgateError)
250
+ return err;
251
+ return new errors_js_1.ClikgateError({ message: err instanceof Error ? err.message : String(err), code: 'unexpected_error' });
252
+ }
253
+ /** @internal Resolve true if `p` settles within `ms`, false otherwise. Never rejects. */
254
+ function withTimeout(p, ms) {
255
+ return new Promise((resolve) => {
256
+ const t = setTimeout(() => resolve(false), ms);
257
+ t.unref?.();
258
+ p.then(() => {
259
+ clearTimeout(t);
260
+ resolve(true);
261
+ }, () => {
262
+ clearTimeout(t);
263
+ resolve(true);
264
+ });
265
+ });
266
+ }
267
+ /**
268
+ * Goal events: the outcomes your business cares about (`account_opened`, `loan_disbursed`, `order_paid`).
269
+ * `goals.send` waits for the API and throws on failure; `clikgate.goal()` is the fire-and-forget version.
270
+ */
271
+ class Goals {
272
+ core;
273
+ /** @internal */
274
+ constructor(core) {
275
+ this.core = core;
276
+ }
277
+ /**
278
+ * Send one goal event and wait for the result. Each call sends a random `Idempotency-Key`, reused
279
+ * across that call's retries; the API itself ignores a second event with the same goal and
280
+ * reference, so a resend never counts twice.
281
+ *
282
+ * @returns the goal event: `status` (`GoalStatus`: counted, waiting or refused), `reason`, `goal_kind`,
283
+ * `attributed_to`, `first_for_click`, … `waiting` and `refused` are results, not errors.
284
+ * @throws {InvalidRequestError} local validation or a 4xx; {@link PrivateModeFieldRejectedError} in private mode.
285
+ * @example
286
+ * const event = await clikgate.goals.send('account_opened', {
287
+ * clickId: application.clickId, // kept since the visitor landed
288
+ * reference: 'APP-55231',
289
+ * value: '2000000', // ₦2,000,000 in normal units, as a string
290
+ * currency: 'NGN',
291
+ * });
292
+ * if (event.status === GoalStatus.Counted) console.log('attributed to', event.attributed_to?.link_id);
293
+ *
294
+ * // A Payment goal, right after your server verified the payment with the gateway:
295
+ * await clikgate.goals.send('order_paid', { reference: 'T123456', provider: Provider.Paystack, value: '7500', currency: 'NGN', clickId });
296
+ */
297
+ async send(key, options, requestOptions = {}) {
298
+ const wire = buildGoalWire(this.core, key, options);
299
+ return this.sendWire(wire, requestOptions);
300
+ }
301
+ /** @internal */
302
+ async sendWire(wire, requestOptions = {}) {
303
+ const state = await this.core.guardState();
304
+ checkBeforeSend(this.core, state, wire);
305
+ let data;
306
+ try {
307
+ ({ data } = await this.core.requester.request({
308
+ method: 'POST',
309
+ path: '/v1/goals/events',
310
+ body: wire,
311
+ ...requestOptions,
312
+ }));
313
+ }
314
+ catch (err) {
315
+ if (err instanceof errors_js_1.ClikgateError)
316
+ this.core.noteRefusedGoal(wire.goal, err.code);
317
+ throw err;
318
+ }
319
+ this.core.noteRefusedGoal(wire.goal, data?.reason);
320
+ return data;
321
+ }
322
+ /**
323
+ * Send up to 500 goal events in one request. Per-event failures are returned, not thrown.
324
+ *
325
+ * @throws {InvalidRequestError} when an event fails local validation (with `index`), or the batch is empty or too large.
326
+ * @example
327
+ * const result = await clikgate.goals.sendBatch([
328
+ * { goal: 'order_paid', reference: 'ORD-1001', clickId, value: '1500.50', currency: 'NGN' },
329
+ * { goal: 'order_paid', reference: 'ORD-1002', value: '99.90' },
330
+ * ]);
331
+ * for (const item of result.data) if (!item.ok) console.warn(item.index, item.error?.code);
332
+ */
333
+ async sendBatch(events, requestOptions = {}) {
334
+ if (!Array.isArray(events) || events.length === 0)
335
+ throw (0, errors_js_1.localError)('batch_empty', 'Send at least one event.', 'events');
336
+ if (events.length > 500)
337
+ throw (0, errors_js_1.localError)('batch_too_large', 'A batch takes at most 500 events.', 'events');
338
+ const wires = events.map((e, i) => withIndex(i, () => buildGoalWire(this.core, e?.goal, e)));
339
+ const state = await this.core.guardState();
340
+ wires.forEach((w, i) => withIndex(i, () => checkBeforeSend(this.core, state, w)));
341
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/goals/events/batch', body: { events: wires }, ...requestOptions });
342
+ for (const item of data?.data ?? []) {
343
+ this.core.noteRefusedGoal(wires[item.index]?.goal, item.ok ? item.goal_event?.reason : item.error?.code);
344
+ }
345
+ return data;
346
+ }
347
+ /**
348
+ * Reverse a goal event, fully (no value) or partly (a refund, a cancelled loan, a chargeback).
349
+ * The completion still counts; reported value drops by the reversed amount.
350
+ *
351
+ * @example
352
+ * await clikgate.goals.reverse('loan_disbursed', 'LN-2201'); // full
353
+ * await clikgate.goals.reverse('order_paid', 'ORD-1001', { value: '500' }); // partial
354
+ */
355
+ async reverse(key, reference, options = {}, requestOptions = {}) {
356
+ const goal = checkKey(key);
357
+ const ref = checkReference(reference);
358
+ const wire = compact({
359
+ goal,
360
+ reference: ref,
361
+ value: options.value == null ? undefined : (0, money_js_1.formatValue)(options.value, (m) => this.core.warn('inexact_number', m)),
362
+ reason: options.reason,
363
+ });
364
+ const state = await this.core.guardState();
365
+ if (state.guard)
366
+ (0, guard_js_1.guardPayload)('reversal', wire);
367
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/goals/events/reverse', body: wire, ...requestOptions });
368
+ return data;
369
+ }
370
+ }
371
+ exports.Goals = Goals;
372
+ function withIndex(index, fn) {
373
+ try {
374
+ return fn();
375
+ }
376
+ catch (err) {
377
+ if (err instanceof errors_js_1.InvalidRequestError)
378
+ err.index = index;
379
+ throw err;
380
+ }
381
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Wire fields allowed in private mode (SPEC 12.2). `label` is allowed: the API accepts it in private mode only when
3
+ * an Owner switched on "Allow labels in private mode" (`422 labels_off_in_private_mode` otherwise; SPEC 24). The three
4
+ * hashed identifiers (SPEC 25) are allowed on goals and conversions: the API accepts them in private mode only
5
+ * while a destination matches by hashed email or phone.
6
+ */
7
+ export declare const PRIVATE_ALLOWED: {
8
+ readonly goal: Set<string>;
9
+ readonly conversion: Set<string>;
10
+ readonly identify: Set<string>;
11
+ readonly reversal: Set<string>;
12
+ readonly payment_confirmation: Set<string>;
13
+ };
14
+ /** The kind of payload the guard checks. */
15
+ export type GuardKind = keyof typeof PRIVATE_ALLOWED;
16
+ /** The value shown instead of a reference while private mode is on. */
17
+ export declare const REDACTED = "[redacted]";
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDACTED = exports.PRIVATE_ALLOWED = void 0;
4
+ exports.guardPayload = guardPayload;
5
+ const errors_js_1 = require("./errors.js");
6
+ /**
7
+ * Wire fields allowed in private mode (SPEC 12.2). `label` is allowed: the API accepts it in private mode only when
8
+ * an Owner switched on "Allow labels in private mode" (`422 labels_off_in_private_mode` otherwise; SPEC 24). The three
9
+ * hashed identifiers (SPEC 25) are allowed on goals and conversions: the API accepts them in private mode only
10
+ * while a destination matches by hashed email or phone.
11
+ */
12
+ exports.PRIVATE_ALLOWED = {
13
+ goal: new Set(['goal', 'click_id', 'code', 'reference', 'value', 'currency', 'is_first', 'occurred_at', 'consent', 'provider', 'kept_by', 'browser_engine', 'platform', 'label', 'hashed_email', 'hashed_phone_e164', 'hashed_phone_digits']),
14
+ conversion: new Set(['goal', 'click_id', 'code', 'reference', 'value', 'currency', 'is_first', 'occurred_at', 'consent', 'provider', 'kept_by', 'browser_engine', 'platform', 'external_id', 'hashed_email', 'hashed_phone_e164', 'hashed_phone_digits']),
15
+ identify: new Set(['click_id', 'app_id', 'installation_id', 'label']),
16
+ reversal: new Set(['goal', 'reference', 'value', 'external_id', 'amount_minor']),
17
+ payment_confirmation: new Set(['provider', 'reference', 'status', 'amount', 'amount_minor', 'currency', 'occurred_at', 'aliases', 'click_id', 'goal', 'test', 'refund_id', 'source_plugin']),
18
+ };
19
+ /** The value shown instead of a reference while private mode is on. */
20
+ exports.REDACTED = '[redacted]';
21
+ /**
22
+ * @internal Throw PrivateModeFieldRejectedError for the first refused (non-null) wire field:
23
+ * `metadata`, then `consent`, then the rest alphabetically. The message names the field only.
24
+ */
25
+ function guardPayload(kind, wire) {
26
+ const allowed = exports.PRIVATE_ALLOWED[kind];
27
+ const refused = Object.keys(wire).filter((k) => wire[k] !== undefined && wire[k] !== null && !allowed.has(k));
28
+ if (refused.length === 0)
29
+ return;
30
+ const rank = (k) => (k === 'metadata' ? 0 : k === 'consent' ? 1 : 2);
31
+ refused.sort((a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0));
32
+ const field = refused[0];
33
+ throw new errors_js_1.PrivateModeFieldRejectedError({
34
+ message: `Private mode is on: the field "${field}" can't be sent. Only ${[...allowed].join(', ')} are allowed.`,
35
+ code: 'private_mode_field_rejected',
36
+ param: field,
37
+ field,
38
+ httpStatus: null,
39
+ });
40
+ }
@@ -0,0 +1,16 @@
1
+ /** Clock and sleep, replaceable for tests (SPEC section 18). */
2
+ export interface Clock {
3
+ /** Milliseconds since the epoch. */
4
+ now(): number;
5
+ /** Wait `ms` milliseconds. */
6
+ sleep(ms: number): Promise<void>;
7
+ }
8
+ /** Per-call options accepted by every API method. */
9
+ export interface RequestOptions {
10
+ /** Override the `Idempotency-Key` (POST and PATCH only). */
11
+ idempotencyKey?: string;
12
+ /** Override the client's per-attempt timeout (ms). */
13
+ timeout?: number;
14
+ /** Override the client's `maxRetries` for this call. */
15
+ maxRetries?: number;
16
+ }