File size: 24,306 Bytes
6ae30ed
 
 
 
 
 
a336e20
 
 
 
 
6ae30ed
 
 
 
1f0573c
a336e20
6ae30ed
 
 
1f0573c
a336e20
 
 
 
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
 
 
 
 
 
 
adb8fd9
a336e20
 
6ae30ed
a336e20
 
6ae30ed
 
 
 
 
1f0573c
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
6ae30ed
a336e20
 
 
 
 
6ae30ed
a336e20
 
 
 
 
 
 
 
6ae30ed
a336e20
 
1f0573c
6ae30ed
a336e20
 
 
6ae30ed
a336e20
 
 
6ae30ed
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
a336e20
1f0573c
a336e20
1f0573c
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
a336e20
6ae30ed
 
a336e20
1f0573c
 
a336e20
6ae30ed
a336e20
 
1f0573c
a336e20
1f0573c
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
 
 
 
1f0573c
 
 
 
 
 
 
 
6ae30ed
a336e20
1f0573c
 
a336e20
1f0573c
a336e20
 
1f0573c
 
a336e20
 
 
 
6ae30ed
a336e20
 
 
 
6ae30ed
a336e20
 
 
 
 
 
6ae30ed
 
a336e20
 
 
 
 
6ae30ed
a336e20
 
 
6ae30ed
 
a336e20
6ae30ed
a336e20
 
 
 
 
 
 
6ae30ed
a336e20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ae30ed
 
a336e20
 
 
6ae30ed
 
a336e20
 
 
 
 
6ae30ed
a336e20
 
 
 
 
6ae30ed
a336e20
 
 
 
a3306be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ae30ed
1f0573c
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
a336e20
 
 
1f0573c
a336e20
1f0573c
 
 
a336e20
1f0573c
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
a336e20
 
1f0573c
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
 
 
 
 
 
 
 
 
 
a336e20
1f0573c
a336e20
 
1f0573c
 
 
 
a336e20
1f0573c
 
 
a336e20
 
 
6ae30ed
a336e20
 
1f0573c
a336e20
 
 
 
1f0573c
a336e20
 
 
 
 
 
 
6ae30ed
a336e20
 
 
 
 
 
 
 
 
 
 
 
6ae30ed
a336e20
 
6ae30ed
a336e20
 
6ae30ed
a336e20
 
 
 
 
 
 
6ae30ed
a336e20
 
 
 
6ae30ed
a336e20
 
 
 
 
6ae30ed
a336e20
 
6ae30ed
 
a336e20
 
 
 
 
 
 
 
 
 
 
 
6ae30ed
a336e20
 
 
 
6ae30ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f0573c
 
 
 
 
 
 
 
 
 
 
6ae30ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a336e20
6ae30ed
1f0573c
6ae30ed
1f0573c
 
 
 
 
 
6ae30ed
 
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ae30ed
 
1f0573c
 
 
 
 
 
 
 
 
 
 
6ae30ed
1f0573c
 
 
 
6ae30ed
1f0573c
 
 
6ae30ed
 
 
 
 
 
1f0573c
6ae30ed
 
 
 
 
 
 
 
 
a336e20
 
6ae30ed
cc0ce76
 
 
 
 
6ae30ed
 
a336e20
 
1f0573c
 
 
 
 
a336e20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import {
  createRepo,
  uploadFiles,
  whoAmI,
  spaceInfo,
  fileExists
} from '@huggingface/hub';
import { InferenceClient } from '@huggingface/inference';
import bodyParser from 'body-parser';
import fs from 'fs';

import checkUser from './middlewares/checkUser.js';
import { PROVIDERS } from './utils/providers.js';
import { COLORS } from './utils/colors.js';
import { fetchWithTimeout } from './utils/fetch-utils.js';

// Load environment variables from .env file
dotenv.config();

// Define isDev early, before it's used
const isDev =
  process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined;

