@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.
- package/CHANGELOG.md +126 -0
- package/LICENSE +21 -0
- package/README.md +300 -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 +175 -0
- package/dist/cjs/client.js +266 -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/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 +17534 -0
- package/dist/cjs/generated/index.js +8816 -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 +32 -0
- package/dist/cjs/identity.js +99 -0
- package/dist/cjs/index.d.ts +32 -0
- package/dist/cjs/index.js +64 -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 +175 -0
- package/dist/esm/client.js +262 -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/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 +17534 -0
- package/dist/esm/generated/index.js +8754 -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 +32 -0
- package/dist/esm/identity.js +92 -0
- package/dist/esm/index.d.ts +32 -0
- package/dist/esm/index.js +21 -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
package/dist/cjs/http.js
ADDED
|
@@ -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,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,99 @@
|
|
|
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.createIdentityTokenWith = createIdentityTokenWith;
|
|
7
|
+
exports.createIdentityToken = createIdentityToken;
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
9
|
+
const errors_js_1 = require("./errors.js");
|
|
10
|
+
/** The single secret's environment variable. */
|
|
11
|
+
exports.IDENTITY_SECRET_ENV = 'CLIKGATE_IDENTITY_SECRET';
|
|
12
|
+
/** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
|
|
13
|
+
exports.IDENTITY_SECRETS_ENV = 'CLIKGATE_IDENTITY_SECRETS';
|
|
14
|
+
const MAX_CUSTOMER_ID = 255;
|
|
15
|
+
/** @internal True in a browser (window or document) or React Native. */
|
|
16
|
+
function isBrowserOrMobile(g = globalThis) {
|
|
17
|
+
if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined')
|
|
18
|
+
return true;
|
|
19
|
+
const nav = g.navigator;
|
|
20
|
+
return typeof nav === 'object' && nav !== null && nav.product === 'ReactNative';
|
|
21
|
+
}
|
|
22
|
+
function serverOnly() {
|
|
23
|
+
throw new errors_js_1.ClikgateServerOnlyError({
|
|
24
|
+
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',
|
|
25
|
+
code: 'server_only',
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function envMap() {
|
|
29
|
+
const raw = process.env[exports.IDENTITY_SECRETS_ENV];
|
|
30
|
+
if (raw === undefined || raw.trim() === '')
|
|
31
|
+
return null;
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(raw);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
parsed = null;
|
|
38
|
+
}
|
|
39
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === 'string' && v !== '')) {
|
|
40
|
+
// Never echo the value: it holds secrets.
|
|
41
|
+
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 });
|
|
42
|
+
}
|
|
43
|
+
return parsed;
|
|
44
|
+
}
|
|
45
|
+
function resolveSecret(options, source) {
|
|
46
|
+
if (options.secret != null && options.secret !== '')
|
|
47
|
+
return options.secret;
|
|
48
|
+
const appId = options.appId ?? null;
|
|
49
|
+
const map = source.identitySecrets ?? envMap();
|
|
50
|
+
if (appId !== null && map && Object.prototype.hasOwnProperty.call(map, appId) && map[appId])
|
|
51
|
+
return map[appId];
|
|
52
|
+
const single = source.identitySecret || process.env[exports.IDENTITY_SECRET_ENV] || null;
|
|
53
|
+
if (single)
|
|
54
|
+
return single;
|
|
55
|
+
if (appId === null && map && Object.keys(map).length > 0) {
|
|
56
|
+
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' });
|
|
57
|
+
}
|
|
58
|
+
throw new errors_js_1.ConfigurationError({
|
|
59
|
+
message: appId === null
|
|
60
|
+
? `No identity secret: set ${exports.IDENTITY_SECRET_ENV} on your server (Apps › your app › Identity secret).`
|
|
61
|
+
: `No identity secret for this app: add it to ${exports.IDENTITY_SECRETS_ENV} or set ${exports.IDENTITY_SECRET_ENV}.`,
|
|
62
|
+
code: 'missing_identity_secret',
|
|
63
|
+
param: 'secret',
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** @internal */
|
|
67
|
+
function signIdentityToken(secret, customerId, issuedAt) {
|
|
68
|
+
const sig = (0, node_crypto_1.createHmac)('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(`${customerId}.${issuedAt}`, 'utf8')).digest('base64url');
|
|
69
|
+
return `${sig}.${issuedAt}`;
|
|
70
|
+
}
|
|
71
|
+
/** @internal createIdentityToken with an explicit secret source (the client's options). */
|
|
72
|
+
function createIdentityTokenWith(source, customerId, options = {}) {
|
|
73
|
+
if (isBrowserOrMobile())
|
|
74
|
+
serverOnly();
|
|
75
|
+
if (typeof customerId !== 'string' || customerId === '' || [...customerId].length > MAX_CUSTOMER_ID) {
|
|
76
|
+
// Never echo the customer ID.
|
|
77
|
+
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');
|
|
78
|
+
}
|
|
79
|
+
const o = options ?? {};
|
|
80
|
+
const issuedAt = o.issuedAt ?? Math.floor(Date.now() / 1000);
|
|
81
|
+
if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
|
|
82
|
+
throw (0, errors_js_1.localError)('invalid_argument', 'issuedAt must be whole Unix seconds.', 'issued_at');
|
|
83
|
+
return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Create an identity token for the signed-in user. Return it in your sign-in and "current user"
|
|
87
|
+
* responses; the app passes it to `identifyUser()`. Reads `CLIKGATE_IDENTITY_SECRET`, or with `appId` the app's
|
|
88
|
+
* secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
|
|
89
|
+
*
|
|
90
|
+
* Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
|
|
91
|
+
* and `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* import { createIdentityToken } from '@clikgate/node';
|
|
95
|
+
* res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
|
|
96
|
+
*/
|
|
97
|
+
function createIdentityToken(customerId, options = {}) {
|
|
98
|
+
return createIdentityTokenWith({}, customerId, options);
|
|
99
|
+
}
|
|
@@ -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,64 @@
|
|
|
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.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 identity_js_1 = require("./identity.js");
|
|
30
|
+
Object.defineProperty(exports, "createIdentityToken", { enumerable: true, get: function () { return identity_js_1.createIdentityToken; } });
|
|
31
|
+
Object.defineProperty(exports, "IDENTITY_SECRET_ENV", { enumerable: true, get: function () { return identity_js_1.IDENTITY_SECRET_ENV; } });
|
|
32
|
+
Object.defineProperty(exports, "IDENTITY_SECRETS_ENV", { enumerable: true, get: function () { return identity_js_1.IDENTITY_SECRETS_ENV; } });
|
|
33
|
+
var money_js_1 = require("./money.js");
|
|
34
|
+
Object.defineProperty(exports, "formatValue", { enumerable: true, get: function () { return money_js_1.formatValue; } });
|
|
35
|
+
var ads_hashing_js_1 = require("./ads-hashing.js");
|
|
36
|
+
Object.defineProperty(exports, "hashForAds", { enumerable: true, get: function () { return ads_hashing_js_1.hashForAds; } });
|
|
37
|
+
var enums_js_1 = require("./enums.js");
|
|
38
|
+
Object.defineProperty(exports, "GoalKind", { enumerable: true, get: function () { return enums_js_1.GoalKind; } });
|
|
39
|
+
Object.defineProperty(exports, "GoalStatus", { enumerable: true, get: function () { return enums_js_1.GoalStatus; } });
|
|
40
|
+
Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return enums_js_1.Provider; } });
|
|
41
|
+
var payments_js_1 = require("./payments.js");
|
|
42
|
+
Object.defineProperty(exports, "buildFromPaystack", { enumerable: true, get: function () { return payments_js_1.buildFromPaystack; } });
|
|
43
|
+
Object.defineProperty(exports, "buildFromFlutterwave", { enumerable: true, get: function () { return payments_js_1.buildFromFlutterwave; } });
|
|
44
|
+
Object.defineProperty(exports, "buildFromMonnify", { enumerable: true, get: function () { return payments_js_1.buildFromMonnify; } });
|
|
45
|
+
Object.defineProperty(exports, "buildFromStripe", { enumerable: true, get: function () { return payments_js_1.buildFromStripe; } });
|
|
46
|
+
var errors_js_1 = require("./errors.js");
|
|
47
|
+
Object.defineProperty(exports, "ClikgateError", { enumerable: true, get: function () { return errors_js_1.ClikgateError; } });
|
|
48
|
+
Object.defineProperty(exports, "ConfigurationError", { enumerable: true, get: function () { return errors_js_1.ConfigurationError; } });
|
|
49
|
+
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
|
|
50
|
+
Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
|
|
51
|
+
Object.defineProperty(exports, "InvalidRequestError", { enumerable: true, get: function () { return errors_js_1.InvalidRequestError; } });
|
|
52
|
+
Object.defineProperty(exports, "PrivateModeFieldRejectedError", { enumerable: true, get: function () { return errors_js_1.PrivateModeFieldRejectedError; } });
|
|
53
|
+
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
54
|
+
Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
|
|
55
|
+
Object.defineProperty(exports, "LinkLockedError", { enumerable: true, get: function () { return errors_js_1.LinkLockedError; } });
|
|
56
|
+
Object.defineProperty(exports, "IdempotencyError", { enumerable: true, get: function () { return errors_js_1.IdempotencyError; } });
|
|
57
|
+
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
|
|
58
|
+
Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_js_1.ServerError; } });
|
|
59
|
+
Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return errors_js_1.NetworkError; } });
|
|
60
|
+
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_js_1.TimeoutError; } });
|
|
61
|
+
Object.defineProperty(exports, "SignatureVerificationError", { enumerable: true, get: function () { return errors_js_1.SignatureVerificationError; } });
|
|
62
|
+
Object.defineProperty(exports, "ClikgateServerOnlyError", { enumerable: true, get: function () { return errors_js_1.ClikgateServerOnlyError; } });
|
|
63
|
+
var version_js_1 = require("./version.js");
|
|
64
|
+
Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_js_1.VERSION; } });
|
|
@@ -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;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.formatValue = formatValue;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const DECIMAL = /^[0-9]+(\.[0-9]+)?$/;
|
|
6
|
+
function plain(n) {
|
|
7
|
+
const s = String(n);
|
|
8
|
+
if (!/e/i.test(s))
|
|
9
|
+
return s;
|
|
10
|
+
if (Number.isInteger(n))
|
|
11
|
+
return BigInt(n).toString();
|
|
12
|
+
return n.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Format a money value for the wire: always a plain decimal string (SPEC section 8).
|
|
16
|
+
*
|
|
17
|
+
* - strings are trimmed and must look like `2000000` or `1500.50` (no signs, exponents or separators);
|
|
18
|
+
* - integers and bigints are sent as their digits;
|
|
19
|
+
* - non-integer numbers are sent as their shortest decimal form, with an `inexact_number` warning.
|
|
20
|
+
*
|
|
21
|
+
* @throws {InvalidRequestError} code `invalid_value` for anything else.
|
|
22
|
+
* @example
|
|
23
|
+
* formatValue('1500.50'); // '1500.50'
|
|
24
|
+
* formatValue(2_000_000); // '2000000'
|
|
25
|
+
* formatValue(10n ** 18n); // '1000000000000000000'
|
|
26
|
+
*/
|
|
27
|
+
function formatValue(value, warn) {
|
|
28
|
+
const bad = (why) => (0, errors_js_1.localError)('invalid_value', `value ${why}. Pass a decimal string in normal units, like '1500.50'.`, 'value');
|
|
29
|
+
if (typeof value === 'string') {
|
|
30
|
+
const s = value.trim();
|
|
31
|
+
if (!DECIMAL.test(s))
|
|
32
|
+
throw bad('must be a non-negative decimal number');
|
|
33
|
+
return s;
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === 'bigint') {
|
|
36
|
+
if (value < 0n)
|
|
37
|
+
throw bad('must not be negative');
|
|
38
|
+
return value.toString();
|
|
39
|
+
}
|
|
40
|
+
if (typeof value === 'number') {
|
|
41
|
+
if (!Number.isFinite(value))
|
|
42
|
+
throw bad('must be a finite number');
|
|
43
|
+
if (value < 0)
|
|
44
|
+
throw bad('must not be negative');
|
|
45
|
+
if (Number.isSafeInteger(value))
|
|
46
|
+
return String(value);
|
|
47
|
+
warn?.(`value ${String(value)} is a floating-point number and may not be exact; pass a decimal string, like '1500.50', for exact values.`);
|
|
48
|
+
return plain(value);
|
|
49
|
+
}
|
|
50
|
+
throw bad(`has unsupported type ${value === null ? 'null' : typeof value}`);
|
|
51
|
+
}
|
|
@@ -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;
|
package/dist/cjs/next.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.clikgateMiddleware = exports.clikgateProxy = void 0;
|
|
4
|
+
exports.applyClikgate = applyClikgate;
|
|
5
|
+
exports.createClikgateProxy = createClikgateProxy;
|
|
6
|
+
exports.getClickId = getClickId;
|
|
7
|
+
exports.keepRoute = keepRoute;
|
|
8
|
+
/**
|
|
9
|
+
* Next.js add-on: keeps the click ID (SPEC section 17). Next.js 16 calls request middleware a
|
|
10
|
+
* "proxy" (`proxy.ts`, exporting `proxy`); `middleware.ts` still works but is deprecated.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // proxy.ts (Next.js 16+)
|
|
14
|
+
* export { clikgateProxy as proxy } from '@clikgate/node/next';
|
|
15
|
+
* export const config = { matcher: ['/((?!_next/|api/webhooks/).*)'] };
|
|
16
|
+
*
|
|
17
|
+
* // app/signup/route.ts
|
|
18
|
+
* import { cookies } from 'next/headers';
|
|
19
|
+
* import { getClickId } from '@clikgate/node/next';
|
|
20
|
+
* const clickId = getClickId(await cookies());
|
|
21
|
+
*
|
|
22
|
+
* @packageDocumentation
|
|
23
|
+
*/
|
|
24
|
+
const server_js_1 = require("next/server.js");
|
|
25
|
+
const click_ids_js_1 = require("./click-ids.js");
|
|
26
|
+
function helpersFor(param) {
|
|
27
|
+
const name = param ?? (typeof process !== 'undefined' ? process.env.CLIKGATE_CLICK_ID_PARAM : undefined) ?? 'cgid';
|
|
28
|
+
return new click_ids_js_1.ClickIds(() => name);
|
|
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
|
+
function applyClikgate(request, response, options = {}) {
|
|
42
|
+
const { clickIdParam, ...cookie } = options;
|
|
43
|
+
const helpers = helpersFor(clickIdParam);
|
|
44
|
+
const fromQuery = request.nextUrl.searchParams.getAll(helpers.paramName).find((v) => helpers.isValid(v)) ?? null;
|
|
45
|
+
if (fromQuery) {
|
|
46
|
+
const secure = cookie.secure ?? request.nextUrl.protocol === 'https:';
|
|
47
|
+
response.headers.append('set-cookie', helpers.cookieHeader(fromQuery, { ...cookie, secure }));
|
|
48
|
+
response.headers.append('set-cookie', (0, click_ids_js_1.keptMarkerHeader)({ ...cookie, secure }));
|
|
49
|
+
return fromQuery;
|
|
50
|
+
}
|
|
51
|
+
return helpers.fromRequest({ url: request.nextUrl.href, headers: request.headers });
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Build a proxy (or legacy middleware) function with options.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* export const proxy = createClikgateProxy({ days: 30, clickIdParam: 'ref' });
|
|
58
|
+
*/
|
|
59
|
+
function createClikgateProxy(options = {}) {
|
|
60
|
+
return (request) => {
|
|
61
|
+
const response = server_js_1.NextResponse.next();
|
|
62
|
+
applyClikgate(request, response, options);
|
|
63
|
+
return response;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The ready-made proxy for `proxy.ts`: stores a click ID from the query string in the `_cg_<param>` cookie.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* export { clikgateProxy as proxy } from '@clikgate/node/next';
|
|
71
|
+
*/
|
|
72
|
+
exports.clikgateProxy = createClikgateProxy();
|
|
73
|
+
/**
|
|
74
|
+
* The same function for the deprecated `middleware.ts` (`export { clikgateMiddleware as middleware }`).
|
|
75
|
+
*/
|
|
76
|
+
exports.clikgateMiddleware = exports.clikgateProxy;
|
|
77
|
+
/**
|
|
78
|
+
* Read the kept click ID from a cookie store, e.g. `getClickId(await cookies())` in a route handler or
|
|
79
|
+
* server action, or `getClickId(request.cookies)`.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* import { cookies } from 'next/headers';
|
|
83
|
+
* const clickId = getClickId(await cookies());
|
|
84
|
+
*/
|
|
85
|
+
function getClickId(store, clickIdParam) {
|
|
86
|
+
const helpers = helpersFor(clickIdParam);
|
|
87
|
+
const value = store.get(helpers.cookieName)?.value;
|
|
88
|
+
return helpers.isValid(value) ? value : null;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The `/cg/keep` route handler without a client, using the same click-ID parameter as the proxy
|
|
92
|
+
* (`clickIdParam`, else `process.env.CLIKGATE_CLICK_ID_PARAM`, else `cgid`). With a client, use
|
|
93
|
+
* `clikgate.clickIds.keepRoute()` instead.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* // app/cg/keep/route.ts
|
|
97
|
+
* import { keepRoute } from '@clikgate/node/next';
|
|
98
|
+
* export const POST = keepRoute({ days: 90 });
|
|
99
|
+
*/
|
|
100
|
+
function keepRoute(options = {}) {
|
|
101
|
+
const { clickIdParam, ...rest } = options;
|
|
102
|
+
return helpersFor(clickIdParam).keepRoute(rest);
|
|
103
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|