@windrun-huaiin/backend-core 31.0.0 → 31.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/api/user/anonymous/init/fingerprint-only-route.d.ts +8 -0
- package/dist/app/api/user/anonymous/init/fingerprint-only-route.d.ts.map +1 -0
- package/dist/app/api/user/anonymous/init/fingerprint-only-route.js +20 -0
- package/dist/app/api/user/anonymous/init/fingerprint-only-route.mjs +18 -0
- package/dist/app/api/user/anonymous/init/route-shared.d.ts +10 -0
- package/dist/app/api/user/anonymous/init/route-shared.d.ts.map +1 -0
- package/dist/app/api/user/anonymous/init/route-shared.js +557 -0
- package/dist/app/api/user/anonymous/init/route-shared.mjs +555 -0
- package/dist/app/api/user/anonymous/init/route.d.ts +3 -3
- package/dist/app/api/user/anonymous/init/route.d.ts.map +1 -1
- package/dist/app/api/user/anonymous/init/route.js +6 -553
- package/dist/app/api/user/anonymous/init/route.mjs +7 -554
- package/package.json +9 -4
- package/src/app/api/user/anonymous/init/fingerprint-only-route.ts +14 -0
- package/src/app/api/user/anonymous/init/route-shared.ts +710 -0
- package/src/app/api/user/anonymous/init/route.ts +7 -711
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
import { __awaiter, __rest } from 'tslib';
|
|
2
|
+
import { anonymousAggregateService } from '../../../../../services/aggregate/anonymous.aggregate.service.mjs';
|
|
3
|
+
import { extractFingerprintFromNextRequest } from '@windrun-huaiin/third-ui/fingerprint/server';
|
|
4
|
+
import { NextResponse } from 'next/server';
|
|
5
|
+
import { fetchUserContextByClerkUserId, fetchLatestUserContextByFingerprintId, mapSubscriptionToXSubscription, mapCreditToXCredit, mapUserToXUser } from '../../../../../services/context/user-context-service.mjs';
|
|
6
|
+
import { finalizeUserContext } from '../../../../../services/context/user-context-finalizer.mjs';
|
|
7
|
+
|
|
8
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
9
|
+
// Fix BigInt serialization issue
|
|
10
|
+
BigInt.prototype.toJSON = function () {
|
|
11
|
+
return this.toString();
|
|
12
|
+
};
|
|
13
|
+
// ==================== Utilities ====================
|
|
14
|
+
/** Create a successful response payload */
|
|
15
|
+
function createSuccessResponse(params) {
|
|
16
|
+
const response = Object.assign({ success: true, xUser: mapUserToXUser(params.entities.user), xCredit: params.entities.credit ? mapCreditToXCredit(params.entities.credit) : null, xSubscription: mapSubscriptionToXSubscription(params.entities.subscription), isNewUser: params.isNewUser }, params.options);
|
|
17
|
+
return finalizeUserContext(response);
|
|
18
|
+
}
|
|
19
|
+
/** Create an error response */
|
|
20
|
+
function createErrorResponse(message, status = 400) {
|
|
21
|
+
const errorResponse = { error: message };
|
|
22
|
+
return NextResponse.json(errorResponse, { status });
|
|
23
|
+
}
|
|
24
|
+
const SOURCE_REF_MAX_LENGTH = 2048;
|
|
25
|
+
const QUERY_PARAM_MAX_LENGTH = 512;
|
|
26
|
+
const USER_AGENT_MAX_LENGTH = 1024;
|
|
27
|
+
const FIRST_TOUCH_HEADER_MAX_LENGTH = 4096;
|
|
28
|
+
const FIRST_TOUCH_HEADER_NAME = 'x-first-touch';
|
|
29
|
+
function normalizeSourceRef(ref) {
|
|
30
|
+
if (!ref) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const trimmed = ref.trim();
|
|
34
|
+
if (!trimmed) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return trimmed.length > SOURCE_REF_MAX_LENGTH
|
|
38
|
+
? trimmed.slice(0, SOURCE_REF_MAX_LENGTH)
|
|
39
|
+
: trimmed;
|
|
40
|
+
}
|
|
41
|
+
function normalizeQueryParam(value) {
|
|
42
|
+
if (!value) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const trimmed = value.trim();
|
|
46
|
+
if (!trimmed) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return trimmed.length > QUERY_PARAM_MAX_LENGTH
|
|
50
|
+
? trimmed.slice(0, QUERY_PARAM_MAX_LENGTH)
|
|
51
|
+
: trimmed;
|
|
52
|
+
}
|
|
53
|
+
function decodeHeaderValue(value) {
|
|
54
|
+
try {
|
|
55
|
+
return decodeURIComponent(value);
|
|
56
|
+
}
|
|
57
|
+
catch (_a) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function mergeSourceRef(target, source) {
|
|
62
|
+
if (!source) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const entries = Object.entries(source);
|
|
66
|
+
for (const [key, value] of entries) {
|
|
67
|
+
if (value === undefined || value === null) {
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (target[key] === undefined) {
|
|
71
|
+
target[key] = value;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function applySearchParams(sourceRef, params) {
|
|
76
|
+
const setIfEmpty = (key, value) => {
|
|
77
|
+
if (sourceRef[key] !== undefined) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const normalized = normalizeQueryParam(value);
|
|
81
|
+
if (normalized) {
|
|
82
|
+
sourceRef[key] = normalized;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
setIfEmpty('utmSource', params.get('utm_source'));
|
|
86
|
+
setIfEmpty('utmMedium', params.get('utm_medium'));
|
|
87
|
+
setIfEmpty('utmCampaign', params.get('utm_campaign'));
|
|
88
|
+
setIfEmpty('utmTerm', params.get('utm_term'));
|
|
89
|
+
setIfEmpty('utmContent', params.get('utm_content'));
|
|
90
|
+
setIfEmpty('utmId', params.get('utm_id'));
|
|
91
|
+
setIfEmpty('ref', params.get('ref'));
|
|
92
|
+
setIfEmpty('gclid', params.get('gclid'));
|
|
93
|
+
setIfEmpty('fbclid', params.get('fbclid'));
|
|
94
|
+
setIfEmpty('msclkid', params.get('msclkid'));
|
|
95
|
+
setIfEmpty('ttclid', params.get('ttclid'));
|
|
96
|
+
setIfEmpty('twclid', params.get('twclid'));
|
|
97
|
+
setIfEmpty('liFatId', params.get('li_fat_id'));
|
|
98
|
+
}
|
|
99
|
+
function normalizeHost(host) {
|
|
100
|
+
if (!host) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return host.trim().toLowerCase() || null;
|
|
104
|
+
}
|
|
105
|
+
function getRootDomain(host) {
|
|
106
|
+
const normalizedHost = normalizeHost(host);
|
|
107
|
+
if (!normalizedHost) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
const hostname = normalizedHost.split(':')[0];
|
|
111
|
+
if (hostname === 'localhost' || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) {
|
|
112
|
+
return hostname;
|
|
113
|
+
}
|
|
114
|
+
const parts = hostname.split('.').filter(Boolean);
|
|
115
|
+
if (parts.length <= 2) {
|
|
116
|
+
return hostname;
|
|
117
|
+
}
|
|
118
|
+
return parts.slice(-2).join('.');
|
|
119
|
+
}
|
|
120
|
+
function isInternalReferer(landingHost, refererHost) {
|
|
121
|
+
const normalizedLandingHost = normalizeHost(landingHost);
|
|
122
|
+
const normalizedRefererHost = normalizeHost(refererHost);
|
|
123
|
+
if (!normalizedLandingHost || !normalizedRefererHost) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
if (normalizedLandingHost === normalizedRefererHost) {
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
return normalizedLandingHost.endsWith(`.${normalizedRefererHost}`)
|
|
130
|
+
|| normalizedRefererHost.endsWith(`.${normalizedLandingHost}`);
|
|
131
|
+
}
|
|
132
|
+
function detectPlatform(value) {
|
|
133
|
+
const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
|
|
134
|
+
if (!normalized) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const matcherList = [
|
|
138
|
+
{ pattern: /chatgpt|chat-openai|openai/, platform: 'openai', channel: 'ai' },
|
|
139
|
+
{ pattern: /claude|anthropic/, platform: 'anthropic', channel: 'ai' },
|
|
140
|
+
{ pattern: /perplexity/, platform: 'perplexity', channel: 'ai' },
|
|
141
|
+
{ pattern: /gemini/, platform: 'gemini', channel: 'ai' },
|
|
142
|
+
{ pattern: /copilot/, platform: 'copilot', channel: 'ai' },
|
|
143
|
+
{ pattern: /google/, platform: 'google', channel: 'search' },
|
|
144
|
+
{ pattern: /bing/, platform: 'bing', channel: 'search' },
|
|
145
|
+
{ pattern: /baidu/, platform: 'baidu', channel: 'search' },
|
|
146
|
+
{ pattern: /yahoo/, platform: 'yahoo', channel: 'search' },
|
|
147
|
+
{ pattern: /duckduckgo/, platform: 'duckduckgo', channel: 'search' },
|
|
148
|
+
{ pattern: /facebook/, platform: 'facebook', channel: 'social' },
|
|
149
|
+
{ pattern: /instagram/, platform: 'instagram', channel: 'social' },
|
|
150
|
+
{ pattern: /x\.com|twitter/, platform: 'x', channel: 'social' },
|
|
151
|
+
{ pattern: /linkedin/, platform: 'linkedin', channel: 'social' },
|
|
152
|
+
{ pattern: /reddit/, platform: 'reddit', channel: 'social' },
|
|
153
|
+
{ pattern: /youtube/, platform: 'youtube', channel: 'social' },
|
|
154
|
+
];
|
|
155
|
+
const matched = matcherList.find(({ pattern }) => pattern.test(normalized));
|
|
156
|
+
if (!matched) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
return matched.platform;
|
|
160
|
+
}
|
|
161
|
+
function detectChannelFromPlatform(platform) {
|
|
162
|
+
switch (platform) {
|
|
163
|
+
case 'openai':
|
|
164
|
+
case 'anthropic':
|
|
165
|
+
case 'perplexity':
|
|
166
|
+
case 'gemini':
|
|
167
|
+
case 'copilot':
|
|
168
|
+
return 'ai';
|
|
169
|
+
case 'google':
|
|
170
|
+
case 'bing':
|
|
171
|
+
case 'baidu':
|
|
172
|
+
case 'yahoo':
|
|
173
|
+
case 'duckduckgo':
|
|
174
|
+
return 'search';
|
|
175
|
+
case 'facebook':
|
|
176
|
+
case 'instagram':
|
|
177
|
+
case 'x':
|
|
178
|
+
case 'linkedin':
|
|
179
|
+
case 'reddit':
|
|
180
|
+
case 'youtube':
|
|
181
|
+
return 'social';
|
|
182
|
+
default:
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function detectChannelFromUtmMedium(value) {
|
|
187
|
+
const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
|
|
188
|
+
if (!normalized) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
if (/^(cpc|ppc|paid|paid_search|display|banner|affiliate|email|newsletter|push|sms)$/.test(normalized)) {
|
|
192
|
+
return 'campaign';
|
|
193
|
+
}
|
|
194
|
+
if (/^(social|social_paid|social-organic|social_organic)$/.test(normalized)) {
|
|
195
|
+
return 'social';
|
|
196
|
+
}
|
|
197
|
+
if (/^(organic|seo|search)$/.test(normalized)) {
|
|
198
|
+
return 'search';
|
|
199
|
+
}
|
|
200
|
+
if (/^(referral|partner)$/.test(normalized)) {
|
|
201
|
+
return 'referral';
|
|
202
|
+
}
|
|
203
|
+
if (/^(ai|llm)$/.test(normalized)) {
|
|
204
|
+
return 'ai';
|
|
205
|
+
}
|
|
206
|
+
return 'campaign';
|
|
207
|
+
}
|
|
208
|
+
function parseUserAgent(request) {
|
|
209
|
+
var _a, _b, _c, _d, _e;
|
|
210
|
+
const userAgentHeader = request.headers.get('user-agent');
|
|
211
|
+
const secChUaMobile = (_a = normalizeQueryParam(request.headers.get('sec-ch-ua-mobile'))) !== null && _a !== void 0 ? _a : undefined;
|
|
212
|
+
const secChUaPlatform = (_b = normalizeQueryParam(request.headers.get('sec-ch-ua-platform'))) !== null && _b !== void 0 ? _b : undefined;
|
|
213
|
+
const userAgent = (_d = (_c = normalizeSourceRef(userAgentHeader)) === null || _c === void 0 ? void 0 : _c.slice(0, USER_AGENT_MAX_LENGTH)) !== null && _d !== void 0 ? _d : undefined;
|
|
214
|
+
const ua = (_e = userAgent === null || userAgent === void 0 ? void 0 : userAgent.toLowerCase()) !== null && _e !== void 0 ? _e : '';
|
|
215
|
+
let deviceType = 'desktop';
|
|
216
|
+
if (!ua) {
|
|
217
|
+
deviceType = 'unknown';
|
|
218
|
+
}
|
|
219
|
+
else if (/bot|spider|crawler|curl|wget|headless/.test(ua)) {
|
|
220
|
+
deviceType = 'bot';
|
|
221
|
+
}
|
|
222
|
+
else if (/ipad|tablet/.test(ua)) {
|
|
223
|
+
deviceType = 'tablet';
|
|
224
|
+
}
|
|
225
|
+
else if (/mobi|iphone|android/.test(ua) || secChUaMobile === '?1') {
|
|
226
|
+
deviceType = 'mobile';
|
|
227
|
+
}
|
|
228
|
+
let os = 'Unknown';
|
|
229
|
+
if (/iphone|ipad|ipod/.test(ua)) {
|
|
230
|
+
os = 'iOS';
|
|
231
|
+
}
|
|
232
|
+
else if (/android/.test(ua)) {
|
|
233
|
+
os = 'Android';
|
|
234
|
+
}
|
|
235
|
+
else if (/windows nt/.test(ua)) {
|
|
236
|
+
os = 'Windows';
|
|
237
|
+
}
|
|
238
|
+
else if (/mac os x|macintosh/.test(ua)) {
|
|
239
|
+
os = 'macOS';
|
|
240
|
+
}
|
|
241
|
+
else if (/cros/.test(ua)) {
|
|
242
|
+
os = 'Chrome OS';
|
|
243
|
+
}
|
|
244
|
+
else if (/linux/.test(ua)) {
|
|
245
|
+
os = 'Linux';
|
|
246
|
+
}
|
|
247
|
+
if (secChUaPlatform) {
|
|
248
|
+
const normalizedPlatform = secChUaPlatform.replaceAll('"', '');
|
|
249
|
+
if (normalizedPlatform && normalizedPlatform !== 'Unknown') {
|
|
250
|
+
os = normalizedPlatform;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
let browser = 'Unknown';
|
|
254
|
+
if (/edg\//.test(ua)) {
|
|
255
|
+
browser = 'Edge';
|
|
256
|
+
}
|
|
257
|
+
else if (/opr\//.test(ua) || /opera/.test(ua)) {
|
|
258
|
+
browser = 'Opera';
|
|
259
|
+
}
|
|
260
|
+
else if (/samsungbrowser\//.test(ua)) {
|
|
261
|
+
browser = 'Samsung Internet';
|
|
262
|
+
}
|
|
263
|
+
else if (/crios\//.test(ua) || /chrome\//.test(ua)) {
|
|
264
|
+
browser = 'Chrome';
|
|
265
|
+
}
|
|
266
|
+
else if (/firefox\//.test(ua)) {
|
|
267
|
+
browser = 'Firefox';
|
|
268
|
+
}
|
|
269
|
+
else if (/safari\//.test(ua) && !/chrome\//.test(ua) && !/crios\//.test(ua)) {
|
|
270
|
+
browser = 'Safari';
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
userAgent,
|
|
274
|
+
deviceType,
|
|
275
|
+
os,
|
|
276
|
+
browser,
|
|
277
|
+
secChUaMobile,
|
|
278
|
+
secChUaPlatform,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function parseFirstTouchHeader(request) {
|
|
282
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
|
|
283
|
+
const rawHeader = request.headers.get(FIRST_TOUCH_HEADER_NAME);
|
|
284
|
+
const normalizedHeader = (_a = normalizeSourceRef(rawHeader)) === null || _a === void 0 ? void 0 : _a.slice(0, FIRST_TOUCH_HEADER_MAX_LENGTH);
|
|
285
|
+
if (!normalizedHeader) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
const decodedHeader = decodeHeaderValue(normalizedHeader);
|
|
289
|
+
if (!decodedHeader) {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
try {
|
|
293
|
+
const parsed = JSON.parse(decodedHeader);
|
|
294
|
+
const sourceRef = {};
|
|
295
|
+
sourceRef.capturedAt = (_b = normalizeQueryParam(typeof parsed.capturedAt === 'string' ? parsed.capturedAt : null)) !== null && _b !== void 0 ? _b : undefined;
|
|
296
|
+
sourceRef.landingUrl = (_c = normalizeSourceRef(typeof parsed.landingUrl === 'string' ? parsed.landingUrl : null)) !== null && _c !== void 0 ? _c : undefined;
|
|
297
|
+
sourceRef.landingPath = (_d = normalizeSourceRef(typeof parsed.landingPath === 'string' ? parsed.landingPath : null)) !== null && _d !== void 0 ? _d : undefined;
|
|
298
|
+
sourceRef.landingHost = (_e = normalizeHost(typeof parsed.landingHost === 'string' ? parsed.landingHost : null)) !== null && _e !== void 0 ? _e : undefined;
|
|
299
|
+
sourceRef.ref = (_f = normalizeQueryParam(typeof parsed.ref === 'string' ? parsed.ref : null)) !== null && _f !== void 0 ? _f : undefined;
|
|
300
|
+
sourceRef.utmSource = (_g = normalizeQueryParam(typeof parsed.utmSource === 'string' ? parsed.utmSource : null)) !== null && _g !== void 0 ? _g : undefined;
|
|
301
|
+
sourceRef.utmMedium = (_h = normalizeQueryParam(typeof parsed.utmMedium === 'string' ? parsed.utmMedium : null)) !== null && _h !== void 0 ? _h : undefined;
|
|
302
|
+
sourceRef.utmCampaign = (_j = normalizeQueryParam(typeof parsed.utmCampaign === 'string' ? parsed.utmCampaign : null)) !== null && _j !== void 0 ? _j : undefined;
|
|
303
|
+
sourceRef.utmTerm = (_k = normalizeQueryParam(typeof parsed.utmTerm === 'string' ? parsed.utmTerm : null)) !== null && _k !== void 0 ? _k : undefined;
|
|
304
|
+
sourceRef.utmContent = (_l = normalizeQueryParam(typeof parsed.utmContent === 'string' ? parsed.utmContent : null)) !== null && _l !== void 0 ? _l : undefined;
|
|
305
|
+
sourceRef.utmId = (_m = normalizeQueryParam(typeof parsed.utmId === 'string' ? parsed.utmId : null)) !== null && _m !== void 0 ? _m : undefined;
|
|
306
|
+
sourceRef.gclid = (_o = normalizeQueryParam(typeof parsed.gclid === 'string' ? parsed.gclid : null)) !== null && _o !== void 0 ? _o : undefined;
|
|
307
|
+
sourceRef.fbclid = (_p = normalizeQueryParam(typeof parsed.fbclid === 'string' ? parsed.fbclid : null)) !== null && _p !== void 0 ? _p : undefined;
|
|
308
|
+
sourceRef.msclkid = (_q = normalizeQueryParam(typeof parsed.msclkid === 'string' ? parsed.msclkid : null)) !== null && _q !== void 0 ? _q : undefined;
|
|
309
|
+
sourceRef.ttclid = (_r = normalizeQueryParam(typeof parsed.ttclid === 'string' ? parsed.ttclid : null)) !== null && _r !== void 0 ? _r : undefined;
|
|
310
|
+
sourceRef.twclid = (_s = normalizeQueryParam(typeof parsed.twclid === 'string' ? parsed.twclid : null)) !== null && _s !== void 0 ? _s : undefined;
|
|
311
|
+
sourceRef.liFatId = (_t = normalizeQueryParam(typeof parsed.liFatId === 'string' ? parsed.liFatId : null)) !== null && _t !== void 0 ? _t : undefined;
|
|
312
|
+
const externalReferrer = normalizeSourceRef(typeof parsed.externalReferrer === 'string' ? parsed.externalReferrer : null);
|
|
313
|
+
if (externalReferrer) {
|
|
314
|
+
sourceRef.httpRefer = externalReferrer;
|
|
315
|
+
try {
|
|
316
|
+
const refererUrl = new URL(externalReferrer);
|
|
317
|
+
sourceRef.refererHost = (_u = normalizeHost(refererUrl.host)) !== null && _u !== void 0 ? _u : undefined;
|
|
318
|
+
sourceRef.refererPath = (_v = normalizeSourceRef(refererUrl.pathname)) !== null && _v !== void 0 ? _v : undefined;
|
|
319
|
+
sourceRef.refererDomain = (_w = getRootDomain(refererUrl.host)) !== null && _w !== void 0 ? _w : undefined;
|
|
320
|
+
applySearchParams(sourceRef, refererUrl.searchParams);
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
console.warn('Failed to parse first-touch referrer url:', error);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return Object.keys(sourceRef).length > 0 ? sourceRef : null;
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
console.warn('Failed to parse first-touch header:', error);
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function finalizeAttribution(sourceRef) {
|
|
334
|
+
var _a, _b, _c, _d, _e;
|
|
335
|
+
const landingHost = normalizeHost(sourceRef.landingHost);
|
|
336
|
+
const refererHost = normalizeHost(sourceRef.refererHost);
|
|
337
|
+
const internal = isInternalReferer(landingHost, refererHost);
|
|
338
|
+
const hasCampaignMarker = Boolean(sourceRef.utmSource
|
|
339
|
+
|| sourceRef.utmMedium
|
|
340
|
+
|| sourceRef.utmCampaign
|
|
341
|
+
|| sourceRef.utmTerm
|
|
342
|
+
|| sourceRef.utmContent
|
|
343
|
+
|| sourceRef.utmId
|
|
344
|
+
|| sourceRef.ref
|
|
345
|
+
|| sourceRef.gclid
|
|
346
|
+
|| sourceRef.fbclid
|
|
347
|
+
|| sourceRef.msclkid
|
|
348
|
+
|| sourceRef.ttclid
|
|
349
|
+
|| sourceRef.twclid
|
|
350
|
+
|| sourceRef.liFatId);
|
|
351
|
+
if (internal) {
|
|
352
|
+
sourceRef.isInternalReferer = true;
|
|
353
|
+
}
|
|
354
|
+
const utmPlatform = detectPlatform(sourceRef.utmSource) || detectPlatform(sourceRef.ref);
|
|
355
|
+
if (utmPlatform) {
|
|
356
|
+
sourceRef.sourcePlatform = utmPlatform;
|
|
357
|
+
sourceRef.sourceChannel = (_c = (_b = (_a = detectChannelFromPlatform(utmPlatform)) !== null && _a !== void 0 ? _a : detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _b !== void 0 ? _b : sourceRef.sourceChannel) !== null && _c !== void 0 ? _c : 'campaign';
|
|
358
|
+
sourceRef.sourceType = 'campaign';
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (sourceRef.gclid) {
|
|
362
|
+
sourceRef.sourcePlatform = 'google';
|
|
363
|
+
sourceRef.sourceChannel = 'search';
|
|
364
|
+
sourceRef.sourceType = 'campaign';
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (sourceRef.msclkid) {
|
|
368
|
+
sourceRef.sourcePlatform = 'bing';
|
|
369
|
+
sourceRef.sourceChannel = 'search';
|
|
370
|
+
sourceRef.sourceType = 'campaign';
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (sourceRef.fbclid) {
|
|
374
|
+
sourceRef.sourcePlatform = 'facebook';
|
|
375
|
+
sourceRef.sourceChannel = 'social';
|
|
376
|
+
sourceRef.sourceType = 'campaign';
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
if (sourceRef.ttclid) {
|
|
380
|
+
sourceRef.sourcePlatform = 'tiktok';
|
|
381
|
+
sourceRef.sourceChannel = 'social';
|
|
382
|
+
sourceRef.sourceType = 'campaign';
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (sourceRef.twclid) {
|
|
386
|
+
sourceRef.sourcePlatform = 'x';
|
|
387
|
+
sourceRef.sourceChannel = 'social';
|
|
388
|
+
sourceRef.sourceType = 'campaign';
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (sourceRef.liFatId) {
|
|
392
|
+
sourceRef.sourcePlatform = 'linkedin';
|
|
393
|
+
sourceRef.sourceChannel = 'social';
|
|
394
|
+
sourceRef.sourceType = 'campaign';
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (hasCampaignMarker) {
|
|
398
|
+
sourceRef.sourcePlatform = 'other';
|
|
399
|
+
sourceRef.sourceChannel = (_d = detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _d !== void 0 ? _d : 'campaign';
|
|
400
|
+
sourceRef.sourceType = 'campaign';
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (!internal && refererHost) {
|
|
404
|
+
const refererPlatform = detectPlatform(refererHost) || detectPlatform(sourceRef.httpRefer);
|
|
405
|
+
sourceRef.sourcePlatform = refererPlatform !== null && refererPlatform !== void 0 ? refererPlatform : 'other';
|
|
406
|
+
sourceRef.sourceChannel = (_e = detectChannelFromPlatform(refererPlatform)) !== null && _e !== void 0 ? _e : 'referral';
|
|
407
|
+
sourceRef.sourceType = 'referer';
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
sourceRef.sourcePlatform = 'direct';
|
|
411
|
+
sourceRef.sourceChannel = 'direct';
|
|
412
|
+
sourceRef.sourceType = 'direct';
|
|
413
|
+
}
|
|
414
|
+
// Extract the user's first-touch attribution source.
|
|
415
|
+
function extractSourceRef(request) {
|
|
416
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
|
|
417
|
+
const headerRef = request.headers.get('referer') || request.headers.get('referrer');
|
|
418
|
+
const customRef = request.headers.get('x-source-ref');
|
|
419
|
+
const queryRef = request.nextUrl.searchParams.get('ref');
|
|
420
|
+
const firstTouchRef = parseFirstTouchHeader(request);
|
|
421
|
+
const sourceRef = Object.assign({}, parseUserAgent(request));
|
|
422
|
+
mergeSourceRef(sourceRef, firstTouchRef);
|
|
423
|
+
sourceRef.landingUrl = (_b = (_a = sourceRef.landingUrl) !== null && _a !== void 0 ? _a : normalizeSourceRef(request.nextUrl.toString())) !== null && _b !== void 0 ? _b : undefined;
|
|
424
|
+
sourceRef.landingPath = (_d = (_c = sourceRef.landingPath) !== null && _c !== void 0 ? _c : normalizeSourceRef(request.nextUrl.pathname)) !== null && _d !== void 0 ? _d : undefined;
|
|
425
|
+
sourceRef.landingHost = (_f = (_e = sourceRef.landingHost) !== null && _e !== void 0 ? _e : normalizeHost(request.nextUrl.host)) !== null && _f !== void 0 ? _f : undefined;
|
|
426
|
+
sourceRef.ref = (_h = (_g = sourceRef.ref) !== null && _g !== void 0 ? _g : normalizeQueryParam(queryRef)) !== null && _h !== void 0 ? _h : undefined;
|
|
427
|
+
let normalizedHttpRef = null;
|
|
428
|
+
const candidates = [customRef, headerRef];
|
|
429
|
+
for (const candidate of candidates) {
|
|
430
|
+
const normalized = normalizeSourceRef(candidate);
|
|
431
|
+
if (normalized) {
|
|
432
|
+
normalizedHttpRef = normalized;
|
|
433
|
+
sourceRef.httpRefer = (_j = sourceRef.httpRefer) !== null && _j !== void 0 ? _j : normalized;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const searchParams = request.nextUrl.searchParams;
|
|
438
|
+
applySearchParams(sourceRef, searchParams);
|
|
439
|
+
if (normalizedHttpRef) {
|
|
440
|
+
try {
|
|
441
|
+
const refererUrl = new URL(normalizedHttpRef);
|
|
442
|
+
sourceRef.refererHost = (_l = (_k = sourceRef.refererHost) !== null && _k !== void 0 ? _k : normalizeHost(refererUrl.host)) !== null && _l !== void 0 ? _l : undefined;
|
|
443
|
+
sourceRef.refererPath = (_o = (_m = sourceRef.refererPath) !== null && _m !== void 0 ? _m : normalizeSourceRef(refererUrl.pathname)) !== null && _o !== void 0 ? _o : undefined;
|
|
444
|
+
sourceRef.refererDomain = (_q = (_p = sourceRef.refererDomain) !== null && _p !== void 0 ? _p : getRootDomain(refererUrl.host)) !== null && _q !== void 0 ? _q : undefined;
|
|
445
|
+
applySearchParams(sourceRef, refererUrl.searchParams);
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
console.warn('Failed to parse referer url for utm/ref:', error);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
finalizeAttribution(sourceRef);
|
|
452
|
+
return Object.keys(sourceRef).length > 0 ? sourceRef : null;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Query the user by Clerk user ID and return response data.
|
|
456
|
+
*/
|
|
457
|
+
function getUserByClerkId(clerkUserId) {
|
|
458
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
459
|
+
const entities = yield fetchUserContextByClerkUserId(clerkUserId);
|
|
460
|
+
if (!entities) {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
return createSuccessResponse({
|
|
464
|
+
entities,
|
|
465
|
+
isNewUser: false,
|
|
466
|
+
});
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Query the user by fingerprint ID and return response data.
|
|
471
|
+
*/
|
|
472
|
+
function getUserByFingerprintId(fingerprintId) {
|
|
473
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
474
|
+
const result = yield fetchLatestUserContextByFingerprintId(fingerprintId);
|
|
475
|
+
if (!result) {
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
const { totalUsersOnDevice, hasAnonymousUser } = result, entities = __rest(result, ["totalUsersOnDevice", "hasAnonymousUser"]);
|
|
479
|
+
return createSuccessResponse({
|
|
480
|
+
entities,
|
|
481
|
+
isNewUser: false,
|
|
482
|
+
options: {
|
|
483
|
+
totalUsersOnDevice,
|
|
484
|
+
hasAnonymousUser,
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Shared fingerprint request handling logic.
|
|
491
|
+
*/
|
|
492
|
+
function handleFingerprintRequest(request, options) {
|
|
493
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
494
|
+
var _a;
|
|
495
|
+
// Extract the fingerprint ID from the request.
|
|
496
|
+
const fingerprintId = extractFingerprintFromNextRequest(request);
|
|
497
|
+
// Validate the fingerprint ID.
|
|
498
|
+
if (!fingerprintId) {
|
|
499
|
+
return createErrorResponse('Invalid or missing fingerprint ID');
|
|
500
|
+
}
|
|
501
|
+
console.log('Received fingerprintId:', fingerprintId);
|
|
502
|
+
const authIdentity = yield options.getAuthIdentity();
|
|
503
|
+
const clerkUserId = (_a = authIdentity === null || authIdentity === void 0 ? void 0 : authIdentity.providerUserId) !== null && _a !== void 0 ? _a : null;
|
|
504
|
+
try {
|
|
505
|
+
// Prefer Clerk user ID lookup when the user is authenticated.
|
|
506
|
+
let existingUserResult = null;
|
|
507
|
+
if (clerkUserId) {
|
|
508
|
+
// Authenticated users are always resolved by clerkUserId.
|
|
509
|
+
existingUserResult = yield getUserByClerkId(clerkUserId);
|
|
510
|
+
if (existingUserResult && existingUserResult.xUser.fingerprintId !== fingerprintId) {
|
|
511
|
+
// The authenticated user's fingerprint changed. Clerk still identifies the account as the same user.
|
|
512
|
+
// Trust clerkUserId as the source of truth and keep resolving the user's own data by login identity.
|
|
513
|
+
// A single fingerprint can be associated with multiple accounts, so no mutation is needed here.
|
|
514
|
+
console.warn(`Current login user used diff fp_ids: ${clerkUserId}, db_fp_id=${existingUserResult.xUser.fingerprintId}, req_fp_id=${fingerprintId}`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
// For anonymous requests, fall back to fingerprint lookup.
|
|
519
|
+
existingUserResult = yield getUserByFingerprintId(fingerprintId);
|
|
520
|
+
}
|
|
521
|
+
if (existingUserResult) {
|
|
522
|
+
return NextResponse.json(existingUserResult);
|
|
523
|
+
}
|
|
524
|
+
// If the user does not exist and creation is disabled, return 404.
|
|
525
|
+
if (!options.createIfNotExists) {
|
|
526
|
+
return createErrorResponse('User not found', 404);
|
|
527
|
+
}
|
|
528
|
+
const sourceRef = extractSourceRef(request);
|
|
529
|
+
const anonymousInitResult = yield anonymousAggregateService.getOrCreateByFingerprintId(fingerprintId, { sourceRef: sourceRef !== null && sourceRef !== void 0 ? sourceRef : undefined });
|
|
530
|
+
if (anonymousInitResult.isNewUser) {
|
|
531
|
+
console.log(`Created new anonymous user ${anonymousInitResult.user.userId} with fingerprint ${fingerprintId}`);
|
|
532
|
+
}
|
|
533
|
+
// Return the created or existing context.
|
|
534
|
+
const response = createSuccessResponse({
|
|
535
|
+
entities: {
|
|
536
|
+
user: anonymousInitResult.user,
|
|
537
|
+
credit: anonymousInitResult.credit,
|
|
538
|
+
subscription: anonymousInitResult.subscription,
|
|
539
|
+
},
|
|
540
|
+
isNewUser: anonymousInitResult.isNewUser,
|
|
541
|
+
options: {
|
|
542
|
+
totalUsersOnDevice: anonymousInitResult.totalUsersOnDevice,
|
|
543
|
+
hasAnonymousUser: anonymousInitResult.hasAnonymousUser,
|
|
544
|
+
},
|
|
545
|
+
});
|
|
546
|
+
return NextResponse.json(response);
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
console.error('Fingerprint request error:', error);
|
|
550
|
+
return createErrorResponse('Internal server error', 500);
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
export { handleFingerprintRequest };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { NextRequest
|
|
1
|
+
import type { NextRequest } from 'next/server';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Clerk-aware anonymous user initialization API.
|
|
4
4
|
* POST /api/user/anonymous/init
|
|
5
5
|
*/
|
|
6
|
-
export declare function POST(request: NextRequest): Promise<NextResponse<unknown>>;
|
|
6
|
+
export declare function POST(request: NextRequest): Promise<import("next/server").NextResponse<unknown>>;
|
|
7
7
|
//# sourceMappingURL=route.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C;;;GAGG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW,wDAK9C"}
|