// Add global error handlers
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  // Don't exit the process in development to keep the server running
  if (!isDev) {
    process.exit(1);
  }
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // Don't exit the process in development to keep the server running
});

const app = express();

const ipAddresses = new Map();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const PORT = process.env.APP_PORT || 7860;
const REDIRECT_URI =
  process.env.REDIRECT_URI || `http://localhost:${PORT}/auth/login`;
const MODEL_ID = 'deepseek-ai/DeepSeek-V3-0324';
const MAX_REQUESTS_PER_IP = 2;

// Rate limiting for external API
const externalApiRateLimit = new Map();
const EXTERNAL_API_WINDOW_MS = 60000; // 1 minute window
const MAX_REQUESTS_PER_WINDOW = 60; // 60 requests per minute

// Load MCP rules so they are always included in AI calls
const MCP_RULES_PATH = path.join(__dirname, 'MCP_RULES.md');
let mcpRulesContent = '';
try {
  mcpRulesContent = fs.readFileSync(MCP_RULES_PATH, 'utf-8');
} catch (err) {
  console.warn('Could not load MCP rules:', err);
}

app.use(cookieParser());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(
  cors({
    origin: isDev ? 'http://localhost:5173' : true,
    credentials: true
  })
);
app.use(express.static(path.join(__dirname, 'dist')));

const getPTag = (repoId) => {
  return `<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=${repoId}" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p>`;
};

app.get('/api/login', (_req, res) => {
  // res.redirect(
  //   302,
  //   `https://huggingface.co/oauth/authorize?client_id=${process.env.OAUTH_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`
  // );
  // redirect in new tab
  const redirectUrl = `https://huggingface.co/oauth/authorize?client_id=${process.env.OAUTH_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`;
  res.status(200).send({
    ok: true,
    redirectUrl
  });
});

app.get('/auth/login', async (req, res) => {
  const { code } = req.query;

  if (!code) {
    return res.redirect(302, '/');
  }
  const Authorization = `Basic ${Buffer.from(
    `${process.env.OAUTH_CLIENT_ID}:${process.env.OAUTH_CLIENT_SECRET}`
  ).toString('base64')}`;

  try {
    const request_auth = await fetchWithTimeout(
      'https://huggingface.co/oauth/token',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization
        },
        body: new URLSearchParams({
          grant_type: 'authorization_code',
          code: code,
          redirect_uri: REDIRECT_URI
        })
      },
      10000
    );

    if (!request_auth.ok) {
      console.error(`HuggingFace OAuth error: ${request_auth.status}`);
      return res.redirect(302, '/?error=auth_failed');
    }

    const response = await request_auth.json();

    if (!response.access_token) {
      return res.redirect(302, '/?error=no_token');
    }

    res.cookie('hf_token', response.access_token, {
      httpOnly: false,
      secure: !isDev,
      sameSite: isDev ? 'lax' : 'none',
      maxAge: 30 * 24 * 60 * 60 * 1000
    });

    return res.redirect(302, '/');
  } catch (error) {
    console.error('Login error:', error);
    return res.redirect(302, '/?error=auth_error');
  }
});
app.get('/auth/logout', (req, res) => {
  res.clearCookie('hf_token', {
    httpOnly: false,
    secure: !isDev,
    sameSite: isDev ? 'lax' : 'none'
  });
  return res.redirect(302, '/');
});

