1
2
3
4
5
6
7
8import http from 'node:http';
9import { Actor, log } from 'apify';
10
11import { createNormalizer } from './normalizer.js';
12import { preprocess } from './preprocessor.js';
13
14
15
16
17
18
19function normalizeItems(items) {
20 return items.map((item) => {
21 if (typeof item === 'string') {
22 return item;
23 }
24 if (item && typeof item === 'object' && 'input' in item) {
25 return String(item.input ?? '');
26 }
27 return String(item ?? '');
28 });
29}
30
31await Actor.init();
32
33if (Actor.config.get('metaOrigin') === 'STANDBY') {
34 startStandbyServer();
35} else {
36 await runBatchMode();
37 await Actor.exit();
38}
39
40
41
42
43
44function startStandbyServer() {
45 const port = Actor.config.get('containerPort');
46
47 const server = http.createServer(async (req, res) => {
48
49 if (req.headers['x-apify-container-server-readiness-probe']) {
50 res.writeHead(200, { 'Content-Type': 'application/json' });
51 res.end(JSON.stringify({ status: 'ready' }));
52 return;
53 }
54
55
56 if (req.method !== 'GET') {
57 res.writeHead(405, { 'Content-Type': 'application/json' });
58 res.end(JSON.stringify({ error: 'Method not allowed. Use GET.' }));
59 return;
60 }
61
62
63 const reqUrl = new URL(req.url, `http://${req.headers.host}`);
64 if (!reqUrl.searchParams.get('input')) {
65 res.writeHead(200, { 'Content-Type': 'text/html' });
66 res.end(getLandingPageHtml());
67 return;
68 }
69
70 try {
71 const result = await handleStandbyRequest(reqUrl, req);
72 await Actor.pushData(result);
73
74 res.writeHead(200, { 'Content-Type': 'application/json' });
75 res.end(JSON.stringify(result));
76 } catch (err) {
77 const statusCode = err.statusCode || 500;
78 res.writeHead(statusCode, { 'Content-Type': 'application/json' });
79 res.end(JSON.stringify({ error: err.message }));
80 }
81 });
82
83 server.listen(port, () => {
84 console.log(`Superclean Person Names Standby server listening on port ${port}`);
85 });
86}
87
88async function handleStandbyRequest(reqUrl, req) {
89 const input = reqUrl.searchParams.get('input');
90
91 if (!input) {
92 const err = new Error("Provide an 'input' query parameter with the person name to clean.");
93 err.statusCode = 400;
94 throw err;
95 }
96
97 const style = reqUrl.searchParams.get('style') || 'casual';
98 const model = reqUrl.searchParams.get('model') || 'openrouter/auto';
99 const openRouterApiKey = req.headers['x-openrouter-key'] || null;
100
101 const validStyles = ['first', 'casual', 'formal'];
102 if (!validStyles.includes(style)) {
103 const err = new Error(`Invalid style "${style}". Must be one of: ${validStyles.join(', ')}`);
104 err.statusCode = 400;
105 throw err;
106 }
107
108 const trimmed = input.trim();
109 if (!trimmed) {
110 return { id: 1, input, output: '', confidence: 0 };
111 }
112
113
114 const preprocessResult = preprocess(trimmed);
115
116
117 if (preprocessResult.isNonEnglish) {
118 return {
119 id: 1,
120 input: trimmed,
121 output: preprocessResult.extractedEnglish || trimmed,
122 confidence: 0,
123 };
124 }
125
126
127 const item = {
128 id: 1,
129 input: trimmed,
130 preProcessed: preprocessResult.value,
131 isNonEnglish: false,
132 extractedEnglish: preprocessResult.extractedEnglish,
133 detectedComponents: preprocessResult.detectedComponents,
134 };
135
136 const normalizer = createNormalizer(model, style, openRouterApiKey);
137 const normalizedItems = await normalizer.normalize([item]);
138
139 if (normalizedItems.length === 0) {
140 return { id: 1, input: trimmed, output: trimmed, confidence: 0 };
141 }
142
143 return {
144 id: 1,
145 input: trimmed,
146 output: normalizedItems[0].normalized,
147 confidence: Math.round(normalizedItems[0].confidence * 100) / 100,
148 };
149}
150
151
152
153
154
155async function runBatchMode() {
156
157 const input = await Actor.getInput();
158 let { items: rawItems, item } = input || {};
159
160
161 if (typeof item === 'string' && item.trim()) {
162 if (!Array.isArray(rawItems)) rawItems = [];
163 rawItems = [item.trim(), ...rawItems];
164 }
165
166
167 if (typeof rawItems === 'string') rawItems = [rawItems];
168
169
170 if (!rawItems || !Array.isArray(rawItems) || rawItems.length === 0) {
171 await Actor.pushData({ error: 'missing_items', message: 'Input required: provide "items" (array) or "item" (single string). Example: {"items": ["John Smith"]}' });
172 await Actor.exit('Skipped: Input required: provide "items" (array) or "item" (single string). Example: {"items": ["John Smith"]}');
173 return;
174 }
175
176
177 const style = input.style ?? 'casual';
178 const model = input.model ?? 'openrouter/auto';
179 const openRouterApiKey = input.openRouterApiKey ?? null;
180
181
182 const items = normalizeItems(rawItems);
183
184 log.info(`Starting normalization of ${items.length} person names`, {
185 style,
186 model,
187 });
188
189
190 const processedItems = items.map((item, index) => {
191
192 const value = typeof item === 'string' ? item : String(item || '');
193 const id = index + 1;
194
195
196 if (!value.trim()) {
197 log.warning(`Skipping invalid item at index ${index}`, { item });
198 return null;
199 }
200
201
202 const preprocessResult = preprocess(value);
203
204 return {
205 id,
206 input: value,
207 preProcessed: preprocessResult.value,
208 isNonEnglish: preprocessResult.isNonEnglish,
209 extractedEnglish: preprocessResult.extractedEnglish,
210 detectedComponents: preprocessResult.detectedComponents,
211 };
212 });
213
214
215 const validItems = processedItems.filter((item) => item !== null);
216
217 if (validItems.length === 0) {
218 await Actor.pushData({ error: 'no_valid_items', message: 'No valid items to process after input validation' });
219 await Actor.exit('Skipped: No valid items to process after input validation');
220 return;
221 }
222
223
224 const englishItems = validItems.filter((item) => !item.isNonEnglish);
225 const nonEnglishItems = validItems.filter((item) => item.isNonEnglish);
226
227 if (nonEnglishItems.length > 0) {
228 log.info(`Flagging ${nonEnglishItems.length} non-English names for review`);
229 }
230
231 log.info(`Pre-processed ${validItems.length} items (${englishItems.length} English, ${nonEnglishItems.length} non-English)`);
232
233
234 let normalizedItems = [];
235 if (englishItems.length > 0) {
236 const normalizer = createNormalizer(model, style, openRouterApiKey);
237 normalizedItems = await normalizer.normalize(englishItems);
238 }
239
240
241 const englishResults = normalizedItems.map((item) => ({
242 id: item.id,
243 input: item.input,
244 output: item.normalized,
245 confidence: Math.round(item.confidence * 100) / 100,
246 }));
247
248 const nonEnglishResults = nonEnglishItems.map((item) => ({
249 id: item.id,
250 input: item.input,
251 output: item.extractedEnglish || item.input,
252 confidence: 0,
253 }));
254
255 const results = [...englishResults, ...nonEnglishResults];
256
257
258
259 await Actor.pushData(results);
260
261
262 const avgConfidence = results.reduce((sum, r) => sum + r.confidence, 0) / results.length;
263
264 log.info(`Normalization complete`, {
265 totalItems: results.length,
266 averageConfidence: Math.round(avgConfidence * 100) / 100,
267 });
268}
269
270
271
272
273
274function getLandingPageHtml() {
275 return `<!DOCTYPE html>
276<html lang="en">
277<head>
278<meta charset="utf-8">
279<meta name="viewport" content="width=device-width, initial-scale=1">
280<title>Superclean Person Names — Superlative</title>
281<link rel="preconnect" href="https://fonts.googleapis.com">
282<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
283<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
284<style>
285:root{--color-bg:#0a0e14;--color-surface:#12171f;--color-border:#1e2632;--color-text:#e8eaed;--color-text-muted:#8b95a5;--color-accent:#4ade80;--color-accent-dim:rgba(74,222,128,0.15);--font-display:'Space Mono',monospace;--font-body:'DM Sans',sans-serif}
286*{margin:0;padding:0;box-sizing:border-box}
287body{font-family:var(--font-body);background:var(--color-bg);color:var(--color-text);line-height:1.6;min-height:100vh;overflow-x:hidden}
288a{color:var(--color-accent);text-decoration:none;transition:color .2s ease}a:hover{color:#6ee7a0}
289.grid-bg{position:fixed;top:0;left:0;width:100%;height:100%;background-image:linear-gradient(var(--color-border) 1px,transparent 1px),linear-gradient(90deg,var(--color-border) 1px,transparent 1px);background-size:60px 60px;opacity:.3;pointer-events:none;z-index:0}
290.accent-line{position:fixed;top:0;left:0;width:100%;height:2px;background:linear-gradient(90deg,transparent 0%,var(--color-accent) 50%,transparent 100%);animation:shimmer 3s ease-in-out infinite;z-index:10}
291@keyframes shimmer{0%,100%{transform:translateX(-100%)}50%{transform:translateX(100%)}}
292@keyframes fadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
293.container{position:relative;z-index:1;max-width:900px;margin:0 auto;padding:0 24px}
294header{padding:32px 0}.logo{font-family:var(--font-display);font-size:14px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--color-text);display:flex;align-items:center;gap:10px;text-decoration:none}.logo:hover{color:var(--color-text)}.logo-mark{width:28px;height:28px;background:var(--color-accent);display:flex;align-items:center;justify-content:center}.logo-mark svg{width:16px;height:16px}
295.hero{padding:80px 0 60px;animation:fadeUp .8s ease-out}.hero-label{font-family:var(--font-display);font-size:12px;font-weight:400;letter-spacing:.15em;text-transform:uppercase;color:var(--color-accent);margin-bottom:24px;display:flex;align-items:center;gap:12px}.hero-label::before{content:'';width:24px;height:1px;background:var(--color-accent)}
296h1{font-family:var(--font-display);font-size:clamp(28px,5vw,44px);font-weight:700;line-height:1.15;margin-bottom:20px;letter-spacing:-.02em}h1 .highlight{color:var(--color-accent)}
297.hero-desc{font-size:18px;color:var(--color-text-muted);max-width:540px;margin-bottom:28px;line-height:1.7}.hero-link{font-family:var(--font-display);font-size:13px;letter-spacing:.05em;color:var(--color-accent);display:inline-flex;align-items:center;gap:6px}
298.section{padding:60px 0;border-top:1px solid var(--color-border);animation:fadeUp .8s ease-out .2s backwards}.section-label{font-family:var(--font-display);font-size:11px;font-weight:400;letter-spacing:.2em;text-transform:uppercase;color:var(--color-text-muted);margin-bottom:24px}
299h2{font-family:var(--font-display);font-size:20px;font-weight:700;margin-bottom:16px;letter-spacing:-.01em}p,li{font-size:15px;color:var(--color-text-muted);line-height:1.7}li{margin-bottom:6px}ul{margin:.5rem 0 1rem 1.25rem}strong{color:var(--color-text);font-weight:600}
300pre{background:var(--color-surface);color:var(--color-text);padding:16px 20px;overflow-x:auto;margin:12px 0 16px;font-family:var(--font-display);font-size:13px;line-height:1.6;border:1px solid var(--color-border)}code{font-family:var(--font-display);font-size:13px}p code,li code,td code{background:var(--color-accent-dim);color:var(--color-accent);padding:2px 6px}
301table{width:100%;border-collapse:collapse;margin:12px 0 16px;font-size:14px}th,td{border:1px solid var(--color-border);padding:10px 14px;text-align:left}th{background:var(--color-surface);color:var(--color-text-muted);font-family:var(--font-display);font-size:12px;font-weight:400;letter-spacing:.05em;text-transform:uppercase}td{color:var(--color-text-muted)}
302.badge{display:inline-block;background:var(--color-accent-dim);color:var(--color-accent);padding:3px 8px;font-family:var(--font-display);font-size:11px;font-weight:400;letter-spacing:.05em}
303.product-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px;margin-top:24px}.product-card{background:var(--color-surface);border:1px solid var(--color-border);padding:24px;transition:all .3s ease;text-decoration:none;color:inherit;display:block}.product-card:hover{border-color:var(--color-accent);transform:translateY(-2px)}.product-name{font-family:var(--font-display);font-size:14px;font-weight:700;margin-bottom:8px;color:var(--color-text);display:flex;align-items:center;gap:8px}.product-name .status{font-size:9px;font-weight:400;padding:3px 6px;background:var(--color-accent-dim);color:var(--color-accent);letter-spacing:.1em}.product-desc{font-size:14px;color:var(--color-text-muted);line-height:1.5}
304footer{padding:48px 0;border-top:1px solid var(--color-border)}.footer-content{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:24px}.footer-text{font-size:13px;color:var(--color-text-muted)}.footer-links{display:flex;gap:24px}.footer-links a{font-family:var(--font-display);font-size:12px;color:var(--color-text-muted);letter-spacing:.05em}.footer-links a:hover{color:var(--color-accent)}
305@media(max-width:600px){.hero{padding:60px 0 40px}.section{padding:40px 0}.footer-content{flex-direction:column;align-items:flex-start}pre{font-size:12px;padding:12px 14px}}
306</style>
307</head>
308<body>
309<div class="grid-bg"></div>
310<div class="accent-line"></div>
311<div class="container">
312 <header><a href="https://apify.com/superlativetech?fpr=8e9l1" class="logo"><div class="logo-mark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="4 17 10 11 4 5"></polyline><line x1="12" y1="19" x2="20" y2="19"></line></svg></div>Superlative</a></header>
313
314 <section class="hero">
315 <div class="hero-label">Superclean</div>
316 <h1>Person <span class="highlight">Names</span></h1>
317 <p class="hero-desc">Instant person name cleaning. AI-powered normalization for cold email personalization and CRM. Sub-second responses via Standby API.</p>
318 <a href="https://apify.com/superlativetech/superclean-person-names?fpr=8e9l1" class="hero-link">View on Apify Store →</a>
319 </section>
320
321 <section class="section">
322 <div class="section-label">Features</div>
323 <h2>What this does</h2>
324 <ul>
325 <li><strong>AI-powered cleaning</strong> — LLM normalizes person names with context awareness</li>
326 <li><strong>Three styles</strong> — First name only, Casual, Formal</li>
327 <li><strong>Handles titles</strong> — Strips Dr., Mr., Mrs., PhD, MD, etc.</li>
328 <li><strong>BYOK support</strong> — Use your own OpenRouter API key via header</li>
329 <li><strong>Batch mode</strong> — Process hundreds of names via the standard Actor run</li>
330 </ul>
331 </section>
332
333 <section class="section">
334 <div class="section-label">Getting Started</div>
335 <h2>Quick start</h2>
336 <p>Replace <code>YOUR_TOKEN</code> with your Apify API token.</p>
337 <p style="margin-top:16px"><strong>Casual style (default):</strong></p>
338 <pre>curl "https://superlativetech--superclean-person-names.apify.actor?token=YOUR_TOKEN&input=DR.+JOHN+SMITH+III"</pre>
339 <p><strong>First name only:</strong></p>
340 <pre>curl "https://superlativetech--superclean-person-names.apify.actor?token=YOUR_TOKEN&input=DR.+JOHN+SMITH+III&style=first"</pre>
341 <p><strong>With your own OpenRouter key:</strong></p>
342 <pre>curl -H "X-OpenRouter-Key: sk-or-..." "https://superlativetech--superclean-person-names.apify.actor?token=YOUR_TOKEN&input=mcdonald,+sarah+jane"</pre>
343 </section>
344
345 <section class="section">
346 <div class="section-label">Reference</div>
347 <h2>Query parameters</h2>
348 <table>
349 <tr><th>Parameter</th><th>Required</th><th>Description</th></tr>
350 <tr><td><code>input</code></td><td>Yes</td><td>Person name to clean</td></tr>
351 <tr><td><code>style</code></td><td>No</td><td>Output style: <code>first</code>, <code>casual</code> (default), or <code>formal</code></td></tr>
352 <tr><td><code>model</code></td><td>No</td><td>LLM model (default: <code>openrouter/auto</code>)</td></tr>
353 <tr><td><code>token</code></td><td>Yes</td><td>Your Apify API token</td></tr>
354 </table>
355 <h2 style="margin-top:24px">Headers</h2>
356 <table>
357 <tr><th>Header</th><th>Required</th><th>Description</th></tr>
358 <tr><td><code>X-OpenRouter-Key</code></td><td>No</td><td>Your OpenRouter API key for BYOK</td></tr>
359 </table>
360 </section>
361
362 <section class="section">
363 <div class="section-label">Response</div>
364 <h2>Response format</h2>
365 <pre>{
366 "id": 1,
367 "input": "DR. JOHN SMITH III",
368 "output": "John Smith",
369 "confidence": 0.95
370}</pre>
371 </section>
372
373 <section class="section">
374 <div class="section-label">Cost</div>
375 <h2>Pricing</h2>
376 <p>Free to use — you only pay standard Apify platform usage.</p>
377 </section>
378
379 <section class="section">
380 <div class="section-label">Auth</div>
381 <h2>Authentication</h2>
382 <p>Authenticate using either method:</p>
383 <ul>
384 <li>Query parameter: <code>?token=YOUR_APIFY_TOKEN</code></li>
385 <li>Header: <code>Authorization: Bearer YOUR_APIFY_TOKEN</code></li>
386 </ul>
387 <p style="margin-top:8px">Get your token from <a href="https://console.apify.com/settings/integrations">Apify Console → Settings → Integrations</a>.</p>
388 </section>
389
390 <section class="section">
391 <div class="section-label">Superlative</div>
392 <h2>More from Superlative</h2>
393 <div class="product-grid">
394 <a href="https://apify.com/superlativetech/superclean-company-names?fpr=8e9l1" class="product-card"><div class="product-name">Company Names <span class="status">Live</span></div><p class="product-desc">Normalize company names for CRM and cold email outreach.</p></a>
395 <a href="https://apify.com/superlativetech/superclean-job-titles?fpr=8e9l1" class="product-card"><div class="product-name">Job Titles <span class="status">Live</span></div><p class="product-desc">Standardize job titles for outreach sequences.</p></a>
396 <a href="https://apify.com/superlativetech/superclean-product-names?fpr=8e9l1" class="product-card"><div class="product-name">Product Names <span class="status">Live</span></div><p class="product-desc">Normalize product and brand names from exports.</p></a>
397 <a href="https://apify.com/superlativetech/superclean-places?fpr=8e9l1" class="product-card"><div class="product-name">Places <span class="status">Live</span></div><p class="product-desc">Parse and standardize location strings.</p></a>
398 <a href="https://apify.com/superlativetech/superclean-urls?fpr=8e9l1" class="product-card"><div class="product-name">URLs <span class="status">Live</span></div><p class="product-desc">Clean and normalize URLs from lead data.</p></a>
399 <a href="https://apify.com/superlativetech/superclean-phone-numbers?fpr=8e9l1" class="product-card"><div class="product-name">Phone Numbers <span class="status">Live</span></div><p class="product-desc">Format and validate phone numbers.</p></a>
400 <a href="https://apify.com/superlativetech/dns-lookup?fpr=8e9l1" class="product-card"><div class="product-name">Supernet DNS Lookup <span class="status">Live</span></div><p class="product-desc">Look up DNS records for any domain.</p></a>
401 <a href="https://apify.com/superlativetech/http-api?fpr=8e9l1" class="product-card"><div class="product-name">HTTP API <span class="status">Live</span></div><p class="product-desc">General-purpose HTTP request utility.</p></a>
402 </div>
403 </section>
404
405</div>
406</body>
407</html>`;
408}