@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,535 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clickIds = exports.KEPT_COOKIE = exports.PLATFORMS = exports.BROWSER_ENGINES = exports.KEPT_BY = exports.ClickIds = exports.CLICK_ID_HEADER = exports.CLICK_ID_PATTERN = void 0;
4
+ exports.isValid = isValid;
5
+ exports.keptMarkerHeader = keptMarkerHeader;
6
+ exports.browserEngineOf = browserEngineOf;
7
+ exports.platformOf = platformOf;
8
+ exports.appendSetCookie = appendSetCookie;
9
+ const errors_js_1 = require("./errors.js");
10
+ /** The click ID format: a prefixed ULID, `clk_` + 26 uppercase Crockford characters. */
11
+ exports.CLICK_ID_PATTERN = /^clk_[0-9A-Z]{26}$/;
12
+ /** The header a caller (e.g. your mobile app or BFF) can use to pass the click ID. */
13
+ exports.CLICK_ID_HEADER = 'clikgate-click-id';
14
+ const DEFAULT_PARAM = 'cgid';
15
+ const PAYMENT_KEYS = ['cg_click_id', 'cgid', 'clikgate_click_id'];
16
+ const CONTAINERS = ['metadata', 'meta', 'meta_data', 'note_attributes', 'attributes', 'custom_attributes', 'customAttributes'];
17
+ function header(headers, name) {
18
+ if (!headers || typeof headers !== 'object')
19
+ return null;
20
+ const h = headers;
21
+ if (typeof h.get === 'function') {
22
+ const v = h.get.call(headers, name);
23
+ return typeof v === 'string' ? v : null;
24
+ }
25
+ for (const [k, v] of Object.entries(h)) {
26
+ if (k.toLowerCase() !== name)
27
+ continue;
28
+ if (Array.isArray(v))
29
+ return v.join(name === 'cookie' ? '; ' : ', ');
30
+ return typeof v === 'string' ? v : null;
31
+ }
32
+ return null;
33
+ }
34
+ function requestUrl(req) {
35
+ const r = req;
36
+ const raw = typeof r.nextUrl?.href === 'string' ? r.nextUrl.href : typeof r.originalUrl === 'string' ? r.originalUrl : typeof r.url === 'string' ? r.url : null;
37
+ if (raw === null)
38
+ return null;
39
+ try {
40
+ return new URL(raw, 'http://localhost');
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ function cookieValue(cookieHeader, name) {
47
+ if (!cookieHeader)
48
+ return [];
49
+ const out = [];
50
+ for (const part of cookieHeader.split(';')) {
51
+ const eq = part.indexOf('=');
52
+ if (eq < 0)
53
+ continue;
54
+ if (part.slice(0, eq).trim() !== name)
55
+ continue;
56
+ let v = part.slice(eq + 1).trim();
57
+ if (v.startsWith('"') && v.endsWith('"'))
58
+ v = v.slice(1, -1);
59
+ try {
60
+ out.push(decodeURIComponent(v));
61
+ }
62
+ catch {
63
+ out.push(v);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ function parseJson(s) {
69
+ try {
70
+ return JSON.parse(s);
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ function asMap(container) {
77
+ let c = container;
78
+ if (typeof c === 'string')
79
+ c = parseJson(c);
80
+ if (Array.isArray(c)) {
81
+ const m = {};
82
+ for (const item of c) {
83
+ if (!item || typeof item !== 'object')
84
+ continue;
85
+ const i = item;
86
+ const k = i.name ?? i.key ?? i.variable_name ?? i.display_name;
87
+ if (typeof k === 'string')
88
+ m[k] = i.value;
89
+ }
90
+ return m;
91
+ }
92
+ return c && typeof c === 'object' ? c : null;
93
+ }
94
+ function pick(map, depth = 0) {
95
+ if (!map)
96
+ return null;
97
+ for (const k of PAYMENT_KEYS) {
98
+ const v = map[k];
99
+ if (isValid(v))
100
+ return v;
101
+ }
102
+ if (depth === 0 && Array.isArray(map.custom_fields))
103
+ return pick(asMap(map.custom_fields), 1);
104
+ return null;
105
+ }
106
+ /**
107
+ * True when `id` is a Clikgate click ID (`clk_` + 26 characters).
108
+ *
109
+ * @example
110
+ * clickIds.isValid('clk_01JCK8Z9V7Q4M2N6P8R0S2T4W6'); // true
111
+ */
112
+ function isValid(id) {
113
+ return typeof id === 'string' && exports.CLICK_ID_PATTERN.test(id);
114
+ }
115
+ /** Click-ID helpers bound to a `click_id_param` (SPEC section 13). */
116
+ class ClickIds {
117
+ param;
118
+ /** @internal */
119
+ constructor(param) {
120
+ this.param = param;
121
+ }
122
+ /** The query parameter name in use (`cgid` unless configured). */
123
+ get paramName() {
124
+ return this.param();
125
+ }
126
+ /** The cookie name: `_cg_<param>`, the same first-party cookie the web script writes. */
127
+ get cookieName() {
128
+ return `_cg_${this.param()}`;
129
+ }
130
+ /** {@inheritDoc isValid} */
131
+ isValid(id) {
132
+ return isValid(id);
133
+ }
134
+ /**
135
+ * Read the click ID from a request: the query parameter, then the `_cg_<param>` cookie, then the
136
+ * `Clikgate-Click-Id` header. Only valid IDs are returned.
137
+ *
138
+ * @example
139
+ * app.post('/signup', (req, res) => {
140
+ * const clickId = clikgate.clickIds.fromRequest(req); // save it with the application
141
+ * });
142
+ */
143
+ fromRequest(req) {
144
+ return this.locate(req)?.id ?? null;
145
+ }
146
+ /** The click ID and where it was found (query, cookie or header). */
147
+ locate(req) {
148
+ if (!req || typeof req !== 'object')
149
+ return null;
150
+ const url = requestUrl(req);
151
+ if (url) {
152
+ for (const v of url.searchParams.getAll(this.param()))
153
+ if (isValid(v))
154
+ return { id: v, from: 'query' };
155
+ }
156
+ const headers = req.headers;
157
+ for (const v of cookieValue(header(headers, 'cookie'), this.cookieName))
158
+ if (isValid(v))
159
+ return { id: v, from: 'cookie' };
160
+ const h = header(headers, exports.CLICK_ID_HEADER)?.trim();
161
+ return isValid(h) ? { id: h, from: 'header' } : null;
162
+ }
163
+ /**
164
+ * The visitor context to send with a goal (SPEC 13.1): the click ID, how it was kept, and the browser engine and
165
+ * platform parsed from the `User-Agent` here in the SDK (the User-Agent itself is never sent). Spread it into the
166
+ * goal options.
167
+ *
168
+ * - `keptBy` is `server_cookie` when the ID came from the cookie and the `_cg_kept=s` marker is there (your server
169
+ * set it, see {@link keepRoute} and {@link persist}), `script_cookie` for the cookie without the marker, `form`
170
+ * for the `Clikgate-Click-Id` header, and `null` when it came from the URL or there is none.
171
+ *
172
+ * @example
173
+ * app.post('/signup', (req, res) => {
174
+ * clikgate.goal('account_opened', { reference: application.id, ...clikgate.clickIds.context(req) });
175
+ * });
176
+ */
177
+ context(req) {
178
+ const found = this.locate(req);
179
+ const headers = req && typeof req === 'object' ? req.headers : undefined;
180
+ let keptBy = null;
181
+ if (found?.from === 'cookie')
182
+ keptBy = cookieValue(header(headers, 'cookie'), exports.KEPT_COOKIE).includes(KEPT_VALUE) ? 'server_cookie' : 'script_cookie';
183
+ else if (found?.from === 'header')
184
+ keptBy = 'form';
185
+ const ua = header(headers, 'user-agent') ?? '';
186
+ return { clickId: found?.id ?? null, keptBy, browserEngine: browserEngineOf(ua), platform: platformOf(ua) };
187
+ }
188
+ /**
189
+ * The `Set-Cookie` value that keeps the click ID: `SameSite=Lax`, `Secure` on HTTPS, not `HttpOnly`
190
+ * (the web script reads it).
191
+ *
192
+ * @example
193
+ * clikgate.clickIds.cookieHeader(clickId, { days: 30 });
194
+ * // '_cg_cgid=clk_…; Path=/; Max-Age=2592000; SameSite=Lax; Secure'
195
+ */
196
+ cookieHeader(id, options = {}) {
197
+ if (!isValid(id))
198
+ throw (0, errors_js_1.localError)('invalid_click_id', 'That is not a Clikgate click ID (clk_ + 26 characters).', 'click_id');
199
+ const days = options.days ?? 30;
200
+ const parts = [`${this.cookieName}=${id}`, 'Path=/', `Max-Age=${Math.round(days * 86400)}`];
201
+ if (options.domain)
202
+ parts.push(`Domain=${options.domain}`);
203
+ parts.push('SameSite=Lax');
204
+ if (options.secure ?? true)
205
+ parts.push('Secure');
206
+ return parts.join('; ');
207
+ }
208
+ /**
209
+ * Add the click-ID cookie to a response, keeping any `Set-Cookie` headers already there.
210
+ *
211
+ * @example
212
+ * const clickId = clikgate.clickIds.fromRequest(req);
213
+ * if (clickId) clikgate.clickIds.persist(res, clickId);
214
+ */
215
+ persist(res, id, options = {}) {
216
+ const secure = options.secure ?? inferSecure(res);
217
+ appendSetCookie(res, this.cookieHeader(id, { ...options, secure }));
218
+ appendSetCookie(res, keptMarkerHeader({ ...options, secure }));
219
+ }
220
+ /**
221
+ * The `/cg/keep` handler (SPEC 13.1): the web script's `data-server-endpoint="/cg/keep"` posts the click ID from the
222
+ * page URL here, and your server sets the `_cg_<param>` cookie (plus the `_cg_kept=s` marker) for `days` days.
223
+ * Safari, and every browser on iPhone, keeps a click ID saved by a script for up to 7 days (sometimes less); a cookie
224
+ * your server sets lasts as long as you choose, up to the browser's limit. Serve it from the same host as your website.
225
+ *
226
+ * Returns a Fetch handler (`(Request) => Promise<Response>`, e.g. a Next.js App Router `POST`), with
227
+ * `.express` (Express/Connect) and `.node` (`node:http`) adapters, and `.handle` for any other framework.
228
+ * Only same-origin `POST`s with a valid, matching click ID are accepted; every answer is `no-store` with an
229
+ * empty body. `secure` defaults to true here.
230
+ *
231
+ * @throws InvalidRequestError `invalid_argument` when `days` is not 1-400.
232
+ * @example
233
+ * // app/cg/keep/route.ts
234
+ * export const POST = clikgate.clickIds.keepRoute();
235
+ * // Express
236
+ * app.all('/cg/keep', clikgate.clickIds.keepRoute({ days: 90 }).express);
237
+ */
238
+ keepRoute(options = {}) {
239
+ const days = options.days ?? 30;
240
+ if (typeof days !== 'number' || !Number.isFinite(days) || days < 1 || days > 400) {
241
+ throw (0, errors_js_1.localError)('invalid_argument', 'days must be between 1 and 400 (browsers keep a cookie for at most 400 days).', 'days');
242
+ }
243
+ const cookie = { days, secure: options.secure ?? true, domain: options.domain };
244
+ const handle = (input) => keepCore(input, (id, o) => this.cookieHeader(id, o), cookie);
245
+ const route = (async (request) => {
246
+ const out = await handle({ method: request.method, headers: request.headers, readBody: () => readFetchBody(request), url: request.url });
247
+ return new Response(null, { status: out.status, headers: out.headers });
248
+ });
249
+ route.handle = handle;
250
+ route.node = (req, res) => {
251
+ void handle({ method: req.method ?? '', headers: req.headers, readBody: () => readNodeBody(req) }).then((out) => writeNode(req, res, out));
252
+ };
253
+ route.express = (req, res, next) => {
254
+ handle({ method: req.method ?? '', headers: req.headers, readBody: () => readNodeBody(req) }).then((out) => writeNode(req, res, out), (err) => (next ? next(err) : writeNode(req, res, { status: 400, headers: [...NO_STORE] })));
255
+ };
256
+ return route;
257
+ }
258
+ /**
259
+ * Find the click ID in a payment provider's payload: Paystack `metadata` (and `custom_fields`),
260
+ * Flutterwave `meta`, Shopify note or cart attributes, WooCommerce order meta, or your own webhook.
261
+ *
262
+ * @example
263
+ * app.post('/paystack/webhook', express.json(), (req, res) => {
264
+ * const clickId = clikgate.clickIds.fromPaymentMetadata(req.body);
265
+ * });
266
+ */
267
+ fromPaymentMetadata(payload) {
268
+ let p = payload;
269
+ if (typeof p === 'string')
270
+ p = parseJson(p);
271
+ if (!p || typeof p !== 'object' || Array.isArray(p))
272
+ return null;
273
+ const root = p;
274
+ const candidates = [root];
275
+ if (root.data && typeof root.data === 'object' && !Array.isArray(root.data))
276
+ candidates.push(root.data);
277
+ for (const c of candidates) {
278
+ const own = pick(c);
279
+ if (own)
280
+ return own;
281
+ for (const name of CONTAINERS) {
282
+ if (c[name] === undefined)
283
+ continue;
284
+ const found = pick(asMap(c[name]));
285
+ if (found)
286
+ return found;
287
+ }
288
+ }
289
+ return null;
290
+ }
291
+ }
292
+ exports.ClickIds = ClickIds;
293
+ /** Every `kept_by` value. */
294
+ exports.KEPT_BY = ['server_cookie', 'script_cookie', 'form', 'payment_metadata', 'unknown'];
295
+ /** Every `browser_engine` value. */
296
+ exports.BROWSER_ENGINES = ['webkit_ios', 'safari_mac', 'chromium', 'gecko', 'other'];
297
+ /** Every `platform` value. */
298
+ exports.PLATFORMS = ['ios', 'android', 'macos', 'windows', 'linux', 'other'];
299
+ /** The marker cookie that tells the web script (and `context()`) that your server kept the click ID. */
300
+ exports.KEPT_COOKIE = '_cg_kept';
301
+ const KEPT_VALUE = 's';
302
+ const KEEP_MAX_BODY = 1024;
303
+ const NO_STORE = [['Cache-Control', 'no-store, private']];
304
+ /** @internal `_cg_kept=s` with the click-ID cookie's attributes. */
305
+ function keptMarkerHeader(options) {
306
+ const parts = [`${exports.KEPT_COOKIE}=${KEPT_VALUE}`, 'Path=/', `Max-Age=${Math.round((options.days ?? 30) * 86400)}`];
307
+ if (options.domain)
308
+ parts.push(`Domain=${options.domain}`);
309
+ parts.push('SameSite=Lax');
310
+ if (options.secure ?? true)
311
+ parts.push('Secure');
312
+ return parts.join('; ');
313
+ }
314
+ /** @internal The `browser_engine` for a User-Agent (SPEC 13.1 table, checked in order). */
315
+ function browserEngineOf(ua) {
316
+ if (/iPhone|iPad|iPod/.test(ua))
317
+ return 'webkit_ios';
318
+ if (ua.includes('Firefox/'))
319
+ return 'gecko';
320
+ if (/Chrome\/|Chromium\/|Edg\/|OPR\/|SamsungBrowser\//.test(ua))
321
+ return 'chromium';
322
+ if (ua.includes('Macintosh') && ua.includes('Safari/') && ua.includes('Version/'))
323
+ return 'safari_mac';
324
+ return 'other';
325
+ }
326
+ /** @internal The `platform` for a User-Agent (SPEC 13.1 table, checked in order). */
327
+ function platformOf(ua) {
328
+ if (/iPhone|iPad|iPod/.test(ua))
329
+ return 'ios';
330
+ if (ua.includes('Android'))
331
+ return 'android';
332
+ if (ua.includes('Macintosh') || ua.includes('Mac OS X'))
333
+ return 'macos';
334
+ if (ua.includes('Windows'))
335
+ return 'windows';
336
+ if (ua.includes('Linux') || ua.includes('X11'))
337
+ return 'linux';
338
+ return 'other';
339
+ }
340
+ function expectedHost(input) {
341
+ const forwarded = header(input.headers, 'x-forwarded-host')?.split(',')[0]?.trim();
342
+ if (forwarded)
343
+ return forwarded;
344
+ const host = header(input.headers, 'host')?.trim();
345
+ if (host)
346
+ return host;
347
+ if (!input.url)
348
+ return null;
349
+ try {
350
+ return new URL(input.url).host || null;
351
+ }
352
+ catch {
353
+ return null;
354
+ }
355
+ }
356
+ function sameOrigin(input) {
357
+ const site = header(input.headers, 'sec-fetch-site');
358
+ if (site !== null)
359
+ return site.trim().toLowerCase() === 'same-origin';
360
+ const origin = header(input.headers, 'origin')?.trim().toLowerCase();
361
+ const host = expectedHost(input)?.toLowerCase();
362
+ if (!origin || !host)
363
+ return false;
364
+ return origin === `https://${host}` || origin === `http://${host}`;
365
+ }
366
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
367
+ /** @internal The one `/cg/keep` implementation every adapter calls (SPEC 13.1). Never logs or echoes the input. */
368
+ async function keepCore(input, cookieHeader, cookie) {
369
+ const refuse = (status) => ({ status, headers: status === 405 ? [...NO_STORE, ['Allow', 'POST']] : [...NO_STORE] });
370
+ if (String(input.method).toUpperCase() !== 'POST')
371
+ return refuse(405);
372
+ if (!sameOrigin(input))
373
+ return refuse(403);
374
+ let bytes;
375
+ try {
376
+ bytes = await input.readBody();
377
+ }
378
+ catch {
379
+ return refuse(400);
380
+ }
381
+ if (!bytes || bytes.byteLength > KEEP_MAX_BODY)
382
+ return refuse(400);
383
+ let body;
384
+ try {
385
+ body = JSON.parse(utf8.decode(bytes));
386
+ }
387
+ catch {
388
+ return refuse(400);
389
+ }
390
+ if (!body || typeof body !== 'object' || Array.isArray(body))
391
+ return refuse(400);
392
+ const { click_id: id, page_click_id: pageId } = body;
393
+ if (!isValid(id) || !isValid(pageId) || id !== pageId)
394
+ return refuse(400);
395
+ return {
396
+ status: 204,
397
+ headers: [...NO_STORE, ['Set-Cookie', cookieHeader(id, cookie)], ['Set-Cookie', keptMarkerHeader(cookie)]],
398
+ };
399
+ }
400
+ async function readFetchBody(request) {
401
+ if (!request.body)
402
+ return new Uint8Array(0);
403
+ const reader = request.body.getReader();
404
+ const chunks = [];
405
+ let size = 0;
406
+ for (;;) {
407
+ const { done, value } = await reader.read();
408
+ if (done)
409
+ break;
410
+ size += value.byteLength;
411
+ if (size > KEEP_MAX_BODY) {
412
+ void reader.cancel().catch(() => undefined);
413
+ return null;
414
+ }
415
+ chunks.push(value);
416
+ }
417
+ return concat(chunks, size);
418
+ }
419
+ function concat(chunks, size) {
420
+ const out = new Uint8Array(size);
421
+ let at = 0;
422
+ for (const c of chunks) {
423
+ out.set(c, at);
424
+ at += c.byteLength;
425
+ }
426
+ return out;
427
+ }
428
+ function readNodeBody(req) {
429
+ // already read by a body parser (express.json(), express.text(), express.raw(), …)
430
+ if (req.readableEnded || req.body !== undefined) {
431
+ const b = req.body;
432
+ if (b instanceof Uint8Array)
433
+ return Promise.resolve(b);
434
+ if (typeof b === 'string')
435
+ return Promise.resolve(new TextEncoder().encode(b));
436
+ if (b && typeof b === 'object')
437
+ return Promise.resolve(new TextEncoder().encode(JSON.stringify(b)));
438
+ return Promise.resolve(new Uint8Array(0));
439
+ }
440
+ return new Promise((resolve, reject) => {
441
+ const chunks = [];
442
+ let size = 0;
443
+ const cleanup = () => {
444
+ req.off('data', onData);
445
+ req.off('end', onEnd);
446
+ req.off('error', onError);
447
+ };
448
+ const onData = (chunk) => {
449
+ const c = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
450
+ size += c.byteLength;
451
+ if (size > KEEP_MAX_BODY) {
452
+ cleanup();
453
+ req.pause();
454
+ resolve(null);
455
+ return;
456
+ }
457
+ chunks.push(c);
458
+ };
459
+ const onEnd = () => {
460
+ cleanup();
461
+ resolve(concat(chunks, size));
462
+ };
463
+ const onError = (err) => {
464
+ cleanup();
465
+ reject(err);
466
+ };
467
+ req.on('data', onData);
468
+ req.on('end', onEnd);
469
+ req.on('error', onError);
470
+ });
471
+ }
472
+ function writeNode(req, res, out) {
473
+ if (res.headersSent)
474
+ return;
475
+ res.statusCode = out.status;
476
+ for (const [name, value] of out.headers) {
477
+ if (name === 'Set-Cookie')
478
+ appendSetCookie(res, value);
479
+ else
480
+ res.setHeader(name, value);
481
+ }
482
+ if (!req.readableEnded && req.isPaused()) {
483
+ // a body over 1 KB was left unread: close the connection after answering
484
+ res.setHeader('Connection', 'close');
485
+ res.once('finish', () => req.destroy());
486
+ }
487
+ res.end();
488
+ }
489
+ function inferSecure(res) {
490
+ const r = res;
491
+ if (r.request && typeof r.request.protocol === 'string')
492
+ return r.request.protocol === 'https';
493
+ const req = r.req;
494
+ if (!req)
495
+ return true;
496
+ const proto = header(req.headers, 'x-forwarded-proto');
497
+ if (proto)
498
+ return proto.split(',')[0].trim().toLowerCase() === 'https';
499
+ if (req.socket)
500
+ return !!req.socket.encrypted;
501
+ return true;
502
+ }
503
+ /** @internal Append a Set-Cookie header to any supported response type. */
504
+ function appendSetCookie(res, value) {
505
+ const r = res;
506
+ // Fastify reply: header() appends for set-cookie
507
+ if (typeof r.header === 'function' && 'raw' in r) {
508
+ r.header.call(res, 'set-cookie', value);
509
+ return;
510
+ }
511
+ // Node >= 18.3 ServerResponse (Express, Connect)
512
+ if (typeof r.appendHeader === 'function') {
513
+ r.appendHeader.call(res, 'Set-Cookie', value);
514
+ return;
515
+ }
516
+ if (typeof r.getHeader === 'function' && typeof r.setHeader === 'function') {
517
+ const existing = r.getHeader.call(res, 'Set-Cookie');
518
+ const list = existing === undefined ? [] : Array.isArray(existing) ? existing.map(String) : [String(existing)];
519
+ r.setHeader.call(res, 'Set-Cookie', [...list, value]);
520
+ return;
521
+ }
522
+ // Fetch Response / NextResponse
523
+ if (r.headers && typeof r.headers.append === 'function') {
524
+ r.headers.append.call(r.headers, 'set-cookie', value);
525
+ return;
526
+ }
527
+ // a Headers object itself
528
+ if (typeof r.append === 'function') {
529
+ r.append.call(res, 'set-cookie', value);
530
+ return;
531
+ }
532
+ throw (0, errors_js_1.localError)('invalid_argument', 'persist() needs a response with setHeader/appendHeader or Fetch headers.', 'response');
533
+ }
534
+ /** Click-ID helpers with the default parameter (`cgid`), usable without a client. */
535
+ exports.clickIds = new ClickIds(() => DEFAULT_PARAM);