app.get('/api/@me', async (req, res) => {
  const { hf_token } = req.cookies;

  if (!hf_token) {
    return res.status(401).send({
      ok: false,
      openLogin: true,
      message: 'Please log in to continue'
    });
  }

  try {
    const request_user = await fetchWithTimeout(
      'https://huggingface.co/oauth/userinfo',
      {
        headers: {
          Authorization: `Bearer ${hf_token}`
        }
      },
      8000 // 8 second timeout
    );

    if (!request_user.ok) {
      const errorText = await request_user.text();
      console.error(
        `HuggingFace API error: ${request_user.status} - ${errorText}`
      );

      res.clearCookie('hf_token', {
        httpOnly: false,
        secure: !isDev,
        sameSite: isDev ? 'lax' : 'none'
      });

      return res.status(401).send({
        ok: false,
        openLogin: true,
        message: 'Session expired. Please log in again.'
      });
    }

    const user = await request_user.json();
    res.send(user);
  } catch (err) {
    console.error('Error fetching user info:', err);

    // Handle timeout specifically
    const message =
      err.name === 'AbortError'
        ? 'Request to authentication service timed out. Please try again later.'
        : err.message || 'An error occurred while fetching user information';

    res.clearCookie('hf_token', {
      httpOnly: false,
      secure: !isDev,
      sameSite: isDev ? 'lax' : 'none'
    });

    res.status(401).send({
      ok: false,
      openLogin: true,
      message
    });
  }
});

app.post('/api/deploy', checkUser, async (req, res) => {
  const { html, title, path } = req.body;
  if (!html || (!path && !title)) {
    return res.status(400).send({
      ok: false,
      message: 'Missing required fields'
    });
  }

  const { hf_token } = req.cookies;
  try {
    const repo = {
      type: 'space',
      name: path ?? ''
    };

    let readme;
    let newHtml = html;

    if (!path || path === '') {
      const { name: username } = await whoAmI({ accessToken: hf_token });
      const newTitle = title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .split('-')
        .filter(Boolean)
        .join('-')
        .slice(0, 96);

      const repoId = `${username}/${newTitle}`;
      repo.name = repoId;

      await createRepo({
        repo,
        accessToken: hf_token
      });
      const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)];
      const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)];
      readme = `---
title: ${newTitle}
emoji: 🐳
colorFrom: ${colorFrom}
colorTo: ${colorTo}
sdk: static
pinned: false
tags:
  - deepsite
---

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference`;
    }

    newHtml = html.replace(/<\/body>/, `${getPTag(repo.name)}</body>`);
    const file = new Blob([newHtml], { type: 'text/html' });
    file.name = 'index.html'; // Add name property to the Blob

    const files = [file];
    if (readme) {
      const readmeFile = new Blob([readme], { type: 'text/markdown' });
      readmeFile.name = 'README.md'; // Add name property to the Blob
      files.push(readmeFile);
    }
    await uploadFiles({
      repo,
      files,
      accessToken: hf_token
    });
    return res.status(200).send({ ok: true, path: repo.name });
  } catch (err) {
    return res.status(500).send({
      ok: false,
      message: err.message
    });
  }
});

// Update the download endpoint to use POST and accept HTML content directly
app.post('/api/download', (req, res) => {
  const { html, filename, destination } = req.body;

  if (!html || !destination) {
    return res.status(400).json({
      ok: false,
      message: 'Missing required parameters: html and destination'
    });
  }

  try {
    // Create the destination directory if it doesn't exist
    fs.mkdirSync(destination, { recursive: true });

    // Construct the full file path
    const filePath = path.join(destination, filename || 'index.html');

    // Write the file
    fs.writeFileSync(filePath, html, 'utf8');

    return res.json({
      ok: true,
      message: `File saved successfully to ${filePath}`,
      path: filePath
    });
  } catch (err) {
    console.error('Error saving file:', err);
    return res.status(500).json({
      ok: false,
      message: `Error saving file: ${err.message}`
    });
  }
});

