@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,138 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ClikgateError, NetworkError, RateLimitError, ServerError, TimeoutError, errorFromResponse, localError, retryAfterMs } from './errors.js';
3
+ /** @internal The default clock. */
4
+ export const systemClock = {
5
+ now: () => Date.now(),
6
+ sleep: (ms) => new Promise((resolve) => {
7
+ setTimeout(resolve, ms);
8
+ }),
9
+ };
10
+ const BACKOFF_BASE_MS = 500;
11
+ const BACKOFF_CAP_MS = 20_000;
12
+ const MAX_RETRY_AFTER_MS = 60_000;
13
+ const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
14
+ /** @internal Encode one path segment (RFC 3986 unreserved characters kept). */
15
+ export function encodePathSegment(s) {
16
+ return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
17
+ }
18
+ /** @internal Format a Date (or pass a string through) as RFC 3339 UTC (SPEC section 4). */
19
+ export function formatDate(d) {
20
+ if (typeof d === 'string')
21
+ return d;
22
+ const iso = d.toISOString();
23
+ return iso.endsWith('.000Z') ? `${iso.slice(0, -5)}Z` : iso;
24
+ }
25
+ function isPlainObject(v) {
26
+ return typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date);
27
+ }
28
+ /** @internal Exported for tests. */
29
+ export function queryString(query) {
30
+ if (!query)
31
+ return '';
32
+ const parts = [];
33
+ const add = (k, v) => {
34
+ if (v === undefined || v === null)
35
+ return;
36
+ const s = v instanceof Date ? formatDate(v) : typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v);
37
+ parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(s)}`);
38
+ };
39
+ for (const [k, v] of Object.entries(query)) {
40
+ if (Array.isArray(v))
41
+ v.forEach((item) => add(k, item));
42
+ else if (isPlainObject(v)) {
43
+ // A map (e.g. `metadata: { seller_id: 'sel_ada' }`) is sent as `metadata[seller_id]=sel_ada` (SPEC section 21).
44
+ for (const [sub, sv] of Object.entries(v))
45
+ add(`${k}[${sub}]`, sv);
46
+ }
47
+ else
48
+ add(k, v);
49
+ }
50
+ return parts.length ? `?${parts.join('&')}` : '';
51
+ }
52
+ /** @internal JSON body: drops `undefined`, keeps explicit `null`, formats Dates and bigints. */
53
+ export function toJson(body) {
54
+ return JSON.stringify(body, (_k, v) => {
55
+ if (typeof v === 'bigint')
56
+ return v.toString();
57
+ return v;
58
+ });
59
+ }
60
+ /** @internal The one HTTP pipeline every call (hand-written and generated) goes through. */
61
+ export class Requester {
62
+ s;
63
+ constructor(s) {
64
+ this.s = s;
65
+ }
66
+ /** Full-jitter backoff for retry number `n` (0-based). */
67
+ backoffMs(n) {
68
+ return Math.floor(this.s.random() * Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** n));
69
+ }
70
+ /** Send a JSON request and parse the JSON answer (`null` for an empty body). */
71
+ async request(req) {
72
+ const res = await this.send(req);
73
+ const text = new TextDecoder().decode(res.body);
74
+ const data = (text.trim() ? JSON.parse(text) : null);
75
+ return { status: res.status, data, headers: res.headers };
76
+ }
77
+ /** Send a request; resolves with the 2xx response or throws a typed error (after retries). */
78
+ async send(req) {
79
+ const url = `${this.s.baseUrl}${req.path}${queryString(req.query)}`;
80
+ const headers = {
81
+ authorization: `Bearer ${this.s.apiKey}`,
82
+ 'user-agent': this.s.userAgent,
83
+ accept: 'application/json',
84
+ };
85
+ let body;
86
+ if (req.body !== undefined) {
87
+ body = new TextEncoder().encode(toJson(req.body));
88
+ headers['content-type'] = 'application/json';
89
+ }
90
+ if (req.method === 'POST' || req.method === 'PATCH')
91
+ headers['idempotency-key'] = req.idempotencyKey ?? randomUUID();
92
+ const maxRetries = req.maxRetries ?? this.s.maxRetries;
93
+ const timeoutMs = req.timeout ?? this.s.timeoutMs;
94
+ for (let attempt = 0;; attempt++) {
95
+ let error;
96
+ let res;
97
+ try {
98
+ res = await this.s.transport({ method: req.method, url, headers, body, timeoutMs });
99
+ }
100
+ catch (err) {
101
+ error = err instanceof ClikgateError ? err : new NetworkError({ message: 'Could not reach the Clikgate API.', code: 'network_error' });
102
+ if (attempt >= maxRetries)
103
+ throw error;
104
+ await this.s.clock.sleep(this.backoffMs(attempt));
105
+ continue;
106
+ }
107
+ if (res.status >= 200 && res.status < 300)
108
+ return res;
109
+ error = errorFromResponse(res.status, res.headers, res.body, this.s.clock.now());
110
+ if (!RETRYABLE_STATUS.has(res.status))
111
+ throw error;
112
+ let delay = this.backoffMs(attempt);
113
+ if (res.status === 429 || res.status === 503) {
114
+ const ra = retryAfterMs(res.headers, this.s.clock.now());
115
+ if (ra !== null) {
116
+ if (ra > MAX_RETRY_AFTER_MS)
117
+ throw error;
118
+ delay = ra;
119
+ }
120
+ }
121
+ if (attempt >= maxRetries)
122
+ throw error;
123
+ await this.s.clock.sleep(delay);
124
+ }
125
+ }
126
+ }
127
+ /** @internal True when the error class is retryable at the batch level (SPEC 9.3). */
128
+ export function isRetryable(err) {
129
+ if (err instanceof NetworkError || err instanceof TimeoutError || err instanceof RateLimitError)
130
+ return true;
131
+ return err instanceof ServerError && err.httpStatus !== null && RETRYABLE_STATUS.has(err.httpStatus);
132
+ }
133
+ /** @internal Require a non-empty id argument. */
134
+ export function requireId(id, name = 'id') {
135
+ if (typeof id !== 'string' || id.length === 0)
136
+ throw localError('invalid_argument', `${name} must be a non-empty string.`, name);
137
+ return id;
138
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Identity tokens (SDK spec 8.5): your server proves to Clikgate that a customer ID belongs to the
3
+ * person signed in to your app. The app passes the token to the mobile SDK's `identifyUser()`.
4
+ *
5
+ * `token = base64url_nopad(HMAC_SHA256(secret, customerId + "." + issuedAt)) + "." + issuedAt`, the same signer
6
+ * Clikgate verifies with. No network call. Guide: https://clikgate.com/docs/identify-users
7
+ */
8
+ export interface IdentityTokenOptions {
9
+ /** The Clikgate app ID (`app_…`). Picks that app's secret from `identitySecrets` / `CLIKGATE_IDENTITY_SECRETS`. */
10
+ appId?: string | null;
11
+ /** The identity secret to sign with. Default: the app's secret from the map, else `CLIKGATE_IDENTITY_SECRET`. */
12
+ secret?: string | null;
13
+ /** Unix seconds the token was issued at. Default: now. */
14
+ issuedAt?: number;
15
+ }
16
+ /** The single secret's environment variable. */
17
+ export declare const IDENTITY_SECRET_ENV = "CLIKGATE_IDENTITY_SECRET";
18
+ /** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
19
+ export declare const IDENTITY_SECRETS_ENV = "CLIKGATE_IDENTITY_SECRETS";
20
+ /**
21
+ * Create an identity token for the signed-in user. Return it in your sign-in and "current user"
22
+ * responses; the app passes it to `identifyUser()`. Reads `CLIKGATE_IDENTITY_SECRET`, or with `appId` the app's
23
+ * secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
24
+ *
25
+ * Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
26
+ * and `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID.
27
+ *
28
+ * @example
29
+ * import { createIdentityToken } from '@clikgate/node';
30
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
31
+ */
32
+ export declare function createIdentityToken(customerId: string, options?: IdentityTokenOptions): string;
@@ -0,0 +1,92 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { ClikgateServerOnlyError, ConfigurationError, localError } from './errors.js';
3
+ /** The single secret's environment variable. */
4
+ export const IDENTITY_SECRET_ENV = 'CLIKGATE_IDENTITY_SECRET';
5
+ /** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
6
+ export const IDENTITY_SECRETS_ENV = 'CLIKGATE_IDENTITY_SECRETS';
7
+ const MAX_CUSTOMER_ID = 255;
8
+ /** @internal True in a browser (window or document) or React Native. */
9
+ export function isBrowserOrMobile(g = globalThis) {
10
+ if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined')
11
+ return true;
12
+ const nav = g.navigator;
13
+ return typeof nav === 'object' && nav !== null && nav.product === 'ReactNative';
14
+ }
15
+ function serverOnly() {
16
+ throw new ClikgateServerOnlyError({
17
+ message: 'createIdentityToken() runs on your server only: it needs your identity secret, which must never be in an app or website. Return the token from your sign-in response instead. See https://clikgate.com/docs/identify-users',
18
+ code: 'server_only',
19
+ });
20
+ }
21
+ function envMap() {
22
+ const raw = process.env[IDENTITY_SECRETS_ENV];
23
+ if (raw === undefined || raw.trim() === '')
24
+ return null;
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(raw);
28
+ }
29
+ catch {
30
+ parsed = null;
31
+ }
32
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === 'string' && v !== '')) {
33
+ // Never echo the value: it holds secrets.
34
+ throw new ConfigurationError({ message: `${IDENTITY_SECRETS_ENV} must be a JSON object of app IDs to identity secrets, e.g. {"app_…": "cgis_…"}.`, code: 'invalid_identity_secrets', param: IDENTITY_SECRETS_ENV });
35
+ }
36
+ return parsed;
37
+ }
38
+ function resolveSecret(options, source) {
39
+ if (options.secret != null && options.secret !== '')
40
+ return options.secret;
41
+ const appId = options.appId ?? null;
42
+ const map = source.identitySecrets ?? envMap();
43
+ if (appId !== null && map && Object.prototype.hasOwnProperty.call(map, appId) && map[appId])
44
+ return map[appId];
45
+ const single = source.identitySecret || process.env[IDENTITY_SECRET_ENV] || null;
46
+ if (single)
47
+ return single;
48
+ if (appId === null && map && Object.keys(map).length > 0) {
49
+ throw new ConfigurationError({ message: `Several apps' identity secrets are set (${IDENTITY_SECRETS_ENV}): pass { appId } to choose one.`, code: 'missing_identity_secret', param: 'appId' });
50
+ }
51
+ throw new ConfigurationError({
52
+ message: appId === null
53
+ ? `No identity secret: set ${IDENTITY_SECRET_ENV} on your server (Apps › your app › Identity secret).`
54
+ : `No identity secret for this app: add it to ${IDENTITY_SECRETS_ENV} or set ${IDENTITY_SECRET_ENV}.`,
55
+ code: 'missing_identity_secret',
56
+ param: 'secret',
57
+ });
58
+ }
59
+ /** @internal */
60
+ export function signIdentityToken(secret, customerId, issuedAt) {
61
+ const sig = createHmac('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(`${customerId}.${issuedAt}`, 'utf8')).digest('base64url');
62
+ return `${sig}.${issuedAt}`;
63
+ }
64
+ /** @internal createIdentityToken with an explicit secret source (the client's options). */
65
+ export function createIdentityTokenWith(source, customerId, options = {}) {
66
+ if (isBrowserOrMobile())
67
+ serverOnly();
68
+ if (typeof customerId !== 'string' || customerId === '' || [...customerId].length > MAX_CUSTOMER_ID) {
69
+ // Never echo the customer ID.
70
+ throw localError('invalid_customer_id', 'customerId must be your own user ID as a string of 1-255 characters (never an email or phone number).', 'customer_id');
71
+ }
72
+ const o = options ?? {};
73
+ const issuedAt = o.issuedAt ?? Math.floor(Date.now() / 1000);
74
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
75
+ throw localError('invalid_argument', 'issuedAt must be whole Unix seconds.', 'issued_at');
76
+ return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
77
+ }
78
+ /**
79
+ * Create an identity token for the signed-in user. Return it in your sign-in and "current user"
80
+ * responses; the app passes it to `identifyUser()`. Reads `CLIKGATE_IDENTITY_SECRET`, or with `appId` the app's
81
+ * secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
82
+ *
83
+ * Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
84
+ * and `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID.
85
+ *
86
+ * @example
87
+ * import { createIdentityToken } from '@clikgate/node';
88
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
89
+ */
90
+ export function createIdentityToken(customerId, options = {}) {
91
+ return createIdentityTokenWith({}, customerId, options);
92
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The official Clikgate server SDK for Node.js and TypeScript.
3
+ *
4
+ * @example
5
+ * import { Clikgate, Provider } from '@clikgate/node';
6
+ * const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY
7
+ * clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
8
+ * clikgate.goal('order_paid', { clickId, reference: 'T123456', provider: Provider.Paystack, value: '7500' }); // a Payment goal
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ export { Clikgate, type ClikgateOptions, type IdentifyUserParams, type PersonIdentified } from './client.js';
13
+ export { ClickIds, clickIds, isValid as isValidClickId, CLICK_ID_PATTERN, CLICK_ID_HEADER, KEPT_COOKIE, KEPT_BY, BROWSER_ENGINES, PLATFORMS, type PersistOptions, type RequestLike, type ResponseLike, type KeptBy, type BrowserEngine, type Platform, type ClickContext, type KeepRoute, type KeepRouteOptions, type KeepInput, type KeepResult, } from './click-ids.js';
14
+ export { webhooks, type VerifyOptions, type RawBody } from './webhooks.js';
15
+ export { createIdentityToken, IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV, type IdentityTokenOptions } from './identity.js';
16
+ export { formatValue, type MoneyInput } from './money.js';
17
+ export { hashForAds, type HashForAdsInput, type HashedIdentifiers } from './ads-hashing.js';
18
+ export { GoalKind, GoalStatus, Provider } from './enums.js';
19
+ export type { GoalOptions, GoalBatchEvent, ReverseOptions } from './goals.js';
20
+ export type { ErrorContext, OnError } from './core.js';
21
+ export type { Logger, WarningCode } from './logger.js';
22
+ export type { Clock, RequestOptions } from './http.js';
23
+ export type { FetchLike } from './transport.js';
24
+ export type { QrOptions, LinkIterator, Conversions, Links, Clicks } from './resources.js';
25
+ export type { Goals } from './goals.js';
26
+ export { buildFromPaystack, buildFromFlutterwave, buildFromMonnify, buildFromStripe, type Payments, type PaymentStatus, type PaymentConfirmParams, type PaymentConfirmation, type PaymentConfirmationBody, type PaymentHelperOptions, } from './payments.js';
27
+ export type { GoalEvent, GoalAttribution, GoalPayment, GoalBatchItem, GoalBatchResult, Link, LinkWarning, LinkChangeRequest, LinkUpdateResult, Click, Conversion, ListPage, ServerSdkConfig, ConfigGoal, WebhookEvent, QrCode, } from './types.js';
28
+ export { ClikgateError, ConfigurationError, AuthenticationError, PermissionError, InvalidRequestError, PrivateModeFieldRejectedError, NotFoundError, ConflictError, LinkLockedError, IdempotencyError, RateLimitError, ServerError, NetworkError, TimeoutError, SignatureVerificationError, ClikgateServerOnlyError, type KnownErrorCode, } from './errors.js';
29
+ export { VERSION } from './version.js';
30
+ /** Types of the generated `clikgate.api.*` layer (request bodies and responses, as in openapi.json). */
31
+ export type * as ApiTypes from './generated/index.js';
32
+ export type { ApiClient } from './generated/index.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The official Clikgate server SDK for Node.js and TypeScript.
3
+ *
4
+ * @example
5
+ * import { Clikgate, Provider } from '@clikgate/node';
6
+ * const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY
7
+ * clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
8
+ * clikgate.goal('order_paid', { clickId, reference: 'T123456', provider: Provider.Paystack, value: '7500' }); // a Payment goal
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ export { Clikgate } from './client.js';
13
+ export { ClickIds, clickIds, isValid as isValidClickId, CLICK_ID_PATTERN, CLICK_ID_HEADER, KEPT_COOKIE, KEPT_BY, BROWSER_ENGINES, PLATFORMS, } from './click-ids.js';
14
+ export { webhooks } from './webhooks.js';
15
+ export { createIdentityToken, IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV } from './identity.js';
16
+ export { formatValue } from './money.js';
17
+ export { hashForAds } from './ads-hashing.js';
18
+ export { GoalKind, GoalStatus, Provider } from './enums.js';
19
+ export { buildFromPaystack, buildFromFlutterwave, buildFromMonnify, buildFromStripe, } from './payments.js';
20
+ export { ClikgateError, ConfigurationError, AuthenticationError, PermissionError, InvalidRequestError, PrivateModeFieldRejectedError, NotFoundError, ConflictError, LinkLockedError, IdempotencyError, RateLimitError, ServerError, NetworkError, TimeoutError, SignatureVerificationError, ClikgateServerOnlyError, } from './errors.js';
21
+ export { VERSION } from './version.js';
@@ -0,0 +1,9 @@
1
+ /** A console-compatible logger. `warn` and `error` are required; `info` and `debug` are optional. */
2
+ export interface Logger {
3
+ warn(message: string, context?: Record<string, unknown>): void;
4
+ error(message: string, context?: Record<string, unknown>): void;
5
+ info?(message: string, context?: Record<string, unknown>): void;
6
+ debug?(message: string, context?: Record<string, unknown>): void;
7
+ }
8
+ /** Stable warning codes (SPEC section 15). */
9
+ export type WarningCode = 'inexact_number' | 'unknown_goal' | 'value_not_allowed' | 'value_required' | 'config_unavailable' | 'sdk_below_minimum_version' | 'queue_full_dropped' | 'unrecognised_payment_response';
@@ -0,0 +1,5 @@
1
+ /** @internal The default logger: warnings and errors to the console, prefixed. */
2
+ export const consoleLogger = {
3
+ warn: (message, context) => console.warn(`[clikgate] ${message}`, ...(context ? [context] : [])),
4
+ error: (message, context) => console.error(`[clikgate] ${message}`, ...(context ? [context] : [])),
5
+ };
@@ -0,0 +1,16 @@
1
+ /** A money amount in normal units (₦2,000,000 is `2000000`). Prefer a decimal string for exact values. */
2
+ export type MoneyInput = string | number | bigint;
3
+ /**
4
+ * Format a money value for the wire: always a plain decimal string (SPEC section 8).
5
+ *
6
+ * - strings are trimmed and must look like `2000000` or `1500.50` (no signs, exponents or separators);
7
+ * - integers and bigints are sent as their digits;
8
+ * - non-integer numbers are sent as their shortest decimal form, with an `inexact_number` warning.
9
+ *
10
+ * @throws {InvalidRequestError} code `invalid_value` for anything else.
11
+ * @example
12
+ * formatValue('1500.50'); // '1500.50'
13
+ * formatValue(2_000_000); // '2000000'
14
+ * formatValue(10n ** 18n); // '1000000000000000000'
15
+ */
16
+ export declare function formatValue(value: MoneyInput, warn?: InexactWarn): string;
@@ -0,0 +1,48 @@
1
+ import { localError } from './errors.js';
2
+ const DECIMAL = /^[0-9]+(\.[0-9]+)?$/;
3
+ function plain(n) {
4
+ const s = String(n);
5
+ if (!/e/i.test(s))
6
+ return s;
7
+ if (Number.isInteger(n))
8
+ return BigInt(n).toString();
9
+ return n.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
10
+ }
11
+ /**
12
+ * Format a money value for the wire: always a plain decimal string (SPEC section 8).
13
+ *
14
+ * - strings are trimmed and must look like `2000000` or `1500.50` (no signs, exponents or separators);
15
+ * - integers and bigints are sent as their digits;
16
+ * - non-integer numbers are sent as their shortest decimal form, with an `inexact_number` warning.
17
+ *
18
+ * @throws {InvalidRequestError} code `invalid_value` for anything else.
19
+ * @example
20
+ * formatValue('1500.50'); // '1500.50'
21
+ * formatValue(2_000_000); // '2000000'
22
+ * formatValue(10n ** 18n); // '1000000000000000000'
23
+ */
24
+ export function formatValue(value, warn) {
25
+ const bad = (why) => localError('invalid_value', `value ${why}. Pass a decimal string in normal units, like '1500.50'.`, 'value');
26
+ if (typeof value === 'string') {
27
+ const s = value.trim();
28
+ if (!DECIMAL.test(s))
29
+ throw bad('must be a non-negative decimal number');
30
+ return s;
31
+ }
32
+ if (typeof value === 'bigint') {
33
+ if (value < 0n)
34
+ throw bad('must not be negative');
35
+ return value.toString();
36
+ }
37
+ if (typeof value === 'number') {
38
+ if (!Number.isFinite(value))
39
+ throw bad('must be a finite number');
40
+ if (value < 0)
41
+ throw bad('must not be negative');
42
+ if (Number.isSafeInteger(value))
43
+ return String(value);
44
+ warn?.(`value ${String(value)} is a floating-point number and may not be exact; pass a decimal string, like '1500.50', for exact values.`);
45
+ return plain(value);
46
+ }
47
+ throw bad(`has unsupported type ${value === null ? 'null' : typeof value}`);
48
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Next.js add-on: keeps the click ID (SPEC section 17). Next.js 16 calls request middleware a
3
+ * "proxy" (`proxy.ts`, exporting `proxy`); `middleware.ts` still works but is deprecated.
4
+ *
5
+ * @example
6
+ * // proxy.ts (Next.js 16+)
7
+ * export { clikgateProxy as proxy } from '@clikgate/node/next';
8
+ * export const config = { matcher: ['/((?!_next/|api/webhooks/).*)'] };
9
+ *
10
+ * // app/signup/route.ts
11
+ * import { cookies } from 'next/headers';
12
+ * import { getClickId } from '@clikgate/node/next';
13
+ * const clickId = getClickId(await cookies());
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import { NextResponse, type NextRequest } from 'next/server.js';
18
+ import { type KeepRoute, type KeepRouteOptions, type PersistOptions } from './click-ids.js';
19
+ /** A cookie store: `request.cookies` or the awaited `cookies()` from `next/headers`. */
20
+ export interface CookieStoreLike {
21
+ get(name: string): {
22
+ value: string;
23
+ } | undefined;
24
+ }
25
+ /** Options for {@link createClikgateProxy}. */
26
+ export interface ClikgateProxyOptions extends PersistOptions {
27
+ /** The click-ID parameter (default `process.env.CLIKGATE_CLICK_ID_PARAM`, else `cgid`). */
28
+ clickIdParam?: string;
29
+ }
30
+ /**
31
+ * Add the click-ID cookie to an existing response when the request's query string carries a click ID.
32
+ * Use it inside your own proxy.
33
+ *
34
+ * @example
35
+ * export function proxy(request: NextRequest) {
36
+ * const response = NextResponse.next();
37
+ * applyClikgate(request, response);
38
+ * return response;
39
+ * }
40
+ */
41
+ export declare function applyClikgate(request: NextRequest, response: NextResponse, options?: ClikgateProxyOptions): string | null;
42
+ /**
43
+ * Build a proxy (or legacy middleware) function with options.
44
+ *
45
+ * @example
46
+ * export const proxy = createClikgateProxy({ days: 30, clickIdParam: 'ref' });
47
+ */
48
+ export declare function createClikgateProxy(options?: ClikgateProxyOptions): (request: NextRequest) => NextResponse;
49
+ /**
50
+ * The ready-made proxy for `proxy.ts`: stores a click ID from the query string in the `_cg_<param>` cookie.
51
+ *
52
+ * @example
53
+ * export { clikgateProxy as proxy } from '@clikgate/node/next';
54
+ */
55
+ export declare const clikgateProxy: (request: NextRequest) => NextResponse;
56
+ /**
57
+ * The same function for the deprecated `middleware.ts` (`export { clikgateMiddleware as middleware }`).
58
+ */
59
+ export declare const clikgateMiddleware: (request: NextRequest) => NextResponse;
60
+ /**
61
+ * Read the kept click ID from a cookie store, e.g. `getClickId(await cookies())` in a route handler or
62
+ * server action, or `getClickId(request.cookies)`.
63
+ *
64
+ * @example
65
+ * import { cookies } from 'next/headers';
66
+ * const clickId = getClickId(await cookies());
67
+ */
68
+ export declare function getClickId(store: CookieStoreLike, clickIdParam?: string): string | null;
69
+ /**
70
+ * The `/cg/keep` route handler without a client, using the same click-ID parameter as the proxy
71
+ * (`clickIdParam`, else `process.env.CLIKGATE_CLICK_ID_PARAM`, else `cgid`). With a client, use
72
+ * `clikgate.clickIds.keepRoute()` instead.
73
+ *
74
+ * @example
75
+ * // app/cg/keep/route.ts
76
+ * import { keepRoute } from '@clikgate/node/next';
77
+ * export const POST = keepRoute({ days: 90 });
78
+ */
79
+ export declare function keepRoute(options?: KeepRouteOptions & {
80
+ clickIdParam?: string;
81
+ }): KeepRoute;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Next.js add-on: keeps the click ID (SPEC section 17). Next.js 16 calls request middleware a
3
+ * "proxy" (`proxy.ts`, exporting `proxy`); `middleware.ts` still works but is deprecated.
4
+ *
5
+ * @example
6
+ * // proxy.ts (Next.js 16+)
7
+ * export { clikgateProxy as proxy } from '@clikgate/node/next';
8
+ * export const config = { matcher: ['/((?!_next/|api/webhooks/).*)'] };
9
+ *
10
+ * // app/signup/route.ts
11
+ * import { cookies } from 'next/headers';
12
+ * import { getClickId } from '@clikgate/node/next';
13
+ * const clickId = getClickId(await cookies());
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import { NextResponse } from 'next/server.js';
18
+ import { ClickIds, keptMarkerHeader } from './click-ids.js';
19
+ function helpersFor(param) {
20
+ const name = param ?? (typeof process !== 'undefined' ? process.env.CLIKGATE_CLICK_ID_PARAM : undefined) ?? 'cgid';
21
+ return new ClickIds(() => name);
22
+ }
23
+ /**
24
+ * Add the click-ID cookie to an existing response when the request's query string carries a click ID.
25
+ * Use it inside your own proxy.
26
+ *
27
+ * @example
28
+ * export function proxy(request: NextRequest) {
29
+ * const response = NextResponse.next();
30
+ * applyClikgate(request, response);
31
+ * return response;
32
+ * }
33
+ */
34
+ export function applyClikgate(request, response, options = {}) {
35
+ const { clickIdParam, ...cookie } = options;
36
+ const helpers = helpersFor(clickIdParam);
37
+ const fromQuery = request.nextUrl.searchParams.getAll(helpers.paramName).find((v) => helpers.isValid(v)) ?? null;
38
+ if (fromQuery) {
39
+ const secure = cookie.secure ?? request.nextUrl.protocol === 'https:';
40
+ response.headers.append('set-cookie', helpers.cookieHeader(fromQuery, { ...cookie, secure }));
41
+ response.headers.append('set-cookie', keptMarkerHeader({ ...cookie, secure }));
42
+ return fromQuery;
43
+ }
44
+ return helpers.fromRequest({ url: request.nextUrl.href, headers: request.headers });
45
+ }
46
+ /**
47
+ * Build a proxy (or legacy middleware) function with options.
48
+ *
49
+ * @example
50
+ * export const proxy = createClikgateProxy({ days: 30, clickIdParam: 'ref' });
51
+ */
52
+ export function createClikgateProxy(options = {}) {
53
+ return (request) => {
54
+ const response = NextResponse.next();
55
+ applyClikgate(request, response, options);
56
+ return response;
57
+ };
58
+ }
59
+ /**
60
+ * The ready-made proxy for `proxy.ts`: stores a click ID from the query string in the `_cg_<param>` cookie.
61
+ *
62
+ * @example
63
+ * export { clikgateProxy as proxy } from '@clikgate/node/next';
64
+ */
65
+ export const clikgateProxy = createClikgateProxy();
66
+ /**
67
+ * The same function for the deprecated `middleware.ts` (`export { clikgateMiddleware as middleware }`).
68
+ */
69
+ export const clikgateMiddleware = clikgateProxy;
70
+ /**
71
+ * Read the kept click ID from a cookie store, e.g. `getClickId(await cookies())` in a route handler or
72
+ * server action, or `getClickId(request.cookies)`.
73
+ *
74
+ * @example
75
+ * import { cookies } from 'next/headers';
76
+ * const clickId = getClickId(await cookies());
77
+ */
78
+ export function getClickId(store, clickIdParam) {
79
+ const helpers = helpersFor(clickIdParam);
80
+ const value = store.get(helpers.cookieName)?.value;
81
+ return helpers.isValid(value) ? value : null;
82
+ }
83
+ /**
84
+ * The `/cg/keep` route handler without a client, using the same click-ID parameter as the proxy
85
+ * (`clickIdParam`, else `process.env.CLIKGATE_CLICK_ID_PARAM`, else `cgid`). With a client, use
86
+ * `clikgate.clickIds.keepRoute()` instead.
87
+ *
88
+ * @example
89
+ * // app/cg/keep/route.ts
90
+ * import { keepRoute } from '@clikgate/node/next';
91
+ * export const POST = keepRoute({ days: 90 });
92
+ */
93
+ export function keepRoute(options = {}) {
94
+ const { clickIdParam, ...rest } = options;
95
+ return helpersFor(clickIdParam).keepRoute(rest);
96
+ }
@@ -0,0 +1 @@
1
+ {"type":"module"}