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