app.post('/api/ask-ai', async (req, res) => {
  try {
    const { prompt, html, previousPrompt, provider } = req.body;
    if (!prompt) {
      return res.status(400).send({
        ok: false,
        message: 'Missing required fields'
      });
    }

    const { hf_token } = req.cookies;
    let token = hf_token;
    const ip =
      req.headers['x-forwarded-for']?.split(',')[0].trim() ||
      req.headers['x-real-ip'] ||
      req.socket.remoteAddress ||
      req.ip ||
      '0.0.0.0';

    if (!hf_token) {
      ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1);
      if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) {
        return res.status(429).send({
          ok: false,
          openLogin: true,
          message: 'Log In to continue using the service'
        });
      }

      token = process.env.DEFAULT_HF_TOKEN;
      if (!token) {
        console.error('No DEFAULT_HF_TOKEN defined in environment variables');
        return res.status(500).send({
          ok: false,
          message: 'Server configuration error. Please try again later.'
        });
      }
    }

    // Set up response headers for streaming
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    let client;
    try {
      client = new InferenceClient(token);
    } catch (error) {
      console.error('Error creating InferenceClient:', error);
      return res.status(500).send({
        ok: false,
        message: 'Failed to initialize AI client. Please try again.'
      });
    }

    let completeResponse = '';

    let TOKENS_USED = prompt?.length || 0;
    if (previousPrompt) TOKENS_USED += previousPrompt.length || 0;
    if (html) TOKENS_USED += html.length || 0;

    // Make sure provider is defined
    let selectedProviderName = provider;
    if (!selectedProviderName || !PROVIDERS[selectedProviderName]) {
      selectedProviderName = 'auto';
    }

    const DEFAULT_PROVIDER = PROVIDERS.novita;
    const selectedProvider =
      selectedProviderName === 'auto'
        ? DEFAULT_PROVIDER
        : PROVIDERS[selectedProviderName] ?? DEFAULT_PROVIDER;

    if (
      selectedProviderName !== 'auto' &&
      TOKENS_USED >= selectedProvider.max_tokens
    ) {
      return res.status(400).send({
        ok: false,
        openSelectProvider: true,
        message: `Context is too long. ${selectedProvider.name} allow ${selectedProvider.max_tokens} max tokens.`
      });
    }

    // Prepend MCP rules as a system message
    const messages = [
      {
        role: 'system',
        content: 'Do not modify the prompt. Forward it exactly as received.'
      },
      {
        role: 'system',
        content: `ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. Use as much as you can TailwindCSS for the CSS, if you can't do something with TailwindCSS, then use custom CSS (make sure to import <script src="https://cdn.tailwindcss.com"></script> in the head). Also, try to ellaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE`
      },
      ...(previousPrompt ? [{ role: 'user', content: previousPrompt }] : []),
      ...(html
        ? [{ role: 'assistant', content: `The current code is: ${html}.` }]
        : []),
      { role: 'user', content: prompt }
    ];

    let chatCompletion;
    try {
      chatCompletion = client.chatCompletionStream({
        model: MODEL_ID,
        provider: selectedProvider.id,
        messages,
        ...(selectedProvider.id !== 'sambanova'
          ? { max_tokens: selectedProvider.max_tokens }
          : {})
      });
    } catch (error) {
      console.error('Error creating chat completion stream:', error);
      return res.status(500).send({
        ok: false,
        message: 'Failed to start AI processing. Please try again.'
      });
    }

    let isResponseComplete = false;

    const streamHandler = async () => {
      try {
        while (!isResponseComplete) {
          let nextValue;
          try {
            nextValue = await chatCompletion.next();
          } catch (error) {
            console.error('Error getting next value from stream:', error);
            isResponseComplete = true;
            if (!res.headersSent) {
              return res.status(500).send({
                ok: false,
                message: 'Stream interrupted. Please try again.'
              });
            } else {
              return res.end();
            }
          }

          const { done, value } = nextValue;
          if (done) {
            isResponseComplete = true;
            break;
          }

          const chunk = value.choices[0]?.delta?.content;
          if (chunk) {
            if (selectedProviderName !== 'sambanova') {
              try {
                res.write(chunk);
              } catch (error) {
                console.error('Error writing chunk to response:', error);
                isResponseComplete = true;
                break;
              }
              completeResponse += chunk;

              if (completeResponse.includes('</html>')) {
                isResponseComplete = true;
                break;
              }
            } else {
              let newChunk = chunk;
              if (chunk.includes('</html>')) {
                // Replace everything after the last </html> tag with an empty string
                newChunk = newChunk.replace(/<\/html>[\s\S]*/, '</html>');
              }
              completeResponse += newChunk;
              try {
                res.write(newChunk);
              } catch (error) {
                console.error('Error writing chunk to response:', error);
                isResponseComplete = true;
                break;
              }
              if (newChunk.includes('</html>')) {
                isResponseComplete = true;
                break;
              }
            }
          }
        }
        // Ensure we end the response
        res.end();
      } catch (error) {
        console.error('Stream processing error:', error);
        if (!res.headersSent) {
          res.status(500).send({
            ok: false,
            message: error.message || 'Error while streaming the response'
          });
        } else {
          res.end();
        }
      }
    };

    // Start processing the stream
    streamHandler();
  } catch (error) {
    console.error('Global error in /api/ask-ai endpoint:', error);

    if (error.message?.includes('exceeded your monthly included credits')) {
      return res.status(402).send({
        ok: false,
        openProModal: true,
        message: error.message
      });
    }

    if (!res.headersSent) {
      res.status(500).send({
        ok: false,
        message:
          error.message || 'An unexpected error occurred. Please try again.'
      });
    } else {
      res.end();
    }
  }
});

