@clikgate/node 0.0.0-stage → 2.0.1
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 +136 -0
- package/LICENSE +21 -0
- package/README.md +311 -2
- package/SECURITY.md +34 -0
- package/dist/cjs/ads-hashing.d.ts +37 -0
- package/dist/cjs/ads-hashing.js +67 -0
- package/dist/cjs/click-ids.d.ts +184 -0
- package/dist/cjs/click-ids.js +535 -0
- package/dist/cjs/client.d.ts +191 -0
- package/dist/cjs/client.js +291 -0
- package/dist/cjs/config.d.ts +12 -0
- package/dist/cjs/config.js +87 -0
- package/dist/cjs/core.d.ts +15 -0
- package/dist/cjs/core.js +100 -0
- package/dist/cjs/customer-id.d.ts +26 -0
- package/dist/cjs/customer-id.js +52 -0
- package/dist/cjs/enums.d.ts +48 -0
- package/dist/cjs/enums.js +47 -0
- package/dist/cjs/errors.d.ts +117 -0
- package/dist/cjs/errors.js +257 -0
- package/dist/cjs/express.d.ts +49 -0
- package/dist/cjs/express.js +44 -0
- package/dist/cjs/fastify.d.ts +47 -0
- package/dist/cjs/fastify.js +35 -0
- package/dist/cjs/generated/index.d.ts +17793 -0
- package/dist/cjs/generated/index.js +8896 -0
- package/dist/cjs/goals.d.ts +116 -0
- package/dist/cjs/goals.js +381 -0
- package/dist/cjs/guard.d.ts +17 -0
- package/dist/cjs/guard.js +40 -0
- package/dist/cjs/http.d.ts +16 -0
- package/dist/cjs/http.js +148 -0
- package/dist/cjs/identity.d.ts +42 -0
- package/dist/cjs/identity.js +133 -0
- package/dist/cjs/index.d.ts +34 -0
- package/dist/cjs/index.js +70 -0
- package/dist/cjs/known-customers.d.ts +45 -0
- package/dist/cjs/known-customers.js +95 -0
- package/dist/cjs/logger.d.ts +9 -0
- package/dist/cjs/logger.js +8 -0
- package/dist/cjs/money.d.ts +16 -0
- package/dist/cjs/money.js +51 -0
- package/dist/cjs/next.d.ts +81 -0
- package/dist/cjs/next.js +103 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payments.d.ts +174 -0
- package/dist/cjs/payments.js +485 -0
- package/dist/cjs/resources.d.ts +109 -0
- package/dist/cjs/resources.js +189 -0
- package/dist/cjs/shutdown.d.ts +2 -0
- package/dist/cjs/shutdown.js +51 -0
- package/dist/cjs/transport.d.ts +14 -0
- package/dist/cjs/transport.js +204 -0
- package/dist/cjs/types.d.ts +218 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/user-agent.d.ts +1 -0
- package/dist/cjs/user-agent.js +53 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +36 -0
- package/dist/cjs/webhooks.js +108 -0
- package/dist/esm/ads-hashing.d.ts +37 -0
- package/dist/esm/ads-hashing.js +62 -0
- package/dist/esm/click-ids.d.ts +184 -0
- package/dist/esm/click-ids.js +526 -0
- package/dist/esm/client.d.ts +191 -0
- package/dist/esm/client.js +287 -0
- package/dist/esm/config.d.ts +12 -0
- package/dist/esm/config.js +82 -0
- package/dist/esm/core.d.ts +15 -0
- package/dist/esm/core.js +96 -0
- package/dist/esm/customer-id.d.ts +26 -0
- package/dist/esm/customer-id.js +47 -0
- package/dist/esm/enums.d.ts +48 -0
- package/dist/esm/enums.js +44 -0
- package/dist/esm/errors.d.ts +117 -0
- package/dist/esm/errors.js +234 -0
- package/dist/esm/express.d.ts +49 -0
- package/dist/esm/express.js +40 -0
- package/dist/esm/fastify.d.ts +47 -0
- package/dist/esm/fastify.js +32 -0
- package/dist/esm/generated/index.d.ts +17793 -0
- package/dist/esm/generated/index.js +8833 -0
- package/dist/esm/goals.d.ts +116 -0
- package/dist/esm/goals.js +371 -0
- package/dist/esm/guard.d.ts +17 -0
- package/dist/esm/guard.js +36 -0
- package/dist/esm/http.d.ts +16 -0
- package/dist/esm/http.js +138 -0
- package/dist/esm/identity.d.ts +42 -0
- package/dist/esm/identity.js +125 -0
- package/dist/esm/index.d.ts +34 -0
- package/dist/esm/index.js +23 -0
- package/dist/esm/known-customers.d.ts +45 -0
- package/dist/esm/known-customers.js +90 -0
- package/dist/esm/logger.d.ts +9 -0
- package/dist/esm/logger.js +5 -0
- package/dist/esm/money.d.ts +16 -0
- package/dist/esm/money.js +48 -0
- package/dist/esm/next.d.ts +81 -0
- package/dist/esm/next.js +96 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payments.d.ts +174 -0
- package/dist/esm/payments.js +476 -0
- package/dist/esm/resources.d.ts +109 -0
- package/dist/esm/resources.js +183 -0
- package/dist/esm/shutdown.d.ts +2 -0
- package/dist/esm/shutdown.js +47 -0
- package/dist/esm/transport.d.ts +14 -0
- package/dist/esm/transport.js +166 -0
- package/dist/esm/types.d.ts +218 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/user-agent.d.ts +1 -0
- package/dist/esm/user-agent.js +16 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +36 -0
- package/dist/esm/webhooks.js +105 -0
- package/package.json +128 -4
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { ClickIds } from './click-ids.js';
|
|
2
|
+
import { type OnError } from './core.js';
|
|
3
|
+
import { type IdentityTokenOptions } from './identity.js';
|
|
4
|
+
import type { RequestOptions } from './http.js';
|
|
5
|
+
import { ApiClient } from './generated/index.js';
|
|
6
|
+
import { Goals, type GoalOptions } from './goals.js';
|
|
7
|
+
import { type Clock } from './http.js';
|
|
8
|
+
import { type Logger } from './logger.js';
|
|
9
|
+
import { Payments } from './payments.js';
|
|
10
|
+
import { KnownCustomers } from './known-customers.js';
|
|
11
|
+
import { Clicks, Conversions, Links } from './resources.js';
|
|
12
|
+
import { type FetchLike } from './transport.js';
|
|
13
|
+
import type { ServerSdkConfig } from './types.js';
|
|
14
|
+
import { webhooks } from './webhooks.js';
|
|
15
|
+
/** Client options (SPEC section 3). Every option is optional. */
|
|
16
|
+
/** `identifyUser()`: at least one of `clickId`, `appId` + `installationId`, `customerId`. */
|
|
17
|
+
export interface IdentifyUserParams {
|
|
18
|
+
/** The Clikgate click ID you kept (`clk_…`). */
|
|
19
|
+
clickId?: string | null;
|
|
20
|
+
/** An app installation: the app's ID and the SDK's installation ID, together. */
|
|
21
|
+
appId?: string | null;
|
|
22
|
+
installationId?: string | null;
|
|
23
|
+
/** Your customer ID. With a click or installation, links it to this customer. */
|
|
24
|
+
customerId?: string | null;
|
|
25
|
+
/** A label your team sees instead of the click ID (1–80 characters, `''` clears it). */
|
|
26
|
+
label?: string | null;
|
|
27
|
+
/**
|
|
28
|
+
* When this customer became your customer: `'YYYY-MM-DD'`, an ISO 8601 date-time with offset, a
|
|
29
|
+
* `Date` or Unix seconds. Needs `customerId`. Clikgate keeps the earliest date it gets. Not in private mode.
|
|
30
|
+
*/
|
|
31
|
+
customerSince?: string | Date | number | null;
|
|
32
|
+
/** `true` lets `customerSince` move a wrong date later (audit-logged). Default: the earliest date is kept. */
|
|
33
|
+
customerSinceReplace?: boolean | null;
|
|
34
|
+
}
|
|
35
|
+
/** The answer of `identifyUser()`. */
|
|
36
|
+
export interface PersonIdentified {
|
|
37
|
+
object: 'person_identified';
|
|
38
|
+
person_id: string;
|
|
39
|
+
/** `plan`: below Growth the label isn't stored; `lower_rank`: a label your team set was kept. */
|
|
40
|
+
label_ignored: 'plan' | 'lower_rank' | null;
|
|
41
|
+
/** Why `customerSince` wasn't used: `unverified` or `invalid`. */
|
|
42
|
+
customer_since_ignored?: 'unverified' | 'invalid' | null;
|
|
43
|
+
/** The customer ID looks like an email, phone number or national ID: use your own user ID instead. */
|
|
44
|
+
customer_id_warning?: 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | null;
|
|
45
|
+
}
|
|
46
|
+
export interface ClikgateOptions {
|
|
47
|
+
/** `cg_live_…` or `cg_test_…`. Default: `process.env.CLIKGATE_API_KEY`. The mode comes from the prefix. */
|
|
48
|
+
apiKey?: string;
|
|
49
|
+
/** Default `process.env.CLIKGATE_BASE_URL`, else `https://api.clikgate.com`. */
|
|
50
|
+
baseUrl?: string;
|
|
51
|
+
/** Per-attempt timeout in milliseconds (default 10 000). */
|
|
52
|
+
timeout?: number;
|
|
53
|
+
/** Retries for network errors, timeouts and HTTP 429, 500, 502, 503 and 504 (default 3, at most 10). */
|
|
54
|
+
maxRetries?: number;
|
|
55
|
+
/** `background` (default: `goal()` queues and batches) or `sync` (`goal()` sends at once). */
|
|
56
|
+
sendMode?: 'background' | 'sync';
|
|
57
|
+
/** `auto` (default: follow the organisation's setting from `/v1/server-sdk/config`), `true` (always guard), `false` (never guard locally). */
|
|
58
|
+
privateMode?: 'auto' | boolean;
|
|
59
|
+
/** The click-ID query parameter (default: from config, else `cgid`). */
|
|
60
|
+
clickIdParam?: string;
|
|
61
|
+
/** A console-compatible logger. Default: `console`, warnings and errors only. */
|
|
62
|
+
logger?: Logger;
|
|
63
|
+
/** Called for failures that can't be thrown (background sends, every `goal()`). */
|
|
64
|
+
onError?: OnError;
|
|
65
|
+
/** A `fetch`-compatible function to send requests with (proxies, mTLS, tracing). Default: built-in node:https. */
|
|
66
|
+
httpClient?: FetchLike;
|
|
67
|
+
/** An `http(s)://user:pass@host:port` proxy, or `false` to ignore `HTTPS_PROXY`/`HTTP_PROXY`. Default: the environment. */
|
|
68
|
+
proxy?: string | false;
|
|
69
|
+
/** Background batch size, 1–500 (default 100). */
|
|
70
|
+
batchSize?: number;
|
|
71
|
+
/** Background flush interval in ms (default 1000). */
|
|
72
|
+
flushInterval?: number;
|
|
73
|
+
/** Background queue bound (default 10 000); when full, the oldest event is dropped. */
|
|
74
|
+
maxQueueSize?: number;
|
|
75
|
+
/** Flush on `beforeExit`, `SIGTERM` and `SIGINT` (default true). */
|
|
76
|
+
shutdownHooks?: boolean;
|
|
77
|
+
/** The identity secret for `createIdentityToken()`. Default: `process.env.CLIKGATE_IDENTITY_SECRET`. */
|
|
78
|
+
identitySecret?: string;
|
|
79
|
+
/** Several apps' identity secrets, by app ID. Default: `process.env.CLIKGATE_IDENTITY_SECRETS` (a JSON object). */
|
|
80
|
+
identitySecrets?: Record<string, string>;
|
|
81
|
+
/** Advanced (tests): replace the clock and sleep. */
|
|
82
|
+
clock?: Clock;
|
|
83
|
+
/** Advanced (tests): the random source for backoff jitter, in [0, 1). */
|
|
84
|
+
random?: () => number;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The Clikgate client. Create one and reuse it; it is safe to share across requests.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* import { Clikgate } from '@clikgate/node';
|
|
91
|
+
* const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY
|
|
92
|
+
* clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
|
|
93
|
+
*/
|
|
94
|
+
export declare class Clikgate {
|
|
95
|
+
/** `live` or `test`, from the API key prefix. */
|
|
96
|
+
readonly mode: 'live' | 'test';
|
|
97
|
+
/** Goal events. */
|
|
98
|
+
readonly goals: Goals;
|
|
99
|
+
/** Conversions (older API). */
|
|
100
|
+
readonly conversions: Conversions;
|
|
101
|
+
/** Payments your server has verified: `confirm`, `fromPaystack`, `fromFlutterwave`, `fromMonnify`, `fromStripe`. */
|
|
102
|
+
readonly payments: Payments;
|
|
103
|
+
/** Links. */
|
|
104
|
+
readonly links: Links;
|
|
105
|
+
/** Clicks. */
|
|
106
|
+
readonly clicks: Clicks;
|
|
107
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
108
|
+
readonly knownCustomers: KnownCustomers;
|
|
109
|
+
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
110
|
+
readonly clickIds: ClickIds;
|
|
111
|
+
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
112
|
+
readonly api: ApiClient;
|
|
113
|
+
/** Webhook verification (also available without a client: `import { webhooks } from '@clikgate/node'`). */
|
|
114
|
+
readonly webhooks: {
|
|
115
|
+
verify: typeof webhooks.verify;
|
|
116
|
+
verifyAny: typeof webhooks.verifyAny;
|
|
117
|
+
};
|
|
118
|
+
private readonly core;
|
|
119
|
+
private readonly queue;
|
|
120
|
+
private readonly sendMode;
|
|
121
|
+
private readonly identitySource;
|
|
122
|
+
private closed;
|
|
123
|
+
private readonly shutdownEntry;
|
|
124
|
+
constructor(options?: ClikgateOptions);
|
|
125
|
+
/**
|
|
126
|
+
* Record a goal without waiting. **Never throws**: failures go to `logger` and `onError`.
|
|
127
|
+
* In background mode the event is queued and sent in batches; call `await clikgate.flush()`
|
|
128
|
+
* before a serverless function returns.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* clikgate.goal('account_opened', { clickId: application.clickId, reference: 'APP-55231', value: '2000000', currency: 'NGN' });
|
|
132
|
+
*/
|
|
133
|
+
goal(key: string, options: GoalOptions): void;
|
|
134
|
+
/**
|
|
135
|
+
* Create an identity token for the signed-in user (path A of https://clikgate.com/docs/identify-users).
|
|
136
|
+
* Return it in your sign-in and "current user" responses; the app passes it to the mobile SDK's `identifyUser()`.
|
|
137
|
+
* Uses `identitySecret` / `identitySecrets` from the options, else `CLIKGATE_IDENTITY_SECRET` /
|
|
138
|
+
* `CLIKGATE_IDENTITY_SECRETS`. No network call. Throws `ClikgateServerOnlyError` in a browser or React Native.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* res.json({ user, clikgateIdentityToken: clikgate.createIdentityToken(user.id) });
|
|
142
|
+
* clikgate.createIdentityToken(user.id, { appId: 'app_…' }); // several apps
|
|
143
|
+
*/
|
|
144
|
+
createIdentityToken(customerId: string, options?: IdentityTokenOptions): string;
|
|
145
|
+
/**
|
|
146
|
+
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation (`appId` +
|
|
147
|
+
* `installationId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
148
|
+
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
149
|
+
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
150
|
+
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
151
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
152
|
+
* referrals or new customers; it is refused in private mode too.
|
|
153
|
+
*
|
|
154
|
+
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
|
|
155
|
+
* `getInstallationId()` and sends it in its sign-in request; your server calls this with
|
|
156
|
+
* `{ appId, installationId, customerId, label? }` after sign-in and at every signed-in app open. When the app sends
|
|
157
|
+
* no installation ID (tracking is off), skip the call. Clikgate accepts installations active in the last 7 days.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* await clikgate.identifyUser({ clickId: order.clickId, customerId: 'user_42', label: 'Ada (VIP)' });
|
|
161
|
+
* if (body.installationId) await clikgate.identifyUser({ appId: 'app_…', installationId: body.installationId, customerId: user.id });
|
|
162
|
+
*/
|
|
163
|
+
identifyUser(params: IdentifyUserParams, requestOptions?: RequestOptions): Promise<PersonIdentified>;
|
|
164
|
+
/**
|
|
165
|
+
* The organisation's server SDK config (private mode, click-ID parameter, goals), cached for 10 minutes.
|
|
166
|
+
* `null` when it can't be loaded.
|
|
167
|
+
*
|
|
168
|
+
* @example
|
|
169
|
+
* const config = await clikgate.config();
|
|
170
|
+
* if (config?.private_mode) console.log('private mode is on');
|
|
171
|
+
*/
|
|
172
|
+
config(): Promise<ServerSdkConfig | null>;
|
|
173
|
+
/**
|
|
174
|
+
* Send everything queued (and wait for sends in flight). Resolves `true` when done within `timeout` ms.
|
|
175
|
+
* Never rejects.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* export async function handler(event) {
|
|
179
|
+
* clikgate.goal('order_paid', { reference: event.orderId, value: event.amount });
|
|
180
|
+
* await clikgate.flush();
|
|
181
|
+
* }
|
|
182
|
+
*/
|
|
183
|
+
flush(timeout?: number): Promise<boolean>;
|
|
184
|
+
/**
|
|
185
|
+
* Stop timers and shutdown hooks, then flush. Later `goal()` calls go to `onError` (`client_closed`).
|
|
186
|
+
*
|
|
187
|
+
* @example
|
|
188
|
+
* process.on('SIGTERM', async () => { await clikgate.close(); server.close(); });
|
|
189
|
+
*/
|
|
190
|
+
close(timeout?: number): Promise<boolean>;
|
|
191
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { ClickIds } from './click-ids.js';
|
|
2
|
+
import { ConfigCache } from './config.js';
|
|
3
|
+
import { Core } from './core.js';
|
|
4
|
+
import { ConfigurationError, localError } from './errors.js';
|
|
5
|
+
import { createIdentityTokenWith } from './identity.js';
|
|
6
|
+
import { guardPayload } from './guard.js';
|
|
7
|
+
import { ApiClient } from './generated/index.js';
|
|
8
|
+
import { GoalQueue, Goals, asClikgateError, buildGoalWire, checkBeforeSend } from './goals.js';
|
|
9
|
+
import { Requester, systemClock } from './http.js';
|
|
10
|
+
import { consoleLogger } from './logger.js';
|
|
11
|
+
import { Payments } from './payments.js';
|
|
12
|
+
import { KnownCustomers } from './known-customers.js';
|
|
13
|
+
import { Clicks, Conversions, Links } from './resources.js';
|
|
14
|
+
import { registerShutdown, unregisterShutdown } from './shutdown.js';
|
|
15
|
+
import { fetchTransport, nodeTransport } from './transport.js';
|
|
16
|
+
import { userAgent } from './user-agent.js';
|
|
17
|
+
import { webhooks } from './webhooks.js';
|
|
18
|
+
/** @internal The wire form of identifyUser's customerSince. */
|
|
19
|
+
function sinceWire(value) {
|
|
20
|
+
if (typeof value === 'string') {
|
|
21
|
+
if (!/^\d{4}-\d{2}-\d{2}(T.+)?$/.test(value))
|
|
22
|
+
throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
const ms = value instanceof Date ? value.getTime() : typeof value === 'number' && Number.isSafeInteger(value) ? value * 1000 : Number.NaN;
|
|
26
|
+
if (!Number.isFinite(ms))
|
|
27
|
+
throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
28
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
29
|
+
}
|
|
30
|
+
const KEY = /^cg_(live|test)_[A-Za-z0-9_]+$/;
|
|
31
|
+
const PARAM = /^[A-Za-z0-9_]{1,32}$/;
|
|
32
|
+
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
33
|
+
function keyType(k) {
|
|
34
|
+
if (k.startsWith('cg_sdk_'))
|
|
35
|
+
return 'a mobile SDK key (cg_sdk_…)';
|
|
36
|
+
if (k.startsWith('cg_site_'))
|
|
37
|
+
return 'a web script site key (cg_site_…)';
|
|
38
|
+
if (k.startsWith('cg_cli_'))
|
|
39
|
+
return 'a setup command token (cg_cli_…)';
|
|
40
|
+
return 'not a Clikgate server API key';
|
|
41
|
+
}
|
|
42
|
+
function int(name, v, def, min, max) {
|
|
43
|
+
if (v === undefined)
|
|
44
|
+
return def;
|
|
45
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max)
|
|
46
|
+
throw new ConfigurationError({ message: `${name} must be a number from ${min} to ${max}.`, code: 'invalid_option', param: name });
|
|
47
|
+
return v;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The Clikgate client. Create one and reuse it; it is safe to share across requests.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* import { Clikgate } from '@clikgate/node';
|
|
54
|
+
* const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY
|
|
55
|
+
* clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
|
|
56
|
+
*/
|
|
57
|
+
export class Clikgate {
|
|
58
|
+
/** `live` or `test`, from the API key prefix. */
|
|
59
|
+
mode;
|
|
60
|
+
/** Goal events. */
|
|
61
|
+
goals;
|
|
62
|
+
/** Conversions (older API). */
|
|
63
|
+
conversions;
|
|
64
|
+
/** Payments your server has verified: `confirm`, `fromPaystack`, `fromFlutterwave`, `fromMonnify`, `fromStripe`. */
|
|
65
|
+
payments;
|
|
66
|
+
/** Links. */
|
|
67
|
+
links;
|
|
68
|
+
/** Clicks. */
|
|
69
|
+
clicks;
|
|
70
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
71
|
+
knownCustomers;
|
|
72
|
+
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
73
|
+
clickIds;
|
|
74
|
+
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
75
|
+
api;
|
|
76
|
+
/** Webhook verification (also available without a client: `import { webhooks } from '@clikgate/node'`). */
|
|
77
|
+
webhooks;
|
|
78
|
+
core;
|
|
79
|
+
queue;
|
|
80
|
+
sendMode;
|
|
81
|
+
identitySource;
|
|
82
|
+
closed = false;
|
|
83
|
+
shutdownEntry;
|
|
84
|
+
constructor(options = {}) {
|
|
85
|
+
const apiKey = options.apiKey ?? process.env.CLIKGATE_API_KEY;
|
|
86
|
+
if (!apiKey)
|
|
87
|
+
throw new ConfigurationError({ message: 'No API key: pass { apiKey } or set CLIKGATE_API_KEY (cg_live_… or cg_test_…).', code: 'missing_api_key', param: 'apiKey' });
|
|
88
|
+
const m = KEY.exec(apiKey);
|
|
89
|
+
if (!m)
|
|
90
|
+
throw new ConfigurationError({ message: `The API key is ${keyType(apiKey)}. Server SDKs need a cg_live_… or cg_test_… API key from Developers → API keys.`, code: 'invalid_api_key', param: 'apiKey' });
|
|
91
|
+
this.mode = m[1];
|
|
92
|
+
const baseUrl = (options.baseUrl ?? process.env.CLIKGATE_BASE_URL ?? 'https://api.clikgate.com').replace(/\/+$/, '');
|
|
93
|
+
let parsed;
|
|
94
|
+
try {
|
|
95
|
+
parsed = new URL(baseUrl);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new ConfigurationError({ message: 'baseUrl is not a URL.', code: 'invalid_option', param: 'baseUrl' });
|
|
99
|
+
}
|
|
100
|
+
if (!(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOCAL.has(parsed.hostname)))) {
|
|
101
|
+
throw new ConfigurationError({ message: 'baseUrl must use https:// (http:// only for localhost).', code: 'invalid_option', param: 'baseUrl' });
|
|
102
|
+
}
|
|
103
|
+
const timeoutMs = int('timeout', options.timeout, 10_000, 1, 600_000);
|
|
104
|
+
const maxRetries = int('maxRetries', options.maxRetries, 3, 0, 10);
|
|
105
|
+
const batchSize = int('batchSize', options.batchSize, 100, 1, 500);
|
|
106
|
+
const flushIntervalMs = int('flushInterval', options.flushInterval, 1000, 1, 3_600_000);
|
|
107
|
+
const maxQueueSize = int('maxQueueSize', options.maxQueueSize, 10_000, 1, 1_000_000);
|
|
108
|
+
if (options.clickIdParam !== undefined && !PARAM.test(options.clickIdParam)) {
|
|
109
|
+
throw new ConfigurationError({ message: 'clickIdParam must be 1-32 letters, digits or underscores.', code: 'invalid_option', param: 'clickIdParam' });
|
|
110
|
+
}
|
|
111
|
+
const sendMode = options.sendMode ?? 'background';
|
|
112
|
+
if (sendMode !== 'background' && sendMode !== 'sync')
|
|
113
|
+
throw new ConfigurationError({ message: "sendMode must be 'background' or 'sync'.", code: 'invalid_option', param: 'sendMode' });
|
|
114
|
+
const privateMode = options.privateMode ?? 'auto';
|
|
115
|
+
if (privateMode !== 'auto' && privateMode !== true && privateMode !== false)
|
|
116
|
+
throw new ConfigurationError({ message: "privateMode must be 'auto', true or false.", code: 'invalid_option', param: 'privateMode' });
|
|
117
|
+
const clock = options.clock ?? systemClock;
|
|
118
|
+
const logger = options.logger ?? consoleLogger;
|
|
119
|
+
const transport = options.httpClient ? fetchTransport(options.httpClient) : nodeTransport(options.proxy);
|
|
120
|
+
const requester = new Requester({ apiKey, baseUrl, timeoutMs, maxRetries, userAgent: userAgent(), transport, clock, random: options.random ?? Math.random });
|
|
121
|
+
const configCache = new ConfigCache(requester, clock, logger, timeoutMs);
|
|
122
|
+
this.core = new Core(requester, logger, clock, privateMode, configCache, options.onError);
|
|
123
|
+
this.sendMode = sendMode;
|
|
124
|
+
this.identitySource = { identitySecret: options.identitySecret ?? null, identitySecrets: options.identitySecrets ? { ...options.identitySecrets } : null };
|
|
125
|
+
this.queue = new GoalQueue(this.core, { batchSize, flushIntervalMs, maxQueueSize });
|
|
126
|
+
this.goals = new Goals(this.core);
|
|
127
|
+
this.conversions = new Conversions(this.core);
|
|
128
|
+
this.payments = new Payments(this.core);
|
|
129
|
+
this.links = new Links(this.core);
|
|
130
|
+
this.clicks = new Clicks(this.core);
|
|
131
|
+
this.knownCustomers = new KnownCustomers(this.core);
|
|
132
|
+
const explicitParam = options.clickIdParam;
|
|
133
|
+
this.clickIds = new ClickIds(() => explicitParam ?? configCache.peek()?.click_id_param ?? 'cgid');
|
|
134
|
+
this.api = new ApiClient(requester);
|
|
135
|
+
this.webhooks = {
|
|
136
|
+
verify: (rawBody, header, secret, o = {}) => webhooks.verify(rawBody, header, secret, { now: Math.floor(clock.now() / 1000), ...o }),
|
|
137
|
+
verifyAny: (rawBody, header, secrets, o = {}) => webhooks.verifyAny(rawBody, header, secrets, { now: Math.floor(clock.now() / 1000), ...o }),
|
|
138
|
+
};
|
|
139
|
+
if (options.shutdownHooks ?? true) {
|
|
140
|
+
this.shutdownEntry = { busy: () => this.queue.busy, flush: (ms) => this.flush(ms) };
|
|
141
|
+
registerShutdown(this.shutdownEntry);
|
|
142
|
+
}
|
|
143
|
+
else
|
|
144
|
+
this.shutdownEntry = null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Record a goal without waiting. **Never throws**: failures go to `logger` and `onError`.
|
|
148
|
+
* In background mode the event is queued and sent in batches; call `await clikgate.flush()`
|
|
149
|
+
* before a serverless function returns.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* clikgate.goal('account_opened', { clickId: application.clickId, reference: 'APP-55231', value: '2000000', currency: 'NGN' });
|
|
153
|
+
*/
|
|
154
|
+
goal(key, options) {
|
|
155
|
+
const shown = () => ({ goal: String(key), reference: this.core.shownReference(options?.reference) });
|
|
156
|
+
if (this.closed) {
|
|
157
|
+
this.core.report(localError('client_closed', 'This Clikgate client is closed.'), { operation: 'goal', events: [shown()], dropped: true });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
let wire;
|
|
161
|
+
try {
|
|
162
|
+
wire = buildGoalWire(this.core, key, options);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
this.core.report(asClikgateError(err), { operation: 'goal', events: [shown()], dropped: true });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (this.sendMode === 'background') {
|
|
169
|
+
this.queue.enqueue(wire);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const w = wire;
|
|
173
|
+
const p = (async () => {
|
|
174
|
+
try {
|
|
175
|
+
const state = await this.core.guardState();
|
|
176
|
+
checkBeforeSend(this.core, state, w);
|
|
177
|
+
await this.core.requester.request({ method: 'POST', path: '/v1/goals/events', body: w });
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
this.core.report(asClikgateError(err), { operation: 'goal', events: [shown()], dropped: true });
|
|
181
|
+
}
|
|
182
|
+
})();
|
|
183
|
+
this.queue.holdSend(p);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Create an identity token for the signed-in user (path A of https://clikgate.com/docs/identify-users).
|
|
187
|
+
* Return it in your sign-in and "current user" responses; the app passes it to the mobile SDK's `identifyUser()`.
|
|
188
|
+
* Uses `identitySecret` / `identitySecrets` from the options, else `CLIKGATE_IDENTITY_SECRET` /
|
|
189
|
+
* `CLIKGATE_IDENTITY_SECRETS`. No network call. Throws `ClikgateServerOnlyError` in a browser or React Native.
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* res.json({ user, clikgateIdentityToken: clikgate.createIdentityToken(user.id) });
|
|
193
|
+
* clikgate.createIdentityToken(user.id, { appId: 'app_…' }); // several apps
|
|
194
|
+
*/
|
|
195
|
+
createIdentityToken(customerId, options = {}) {
|
|
196
|
+
return createIdentityTokenWith(this.identitySource, customerId, options);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation (`appId` +
|
|
200
|
+
* `installationId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
201
|
+
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
202
|
+
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
203
|
+
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
204
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
205
|
+
* referrals or new customers; it is refused in private mode too.
|
|
206
|
+
*
|
|
207
|
+
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
|
|
208
|
+
* `getInstallationId()` and sends it in its sign-in request; your server calls this with
|
|
209
|
+
* `{ appId, installationId, customerId, label? }` after sign-in and at every signed-in app open. When the app sends
|
|
210
|
+
* no installation ID (tracking is off), skip the call. Clikgate accepts installations active in the last 7 days.
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* await clikgate.identifyUser({ clickId: order.clickId, customerId: 'user_42', label: 'Ada (VIP)' });
|
|
214
|
+
* if (body.installationId) await clikgate.identifyUser({ appId: 'app_…', installationId: body.installationId, customerId: user.id });
|
|
215
|
+
*/
|
|
216
|
+
async identifyUser(params, requestOptions = {}) {
|
|
217
|
+
const p = (params ?? {});
|
|
218
|
+
if ((p.appId == null) !== (p.installationId == null)) {
|
|
219
|
+
throw localError('invalid_request', 'Send appId and installationId together.', p.appId == null ? 'app_id' : 'installation_id');
|
|
220
|
+
}
|
|
221
|
+
if (p.clickId == null && p.installationId == null && p.customerId == null) {
|
|
222
|
+
throw localError('invalid_request', 'Send clickId, appId + installationId, or customerId.', 'click_id');
|
|
223
|
+
}
|
|
224
|
+
const body = {};
|
|
225
|
+
if (p.clickId != null)
|
|
226
|
+
body.click_id = p.clickId;
|
|
227
|
+
if (p.appId != null)
|
|
228
|
+
body.app_id = p.appId;
|
|
229
|
+
if (p.installationId != null)
|
|
230
|
+
body.installation_id = p.installationId;
|
|
231
|
+
if (p.customerId != null)
|
|
232
|
+
body.customer_id = p.customerId;
|
|
233
|
+
if (p.label != null)
|
|
234
|
+
body.label = p.label;
|
|
235
|
+
if (p.customerSince != null) {
|
|
236
|
+
if (p.customerId == null)
|
|
237
|
+
throw localError('invalid_request', 'customerSince needs customerId.', 'customer_since');
|
|
238
|
+
body.customer_since = sinceWire(p.customerSince);
|
|
239
|
+
}
|
|
240
|
+
if (p.customerSinceReplace === true)
|
|
241
|
+
body.customer_since_replace = true;
|
|
242
|
+
const state = await this.core.guardState();
|
|
243
|
+
if (state.guard)
|
|
244
|
+
guardPayload('identify', body);
|
|
245
|
+
const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/people/identify', body, ...requestOptions });
|
|
246
|
+
return data;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The organisation's server SDK config (private mode, click-ID parameter, goals), cached for 10 minutes.
|
|
250
|
+
* `null` when it can't be loaded.
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* const config = await clikgate.config();
|
|
254
|
+
* if (config?.private_mode) console.log('private mode is on');
|
|
255
|
+
*/
|
|
256
|
+
config() {
|
|
257
|
+
return this.core.configCache.get();
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Send everything queued (and wait for sends in flight). Resolves `true` when done within `timeout` ms.
|
|
261
|
+
* Never rejects.
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* export async function handler(event) {
|
|
265
|
+
* clikgate.goal('order_paid', { reference: event.orderId, value: event.amount });
|
|
266
|
+
* await clikgate.flush();
|
|
267
|
+
* }
|
|
268
|
+
*/
|
|
269
|
+
flush(timeout = 10_000) {
|
|
270
|
+
return this.queue.flush(timeout);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Stop timers and shutdown hooks, then flush. Later `goal()` calls go to `onError` (`client_closed`).
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* process.on('SIGTERM', async () => { await clikgate.close(); server.close(); });
|
|
277
|
+
*/
|
|
278
|
+
async close(timeout = 10_000) {
|
|
279
|
+
if (!this.closed) {
|
|
280
|
+
this.closed = true;
|
|
281
|
+
this.queue.stop();
|
|
282
|
+
if (this.shutdownEntry)
|
|
283
|
+
unregisterShutdown(this.shutdownEntry);
|
|
284
|
+
}
|
|
285
|
+
return this.queue.flush(timeout);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ServerSdkConfig } from './types.js';
|
|
2
|
+
/** How long a fetched config is used (SPEC 12.1). */
|
|
3
|
+
export declare const CONFIG_TTL_MS: number;
|
|
4
|
+
/** How long to wait after a failed config fetch. */
|
|
5
|
+
export declare const CONFIG_RETRY_MS: number;
|
|
6
|
+
/** The guard state the senders need. */
|
|
7
|
+
export interface GuardState {
|
|
8
|
+
/** True when the private-mode guard applies. */
|
|
9
|
+
guard: boolean;
|
|
10
|
+
/** The loaded config, if any. */
|
|
11
|
+
config: ServerSdkConfig | null;
|
|
12
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { VERSION } from './version.js';
|
|
2
|
+
/** How long a fetched config is used (SPEC 12.1). */
|
|
3
|
+
export const CONFIG_TTL_MS = 10 * 60 * 1000;
|
|
4
|
+
/** How long to wait after a failed config fetch. */
|
|
5
|
+
export const CONFIG_RETRY_MS = 60 * 1000;
|
|
6
|
+
const CONFIG_TIMEOUT_CAP_MS = 5000;
|
|
7
|
+
/** @internal Compare two semver strings (pre-release suffixes ignored). */
|
|
8
|
+
export function semverLess(a, b) {
|
|
9
|
+
const parse = (v) => v.split(/[-+]/)[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
|
|
10
|
+
const x = parse(a);
|
|
11
|
+
const y = parse(b);
|
|
12
|
+
for (let i = 0; i < 3; i++) {
|
|
13
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
14
|
+
if (d !== 0)
|
|
15
|
+
return d < 0;
|
|
16
|
+
}
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
/** @internal Loads and caches `GET /v1/server-sdk/config` (single attempt, 10-minute cache, fail closed). */
|
|
20
|
+
export class ConfigCache {
|
|
21
|
+
requester;
|
|
22
|
+
clock;
|
|
23
|
+
logger;
|
|
24
|
+
timeoutMs;
|
|
25
|
+
value = null;
|
|
26
|
+
fetchedAt = 0;
|
|
27
|
+
failedAt = null;
|
|
28
|
+
inflight = null;
|
|
29
|
+
versionWarned = false;
|
|
30
|
+
constructor(requester, clock, logger, timeoutMs) {
|
|
31
|
+
this.requester = requester;
|
|
32
|
+
this.clock = clock;
|
|
33
|
+
this.logger = logger;
|
|
34
|
+
this.timeoutMs = timeoutMs;
|
|
35
|
+
}
|
|
36
|
+
/** The cached config without fetching (may be stale or null). */
|
|
37
|
+
peek() {
|
|
38
|
+
return this.value;
|
|
39
|
+
}
|
|
40
|
+
/** The config, fetching it when the cache is empty or stale. `null` when unavailable. */
|
|
41
|
+
async get() {
|
|
42
|
+
const now = this.clock.now();
|
|
43
|
+
if (this.value && now - this.fetchedAt < CONFIG_TTL_MS)
|
|
44
|
+
return this.value;
|
|
45
|
+
if (this.failedAt !== null && now - this.failedAt < CONFIG_RETRY_MS)
|
|
46
|
+
return null;
|
|
47
|
+
if (!this.inflight) {
|
|
48
|
+
this.inflight = this.fetch().finally(() => {
|
|
49
|
+
this.inflight = null;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return this.inflight;
|
|
53
|
+
}
|
|
54
|
+
async fetch() {
|
|
55
|
+
try {
|
|
56
|
+
const { data } = await this.requester.request({
|
|
57
|
+
method: 'GET',
|
|
58
|
+
path: '/v1/server-sdk/config',
|
|
59
|
+
maxRetries: 0,
|
|
60
|
+
timeout: Math.min(this.timeoutMs, CONFIG_TIMEOUT_CAP_MS),
|
|
61
|
+
});
|
|
62
|
+
if (!data || typeof data !== 'object' || typeof data.private_mode !== 'boolean')
|
|
63
|
+
throw new Error('unexpected config body');
|
|
64
|
+
this.value = data;
|
|
65
|
+
this.fetchedAt = this.clock.now();
|
|
66
|
+
this.failedAt = null;
|
|
67
|
+
const minimum = data.minimum_sdk_versions?.node;
|
|
68
|
+
if (!this.versionWarned && typeof minimum === 'string' && semverLess(VERSION, minimum)) {
|
|
69
|
+
this.versionWarned = true;
|
|
70
|
+
this.logger.warn(`@clikgate/node ${VERSION} is below the minimum version ${minimum} for your organisation. Please upgrade.`, { code: 'sdk_below_minimum_version' });
|
|
71
|
+
}
|
|
72
|
+
return data;
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
this.value = null;
|
|
76
|
+
this.failedAt = this.clock.now();
|
|
77
|
+
const why = err instanceof Error && 'code' in err ? String(err.code) : 'error';
|
|
78
|
+
this.logger.warn(`Could not load the server SDK config (${why}); the private-mode guard stays on until it loads.`, { code: 'config_unavailable' });
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type ClikgateError } from './errors.js';
|
|
2
|
+
/** What `onError` receives next to the error (SPEC 9.5). Never values, metadata or consent. */
|
|
3
|
+
export interface ErrorContext {
|
|
4
|
+
/** `goal`, `goals.batch` or `config`. */
|
|
5
|
+
operation: 'goal' | 'goals.batch' | 'config';
|
|
6
|
+
/** The affected events; references are `[redacted]` while private mode is on. */
|
|
7
|
+
events: Array<{
|
|
8
|
+
goal: string;
|
|
9
|
+
reference: string;
|
|
10
|
+
}>;
|
|
11
|
+
/** True when the events won't be retried. */
|
|
12
|
+
dropped: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Called for failures that can't be thrown (background sends and every `goal()` call). */
|
|
15
|
+
export type OnError = (error: ClikgateError, context: ErrorContext) => void;
|