@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.
Files changed (119) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +311 -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 +191 -0
  10. package/dist/cjs/client.js +291 -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/customer-id.d.ts +26 -0
  16. package/dist/cjs/customer-id.js +52 -0
  17. package/dist/cjs/enums.d.ts +48 -0
  18. package/dist/cjs/enums.js +47 -0
  19. package/dist/cjs/errors.d.ts +117 -0
  20. package/dist/cjs/errors.js +257 -0
  21. package/dist/cjs/express.d.ts +49 -0
  22. package/dist/cjs/express.js +44 -0
  23. package/dist/cjs/fastify.d.ts +47 -0
  24. package/dist/cjs/fastify.js +35 -0
  25. package/dist/cjs/generated/index.d.ts +17793 -0
  26. package/dist/cjs/generated/index.js +8896 -0
  27. package/dist/cjs/goals.d.ts +116 -0
  28. package/dist/cjs/goals.js +381 -0
  29. package/dist/cjs/guard.d.ts +17 -0
  30. package/dist/cjs/guard.js +40 -0
  31. package/dist/cjs/http.d.ts +16 -0
  32. package/dist/cjs/http.js +148 -0
  33. package/dist/cjs/identity.d.ts +42 -0
  34. package/dist/cjs/identity.js +133 -0
  35. package/dist/cjs/index.d.ts +34 -0
  36. package/dist/cjs/index.js +70 -0
  37. package/dist/cjs/known-customers.d.ts +45 -0
  38. package/dist/cjs/known-customers.js +95 -0
  39. package/dist/cjs/logger.d.ts +9 -0
  40. package/dist/cjs/logger.js +8 -0
  41. package/dist/cjs/money.d.ts +16 -0
  42. package/dist/cjs/money.js +51 -0
  43. package/dist/cjs/next.d.ts +81 -0
  44. package/dist/cjs/next.js +103 -0
  45. package/dist/cjs/package.json +1 -0
  46. package/dist/cjs/payments.d.ts +174 -0
  47. package/dist/cjs/payments.js +485 -0
  48. package/dist/cjs/resources.d.ts +109 -0
  49. package/dist/cjs/resources.js +189 -0
  50. package/dist/cjs/shutdown.d.ts +2 -0
  51. package/dist/cjs/shutdown.js +51 -0
  52. package/dist/cjs/transport.d.ts +14 -0
  53. package/dist/cjs/transport.js +204 -0
  54. package/dist/cjs/types.d.ts +218 -0
  55. package/dist/cjs/types.js +2 -0
  56. package/dist/cjs/user-agent.d.ts +1 -0
  57. package/dist/cjs/user-agent.js +53 -0
  58. package/dist/cjs/version.d.ts +2 -0
  59. package/dist/cjs/version.js +5 -0
  60. package/dist/cjs/webhooks.d.ts +36 -0
  61. package/dist/cjs/webhooks.js +108 -0
  62. package/dist/esm/ads-hashing.d.ts +37 -0
  63. package/dist/esm/ads-hashing.js +62 -0
  64. package/dist/esm/click-ids.d.ts +184 -0
  65. package/dist/esm/click-ids.js +526 -0
  66. package/dist/esm/client.d.ts +191 -0
  67. package/dist/esm/client.js +287 -0
  68. package/dist/esm/config.d.ts +12 -0
  69. package/dist/esm/config.js +82 -0
  70. package/dist/esm/core.d.ts +15 -0
  71. package/dist/esm/core.js +96 -0
  72. package/dist/esm/customer-id.d.ts +26 -0
  73. package/dist/esm/customer-id.js +47 -0
  74. package/dist/esm/enums.d.ts +48 -0
  75. package/dist/esm/enums.js +44 -0
  76. package/dist/esm/errors.d.ts +117 -0
  77. package/dist/esm/errors.js +234 -0
  78. package/dist/esm/express.d.ts +49 -0
  79. package/dist/esm/express.js +40 -0
  80. package/dist/esm/fastify.d.ts +47 -0
  81. package/dist/esm/fastify.js +32 -0
  82. package/dist/esm/generated/index.d.ts +17793 -0
  83. package/dist/esm/generated/index.js +8833 -0
  84. package/dist/esm/goals.d.ts +116 -0
  85. package/dist/esm/goals.js +371 -0
  86. package/dist/esm/guard.d.ts +17 -0
  87. package/dist/esm/guard.js +36 -0
  88. package/dist/esm/http.d.ts +16 -0
  89. package/dist/esm/http.js +138 -0
  90. package/dist/esm/identity.d.ts +42 -0
  91. package/dist/esm/identity.js +125 -0
  92. package/dist/esm/index.d.ts +34 -0
  93. package/dist/esm/index.js +23 -0
  94. package/dist/esm/known-customers.d.ts +45 -0
  95. package/dist/esm/known-customers.js +90 -0
  96. package/dist/esm/logger.d.ts +9 -0
  97. package/dist/esm/logger.js +5 -0
  98. package/dist/esm/money.d.ts +16 -0
  99. package/dist/esm/money.js +48 -0
  100. package/dist/esm/next.d.ts +81 -0
  101. package/dist/esm/next.js +96 -0
  102. package/dist/esm/package.json +1 -0
  103. package/dist/esm/payments.d.ts +174 -0
  104. package/dist/esm/payments.js +476 -0
  105. package/dist/esm/resources.d.ts +109 -0
  106. package/dist/esm/resources.js +183 -0
  107. package/dist/esm/shutdown.d.ts +2 -0
  108. package/dist/esm/shutdown.js +47 -0
  109. package/dist/esm/transport.d.ts +14 -0
  110. package/dist/esm/transport.js +166 -0
  111. package/dist/esm/types.d.ts +218 -0
  112. package/dist/esm/types.js +1 -0
  113. package/dist/esm/user-agent.d.ts +1 -0
  114. package/dist/esm/user-agent.js +16 -0
  115. package/dist/esm/version.d.ts +2 -0
  116. package/dist/esm/version.js +2 -0
  117. package/dist/esm/webhooks.d.ts +36 -0
  118. package/dist/esm/webhooks.js +105 -0
  119. package/package.json +128 -4
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Requester = exports.systemClock = void 0;
4
+ exports.encodePathSegment = encodePathSegment;
5
+ exports.formatDate = formatDate;
6
+ exports.queryString = queryString;
7
+ exports.toJson = toJson;
8
+ exports.isRetryable = isRetryable;
9
+ exports.requireId = requireId;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const errors_js_1 = require("./errors.js");
12
+ /** @internal The default clock. */
13
+ exports.systemClock = {
14
+ now: () => Date.now(),
15
+ sleep: (ms) => new Promise((resolve) => {
16
+ setTimeout(resolve, ms);
17
+ }),
18
+ };
19
+ const BACKOFF_BASE_MS = 500;
20
+ const BACKOFF_CAP_MS = 20_000;
21
+ const MAX_RETRY_AFTER_MS = 60_000;
22
+ const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
23
+ /** @internal Encode one path segment (RFC 3986 unreserved characters kept). */
24
+ function encodePathSegment(s) {
25
+ return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
26
+ }
27
+ /** @internal Format a Date (or pass a string through) as RFC 3339 UTC (SPEC section 4). */
28
+ function formatDate(d) {
29
+ if (typeof d === 'string')
30
+ return d;
31
+ const iso = d.toISOString();
32
+ return iso.endsWith('.000Z') ? `${iso.slice(0, -5)}Z` : iso;
33
+ }
34
+ function isPlainObject(v) {
35
+ return typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date);
36
+ }
37
+ /** @internal Exported for tests. */
38
+ function queryString(query) {
39
+ if (!query)
40
+ return '';
41
+ const parts = [];
42
+ const add = (k, v) => {
43
+ if (v === undefined || v === null)
44
+ return;
45
+ const s = v instanceof Date ? formatDate(v) : typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v);
46
+ parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(s)}`);
47
+ };
48
+ for (const [k, v] of Object.entries(query)) {
49
+ if (Array.isArray(v))
50
+ v.forEach((item) => add(k, item));
51
+ else if (isPlainObject(v)) {
52
+ // A map (e.g. `metadata: { seller_id: 'sel_ada' }`) is sent as `metadata[seller_id]=sel_ada` (SPEC section 21).
53
+ for (const [sub, sv] of Object.entries(v))
54
+ add(`${k}[${sub}]`, sv);
55
+ }
56
+ else
57
+ add(k, v);
58
+ }
59
+ return parts.length ? `?${parts.join('&')}` : '';
60
+ }
61
+ /** @internal JSON body: drops `undefined`, keeps explicit `null`, formats Dates and bigints. */
62
+ function toJson(body) {
63
+ return JSON.stringify(body, (_k, v) => {
64
+ if (typeof v === 'bigint')
65
+ return v.toString();
66
+ return v;
67
+ });
68
+ }
69
+ /** @internal The one HTTP pipeline every call (hand-written and generated) goes through. */
70
+ class Requester {
71
+ s;
72
+ constructor(s) {
73
+ this.s = s;
74
+ }
75
+ /** Full-jitter backoff for retry number `n` (0-based). */
76
+ backoffMs(n) {
77
+ return Math.floor(this.s.random() * Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** n));
78
+ }
79
+ /** Send a JSON request and parse the JSON answer (`null` for an empty body). */
80
+ async request(req) {
81
+ const res = await this.send(req);
82
+ const text = new TextDecoder().decode(res.body);
83
+ const data = (text.trim() ? JSON.parse(text) : null);
84
+ return { status: res.status, data, headers: res.headers };
85
+ }
86
+ /** Send a request; resolves with the 2xx response or throws a typed error (after retries). */
87
+ async send(req) {
88
+ const url = `${this.s.baseUrl}${req.path}${queryString(req.query)}`;
89
+ const headers = {
90
+ authorization: `Bearer ${this.s.apiKey}`,
91
+ 'user-agent': this.s.userAgent,
92
+ accept: 'application/json',
93
+ };
94
+ let body;
95
+ if (req.body !== undefined) {
96
+ body = new TextEncoder().encode(toJson(req.body));
97
+ headers['content-type'] = 'application/json';
98
+ }
99
+ if (req.method === 'POST' || req.method === 'PATCH')
100
+ headers['idempotency-key'] = req.idempotencyKey ?? (0, node_crypto_1.randomUUID)();
101
+ const maxRetries = req.maxRetries ?? this.s.maxRetries;
102
+ const timeoutMs = req.timeout ?? this.s.timeoutMs;
103
+ for (let attempt = 0;; attempt++) {
104
+ let error;
105
+ let res;
106
+ try {
107
+ res = await this.s.transport({ method: req.method, url, headers, body, timeoutMs });
108
+ }
109
+ catch (err) {
110
+ error = err instanceof errors_js_1.ClikgateError ? err : new errors_js_1.NetworkError({ message: 'Could not reach the Clikgate API.', code: 'network_error' });
111
+ if (attempt >= maxRetries)
112
+ throw error;
113
+ await this.s.clock.sleep(this.backoffMs(attempt));
114
+ continue;
115
+ }
116
+ if (res.status >= 200 && res.status < 300)
117
+ return res;
118
+ error = (0, errors_js_1.errorFromResponse)(res.status, res.headers, res.body, this.s.clock.now());
119
+ if (!RETRYABLE_STATUS.has(res.status))
120
+ throw error;
121
+ let delay = this.backoffMs(attempt);
122
+ if (res.status === 429 || res.status === 503) {
123
+ const ra = (0, errors_js_1.retryAfterMs)(res.headers, this.s.clock.now());
124
+ if (ra !== null) {
125
+ if (ra > MAX_RETRY_AFTER_MS)
126
+ throw error;
127
+ delay = ra;
128
+ }
129
+ }
130
+ if (attempt >= maxRetries)
131
+ throw error;
132
+ await this.s.clock.sleep(delay);
133
+ }
134
+ }
135
+ }
136
+ exports.Requester = Requester;
137
+ /** @internal True when the error class is retryable at the batch level (SPEC 9.3). */
138
+ function isRetryable(err) {
139
+ if (err instanceof errors_js_1.NetworkError || err instanceof errors_js_1.TimeoutError || err instanceof errors_js_1.RateLimitError)
140
+ return true;
141
+ return err instanceof errors_js_1.ServerError && err.httpStatus !== null && RETRYABLE_STATUS.has(err.httpStatus);
142
+ }
143
+ /** @internal Require a non-empty id argument. */
144
+ function requireId(id, name = 'id') {
145
+ if (typeof id !== 'string' || id.length === 0)
146
+ throw (0, errors_js_1.localError)('invalid_argument', `${name} must be a non-empty string.`, name);
147
+ return id;
148
+ }
@@ -0,0 +1,42 @@
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. With `customerSince` the token is version 2 and also carries the date the
7
+ * person became your customer: `signature.issuedAt.customerSince`. No network call.
8
+ * Guide: https://clikgate.com/docs/identify-users
9
+ */
10
+ export interface IdentityTokenOptions {
11
+ /** The Clikgate app ID (`app_…`). Picks that app's secret from `identitySecrets` / `CLIKGATE_IDENTITY_SECRETS`. */
12
+ appId?: string | null;
13
+ /** The identity secret to sign with. Default: the app's secret from the map, else `CLIKGATE_IDENTITY_SECRET`. */
14
+ secret?: string | null;
15
+ /** Unix seconds the token was issued at. Default: now. */
16
+ issuedAt?: number;
17
+ /**
18
+ * When this person became your customer (their account's creation time): a `Date` or Unix seconds. Makes a version 2
19
+ * token, so Clikgate can tell an existing customer from a new one (referrals, new customers). Not in private mode.
20
+ */
21
+ customerSince?: Date | number | null;
22
+ }
23
+ /** The single secret's environment variable. */
24
+ export declare const IDENTITY_SECRET_ENV = "CLIKGATE_IDENTITY_SECRET";
25
+ /** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
26
+ export declare const IDENTITY_SECRETS_ENV = "CLIKGATE_IDENTITY_SECRETS";
27
+ /**
28
+ * Create an identity token for the signed-in user. Return it in your sign-in and "current user"
29
+ * responses; the app passes it to `identifyUser()`. Reads `CLIKGATE_IDENTITY_SECRET`, or with `appId` the app's
30
+ * secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
31
+ *
32
+ * Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
33
+ * `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID, and `InvalidRequestError`
34
+ * (`invalid_argument`, param `customer_since`) for an account date before 1990 or after the token's issue time.
35
+ *
36
+ * @example
37
+ * import { createIdentityToken } from '@clikgate/node';
38
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
39
+ * // With the account date (version 2), so existing customers are never counted as referrals or new customers:
40
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) });
41
+ */
42
+ export declare function createIdentityToken(customerId: string, options?: IdentityTokenOptions): string;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IDENTITY_SECRETS_ENV = exports.IDENTITY_SECRET_ENV = void 0;
4
+ exports.isBrowserOrMobile = isBrowserOrMobile;
5
+ exports.signIdentityToken = signIdentityToken;
6
+ exports.signIdentityTokenV2 = signIdentityTokenV2;
7
+ exports.createIdentityTokenWith = createIdentityTokenWith;
8
+ exports.createIdentityToken = createIdentityToken;
9
+ const node_crypto_1 = require("node:crypto");
10
+ const customer_id_js_1 = require("./customer-id.js");
11
+ const errors_js_1 = require("./errors.js");
12
+ /** The single secret's environment variable. */
13
+ exports.IDENTITY_SECRET_ENV = 'CLIKGATE_IDENTITY_SECRET';
14
+ /** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
15
+ exports.IDENTITY_SECRETS_ENV = 'CLIKGATE_IDENTITY_SECRETS';
16
+ const MAX_CUSTOMER_ID = 255;
17
+ /** 1990-01-01: earlier account dates are refused. */
18
+ const MIN_CUSTOMER_SINCE = 631_152_000;
19
+ /** The clock allowance for an account date after `issuedAt`. */
20
+ const CLOCK_ALLOWANCE = 300;
21
+ /** @internal True in a browser (window or document) or React Native. */
22
+ function isBrowserOrMobile(g = globalThis) {
23
+ if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined')
24
+ return true;
25
+ const nav = g.navigator;
26
+ return typeof nav === 'object' && nav !== null && nav.product === 'ReactNative';
27
+ }
28
+ function serverOnly() {
29
+ throw new errors_js_1.ClikgateServerOnlyError({
30
+ 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',
31
+ code: 'server_only',
32
+ });
33
+ }
34
+ function envMap() {
35
+ const raw = process.env[exports.IDENTITY_SECRETS_ENV];
36
+ if (raw === undefined || raw.trim() === '')
37
+ return null;
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(raw);
41
+ }
42
+ catch {
43
+ parsed = null;
44
+ }
45
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === 'string' && v !== '')) {
46
+ // Never echo the value: it holds secrets.
47
+ throw new errors_js_1.ConfigurationError({ message: `${exports.IDENTITY_SECRETS_ENV} must be a JSON object of app IDs to identity secrets, e.g. {"app_…": "cgis_…"}.`, code: 'invalid_identity_secrets', param: exports.IDENTITY_SECRETS_ENV });
48
+ }
49
+ return parsed;
50
+ }
51
+ function resolveSecret(options, source) {
52
+ if (options.secret != null && options.secret !== '')
53
+ return options.secret;
54
+ const appId = options.appId ?? null;
55
+ const map = source.identitySecrets ?? envMap();
56
+ if (appId !== null && map && Object.prototype.hasOwnProperty.call(map, appId) && map[appId])
57
+ return map[appId];
58
+ const single = source.identitySecret || process.env[exports.IDENTITY_SECRET_ENV] || null;
59
+ if (single)
60
+ return single;
61
+ if (appId === null && map && Object.keys(map).length > 0) {
62
+ throw new errors_js_1.ConfigurationError({ message: `Several apps' identity secrets are set (${exports.IDENTITY_SECRETS_ENV}): pass { appId } to choose one.`, code: 'missing_identity_secret', param: 'appId' });
63
+ }
64
+ throw new errors_js_1.ConfigurationError({
65
+ message: appId === null
66
+ ? `No identity secret: set ${exports.IDENTITY_SECRET_ENV} on your server (Apps › your app › Identity secret).`
67
+ : `No identity secret for this app: add it to ${exports.IDENTITY_SECRETS_ENV} or set ${exports.IDENTITY_SECRET_ENV}.`,
68
+ code: 'missing_identity_secret',
69
+ param: 'secret',
70
+ });
71
+ }
72
+ /** @internal */
73
+ function signIdentityToken(secret, customerId, issuedAt) {
74
+ const sig = (0, node_crypto_1.createHmac)('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(`${customerId}.${issuedAt}`, 'utf8')).digest('base64url');
75
+ return `${sig}.${issuedAt}`;
76
+ }
77
+ /**
78
+ * @internal Version 2: the MAC input is
79
+ * `"v2\n" + utf8Length(cid) + ":" + cid + "\n" + issuedAt + "\n" + customerSince`, cid in canonical form.
80
+ */
81
+ function signIdentityTokenV2(secret, customerId, issuedAt, customerSince) {
82
+ const cid = (0, customer_id_js_1.canonicalCustomerId)(customerId);
83
+ const msg = `v2\n${Buffer.byteLength(cid, 'utf8')}:${cid}\n${issuedAt}\n${customerSince}`;
84
+ const sig = (0, node_crypto_1.createHmac)('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(msg, 'utf8')).digest('base64url');
85
+ return `${sig}.${issuedAt}.${customerSince}`;
86
+ }
87
+ function sinceSeconds(value) {
88
+ const s = value instanceof Date ? Math.floor(value.getTime() / 1000) : value;
89
+ if (typeof s !== 'number' || !Number.isSafeInteger(s))
90
+ throw (0, errors_js_1.localError)('invalid_argument', 'customerSince must be a Date or whole Unix seconds.', 'customer_since');
91
+ return s;
92
+ }
93
+ /** @internal createIdentityToken with an explicit secret source (the client's options). */
94
+ function createIdentityTokenWith(source, customerId, options = {}) {
95
+ if (isBrowserOrMobile())
96
+ serverOnly();
97
+ if (typeof customerId !== 'string' || customerId === '' || [...customerId].length > MAX_CUSTOMER_ID) {
98
+ // Never echo the customer ID.
99
+ throw (0, errors_js_1.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');
100
+ }
101
+ const o = options ?? {};
102
+ const issuedAt = o.issuedAt ?? Math.floor(Date.now() / 1000);
103
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
104
+ throw (0, errors_js_1.localError)('invalid_argument', 'issuedAt must be whole Unix seconds.', 'issued_at');
105
+ if (o.customerSince == null)
106
+ return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
107
+ const since = sinceSeconds(o.customerSince);
108
+ if (since < MIN_CUSTOMER_SINCE || since > issuedAt + CLOCK_ALLOWANCE) {
109
+ throw (0, errors_js_1.localError)('invalid_argument', 'customerSince must be between 1990 and the time the token is issued.', 'customer_since');
110
+ }
111
+ const cid = (0, customer_id_js_1.canonicalCustomerId)(customerId);
112
+ if (cid === '')
113
+ throw (0, errors_js_1.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');
114
+ return signIdentityTokenV2(resolveSecret(o, source), cid, issuedAt, since);
115
+ }
116
+ /**
117
+ * Create an identity token for the signed-in user. Return it in your sign-in and "current user"
118
+ * responses; the app passes it to `identifyUser()`. Reads `CLIKGATE_IDENTITY_SECRET`, or with `appId` the app's
119
+ * secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
120
+ *
121
+ * Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
122
+ * `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID, and `InvalidRequestError`
123
+ * (`invalid_argument`, param `customer_since`) for an account date before 1990 or after the token's issue time.
124
+ *
125
+ * @example
126
+ * import { createIdentityToken } from '@clikgate/node';
127
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
128
+ * // With the account date (version 2), so existing customers are never counted as referrals or new customers:
129
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) });
130
+ */
131
+ function createIdentityToken(customerId, options = {}) {
132
+ return createIdentityTokenWith({}, customerId, options);
133
+ }
@@ -0,0 +1,34 @@
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 { canonicalCustomerId, customerIdWarning, CUSTOMER_ID_MAX_LENGTH, type CustomerIdWarning } from './customer-id.js';
16
+ export { KNOWN_CUSTOMERS_BATCH, type KnownCustomers, type KnownCustomer, type KnownCustomerRefusal, type KnownCustomersImportResult } from './known-customers.js';
17
+ export { createIdentityToken, IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV, type IdentityTokenOptions } from './identity.js';
18
+ export { formatValue, type MoneyInput } from './money.js';
19
+ export { hashForAds, type HashForAdsInput, type HashedIdentifiers } from './ads-hashing.js';
20
+ export { GoalKind, GoalStatus, Provider } from './enums.js';
21
+ export type { GoalOptions, GoalBatchEvent, ReverseOptions } from './goals.js';
22
+ export type { ErrorContext, OnError } from './core.js';
23
+ export type { Logger, WarningCode } from './logger.js';
24
+ export type { Clock, RequestOptions } from './http.js';
25
+ export type { FetchLike } from './transport.js';
26
+ export type { QrOptions, LinkIterator, Conversions, Links, Clicks } from './resources.js';
27
+ export type { Goals } from './goals.js';
28
+ export { buildFromPaystack, buildFromFlutterwave, buildFromMonnify, buildFromStripe, type Payments, type PaymentStatus, type PaymentConfirmParams, type PaymentConfirmation, type PaymentConfirmationBody, type PaymentHelperOptions, } from './payments.js';
29
+ export type { GoalEvent, GoalAttribution, GoalPayment, GoalBatchItem, GoalBatchResult, Link, LinkWarning, LinkChangeRequest, LinkUpdateResult, Click, Conversion, ListPage, ServerSdkConfig, ConfigGoal, WebhookEvent, QrCode, } from './types.js';
30
+ export { ClikgateError, ConfigurationError, AuthenticationError, PermissionError, InvalidRequestError, PrivateModeFieldRejectedError, NotFoundError, ConflictError, LinkLockedError, IdempotencyError, RateLimitError, ServerError, NetworkError, TimeoutError, SignatureVerificationError, ClikgateServerOnlyError, type KnownErrorCode, } from './errors.js';
31
+ export { VERSION } from './version.js';
32
+ /** Types of the generated `clikgate.api.*` layer (request bodies and responses, as in openapi.json). */
33
+ export type * as ApiTypes from './generated/index.js';
34
+ export type { ApiClient } from './generated/index.js';
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = exports.ClikgateServerOnlyError = exports.SignatureVerificationError = exports.TimeoutError = exports.NetworkError = exports.ServerError = exports.RateLimitError = exports.IdempotencyError = exports.LinkLockedError = exports.ConflictError = exports.NotFoundError = exports.PrivateModeFieldRejectedError = exports.InvalidRequestError = exports.PermissionError = exports.AuthenticationError = exports.ConfigurationError = exports.ClikgateError = exports.buildFromStripe = exports.buildFromMonnify = exports.buildFromFlutterwave = exports.buildFromPaystack = exports.Provider = exports.GoalStatus = exports.GoalKind = exports.hashForAds = exports.formatValue = exports.IDENTITY_SECRETS_ENV = exports.IDENTITY_SECRET_ENV = exports.createIdentityToken = exports.KNOWN_CUSTOMERS_BATCH = exports.CUSTOMER_ID_MAX_LENGTH = exports.customerIdWarning = exports.canonicalCustomerId = exports.webhooks = exports.PLATFORMS = exports.BROWSER_ENGINES = exports.KEPT_BY = exports.KEPT_COOKIE = exports.CLICK_ID_HEADER = exports.CLICK_ID_PATTERN = exports.isValidClickId = exports.clickIds = exports.ClickIds = exports.Clikgate = void 0;
4
+ /**
5
+ * The official Clikgate server SDK for Node.js and TypeScript.
6
+ *
7
+ * @example
8
+ * import { Clikgate, Provider } from '@clikgate/node';
9
+ * const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY
10
+ * clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
11
+ * clikgate.goal('order_paid', { clickId, reference: 'T123456', provider: Provider.Paystack, value: '7500' }); // a Payment goal
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ var client_js_1 = require("./client.js");
16
+ Object.defineProperty(exports, "Clikgate", { enumerable: true, get: function () { return client_js_1.Clikgate; } });
17
+ var click_ids_js_1 = require("./click-ids.js");
18
+ Object.defineProperty(exports, "ClickIds", { enumerable: true, get: function () { return click_ids_js_1.ClickIds; } });
19
+ Object.defineProperty(exports, "clickIds", { enumerable: true, get: function () { return click_ids_js_1.clickIds; } });
20
+ Object.defineProperty(exports, "isValidClickId", { enumerable: true, get: function () { return click_ids_js_1.isValid; } });
21
+ Object.defineProperty(exports, "CLICK_ID_PATTERN", { enumerable: true, get: function () { return click_ids_js_1.CLICK_ID_PATTERN; } });
22
+ Object.defineProperty(exports, "CLICK_ID_HEADER", { enumerable: true, get: function () { return click_ids_js_1.CLICK_ID_HEADER; } });
23
+ Object.defineProperty(exports, "KEPT_COOKIE", { enumerable: true, get: function () { return click_ids_js_1.KEPT_COOKIE; } });
24
+ Object.defineProperty(exports, "KEPT_BY", { enumerable: true, get: function () { return click_ids_js_1.KEPT_BY; } });
25
+ Object.defineProperty(exports, "BROWSER_ENGINES", { enumerable: true, get: function () { return click_ids_js_1.BROWSER_ENGINES; } });
26
+ Object.defineProperty(exports, "PLATFORMS", { enumerable: true, get: function () { return click_ids_js_1.PLATFORMS; } });
27
+ var webhooks_js_1 = require("./webhooks.js");
28
+ Object.defineProperty(exports, "webhooks", { enumerable: true, get: function () { return webhooks_js_1.webhooks; } });
29
+ var customer_id_js_1 = require("./customer-id.js");
30
+ Object.defineProperty(exports, "canonicalCustomerId", { enumerable: true, get: function () { return customer_id_js_1.canonicalCustomerId; } });
31
+ Object.defineProperty(exports, "customerIdWarning", { enumerable: true, get: function () { return customer_id_js_1.customerIdWarning; } });
32
+ Object.defineProperty(exports, "CUSTOMER_ID_MAX_LENGTH", { enumerable: true, get: function () { return customer_id_js_1.CUSTOMER_ID_MAX_LENGTH; } });
33
+ var known_customers_js_1 = require("./known-customers.js");
34
+ Object.defineProperty(exports, "KNOWN_CUSTOMERS_BATCH", { enumerable: true, get: function () { return known_customers_js_1.KNOWN_CUSTOMERS_BATCH; } });
35
+ var identity_js_1 = require("./identity.js");
36
+ Object.defineProperty(exports, "createIdentityToken", { enumerable: true, get: function () { return identity_js_1.createIdentityToken; } });
37
+ Object.defineProperty(exports, "IDENTITY_SECRET_ENV", { enumerable: true, get: function () { return identity_js_1.IDENTITY_SECRET_ENV; } });
38
+ Object.defineProperty(exports, "IDENTITY_SECRETS_ENV", { enumerable: true, get: function () { return identity_js_1.IDENTITY_SECRETS_ENV; } });
39
+ var money_js_1 = require("./money.js");
40
+ Object.defineProperty(exports, "formatValue", { enumerable: true, get: function () { return money_js_1.formatValue; } });
41
+ var ads_hashing_js_1 = require("./ads-hashing.js");
42
+ Object.defineProperty(exports, "hashForAds", { enumerable: true, get: function () { return ads_hashing_js_1.hashForAds; } });
43
+ var enums_js_1 = require("./enums.js");
44
+ Object.defineProperty(exports, "GoalKind", { enumerable: true, get: function () { return enums_js_1.GoalKind; } });
45
+ Object.defineProperty(exports, "GoalStatus", { enumerable: true, get: function () { return enums_js_1.GoalStatus; } });
46
+ Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return enums_js_1.Provider; } });
47
+ var payments_js_1 = require("./payments.js");
48
+ Object.defineProperty(exports, "buildFromPaystack", { enumerable: true, get: function () { return payments_js_1.buildFromPaystack; } });
49
+ Object.defineProperty(exports, "buildFromFlutterwave", { enumerable: true, get: function () { return payments_js_1.buildFromFlutterwave; } });
50
+ Object.defineProperty(exports, "buildFromMonnify", { enumerable: true, get: function () { return payments_js_1.buildFromMonnify; } });
51
+ Object.defineProperty(exports, "buildFromStripe", { enumerable: true, get: function () { return payments_js_1.buildFromStripe; } });
52
+ var errors_js_1 = require("./errors.js");
53
+ Object.defineProperty(exports, "ClikgateError", { enumerable: true, get: function () { return errors_js_1.ClikgateError; } });
54
+ Object.defineProperty(exports, "ConfigurationError", { enumerable: true, get: function () { return errors_js_1.ConfigurationError; } });
55
+ Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
56
+ Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
57
+ Object.defineProperty(exports, "InvalidRequestError", { enumerable: true, get: function () { return errors_js_1.InvalidRequestError; } });
58
+ Object.defineProperty(exports, "PrivateModeFieldRejectedError", { enumerable: true, get: function () { return errors_js_1.PrivateModeFieldRejectedError; } });
59
+ Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
60
+ Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
61
+ Object.defineProperty(exports, "LinkLockedError", { enumerable: true, get: function () { return errors_js_1.LinkLockedError; } });
62
+ Object.defineProperty(exports, "IdempotencyError", { enumerable: true, get: function () { return errors_js_1.IdempotencyError; } });
63
+ Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
64
+ Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_js_1.ServerError; } });
65
+ Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return errors_js_1.NetworkError; } });
66
+ Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_js_1.TimeoutError; } });
67
+ Object.defineProperty(exports, "SignatureVerificationError", { enumerable: true, get: function () { return errors_js_1.SignatureVerificationError; } });
68
+ Object.defineProperty(exports, "ClikgateServerOnlyError", { enumerable: true, get: function () { return errors_js_1.ClikgateServerOnlyError; } });
69
+ var version_js_1 = require("./version.js");
70
+ Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_js_1.VERSION; } });
@@ -0,0 +1,45 @@
1
+ import type { RequestOptions } from './http.js';
2
+ /**
3
+ * Known customers: people who were already your customers before you added Clikgate. Clikgate uses
4
+ * them so an existing customer is never counted as a referral or a new customer. It stores a keyed fingerprint of
5
+ * each ID, not the ID itself. Not available in private mode.
6
+ */
7
+ /** One existing customer: your customer ID and, optionally, when they became a customer. */
8
+ export interface KnownCustomer {
9
+ customerId: string;
10
+ /** When they became a customer: `'YYYY-MM-DD'`, a `Date` or Unix seconds. Only the UTC day is sent. */
11
+ customerSince?: string | Date | number | null;
12
+ }
13
+ /** Why rows were refused. Counts only: the API never returns the refused IDs. */
14
+ export type KnownCustomerRefusal = 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | 'empty' | 'too_long' | 'bad_date' | 'date_out_of_range';
15
+ /** The answer of `knownCustomers.import()`, summed over every batch. */
16
+ export interface KnownCustomersImportResult {
17
+ accepted: number;
18
+ refused: number;
19
+ refused_by_reason: Partial<Record<KnownCustomerRefusal | string, number>>;
20
+ }
21
+ /** The API's batch size; `import()` splits larger lists. */
22
+ export declare const KNOWN_CUSTOMERS_BATCH = 10000;
23
+ /** `clikgate.knownCustomers`: import and remove existing customers (scope `people:write`). */
24
+ export declare class KnownCustomers {
25
+ private readonly core;
26
+ /**
27
+ * Import existing customers (`POST /v1/known-customers/import`), in batches of 10,000. Idempotent per customer ID.
28
+ * Use your own customer IDs, never emails or phone numbers. The result sums every batch; refused rows are counted
29
+ * by reason, never returned.
30
+ *
31
+ * @example
32
+ * const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]);
33
+ * console.log(result.accepted, result.refused_by_reason);
34
+ */
35
+ import(customers: readonly KnownCustomer[], requestOptions?: RequestOptions): Promise<KnownCustomersImportResult>;
36
+ /**
37
+ * Remove one imported customer (`POST /v1/known-customers/remove`; the ID travels in the body, never in a URL).
38
+ *
39
+ * @example
40
+ * const { removed } = await clikgate.knownCustomers.remove('u_10482');
41
+ */
42
+ remove(customerId: string, requestOptions?: RequestOptions): Promise<{
43
+ removed: boolean;
44
+ }>;
45
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KnownCustomers = exports.KNOWN_CUSTOMERS_BATCH = void 0;
4
+ exports.sinceDay = sinceDay;
5
+ const errors_js_1 = require("./errors.js");
6
+ /** The API's batch size; `import()` splits larger lists. */
7
+ exports.KNOWN_CUSTOMERS_BATCH = 10_000;
8
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
9
+ /** @internal The UTC day `YYYY-MM-DD` of a customerSince value. */
10
+ function sinceDay(value) {
11
+ if (typeof value === 'string') {
12
+ if (!DAY.test(value))
13
+ throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
14
+ return value;
15
+ }
16
+ const ms = typeof value === 'number' ? value * 1000 : value instanceof Date ? value.getTime() : Number.NaN;
17
+ if (!Number.isFinite(ms) || (typeof value === 'number' && !Number.isSafeInteger(value))) {
18
+ throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
19
+ }
20
+ return new Date(ms).toISOString().slice(0, 10);
21
+ }
22
+ function privateModeConflict() {
23
+ return new errors_js_1.ConflictError({
24
+ message: "Private mode is on: known customers can't be imported or removed.",
25
+ code: 'private_mode_conflict',
26
+ httpStatus: null,
27
+ });
28
+ }
29
+ /** `clikgate.knownCustomers`: import and remove existing customers (scope `people:write`). */
30
+ class KnownCustomers {
31
+ core;
32
+ /** @internal */
33
+ constructor(core) {
34
+ this.core = core;
35
+ }
36
+ /**
37
+ * Import existing customers (`POST /v1/known-customers/import`), in batches of 10,000. Idempotent per customer ID.
38
+ * Use your own customer IDs, never emails or phone numbers. The result sums every batch; refused rows are counted
39
+ * by reason, never returned.
40
+ *
41
+ * @example
42
+ * const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]);
43
+ * console.log(result.accepted, result.refused_by_reason);
44
+ */
45
+ async import(customers, requestOptions = {}) {
46
+ if (!Array.isArray(customers))
47
+ throw (0, errors_js_1.localError)('invalid_argument', 'customers must be an array.', 'customers');
48
+ const rows = customers.map((c, i) => {
49
+ if (!c || typeof c.customerId !== 'string')
50
+ throw (0, errors_js_1.localError)('invalid_argument', `customers[${i}].customerId must be a string.`, 'customer_id');
51
+ const row = { customer_id: c.customerId };
52
+ if (c.customerSince != null)
53
+ row.customer_since = sinceDay(c.customerSince);
54
+ return row;
55
+ });
56
+ const total = { accepted: 0, refused: 0, refused_by_reason: {} };
57
+ if (rows.length === 0)
58
+ return total;
59
+ if ((await this.core.guardState()).guard)
60
+ throw privateModeConflict();
61
+ const several = rows.length > exports.KNOWN_CUSTOMERS_BATCH;
62
+ for (let i = 0; i < rows.length; i += exports.KNOWN_CUSTOMERS_BATCH) {
63
+ // One idempotency key per batch: a key you pass gets the batch number appended
64
+ const key = requestOptions.idempotencyKey;
65
+ const options = several && key ? { ...requestOptions, idempotencyKey: `${key}-${i / exports.KNOWN_CUSTOMERS_BATCH}` } : requestOptions;
66
+ const { data } = await this.core.requester.request({
67
+ method: 'POST',
68
+ path: '/v1/known-customers/import',
69
+ body: { customers: rows.slice(i, i + exports.KNOWN_CUSTOMERS_BATCH) },
70
+ ...options,
71
+ });
72
+ total.accepted += data.accepted ?? 0;
73
+ total.refused += data.refused ?? 0;
74
+ for (const [reason, n] of Object.entries(data.refused_by_reason ?? {})) {
75
+ total.refused_by_reason[reason] = (total.refused_by_reason[reason] ?? 0) + (n ?? 0);
76
+ }
77
+ }
78
+ return total;
79
+ }
80
+ /**
81
+ * Remove one imported customer (`POST /v1/known-customers/remove`; the ID travels in the body, never in a URL).
82
+ *
83
+ * @example
84
+ * const { removed } = await clikgate.knownCustomers.remove('u_10482');
85
+ */
86
+ async remove(customerId, requestOptions = {}) {
87
+ if (typeof customerId !== 'string' || customerId === '')
88
+ throw (0, errors_js_1.localError)('invalid_customer_id', 'customerId must be a non-empty string.', 'customer_id');
89
+ if ((await this.core.guardState()).guard)
90
+ throw privateModeConflict();
91
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/known-customers/remove', body: { customer_id: customerId }, ...requestOptions });
92
+ return data;
93
+ }
94
+ }
95
+ exports.KnownCustomers = KnownCustomers;
@@ -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,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.consoleLogger = void 0;
4
+ /** @internal The default logger: warnings and errors to the console, prefixed. */
5
+ exports.consoleLogger = {
6
+ warn: (message, context) => console.warn(`[clikgate] ${message}`, ...(context ? [context] : [])),
7
+ error: (message, context) => console.error(`[clikgate] ${message}`, ...(context ? [context] : [])),
8
+ };
@@ -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;