app.get('/api/remix/:username/:repo', async (req, res) => {
  const { username, repo } = req.params;
  const { hf_token } = req.cookies;

  const token = hf_token || process.env.DEFAULT_HF_TOKEN;

  const repoId = `${username}/${repo}`;

  const url = `https://huggingface.co/spaces/${repoId}/raw/main/index.html`;
  try {
    const space = await spaceInfo({
      name: repoId,
      accessToken: token,
      additionalFields: ['author']
    });

    if (!space || space.sdk !== 'static' || space.private) {
      return res.status(404).send({
        ok: false,
        message: 'Space not found'
      });
    }

    const response = await fetch(url);
    if (!response.ok) {
      return res.status(404).send({
        ok: false,
        message: 'Space not found'
      });
    }
    let html = await response.text();
    // remove the last p tag including this url https://enzostvs-deepsite.hf.space
    html = html.replace(getPTag(repoId), '');

    let user = null;

    if (token) {
      const request_user = await fetch(
        'https://huggingface.co/oauth/userinfo',
        {
          headers: {
            Authorization: `Bearer ${hf_token}`
          }
        }
      )
        .then((res) => res.json())
        .catch(() => null);

      user = request_user;
    }

    res.status(200).send({
      ok: true,
      html,
      isOwner: space.author === user?.preferred_username,
      path: repoId
    });
  } catch (error) {
    return res.status(500).send({
      ok: false,
      message: error.message
    });
  }
});

// External API endpoint that doesn't require cookies
app.post('/api/external/ask-ai', async (req, res) => {
  const { prompt, html, previousPrompt, provider } = req.body;
  const api_key = req.headers['x-api-key'];

  if (!prompt) {
    return res.status(400).send({
      ok: false,
      message: 'Missing required fields'
    });
  }

  if (!api_key) {
    return res.status(401).send({
      ok: false,
      message: 'API key is required in X-API-Key header'
    });
  }

  // Rate limiting
  const now = Date.now();
  const windowStart = now - EXTERNAL_API_WINDOW_MS;

  // Clean up old entries
  for (const [key, timestamps] of externalApiRateLimit.entries()) {
    externalApiRateLimit.set(
      key,
      timestamps.filter((ts) => ts > windowStart)
    );
    if (externalApiRateLimit.get(key).length === 0) {
      externalApiRateLimit.delete(key);
    }
  }

  // Check rate limit
  const timestamps = externalApiRateLimit.get(api_key) || [];
  if (timestamps.length >= MAX_REQUESTS_PER_WINDOW) {
    return res.status(429).send({
      ok: false,
      message: 'Rate limit exceeded. Please try again later.'
    });
  }

  // Update rate limit
  timestamps.push(now);
  externalApiRateLimit.set(api_key, timestamps);

  // Set up response headers for streaming
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  let client;
  try {
    client = new InferenceClient(api_key);
  } catch (error) {
    console.error('Error creating external InferenceClient:', error);
    return res.status(500).send({
      ok: false,
      message: 'Failed to initialize AI client. Please try again.'
    });
  }

  let completeResponse = '';

  let TOKENS_USED = prompt?.length;
  if (previousPrompt) TOKENS_USED += previousPrompt.length;
  if (html) TOKENS_USED += html.length;

  const DEFAULT_PROVIDER = PROVIDERS.novita;
  const selectedProvider =
    provider === 'auto'
      ? DEFAULT_PROVIDER
      : PROVIDERS[provider] ?? DEFAULT_PROVIDER;

  if (provider !== 'auto' && TOKENS_USED >= selectedProvider.max_tokens) {
    return res.status(400).send({
      ok: false,
      openSelectProvider: true,
      message: `Context is too long. ${selectedProvider.name} allow ${selectedProvider.max_tokens} max tokens.`
    });
  }

  try {
    const chatCompletion = client.chatCompletionStream({
      model: MODEL_ID,
      provider: selectedProvider.id,
      messages: [
        {
          role: 'system',
          content: `ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. Use as much as you can TailwindCSS for the CSS, if you can't do something with TailwindCSS, then use custom CSS (make sure to import <script src="https://cdn.tailwindcss.com"></script> in the head). Also, try to ellaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE`
        },
        ...(previousPrompt
          ? [
              {
                role: 'user',
                content: previousPrompt
              }
            ]
          : []),
        ...(html
          ? [
              {
                role: 'assistant',
                content: `The current code is: ${html}.`
              }
            ]
          : []),
        {
          role: 'user',
          content: prompt
        }
      ],
      ...(selectedProvider.id !== 'sambanova'
        ? {
            max_tokens: selectedProvider.max_tokens
          }
        : {})
    });

    let isResponseComplete = false;

    const streamHandler = async () => {
      try {
        while (!isResponseComplete) {
          const { done, value } = await chatCompletion.next();
          if (done) {
            isResponseComplete = true;
            break;
          }

          const chunk = value.choices[0]?.delta?.content;
          if (chunk) {
            if (provider !== 'sambanova') {
              res.write(chunk);
              completeResponse += chunk;

              if (completeResponse.includes('</html>')) {
                isResponseComplete = true;
                break;
              }
            } else {
              let newChunk = chunk;
              if (chunk.includes('</html>')) {
                newChunk = newChunk.replace(/<\/html>[\s\S]*/, '</html>');
              }
              completeResponse += newChunk;
              res.write(newChunk);
              if (newChunk.includes('</html>')) {
                isResponseComplete = true;
                break;
              }
            }
          }
        }
        res.end();
      } catch (error) {
        console.error('External API stream processing error:', error);
        if (!res.headersSent) {
          res.status(500).send({
            ok: false,
            message: error.message || 'Error while streaming the response'
          });
        } else {
          res.end();
        }
      }
    };

    // Start processing the stream
    streamHandler();
  } catch (error) {
    console.error('External API request error:', error);

    if (error.message?.includes('exceeded your monthly included credits')) {
      return res.status(402).send({
        ok: false,
        openProModal: true,
        message: error.message
      });
    }

    if (!res.headersSent) {
      res.status(500).send({
        ok: false,
        message:
          error.message || 'An error occurred while processing your request.'
      });
    } else {
      res.end();
    }
  }
});

// Add health check endpoint
app.get('/health', (req, res) => {
  res.status(200).send({ status: 'ok' });
});

app.get('*', (_req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server is running at http://localhost:${PORT}`);
  console.log(`API endpoints available at http://localhost:${PORT}/api/`);
  console.log(`NODE_ENV: ${process.env.NODE_ENV || 'development'}`);
  console.log(`isDev: ${isDev}`);
});