claude-dev-server 1.2.1 → 1.2.3

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.
@@ -1,1869 +0,0 @@
1
- import { spawn } from 'child_process';
2
- import { existsSync, readFileSync } from 'fs';
3
- import { dirname, join, relative, resolve } from 'path';
4
- import http from 'http';
5
- import { fileURLToPath } from 'url';
6
- import { createConnection } from 'net';
7
- import { SourceMapConsumer } from 'source-map';
8
- import { WebSocketServer } from 'ws';
9
- import { readFile } from 'fs/promises';
10
-
11
- // src/universal/index.ts
12
- function spawnClaudeCode(options) {
13
- const port = 5e4 + Math.floor(Math.random() * 1e4);
14
- const ttydProc = spawn("ttyd", [
15
- "--port",
16
- String(port),
17
- "--interface",
18
- "127.0.0.1",
19
- "--writable",
20
- options.claudePath,
21
- ...options.args
22
- ], {
23
- cwd: options.cwd,
24
- env: {
25
- ...process.env,
26
- ...options.env,
27
- TERM: "xterm-256color",
28
- FORCE_COLOR: "1"
29
- }
30
- });
31
- ttydProc.on("exit", (code) => {
32
- console.log(`[claude-dev-server] ttyd exited - code: ${code}`);
33
- });
34
- ttydProc.on("error", (err) => {
35
- console.error(`[claude-dev-server] ttyd error: ${err.message}`);
36
- });
37
- return new Promise((resolve2, reject) => {
38
- ttydProc.stdout?.on("data", (data) => {
39
- const msg = data.toString();
40
- console.log(`[ttyd] ${msg}`);
41
- });
42
- ttydProc.stderr?.on("data", (data) => {
43
- const msg = data.toString();
44
- console.error(`[ttyd stderr] ${msg}`);
45
- });
46
- setTimeout(() => {
47
- resolve2({
48
- wsUrl: `ws://127.0.0.1:${port}`,
49
- process: ttydProc,
50
- port
51
- });
52
- }, 500);
53
- ttydProc.on("error", reject);
54
- });
55
- }
56
- var sourceMapCache = /* @__PURE__ */ new Map();
57
- async function parseSourceMap(sourceMapUrl, content) {
58
- try {
59
- const consumer = await new SourceMapConsumer(content);
60
- sourceMapCache.set(sourceMapUrl, consumer);
61
- } catch (err) {
62
- console.error("Failed to parse source map:", err);
63
- }
64
- }
65
- async function findOriginalPosition(generatedFile, line, column) {
66
- const consumer = sourceMapCache.get(generatedFile);
67
- if (!consumer) {
68
- return null;
69
- }
70
- try {
71
- const position = consumer.originalPositionFor({ line, column });
72
- if (position.source) {
73
- return {
74
- source: position.source,
75
- line: position.line || 1,
76
- column: position.column || 0,
77
- name: position.name
78
- };
79
- }
80
- } catch (err) {
81
- console.error("Failed to find original position:", err);
82
- }
83
- return null;
84
- }
85
- function formatCodeContext(location) {
86
- return `
87
- \u{1F4CD} Code Location:
88
- File: ${location.file}
89
- Line: ${location.line}
90
- Column: ${location.column}
91
- `;
92
- }
93
- function createWebSocketServer(options) {
94
- let wss = null;
95
- let port = 0;
96
- let ttydInfo = null;
97
- const start = async () => {
98
- console.log("[claude-dev-server] Starting ttyd...");
99
- ttydInfo = await spawnClaudeCode({
100
- cwd: options.projectRoot,
101
- claudePath: options.claudePath,
102
- args: options.claudeArgs
103
- });
104
- console.log(`[claude-dev-server] ttyd running at ${ttydInfo.wsUrl}`);
105
- return new Promise((resolve2, reject) => {
106
- wss = new WebSocketServer({ port, host: "127.0.0.1" });
107
- wss.on("listening", () => {
108
- const address = wss.address();
109
- if (address && typeof address === "object") {
110
- port = address.port;
111
- resolve2({ wsPort: port, ttydPort: ttydInfo.port });
112
- }
113
- });
114
- wss.on("error", (err) => {
115
- reject(err);
116
- });
117
- wss.on("connection", (ws) => {
118
- ws.on("message", async (message) => {
119
- try {
120
- const msg = JSON.parse(message.toString());
121
- if (msg.type === "inspect") {
122
- await handleInspect(msg, ws, options.projectRoot);
123
- } else if (msg.type === "loadSourceMap") {
124
- await handleLoadSourceMap(msg, ws, options.projectRoot);
125
- }
126
- } catch (err) {
127
- }
128
- });
129
- ws.send(JSON.stringify({
130
- type: "ready",
131
- ttydUrl: ttydInfo.wsUrl
132
- }));
133
- });
134
- });
135
- };
136
- const stop = () => {
137
- ttydInfo?.process.kill();
138
- wss?.close();
139
- };
140
- return { start, stop };
141
- }
142
- async function handleLoadSourceMap(msg, ws, projectRoot) {
143
- const { sourceMapUrl } = msg;
144
- try {
145
- const mapPath = resolve(projectRoot, sourceMapUrl.replace(/^\//, ""));
146
- const content = await readFile(mapPath, "utf-8");
147
- await parseSourceMap(sourceMapUrl, content);
148
- ws.send(JSON.stringify({
149
- type: "sourceMapLoaded",
150
- sourceMapUrl,
151
- success: true
152
- }));
153
- } catch (err) {
154
- ws.send(JSON.stringify({
155
- type: "sourceMapLoaded",
156
- sourceMapUrl,
157
- success: false,
158
- error: err.message
159
- }));
160
- }
161
- }
162
- async function handleInspect(msg, ws, projectRoot) {
163
- const { url, line, column, sourceMapUrl } = msg;
164
- let location = null;
165
- if (sourceMapUrl) {
166
- const original = await findOriginalPosition(sourceMapUrl, line, column);
167
- if (original) {
168
- location = {
169
- file: resolve(projectRoot, original.source),
170
- line: original.line,
171
- column: original.column
172
- };
173
- }
174
- }
175
- if (!location) {
176
- const match = url.match(/\/@fs\/(.+?)(?:\?|$)|\/@vite\/(.+?)(?:\?|$)/);
177
- if (match) {
178
- location = {
179
- file: decodeURIComponent(match[1] || match[2]),
180
- line,
181
- column
182
- };
183
- }
184
- }
185
- ws.send(JSON.stringify({
186
- type: "inspectResult",
187
- location: location ? {
188
- file: location.file,
189
- line: location.line,
190
- column: location.column,
191
- context: formatCodeContext(location)
192
- } : null
193
- }));
194
- }
195
-
196
- // src/client/injection.js
197
- var CLIENT_STYLES = `
198
- <style id="claude-dev-server-styles">
199
- * {
200
- margin: 0;
201
- padding: 0;
202
- box-sizing: border-box;
203
- }
204
- html, body {
205
- width: 100%;
206
- height: 100%;
207
- overflow: hidden;
208
- background: transparent;
209
- }
210
- .claude-dev-server-container {
211
- display: flex;
212
- width: 100vw;
213
- height: 100vh;
214
- overflow: hidden;
215
- background: transparent;
216
- }
217
- .claude-dev-server-left {
218
- width: 40%;
219
- min-width: 300px;
220
- max-width: 60%;
221
- overflow: hidden;
222
- position: relative;
223
- background: #fff;
224
- display: flex;
225
- flex-direction: column;
226
- }
227
- .claude-dev-server-left iframe {
228
- width: 100%;
229
- height: 100%;
230
- border: none;
231
- }
232
- .claude-dev-server-divider {
233
- width: 6px;
234
- background: #3e3e3e;
235
- position: relative;
236
- cursor: col-resize;
237
- transition: background 0.2s;
238
- flex-shrink: 0;
239
- }
240
- .claude-dev-server-divider:hover,
241
- .claude-dev-server-divider.dragging {
242
- background: #d97757;
243
- }
244
- .claude-dev-server-right {
245
- flex: 1;
246
- min-width: 300px;
247
- overflow: hidden;
248
- position: relative;
249
- display: flex;
250
- flex-direction: column;
251
- }
252
- .claude-dev-server-terminal {
253
- flex: 1;
254
- overflow: hidden;
255
- position: relative;
256
- background: #000;
257
- }
258
- .claude-dev-server-terminal iframe,
259
- .claude-dev-server-terminal-iframe {
260
- width: 100%;
261
- height: 100%;
262
- border: none;
263
- }
264
- .claude-dev-server-dev-iframe {
265
- width: 100%;
266
- height: 100%;
267
- border: none;
268
- }
269
- .claude-dev-server-terminal-header {
270
- padding: 8px 12px;
271
- background: #2d2d2d;
272
- border-bottom: 1px solid #3e3e3e;
273
- display: flex;
274
- justify-content: space-between;
275
- align-items: center;
276
- user-select: none;
277
- min-height: 40px;
278
- }
279
- .claude-dev-server-title {
280
- font-weight: 600;
281
- color: #fff;
282
- display: flex;
283
- align-items: center;
284
- gap: 8px;
285
- font-size: 13px;
286
- font-family: 'SF Mono', 'Monaco', 'Cascadia Code', 'Consolas', monospace;
287
- }
288
- .claude-dev-server-title svg {
289
- width: 14px;
290
- height: 14px;
291
- flex-shrink: 0;
292
- }
293
- .claude-dev-server-actions {
294
- display: flex;
295
- gap: 6px;
296
- }
297
- .claude-dev-server-btn {
298
- background: #d97757;
299
- border: none;
300
- color: #fff;
301
- cursor: pointer;
302
- font-family: inherit;
303
- font-size: 11px;
304
- padding: 4px 10px;
305
- border-radius: 3px;
306
- transition: background 0.15s;
307
- display: flex;
308
- align-items: center;
309
- gap: 4px;
310
- }
311
- .claude-dev-server-btn:hover {
312
- background: #c96a4a;
313
- }
314
- .claude-dev-server-btn.active {
315
- background: #b85d3f;
316
- color: #fff;
317
- }
318
- .claude-dev-server-inspect-overlay {
319
- position: fixed;
320
- top: 0;
321
- left: 0;
322
- right: 0;
323
- bottom: 0;
324
- pointer-events: none;
325
- z-index: 2147483646;
326
- display: none;
327
- }
328
- .claude-dev-server-inspect-overlay.active {
329
- display: block;
330
- }
331
- .claude-dev-server-highlight {
332
- position: absolute;
333
- border: 2px solid #007acc;
334
- background: rgba(0, 122, 204, 0.1);
335
- pointer-events: none;
336
- transition: all 0.1s ease;
337
- }
338
- .claude-dev-server-highlight::after {
339
- content: attr(data-element);
340
- position: absolute;
341
- top: -20px;
342
- left: 0;
343
- background: #007acc;
344
- color: #fff;
345
- font-size: 10px;
346
- padding: 2px 4px;
347
- border-radius: 2px 2px 0 0;
348
- font-family: monospace;
349
- white-space: nowrap;
350
- }
351
- /* Portrait mode */
352
- @media (orientation: portrait) {
353
- .claude-dev-server-container {
354
- flex-direction: column;
355
- }
356
- .claude-dev-server-divider {
357
- width: 100%;
358
- height: 6px;
359
- cursor: row-resize;
360
- }
361
- .claude-dev-server-right {
362
- width: 100%;
363
- min-width: unset;
364
- max-width: unset;
365
- height: 50%;
366
- min-height: 200px;
367
- }
368
- }
369
- </style>
370
- `;
371
- var CLIENT_SCRIPT = `
372
- (() => {
373
- let ws = null
374
- let ttydIframe = null
375
- let devIframe = null
376
- let overlay = null
377
- let isInspectMode = false
378
- let ttydWsUrl = null
379
- let leftPanel = null
380
- let divider = null
381
- let rightPanel = null
382
- let isDragging = false
383
- let inspectListenersRegistered = false
384
-
385
- // Fetch the WebSocket port from the server
386
- async function getWsPort() {
387
- const res = await fetch('/@claude-port')
388
- const data = await res.json()
389
- return data.port
390
- }
391
-
392
- async function initWhenReady() {
393
- try {
394
- const port = await getWsPort()
395
- connect(port)
396
- } catch (err) {
397
- console.error('[Claude Dev Server] Failed to get port:', err)
398
- setTimeout(initWhenReady, 1000)
399
- return
400
- }
401
- // Create overlay first before split layout
402
- createOverlay()
403
- createSplitLayout()
404
- }
405
-
406
- function createSplitLayout() {
407
- // IMPORTANT: Only create layout in the top-level window, not in iframes
408
- // This prevents infinite nesting when the dev iframe loads
409
- if (window.top !== window.self) {
410
- console.log('[Claude Dev Server] Not in top window, skipping layout creation')
411
- return
412
- }
413
-
414
- // Check if already created
415
- if (document.querySelector('.claude-dev-server-container')) return
416
- // Also check if we're already in an injected page
417
- if (window.__CLAUDE_SPLIT_LAYOUT_CREATED__) return
418
- window.__CLAUDE_SPLIT_LAYOUT_CREATED__ = true
419
-
420
- // Get original HTML from window variable (set by server)
421
- // The HTML is Base64 encoded to avoid any escaping issues
422
- let originalHtml
423
- if (window.__CLAUDE_ORIGINAL_HTML_BASE64__) {
424
- // Decode Base64
425
- try {
426
- const decoded = atob(window.__CLAUDE_ORIGINAL_HTML_BASE64__)
427
- // Handle UTF-8 encoding
428
- const bytes = new Uint8Array(decoded.length)
429
- for (let i = 0; i < decoded.length; i++) {
430
- bytes[i] = decoded.charCodeAt(i)
431
- }
432
- originalHtml = new TextDecoder().decode(bytes)
433
- } catch (e) {
434
- console.error('[Claude Dev Server] Failed to decode Base64 HTML:', e)
435
- originalHtml = document.documentElement.outerHTML
436
- }
437
- } else {
438
- originalHtml = document.documentElement.outerHTML
439
- }
440
-
441
- // Create container
442
- const container = document.createElement('div')
443
- container.className = 'claude-dev-server-container'
444
-
445
- // Left panel - terminal (Claude)
446
- leftPanel = document.createElement('div')
447
- leftPanel.className = 'claude-dev-server-left'
448
-
449
- // Terminal header
450
- const header = document.createElement('div')
451
- header.className = 'claude-dev-server-terminal-header'
452
- header.innerHTML = \`
453
- <span class="claude-dev-server-title">
454
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
455
- <path d="M11.376 24L10.776 23.544L10.44 22.8L10.776 21.312L11.16 19.392L11.472 17.856L11.76 15.96L11.928 15.336L11.904 15.288L11.784 15.312L10.344 17.28L8.16 20.232L6.432 22.056L6.024 22.224L5.304 21.864L5.376 21.192L5.784 20.616L8.16 17.568L9.6 15.672L10.536 14.592L10.512 14.448H10.464L4.128 18.576L3 18.72L2.496 18.264L2.568 17.52L2.808 17.28L4.704 15.96L9.432 13.32L9.504 13.08L9.432 12.96H9.192L8.4 12.912L5.712 12.84L3.384 12.744L1.104 12.624L0.528 12.504L0 11.784L0.048 11.424L0.528 11.112L1.224 11.16L2.736 11.28L5.016 11.424L6.672 11.52L9.12 11.784H9.504L9.552 11.616L9.432 11.52L9.336 11.424L6.96 9.84L4.416 8.16L3.072 7.176L2.352 6.672L1.992 6.216L1.848 5.208L2.496 4.488L3.384 4.56L3.6 4.608L4.488 5.304L6.384 6.768L8.88 8.616L9.24 8.904L9.408 8.808V8.736L9.24 8.472L7.896 6.024L6.456 3.528L5.808 2.496L5.64 1.872C5.576 1.656 5.544 1.416 5.544 1.152L6.288 0.144001L6.696 0L7.704 0.144001L8.112 0.504001L8.736 1.92L9.72 4.152L11.28 7.176L11.736 8.088L11.976 8.904L12.072 9.168H12.24V9.024L12.36 7.296L12.6 5.208L12.84 2.52L12.912 1.752L13.296 0.840001L14.04 0.360001L14.616 0.624001L15.096 1.32L15.024 1.752L14.76 3.6L14.184 6.504L13.824 8.472H14.04L14.28 8.208L15.264 6.912L16.92 4.848L17.64 4.032L18.504 3.12L19.056 2.688H20.088L20.832 3.816L20.496 4.992L19.44 6.336L18.552 7.464L17.28 9.168L16.512 10.536L16.584 10.632H16.752L19.608 10.008L21.168 9.744L22.992 9.432L23.832 9.816L23.928 10.2L23.592 11.016L21.624 11.496L19.32 11.952L15.888 12.768L15.84 12.792L15.888 12.864L17.424 13.008L18.096 13.056H19.728L22.752 13.272L23.544 13.8L24 14.424L23.928 14.928L22.704 15.528L21.072 15.144L17.232 14.232L15.936 13.92H15.744V14.016L16.848 15.096L18.84 16.896L21.36 19.224L21.48 19.8L21.168 20.28L20.832 20.232L18.624 18.552L17.76 17.808L15.84 16.2H15.72V16.368L16.152 17.016L18.504 20.544L18.624 21.624L18.456 21.96L17.832 22.176L17.184 22.056L15.792 20.136L14.376 17.952L13.224 16.008L13.104 16.104L12.408 23.352L12.096 23.712L11.376 24Z" fill="#d97757"/>
456
- </svg>
457
- Claude Code
458
- </span>
459
- <div class="claude-dev-server-actions">
460
- <button class="claude-dev-server-btn claude-dev-server-btn-inspect" title="Inspect Element">
461
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
462
- <path d="M19 11V4a2 2 0 00-2-2H4a2 2 0 00-2 2v13a2 2 0 002 2h7"/>
463
- <path d="M12 12l4.166 10 1.48-4.355L22 16.166 12 12z"/>
464
- <path d="M18 18l3 3"/>
465
- </svg>
466
- Inspect
467
- </button>
468
- </div>
469
- \`
470
-
471
- const inspectBtn = header.querySelector('.claude-dev-server-btn-inspect')
472
- inspectBtn.addEventListener('click', () => {
473
- if (isInspectMode) {
474
- disableInspectMode()
475
- } else {
476
- enableInspectMode()
477
- }
478
- })
479
-
480
- // Terminal container
481
- const terminal = document.createElement('div')
482
- terminal.className = 'claude-dev-server-terminal'
483
-
484
- // Ttyd iframe
485
- ttydIframe = document.createElement('iframe')
486
- ttydIframe.className = 'claude-dev-server-terminal-iframe'
487
- ttydIframe.allow = 'clipboard-read; clipboard-write'
488
-
489
- terminal.appendChild(ttydIframe)
490
- leftPanel.appendChild(header)
491
- leftPanel.appendChild(terminal)
492
-
493
- // Divider - draggable
494
- divider = document.createElement('div')
495
- divider.className = 'claude-dev-server-divider'
496
- setupDraggable(divider)
497
-
498
- // Right panel - dev server
499
- rightPanel = document.createElement('div')
500
- rightPanel.className = 'claude-dev-server-right'
501
-
502
- // Create dev server iframe with srcdoc
503
- devIframe = document.createElement('iframe')
504
- devIframe.className = 'claude-dev-server-dev-iframe'
505
- // The HTML already has inspect script injected by server
506
- devIframe.srcdoc = originalHtml
507
-
508
- rightPanel.appendChild(devIframe)
509
-
510
- // Assemble layout: Claude (left) | divider | dev server (right)
511
- container.appendChild(leftPanel)
512
- container.appendChild(divider)
513
- container.appendChild(rightPanel)
514
-
515
- // Replace body content
516
- document.body.innerHTML = ''
517
- document.body.appendChild(container)
518
- document.body.appendChild(overlay)
519
-
520
- // Wait for iframe to load before setting up communication
521
- devIframe.onload = () => {
522
- console.log('[Claude Dev Server] Dev iframe loaded')
523
- // Setup inspect mode communication
524
- setupInspectCommunication()
525
- }
526
- }
527
-
528
- function setupInspectCommunication() {
529
- // Inspect mode is now handled entirely in the outer layer
530
- // We'll access the iframe's document directly
531
- }
532
-
533
- function setupIframeInspectListeners() {
534
- if (!devIframe || !devIframe.contentDocument) return
535
-
536
- // Prevent duplicate listener registration
537
- if (inspectListenersRegistered) {
538
- return
539
- }
540
-
541
- const iframeDoc = devIframe.contentDocument
542
- const iframeWindow = devIframe.contentWindow
543
-
544
- const inspectHandler = (e) => {
545
- if (!isInspectMode) return
546
-
547
- e.preventDefault()
548
- e.stopPropagation()
549
-
550
- if (e.type === 'click') {
551
- const el = e.target
552
- const rect = el.getBoundingClientRect()
553
- const className = el.className ? String(el.className) : ''
554
- // Limit classnames to first 2-3 to avoid overly long selectors
555
- const classNames = className.split(' ').filter(c => c).slice(0, 3)
556
- const selector = el.tagName.toLowerCase() +
557
- (el.id ? '#' + el.id : '') +
558
- (classNames.length ? '.' + classNames.join('.') : '')
559
-
560
- // Highlight element
561
- if (overlay) {
562
- overlay.innerHTML = ''
563
-
564
- // Get iframe position on page
565
- const iframeRect = devIframe.getBoundingClientRect()
566
-
567
- // Calculate highlight position relative to main document
568
- // Element rect is relative to iframe viewport, need to add iframe position
569
- const highlightTop = iframeRect.top + rect.top
570
- const highlightLeft = iframeRect.left + rect.left
571
-
572
- const highlight = document.createElement('div')
573
- highlight.className = 'claude-dev-server-highlight'
574
- highlight.style.top = highlightTop + 'px'
575
- highlight.style.left = highlightLeft + 'px'
576
- highlight.style.width = rect.width + 'px'
577
- highlight.style.height = rect.height + 'px'
578
- highlight.dataset.element = selector
579
- overlay.appendChild(highlight)
580
- }
581
-
582
- // Get source location and send to terminal
583
- getSourceLocationFromElement(el).then(location => {
584
- if (location) {
585
- sendToTerminal(location)
586
- }
587
- disableInspectMode()
588
- })
589
- } else if (e.type === 'mousemove') {
590
- const el = e.target
591
- const rect = el.getBoundingClientRect()
592
- const className = el.className ? String(el.className) : ''
593
- // Limit classnames to first 2-3 to avoid overly long selectors
594
- const classNames = className.split(' ').filter(c => c).slice(0, 3)
595
- const selector = el.tagName.toLowerCase() +
596
- (el.id ? '#' + el.id : '') +
597
- (classNames.length ? '.' + classNames.join('.') : '')
598
-
599
- if (overlay) {
600
- overlay.innerHTML = ''
601
-
602
- // Get iframe position on page
603
- const iframeRect = devIframe.getBoundingClientRect()
604
-
605
- // Calculate highlight position relative to main document
606
- const highlightTop = iframeRect.top + rect.top
607
- const highlightLeft = iframeRect.left + rect.left
608
-
609
- const highlight = document.createElement('div')
610
- highlight.className = 'claude-dev-server-highlight'
611
- highlight.style.top = highlightTop + 'px'
612
- highlight.style.left = highlightLeft + 'px'
613
- highlight.style.width = rect.width + 'px'
614
- highlight.style.height = rect.height + 'px'
615
- highlight.dataset.element = selector
616
- overlay.appendChild(highlight)
617
- }
618
- }
619
- }
620
-
621
- // Store handler reference for later removal
622
- iframeDoc._claudeInspectHandler = inspectHandler
623
-
624
- // Add event listeners in capture phase
625
- iframeDoc.addEventListener('click', inspectHandler, true)
626
- iframeDoc.addEventListener('mousemove', inspectHandler, true)
627
-
628
- // Mark listeners as registered
629
- inspectListenersRegistered = true
630
- }
631
-
632
- async function handleInspectElement(elementInfo) {
633
- // This is now handled directly in setupIframeInspectListeners
634
- }
635
-
636
- async function getSourceLocationFromElement(element) {
637
- // Access the iframe's document to detect Next.js chunks
638
- const iframeDoc = devIframe?.contentDocument || document
639
-
640
- // Early check: detect Next.js by checking for _next/static chunks
641
- const hasNextJsChunks = Array.from(iframeDoc.querySelectorAll('script[src]'))
642
- .some(script => script.getAttribute('src')?.includes('/_next/static/chunks/'))
643
-
644
- if (hasNextJsChunks) {
645
- console.log('[Claude Dev Server] Next.js Turbopack detected, using specialized lookup')
646
-
647
- const pagePath = window.location.pathname
648
- console.log('[Claude Dev Server] Looking up source for page:', pagePath)
649
-
650
- try {
651
- const params = new URLSearchParams({
652
- page: pagePath,
653
- framework: 'nextjs'
654
- })
655
- const lookupUrl = '/@sourcemap-lookup?' + params.toString()
656
- console.log('[Claude Dev Server] Fetching:', lookupUrl)
657
-
658
- const response = await fetch(lookupUrl)
659
- console.log('[Claude Dev Server] Response status:', response.status)
660
-
661
- if (response.ok) {
662
- const result = await response.json()
663
- console.log('[Claude Dev Server] Lookup result:', result)
664
- if (result.file) {
665
- const elClassName = element.className ? String(element.className) : ''
666
- // Limit classnames to first 2-3 to avoid overly long selectors
667
- const classNames = elClassName.split(' ').filter(c => c).slice(0, 3)
668
- const selector = element.tagName.toLowerCase() +
669
- (element.id ? '#' + element.id : '') +
670
- (classNames.length ? '.' + classNames.join('.') : '')
671
-
672
- // Extract text content from element
673
- let textContent = ''
674
- if (element.nodeType === Node.TEXT_NODE) {
675
- textContent = element.textContent ? element.textContent.trim().substring(0, 50) : ''
676
- } else if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
677
- textContent = element.childNodes[0].textContent ? element.childNodes[0].textContent.trim().substring(0, 50) : ''
678
- } else {
679
- for (const child of element.childNodes) {
680
- if (child.nodeType === Node.TEXT_NODE && child.textContent && child.textContent.trim()) {
681
- textContent = child.textContent.trim().substring(0, 50)
682
- break
683
- }
684
- }
685
- }
686
- if (textContent && textContent.length >= 50) {
687
- textContent += '...'
688
- }
689
-
690
- return {
691
- url: result.file,
692
- line: result.line || undefined,
693
- column: result.column || undefined,
694
- selector: selector,
695
- text: textContent,
696
- hint: 'File: ' + result.file
697
- }
698
- }
699
- }
700
- } catch (e) {
701
- console.log('[Claude Dev Server] Next.js lookup failed:', e)
702
- }
703
- // If Next.js lookup failed, continue with normal flow
704
- }
705
-
706
- let sourceFile = null
707
- let sourceLine = 1
708
- let sourceColumn = 1
709
-
710
- // Try to get original line number using source map
711
- // Use server-side source map resolution with source-map library
712
- async function resolveSourceMap(filePath, line, column) {
713
- try {
714
- console.log('[Claude Dev Server] Calling server source map resolution for:', filePath, line, column)
715
-
716
- // Convert absolute file path to URL path for Vite
717
- let urlPath = filePath
718
- if (filePath.startsWith('/Users/')) {
719
- // Convert /Users/.../src/App.jsx to /src/App.jsx
720
- const parts = filePath.split('/')
721
- const srcIndex = parts.indexOf('src')
722
- if (srcIndex >= 0) {
723
- urlPath = '/' + parts.slice(srcIndex).join('/')
724
- }
725
- }
726
-
727
- console.log('[Claude Dev Server] Converted path to URL path:', urlPath)
728
-
729
- // Use the server-side source map resolution with URL path
730
- const params = new URLSearchParams({
731
- file: urlPath,
732
- line: String(line),
733
- col: String(column)
734
- })
735
-
736
- const response = await fetch('/@sourcemap?' + params.toString())
737
- if (!response.ok) {
738
- console.log('[Claude Dev Server] Source map request failed:', response.status)
739
- return null
740
- }
741
-
742
- const result = await response.json()
743
- console.log('[Claude Dev Server] Source map result:', result)
744
-
745
- if (result.error) {
746
- console.log('[Claude Dev Server] Source map error:', result.error)
747
- return null
748
- }
749
-
750
- if (result.file) {
751
- return {
752
- file: result.file,
753
- line: result.line,
754
- column: result.column
755
- }
756
- }
757
-
758
- return null
759
- } catch (e) {
760
- console.log('[Claude Dev Server] Source map lookup failed:', e.message)
761
- return null
762
- }
763
- }
764
-
765
- // Try to extract jsxDEV source location from React Fiber
766
- function extractJsxDevLocation(fiber) {
767
- try {
768
- // The jsxDEV location is stored in the element type's _debugInfo or _source
769
- // React 18 stores it differently - let's check multiple locations
770
- const elementType = fiber.elementType || fiber.type
771
-
772
- // Check if this is a jsxDEV call by looking at the string representation
773
- if (elementType && typeof elementType === 'function') {
774
- const fnStr = elementType.toString()
775
- // jsxDEV functions have a specific pattern
776
- if (fnStr.includes('jsxDEV') || fnStr.includes('jsx')) {
777
- console.log('[Claude Dev Server] Found jsxDEV element type')
778
- }
779
- }
780
-
781
- // Try to get _debugSource which might have jsxDEV metadata
782
- const debugSource = fiber._debugSource || fiber._debugInfo
783
- if (debugSource) {
784
- // For jsxDEV, check if there's a _source object with fileName/lineNumber
785
- const source = debugSource._source || debugSource.source || debugSource
786
- if (source && source.fileName && source.lineNumber !== undefined) {
787
- console.log('[Claude Dev Server] Found _debugSource with source location:', source)
788
- // NOTE: Don't use this directly! The lineNumber might be from transpiled code
789
- // We'll let the source map resolver handle it
790
- return null
791
- }
792
- }
793
-
794
- // Check the memoizedState or other properties for source location
795
- if (fiber.memoizedState) {
796
- // React might store jsxDEV location in memoizedState
797
- console.log('[Claude Dev Server] Checking memoizedState:', fiber.memoizedState)
798
- }
799
-
800
- // Check the memoizedProps or other properties for source location
801
- if (fiber.memoizedProps && fiber.memoizedProps.__source) {
802
- const source = fiber.memoizedProps.__source
803
- console.log('[Claude Dev Server] Found __source in memoizedProps:', source)
804
- return {
805
- file: source.fileName,
806
- line: source.lineNumber,
807
- column: source.columnNumber || 1
808
- }
809
- }
810
-
811
- // Check pendingProps for __source
812
- if (fiber.pendingProps && fiber.pendingProps.__source) {
813
- const source = fiber.pendingProps.__source
814
- console.log('[Claude Dev Server] Found __source in pendingProps:', source)
815
- return {
816
- file: source.fileName,
817
- line: source.lineNumber,
818
- column: source.columnNumber || 1
819
- }
820
- }
821
- } catch (e) {
822
- console.log('[Claude Dev Server] Error extracting jsxDEV location:', e)
823
- }
824
- return null
825
- }
826
-
827
- // Try React DevTools - handle React 18's randomized suffix
828
- const elKeys = Object.keys(element)
829
- let fiberKey = elKeys.find(k => k === '__reactFiber__' || k === '__reactInternalInstance' || k.indexOf('__reactFiber') === 0)
830
- let propsKey = elKeys.find(k => k === '__reactProps__' || k.indexOf('__reactProps') === 0)
831
-
832
- if (fiberKey) {
833
- const fiber = element[fiberKey]
834
- console.log('[Claude Dev Server] Found fiber at key:', fiberKey)
835
-
836
- // Log fiber structure for debugging
837
- console.log('[Claude Dev Server] Fiber structure:', {
838
- _debugSource: fiber._debugSource,
839
- elementType: fiber.elementType,
840
- type: fiber.type,
841
- memoizedProps: fiber.memoizedProps,
842
- pendingProps: fiber.pendingProps
843
- })
844
-
845
- // Log _debugSource details
846
- if (fiber._debugSource) {
847
- console.log('[Claude Dev Server] _debugSource details:', JSON.stringify(fiber._debugSource, null, 2))
848
- }
849
-
850
- // For Next.js, try to get component name from elementType
851
- if (!fiber._debugSource && fiber.elementType) {
852
- const elementType = fiber.elementType
853
- console.log('[Claude Dev Server] elementType:', elementType)
854
- console.log('[Claude Dev Server] elementType.name:', elementType.name)
855
- console.log('[Claude Dev Server] elementType.displayName:', elementType.displayName)
856
-
857
- // Try to get the function string to find component name
858
- if (typeof elementType === 'function') {
859
- const fnStr = elementType.toString()
860
- console.log('[Claude Dev Server] elementType function:', fnStr.substring(0, 200))
861
- }
862
- }
863
-
864
- // First, try to extract jsxDEV source location
865
- const jsxDevLocation = extractJsxDevLocation(fiber)
866
- if (jsxDevLocation) {
867
- sourceFile = jsxDevLocation.file
868
- sourceLine = jsxDevLocation.line
869
- sourceColumn = jsxDevLocation.column
870
-
871
- // Convert absolute path to relative path
872
- if (sourceFile.startsWith('/')) {
873
- const projectRoot = window.__CLAUDE_PROJECT_ROOT__
874
- if (projectRoot && sourceFile.startsWith(projectRoot)) {
875
- sourceFile = sourceFile.substring(projectRoot.length + 1)
876
- if (sourceFile.startsWith('/')) {
877
- sourceFile = sourceFile.substring(1)
878
- }
879
- }
880
- }
881
- console.log('[Claude Dev Server] Using jsxDEV location:', sourceFile, sourceLine)
882
- } else {
883
- // Fall back to _debugSource
884
- const debugSource = fiber._debugSource || fiber.elementType?._debugSource || fiber.type?._debugSource || fiber.alternate?._debugSource
885
- if (debugSource && debugSource.fileName) {
886
- sourceFile = debugSource.fileName
887
- sourceLine = debugSource.lineNumber || 1
888
- sourceColumn = debugSource.columnNumber || 1
889
-
890
- // Convert relative path to absolute path for source map resolution
891
- let absolutePath = sourceFile
892
- if (!sourceFile.startsWith('/')) {
893
- // Relative path - resolve relative to project root
894
- const projectRoot = window.__CLAUDE_PROJECT_ROOT__
895
- absolutePath = projectRoot + '/' + sourceFile
896
- }
897
-
898
- console.log('[Claude Dev Server] Resolving source map for:', absolutePath, 'at line:', sourceLine)
899
-
900
- // Use server-side source map resolution
901
- const original = await resolveSourceMap(absolutePath, sourceLine, sourceColumn)
902
- if (original) {
903
- sourceFile = original.file
904
- sourceLine = original.line
905
- sourceColumn = original.column
906
- console.log('[Claude Dev Server] Original location from source map:', sourceFile, sourceLine)
907
- } else {
908
- // Source map resolution failed, use the original file
909
- // Convert absolute path back to relative
910
- if (absolutePath.startsWith('/')) {
911
- const projectRoot = window.__CLAUDE_PROJECT_ROOT__
912
- if (projectRoot && absolutePath.startsWith(projectRoot)) {
913
- sourceFile = absolutePath.substring(projectRoot.length + 1)
914
- if (sourceFile.startsWith('/')) {
915
- sourceFile = sourceFile.substring(1)
916
- }
917
- }
918
- }
919
- }
920
- console.log('[Claude Dev Server] Final React source:', sourceFile, sourceLine)
921
- } else {
922
- // Try going up the fiber tree
923
- let currentFiber = fiber
924
- let depth = 0
925
- while (currentFiber && depth < 20) {
926
- const jsxDevLoc = extractJsxDevLocation(currentFiber)
927
- if (jsxDevLoc) {
928
- sourceFile = jsxDevLoc.file
929
- sourceLine = jsxDevLoc.line
930
- sourceColumn = jsxDevLoc.column
931
-
932
- if (sourceFile.startsWith('/')) {
933
- const projectRoot = window.__CLAUDE_PROJECT_ROOT__
934
- if (projectRoot && sourceFile.startsWith(projectRoot)) {
935
- sourceFile = sourceFile.substring(projectRoot.length + 1)
936
- if (sourceFile.startsWith('/')) {
937
- sourceFile = sourceFile.substring(1)
938
- }
939
- }
940
- }
941
- console.log('[Claude Dev Server] Found jsxDEV location at depth', depth, ':', sourceFile, sourceLine)
942
- break
943
- }
944
-
945
- const ds = currentFiber._debugSource || currentFiber.elementType?._debugSource || currentFiber.type?._debugSource
946
- if (ds && ds.fileName) {
947
- sourceFile = ds.fileName
948
- sourceLine = ds.lineNumber || 1
949
- sourceColumn = ds.columnNumber || 1
950
-
951
- // Use server-side source map resolution
952
- const original = await resolveSourceMap(sourceFile, sourceLine, sourceColumn)
953
- if (original) {
954
- sourceFile = original.file
955
- sourceLine = original.line
956
- sourceColumn = original.column
957
- } else {
958
- // Convert absolute path to relative path using project root
959
- if (sourceFile.startsWith('/')) {
960
- const projectRoot = window.__CLAUDE_PROJECT_ROOT__
961
- if (projectRoot && sourceFile.startsWith(projectRoot)) {
962
- sourceFile = sourceFile.substring(projectRoot.length + 1)
963
- if (sourceFile.startsWith('/')) {
964
- sourceFile = sourceFile.substring(1)
965
- }
966
- }
967
- }
968
- }
969
- console.log('[Claude Dev Server] Found React source at depth', depth, ':', sourceFile, sourceLine)
970
- break
971
- }
972
- currentFiber = currentFiber.return || currentFiber.alternate
973
- depth++
974
- }
975
- }
976
- }
977
- }
978
-
979
- // Try Vue component
980
- if (!sourceFile) {
981
- const vueComponent = element.__vueParentComponent || element.__vnode
982
- if (vueComponent) {
983
- const type = vueComponent.type || vueComponent.component
984
- if (type && type.__file) {
985
- sourceFile = type.__file
986
- console.log('[Claude Dev Server] Found Vue source:', sourceFile)
987
- }
988
- }
989
- }
990
-
991
- // Try Vite's HMR source map
992
- if (!sourceFile) {
993
- // Look for data-vite-dev-id or similar attributes
994
- const viteId = element.getAttribute('data-vite-dev-id')
995
- if (viteId) {
996
- // Extract file path from viteId (remove query params if any)
997
- const queryIndex = viteId.indexOf('?')
998
- sourceFile = '/' + (queryIndex >= 0 ? viteId.substring(0, queryIndex) : viteId)
999
- console.log('[Claude Dev Server] Found Vite ID:', viteId)
1000
- }
1001
- }
1002
-
1003
- // Check for inline script
1004
- if (!sourceFile) {
1005
- const inlineScripts = iframeDoc.querySelectorAll('script:not([src])')
1006
- if (inlineScripts.length > 0) {
1007
- const pathParts = window.location.pathname.split('/')
1008
- const fileName = pathParts[pathParts.length - 1] || 'index.html'
1009
- sourceFile = '/' + fileName
1010
-
1011
- const html = iframeDoc.documentElement.outerHTML
1012
- const elId = element.id ? element.id : ''
1013
- const elClass = element.className ? element.className : ''
1014
- let elPattern
1015
- if (elId) {
1016
- elPattern = 'id="' + elId + '"'
1017
- } else if (elClass) {
1018
- elPattern = 'class="' + elClass.split(' ')[0] + '"'
1019
- } else {
1020
- elPattern = element.tagName.toLowerCase()
1021
- }
1022
-
1023
- const matchIndex = html.indexOf(elPattern)
1024
- if (matchIndex !== -1) {
1025
- const beforeElement = html.substring(0, matchIndex)
1026
- sourceLine = beforeElement.split('\\n').length
1027
- }
1028
- }
1029
- }
1030
-
1031
- // Find main script
1032
- if (!sourceFile) {
1033
- const scripts = iframeDoc.querySelectorAll('script[src]')
1034
- for (const script of scripts) {
1035
- const src = script.getAttribute('src')
1036
- if (src && !src.includes('cdn') && !src.includes('node_modules') &&
1037
- (src.includes('/src/') || src.includes('/app.') || src.includes('/main.'))) {
1038
- sourceFile = src
1039
- break
1040
- }
1041
- }
1042
- }
1043
-
1044
- // Fallback
1045
- if (!sourceFile) {
1046
- const pathParts = window.location.pathname.split('/')
1047
- const fileName = pathParts[pathParts.length - 1] || 'index.html'
1048
- sourceFile = '/' + fileName
1049
- }
1050
-
1051
- const elClassName = element.className ? String(element.className) : ''
1052
- // Limit classnames to first 2-3 to avoid overly long selectors
1053
- const classNames = elClassName.split(' ').filter(c => c).slice(0, 3)
1054
- const selector = element.tagName.toLowerCase() +
1055
- (element.id ? '#' + element.id : '') +
1056
- (classNames.length ? '.' + classNames.join('.') : '')
1057
-
1058
- // Get text content for better context
1059
- let textContent = ''
1060
- if (element.nodeType === Node.TEXT_NODE) {
1061
- textContent = element.textContent ? element.textContent.trim().substring(0, 50) : ''
1062
- } else if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
1063
- textContent = element.childNodes[0].textContent ? element.childNodes[0].textContent.trim().substring(0, 50) : ''
1064
- } else {
1065
- // Try to get first text node from children
1066
- for (const child of element.childNodes) {
1067
- if (child.nodeType === Node.TEXT_NODE && child.textContent && child.textContent.trim()) {
1068
- textContent = child.textContent.trim().substring(0, 50)
1069
- break
1070
- }
1071
- }
1072
- }
1073
- if (textContent && textContent.length >= 50) {
1074
- textContent += '...'
1075
- }
1076
-
1077
- return {
1078
- url: sourceFile,
1079
- line: sourceLine,
1080
- column: sourceColumn,
1081
- selector: selector,
1082
- text: textContent,
1083
- hint: sourceFile ? 'File: ' + sourceFile : 'Element: ' + selector
1084
- }
1085
- }
1086
-
1087
- function setupDraggable(divider) {
1088
- let startX = 0
1089
- let startWidth = 0
1090
- let containerWidth = 0
1091
-
1092
- // Remove existing listeners to avoid duplicates
1093
- divider.removeEventListener('mousedown', startDrag)
1094
- divider.removeEventListener('touchstart', startDrag)
1095
-
1096
- divider.addEventListener('mousedown', startDrag)
1097
- divider.addEventListener('touchstart', startDrag)
1098
-
1099
- function startDrag(e) {
1100
- isDragging = true
1101
- divider.classList.add('dragging')
1102
-
1103
- // Disable pointer events on iframes to prevent interference
1104
- const iframes = document.querySelectorAll('iframe')
1105
- iframes.forEach(iframe => iframe.style.pointerEvents = 'none')
1106
-
1107
- const clientX = e.touches ? e.touches[0].clientX : e.clientX
1108
- startX = clientX
1109
-
1110
- const container = document.querySelector('.claude-dev-server-container')
1111
- const leftPanelEl = document.querySelector('.claude-dev-server-left')
1112
-
1113
- if (container && leftPanelEl) {
1114
- containerWidth = container.offsetWidth
1115
- startWidth = leftPanelEl.offsetWidth
1116
- }
1117
-
1118
- e.preventDefault()
1119
- }
1120
-
1121
- function drag(e) {
1122
- if (!isDragging) return
1123
-
1124
- // Safety check: if mouse button is not pressed, end drag
1125
- if (e.buttons === 0 && !e.touches) {
1126
- endDrag()
1127
- return
1128
- }
1129
-
1130
- const clientX = e.touches ? e.touches[0].clientX : e.clientX
1131
- const deltaX = clientX - startX
1132
-
1133
- // Calculate new width in pixels, then convert to percentage
1134
- let newWidth = startWidth + deltaX
1135
- let percentage = (newWidth / containerWidth) * 100
1136
-
1137
- // Clamp between 20% and 80%
1138
- const clamped = Math.max(20, Math.min(80, percentage))
1139
-
1140
- const leftPanelEl = document.querySelector('.claude-dev-server-left')
1141
- if (leftPanelEl) {
1142
- leftPanelEl.style.flex = 'none'
1143
- leftPanelEl.style.width = clamped + '%'
1144
- }
1145
- }
1146
-
1147
- function endDrag() {
1148
- if (isDragging) {
1149
- isDragging = false
1150
- divider.classList.remove('dragging')
1151
-
1152
- // Re-enable pointer events on iframes
1153
- const iframes = document.querySelectorAll('iframe')
1154
- iframes.forEach(iframe => iframe.style.pointerEvents = '')
1155
- }
1156
- }
1157
-
1158
- // Use capture phase to ensure events are caught
1159
- // Remove old listeners first to prevent duplicates
1160
- document.removeEventListener('mousemove', drag, true)
1161
- document.removeEventListener('touchmove', drag, true)
1162
- document.removeEventListener('mouseup', endDrag, true)
1163
- document.removeEventListener('touchend', endDrag, true)
1164
-
1165
- document.addEventListener('mousemove', drag, true)
1166
- document.addEventListener('touchmove', drag, { passive: false, capture: true })
1167
- document.addEventListener('mouseup', endDrag, true)
1168
- document.addEventListener('touchend', endDrag, true)
1169
- }
1170
-
1171
- function createOverlay() {
1172
- if (overlay) return
1173
- overlay = document.createElement('div')
1174
- overlay.className = 'claude-dev-server-inspect-overlay'
1175
- document.body.appendChild(overlay)
1176
- }
1177
-
1178
- function enableInspectMode() {
1179
- isInspectMode = true
1180
- if (overlay) overlay.classList.add('active')
1181
- // Setup inspect listeners on the iframe
1182
- setupIframeInspectListeners()
1183
- // Change cursor in iframe
1184
- if (devIframe && devIframe.contentDocument && devIframe.contentDocument.body) {
1185
- devIframe.contentDocument.body.style.cursor = 'crosshair'
1186
- }
1187
- const btn = document.querySelector('.claude-dev-server-btn-inspect')
1188
- if (btn) btn.classList.add('active')
1189
- }
1190
-
1191
- function disableInspectMode() {
1192
- isInspectMode = false
1193
- if (overlay) {
1194
- overlay.classList.remove('active')
1195
- overlay.innerHTML = ''
1196
- }
1197
- // Restore cursor in iframe
1198
- if (devIframe && devIframe.contentDocument && devIframe.contentDocument.body) {
1199
- devIframe.contentDocument.body.style.cursor = ''
1200
- }
1201
- const btn = document.querySelector('.claude-dev-server-btn-inspect')
1202
- if (btn) btn.classList.remove('active')
1203
-
1204
- // Remove inspect listeners to free up resources
1205
- removeIframeInspectListeners()
1206
- }
1207
-
1208
- function removeIframeInspectListeners() {
1209
- if (!devIframe || !devIframe.contentDocument) return
1210
-
1211
- const iframeDoc = devIframe.contentDocument
1212
- const existingHandler = iframeDoc._claudeInspectHandler
1213
-
1214
- if (existingHandler) {
1215
- iframeDoc.removeEventListener('click', existingHandler, true)
1216
- iframeDoc.removeEventListener('mousemove', existingHandler, true)
1217
- delete iframeDoc._claudeInspectHandler
1218
- inspectListenersRegistered = false
1219
- }
1220
- }
1221
-
1222
- async function sendToTerminal(location) {
1223
- // Use format: @filename <selector> "text content" (without line number)
1224
- const filePath = location.url || location.file || 'unknown'
1225
-
1226
- // Build selector - handle Tailwind CSS classes by limiting
1227
- const tagName = location.selector ? location.selector.split(/[.#]/)[0] : 'div'
1228
- let selector = location.selector || tagName
1229
-
1230
- // Get text content for better context
1231
- let textContent = ''
1232
- if (location.text) {
1233
- textContent = location.text
1234
- } else if (location.hint && location.hint.includes('File:')) {
1235
- // No text content available
1236
- }
1237
-
1238
- // Format: @filename <selector> "text content" (no line number)
1239
- let prompt = \`@\${filePath} <\${selector}>\`
1240
- if (textContent) {
1241
- prompt += \` "\${textContent}"\`
1242
- }
1243
-
1244
- console.log('[Claude Dev Server] Sending to terminal:', prompt)
1245
-
1246
- // Store the interval ID so we can clear it if needed
1247
- if (!window._claudeSendRetryInterval) {
1248
- window._claudeSendRetryInterval = null
1249
- }
1250
-
1251
- // Clear any existing retry interval
1252
- if (window._claudeSendRetryInterval) {
1253
- clearInterval(window._claudeSendRetryInterval)
1254
- window._claudeSendRetryInterval = null
1255
- }
1256
-
1257
- // Send to terminal with retry logic
1258
- const sendToTerminalInternal = () => {
1259
- if (!ttydIframe || !ttydIframe.contentWindow) {
1260
- return false
1261
- }
1262
-
1263
- const win = ttydIframe.contentWindow
1264
- if (win.sendToTerminal) {
1265
- win.sendToTerminal(prompt)
1266
- console.log('[Claude Dev Server] Sent via sendToTerminal:', prompt)
1267
- // Clear interval on success
1268
- if (window._claudeSendRetryInterval) {
1269
- clearInterval(window._claudeSendRetryInterval)
1270
- window._claudeSendRetryInterval = null
1271
- }
1272
- return true
1273
- }
1274
-
1275
- return false
1276
- }
1277
-
1278
- // Try immediately
1279
- if (sendToTerminalInternal()) {
1280
- return
1281
- }
1282
-
1283
- // If not ready, wait and retry
1284
- let attempts = 0
1285
- const maxAttempts = 50
1286
- window._claudeSendRetryInterval = setInterval(() => {
1287
- attempts++
1288
- if (sendToTerminalInternal() || attempts >= maxAttempts) {
1289
- clearInterval(window._claudeSendRetryInterval)
1290
- window._claudeSendRetryInterval = null
1291
- if (attempts >= maxAttempts) {
1292
- console.warn('[Claude Dev Server] Could not send to terminal after retries')
1293
- }
1294
- }
1295
- }, 100)
1296
- }
1297
-
1298
- function loadTerminalIframe(ttydUrl) {
1299
- if (!ttydIframe) return
1300
- ttydWsUrl = ttydUrl
1301
- ttydIframe.src = '/ttyd/index.html?ws=' + encodeURIComponent(ttydUrl)
1302
- ttydIframe.onload = () => {
1303
- console.log('[Claude Dev Server] Terminal iframe loaded')
1304
- }
1305
- }
1306
-
1307
- function connect(port) {
1308
- const WS_URL = 'ws://localhost:' + port
1309
- ws = new WebSocket(WS_URL)
1310
-
1311
- ws.onopen = () => {
1312
- console.log('[Claude Dev Server] Connected to control server')
1313
- }
1314
-
1315
- ws.onmessage = (e) => {
1316
- try {
1317
- const msg = JSON.parse(e.data)
1318
- console.log('[Claude Dev Server] Received message:', msg.type, msg)
1319
- if (msg.type === 'ready' && msg.ttydUrl) {
1320
- loadTerminalIframe(msg.ttydUrl)
1321
- }
1322
- } catch (err) {
1323
- console.error('[Claude Dev Server] Message parse error:', err)
1324
- }
1325
- }
1326
-
1327
- ws.onclose = () => {
1328
- console.log('[Claude Dev Server] Control WebSocket disconnected, reconnecting...')
1329
- setTimeout(() => connect(port), 2000)
1330
- }
1331
-
1332
- ws.onerror = (err) => {
1333
- console.error('[Claude Dev Server] Control WebSocket error:', err)
1334
- }
1335
- }
1336
-
1337
- initWhenReady()
1338
-
1339
- document.addEventListener('keydown', (e) => {
1340
- if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'I') {
1341
- e.preventDefault()
1342
- if (isInspectMode) {
1343
- disableInspectMode()
1344
- } else {
1345
- enableInspectMode()
1346
- }
1347
- }
1348
- if (e.key === 'Escape' && isInspectMode) {
1349
- disableInspectMode()
1350
- }
1351
- })
1352
- })()
1353
- `;
1354
-
1355
- // src/universal/index.ts
1356
- var __filename$1 = fileURLToPath(import.meta.url);
1357
- dirname(__filename$1);
1358
- async function startUniversalServer(options = {}) {
1359
- const cwd = options.cwd || process.cwd();
1360
- const port = options.port || 3e3;
1361
- const projectType = options.server?.type || detectProjectType(cwd);
1362
- const targetCommand = options.server?.command || getDefaultCommand(projectType);
1363
- console.log(`[Claude Dev Server] Detected project type: ${projectType}`);
1364
- console.log(`[Claude Dev Server] Starting target server...`);
1365
- const targetServer = spawnTargetServer(targetCommand, cwd);
1366
- console.log(`[Claude Dev Server] Waiting for target server to start (PID: ${targetServer.pid})...`);
1367
- const targetPort = await detectServerPort(targetServer, 3e4);
1368
- if (!targetPort) {
1369
- throw new Error("Failed to detect target server port. Please check if the dev server started successfully.");
1370
- }
1371
- console.log(`[Claude Dev Server] Target server is running on port ${targetPort}`);
1372
- const wsServer = createWebSocketServer({
1373
- port: 0,
1374
- // 自动分配端口
1375
- projectRoot: cwd,
1376
- claudePath: options.claudePath || "claude",
1377
- claudeArgs: options.claudeArgs || []
1378
- });
1379
- const { wsPort, ttydPort } = await wsServer.start();
1380
- console.log(`[Claude Dev Server] Control server running on ws://localhost:${wsPort}`);
1381
- console.log(`[Claude Dev Server] ttyd running on ws://localhost:${ttydPort}`);
1382
- const proxyServer = createProxyServer(targetPort, wsPort, cwd);
1383
- proxyServer.listen(port);
1384
- console.log(`[Claude Dev Server] Proxy server running on http://localhost:${port}`);
1385
- console.log(`
1386
- \u{1F680} Ready! Open http://localhost:${port} in your browser`);
1387
- const cleanup = () => {
1388
- console.log("[Claude Dev Server] Shutting down...");
1389
- targetServer.kill();
1390
- wsServer.stop();
1391
- proxyServer.close();
1392
- process.exit(0);
1393
- };
1394
- process.on("SIGINT", cleanup);
1395
- process.on("SIGTERM", cleanup);
1396
- return { proxyServer, targetServer, wsServer };
1397
- }
1398
- function detectProjectType(cwd) {
1399
- if (existsSync(join(cwd, "vite.config.ts")) || existsSync(join(cwd, "vite.config.js"))) {
1400
- return "vite";
1401
- }
1402
- if (existsSync(join(cwd, "next.config.js")) || existsSync(join(cwd, "next.config.mjs"))) {
1403
- return "next";
1404
- }
1405
- if (existsSync(join(cwd, "webpack.config.js")) || existsSync(join(cwd, "webpack.config.ts"))) {
1406
- return "webpack";
1407
- }
1408
- return "custom";
1409
- }
1410
- function getDefaultCommand(projectType) {
1411
- switch (projectType) {
1412
- case "vite":
1413
- return "npm run dev";
1414
- case "next":
1415
- return "npm run dev";
1416
- case "webpack":
1417
- return "npm run dev";
1418
- default:
1419
- return "npm run dev";
1420
- }
1421
- }
1422
- function spawnTargetServer(command, cwd) {
1423
- const [cmd, ...args] = command.split(" ");
1424
- const child = spawn(cmd, args, {
1425
- cwd,
1426
- stdio: "pipe",
1427
- env: process.env
1428
- });
1429
- child.stdout?.pipe(process.stdout);
1430
- child.stderr?.pipe(process.stderr);
1431
- return child;
1432
- }
1433
- async function detectServerPort(childProcess, timeout) {
1434
- return new Promise((resolve2) => {
1435
- const timeoutId = setTimeout(() => {
1436
- cleanup();
1437
- resolve2(null);
1438
- }, timeout);
1439
- let stdout = "";
1440
- const onData = (chunk) => {
1441
- stdout += chunk.toString();
1442
- const patterns = [
1443
- /localhost:(\d{4,5})/,
1444
- /127\.0\.0\.1:(\d{4,5})/,
1445
- /0\.0\.0\.0:(\d{4,5})/
1446
- ];
1447
- for (const pattern of patterns) {
1448
- const match = stdout.match(pattern);
1449
- if (match) {
1450
- const port = parseInt(match[1], 10);
1451
- console.log(`[Claude Dev Server] Detected port from stdout: ${port}`);
1452
- cleanup();
1453
- resolve2(port);
1454
- return;
1455
- }
1456
- }
1457
- };
1458
- const cleanup = () => {
1459
- clearTimeout(timeoutId);
1460
- childProcess.stdout?.off("data", onData);
1461
- };
1462
- childProcess.stdout?.on("data", onData);
1463
- });
1464
- }
1465
- async function handleSourceMapRequest(projectRoot, filePath, line, column, targetPort) {
1466
- try {
1467
- let content;
1468
- let fullPath = filePath;
1469
- if (filePath.startsWith("/") && targetPort) {
1470
- try {
1471
- const response = await fetch(`http://localhost:${targetPort}${filePath}`);
1472
- if (!response.ok) {
1473
- console.log("[Claude Dev Server] Failed to fetch from Dev Server:", response.status);
1474
- return { error: "Failed to fetch from Dev Server" };
1475
- }
1476
- content = await response.text();
1477
- console.log("[Claude Dev Server] Fetched", content.length, "chars from Dev Server");
1478
- } catch (e) {
1479
- console.log("[Claude Dev Server] Fetch error:", e);
1480
- return { error: "Fetch error: " + e.message };
1481
- }
1482
- } else {
1483
- if (!filePath.startsWith("/")) {
1484
- fullPath = join(projectRoot, filePath);
1485
- }
1486
- if (!existsSync(fullPath)) {
1487
- console.log("[Claude Dev Server] File not found:", fullPath);
1488
- return { error: "File not found" };
1489
- }
1490
- content = readFileSync(fullPath, "utf-8");
1491
- console.log("[Claude Dev Server] Resolving source map for:", fullPath, "at line:", line);
1492
- }
1493
- let sourceMapUrl = null;
1494
- const patterns = [
1495
- /\/\/[@#]\s*sourceMappingURL=([^\s]+)/,
1496
- /\/\*[@#]\s*sourceMappingURL=([^\s]+)\s*\*\//
1497
- ];
1498
- for (const pattern of patterns) {
1499
- const match = content.match(pattern);
1500
- if (match) {
1501
- sourceMapUrl = match[1];
1502
- console.log("[Claude Dev Server] Found sourceMappingURL:", sourceMapUrl.substring(0, 100) + "...");
1503
- break;
1504
- }
1505
- }
1506
- if (!sourceMapUrl) {
1507
- console.log("[Claude Dev Server] No source map found in:", fullPath);
1508
- return { file: relative(projectRoot, fullPath), line, column };
1509
- }
1510
- let sourceMapContent;
1511
- let sourceMap;
1512
- if (sourceMapUrl.startsWith("data:application/json;base64,") || sourceMapUrl.startsWith("data:application/json;charset=utf-8;base64,")) {
1513
- console.log("[Claude Dev Server] Found inline source map");
1514
- const base64Data = sourceMapUrl.split(",", 2)[1];
1515
- sourceMapContent = Buffer.from(base64Data, "base64").toString("utf-8");
1516
- try {
1517
- sourceMap = JSON.parse(sourceMapContent);
1518
- } catch (e) {
1519
- console.log("[Claude Dev Server] Failed to parse inline source map:", e);
1520
- return { file: relative(projectRoot, fullPath), line, column };
1521
- }
1522
- } else if (sourceMapUrl.startsWith("http://") || sourceMapUrl.startsWith("https://")) {
1523
- console.log("[Claude Dev Server] Remote source map not supported:", sourceMapUrl);
1524
- return { file: relative(projectRoot, fullPath), line, column };
1525
- } else {
1526
- let sourceMapPath;
1527
- if (sourceMapUrl.startsWith("/")) {
1528
- sourceMapPath = sourceMapUrl;
1529
- } else {
1530
- sourceMapPath = join(dirname(fullPath), sourceMapUrl);
1531
- }
1532
- console.log("[Claude Dev Server] Reading external source map:", sourceMapPath);
1533
- if (!existsSync(sourceMapPath)) {
1534
- console.log("[Claude Dev Server] Source map file not found:", sourceMapPath);
1535
- return { file: relative(projectRoot, fullPath), line, column };
1536
- }
1537
- sourceMapContent = readFileSync(sourceMapPath, "utf-8");
1538
- sourceMap = JSON.parse(sourceMapContent);
1539
- }
1540
- const consumer = await new SourceMapConsumer(sourceMap);
1541
- const original = consumer.originalPositionFor({
1542
- line,
1543
- column
1544
- });
1545
- consumer.destroy();
1546
- if (original.source && original.line !== null) {
1547
- let originalFile = original.source;
1548
- if (originalFile.startsWith("webpack://")) {
1549
- originalFile = originalFile.replace(/^webpack:\/\/[\/\\]?/, "");
1550
- }
1551
- if (!originalFile.startsWith("/")) {
1552
- const possiblePath = join(projectRoot, originalFile);
1553
- if (existsSync(possiblePath)) {
1554
- } else {
1555
- const fileName = originalFile.split("/").pop() || originalFile.split("\\").pop() || originalFile;
1556
- if (fileName === originalFile) {
1557
- if (filePath.startsWith("/")) {
1558
- originalFile = filePath.substring(1);
1559
- console.log("[Claude Dev Server] Source is just a filename, using filePath:", originalFile);
1560
- } else {
1561
- originalFile = relative(projectRoot, fullPath);
1562
- }
1563
- } else {
1564
- originalFile = relative(projectRoot, possiblePath);
1565
- }
1566
- }
1567
- }
1568
- return {
1569
- file: originalFile,
1570
- line: original.line,
1571
- column: original.column || 1,
1572
- original: {
1573
- source: original.source,
1574
- line: original.line,
1575
- column: original.column,
1576
- name: original.name
1577
- }
1578
- };
1579
- }
1580
- return { file: relative(projectRoot, fullPath), line, column };
1581
- } catch (err) {
1582
- console.error("[Claude Dev Server] Source map resolution error:", err);
1583
- return { error: String(err) };
1584
- }
1585
- }
1586
- async function handleTurbopackLookup(projectRoot, pagePath, targetPort) {
1587
- try {
1588
- console.log("[Claude Dev Server] Turbopack lookup for page:", pagePath);
1589
- const pageRes = await fetch(`http://localhost:${targetPort}${pagePath}`);
1590
- if (!pageRes.ok) {
1591
- return { error: "Failed to fetch page" };
1592
- }
1593
- const html = await pageRes.text();
1594
- const chunkUrls = [];
1595
- const scriptMatches = html.matchAll(/<script[^>]*src="([^"]*\/_next\/static\/chunks\/[^"]*)"/g);
1596
- for (const match of scriptMatches) {
1597
- if (match[1]) {
1598
- chunkUrls.push(match[1]);
1599
- }
1600
- }
1601
- console.log("[Claude Dev Server] Found", chunkUrls.length, "chunk URLs");
1602
- for (const chunkUrl of chunkUrls) {
1603
- try {
1604
- const fullUrl = chunkUrl.startsWith("http") ? chunkUrl : `http://localhost:${targetPort}${chunkUrl}`;
1605
- const chunkRes = await fetch(fullUrl);
1606
- if (!chunkRes.ok) continue;
1607
- const chunkContent = await chunkRes.text();
1608
- const modulePathRegex = /\[project\]([^\s"]+\.(tsx?|jsx?))/g;
1609
- const matches = [...chunkContent.matchAll(modulePathRegex)];
1610
- for (const match of matches) {
1611
- if (match[1]) {
1612
- const sourcePath = match[1];
1613
- let relativePath = sourcePath.replace(/^\[project\]/, "");
1614
- const normalizedPagePath = pagePath.replace(/^\/[^/]+/, "");
1615
- if (relativePath.toLowerCase().includes(normalizedPagePath.toLowerCase()) || relativePath.toLowerCase().includes("login")) {
1616
- console.log("[Claude Dev Server] Found source file:", relativePath);
1617
- return {
1618
- file: relativePath,
1619
- line: void 0
1620
- // Turbopack doesn't provide line numbers
1621
- };
1622
- }
1623
- }
1624
- }
1625
- } catch (e) {
1626
- console.log("[Claude Dev Server] Error fetching chunk:", chunkUrl, e);
1627
- }
1628
- }
1629
- return { error: "Source file not found for page: " + pagePath };
1630
- } catch (err) {
1631
- console.error("[Claude Dev Server] Turbopack lookup error:", err);
1632
- return { error: String(err) };
1633
- }
1634
- }
1635
- function isHtmlPageRequest(req) {
1636
- const accept = req.headers.accept || "";
1637
- const url = req.url || "";
1638
- if (!accept.includes("text/html")) {
1639
- return false;
1640
- }
1641
- if (url.startsWith("/@") || url.startsWith("/_next/") || url.startsWith("/ttyd") || url.startsWith("/dev.html")) {
1642
- return false;
1643
- }
1644
- return true;
1645
- }
1646
- function createProxyServer(targetPort, wsPort, projectRoot) {
1647
- const moduleDir = dirname(fileURLToPath(import.meta.url));
1648
- const assetsPath = join(moduleDir, "assets");
1649
- let ttydHtml;
1650
- let ttydBridgeJs;
1651
- let devHtml;
1652
- try {
1653
- ttydHtml = readFileSync(join(assetsPath, "ttyd-terminal.html"), "utf-8");
1654
- ttydBridgeJs = readFileSync(join(assetsPath, "ttyd-bridge.js"), "utf-8");
1655
- devHtml = readFileSync(join(assetsPath, "dev.html"), "utf-8");
1656
- } catch (e) {
1657
- console.error("[Claude Dev Server] Failed to read assets from", assetsPath);
1658
- console.error("[Claude Dev Server] moduleDir:", moduleDir);
1659
- console.error("[Claude Dev Server] Error:", e.message);
1660
- throw new Error("Assets not found. Please run `npm run build` first.");
1661
- }
1662
- const server = http.createServer((req, res) => {
1663
- const referer = req.headers.referer || "";
1664
- const isFromDevPage = referer.includes("dev.html");
1665
- if (req.url?.startsWith("/dev.html")) {
1666
- const urlParams = new URL(req.url || "", `http://${req.headers.host}`);
1667
- const originalPath = urlParams.searchParams.get("path") || "/";
1668
- const host = req.headers.host || "localhost:3000";
1669
- const origin = `http://${host}`;
1670
- const modifiedDevHtml = devHtml.replace(
1671
- /__CLAUDE_IFRAME_SRC__/g,
1672
- `${origin}${originalPath}`
1673
- ).replace(
1674
- /__CLAUDE_ORIGINAL_PATH__/g,
1675
- originalPath
1676
- );
1677
- res.setHeader("Content-Type", "text/html");
1678
- res.end(modifiedDevHtml);
1679
- return;
1680
- }
1681
- if (!isFromDevPage && isHtmlPageRequest(req)) {
1682
- const currentPath = req.url || "/";
1683
- const devPageUrl = `/dev.html?path=${encodeURIComponent(currentPath)}`;
1684
- res.writeHead(302, { "Location": devPageUrl });
1685
- res.end();
1686
- return;
1687
- }
1688
- if (req.url === "/@claude-port") {
1689
- res.setHeader("Content-Type", "application/json");
1690
- res.end(JSON.stringify({ port: wsPort }));
1691
- return;
1692
- }
1693
- if (req.url?.startsWith("/@sourcemap?")) {
1694
- const url = new URL(req.url, `http://localhost:${wsPort}`);
1695
- const file = url.searchParams.get("file");
1696
- const line = url.searchParams.get("line");
1697
- const column = url.searchParams.get("col");
1698
- if (file && line && column) {
1699
- handleSourceMapRequest(projectRoot, file, parseInt(line), parseInt(column || "1"), targetPort).then((result) => {
1700
- res.setHeader("Content-Type", "application/json");
1701
- res.end(JSON.stringify(result));
1702
- }).catch((err) => {
1703
- console.error("[Claude Dev Server] Source map error:", err);
1704
- res.setHeader("Content-Type", "application/json");
1705
- res.end(JSON.stringify({ error: err.message }));
1706
- });
1707
- return;
1708
- }
1709
- }
1710
- if (req.url?.startsWith("/@sourcemap-lookup?")) {
1711
- const url = new URL(req.url, `http://localhost:${wsPort}`);
1712
- const page = url.searchParams.get("page");
1713
- const framework = url.searchParams.get("framework");
1714
- if (page && framework === "nextjs") {
1715
- handleTurbopackLookup(projectRoot, page, targetPort).then((result) => {
1716
- res.setHeader("Content-Type", "application/json");
1717
- res.end(JSON.stringify(result));
1718
- }).catch((err) => {
1719
- console.error("[Claude Dev Server] Turbopack lookup error:", err);
1720
- res.setHeader("Content-Type", "application/json");
1721
- res.end(JSON.stringify({ error: err.message }));
1722
- });
1723
- return;
1724
- }
1725
- }
1726
- if (req.url?.startsWith("/ttyd/")) {
1727
- const urlPath = req.url.split("?")[0];
1728
- if (urlPath === "/ttyd/index.html" || urlPath === "/ttyd/") {
1729
- res.setHeader("Content-Type", "text/html");
1730
- res.end(ttydHtml);
1731
- return;
1732
- }
1733
- if (urlPath === "/ttyd/ttyd-bridge.js") {
1734
- res.setHeader("Content-Type", "application/javascript");
1735
- res.end(ttydBridgeJs);
1736
- return;
1737
- }
1738
- if (urlPath === "/ttyd/token" || urlPath === "/ttyd/index.html/token") {
1739
- res.setHeader("Content-Type", "application/json");
1740
- res.end(JSON.stringify({ token: "" }));
1741
- return;
1742
- }
1743
- res.statusCode = 404;
1744
- res.end("Not found");
1745
- return;
1746
- }
1747
- const proxyHeaders = { ...req.headers };
1748
- delete proxyHeaders["accept-encoding"];
1749
- const shouldInject = !isFromDevPage;
1750
- const options = {
1751
- hostname: "localhost",
1752
- port: targetPort,
1753
- path: req.url,
1754
- method: req.method,
1755
- headers: proxyHeaders
1756
- };
1757
- const proxyReq = http.request(options, (proxyRes) => {
1758
- if (proxyRes.headers["content-type"]?.includes("text/html") && shouldInject) {
1759
- const body = [];
1760
- proxyRes.on("data", (chunk) => body.push(chunk));
1761
- proxyRes.on("end", () => {
1762
- const html = Buffer.concat(body).toString("utf8");
1763
- const injected = injectScripts(html, wsPort, projectRoot);
1764
- const statusCode = proxyRes.statusCode || 200;
1765
- res.writeHead(statusCode, {
1766
- ...proxyRes.headers,
1767
- "content-length": Buffer.byteLength(injected)
1768
- });
1769
- res.end(injected);
1770
- });
1771
- } else {
1772
- const statusCode = proxyRes.statusCode || 200;
1773
- res.writeHead(statusCode, proxyRes.headers);
1774
- proxyRes.pipe(res);
1775
- }
1776
- });
1777
- proxyReq.on("error", (err) => {
1778
- console.error("[Claude Dev Server] Proxy error:", err);
1779
- res.statusCode = 502;
1780
- res.end("Bad Gateway");
1781
- });
1782
- req.pipe(proxyReq);
1783
- });
1784
- server.on("upgrade", (req, socket, head) => {
1785
- if (req.headers["upgrade"]?.toLowerCase() !== "websocket") {
1786
- return;
1787
- }
1788
- console.log("[Claude Dev Server] WebSocket upgrade request:", req.url);
1789
- const targetSocket = createConnection(targetPort, "localhost", () => {
1790
- console.log("[Claude Dev Server] Connected to target WebSocket server");
1791
- const upgradeRequest = [
1792
- `${req.method} ${req.url} HTTP/1.1`,
1793
- `Host: localhost:${targetPort}`,
1794
- "Upgrade: websocket",
1795
- "Connection: Upgrade",
1796
- `Sec-WebSocket-Key: ${req.headers["sec-websocket-key"]}`,
1797
- `Sec-WebSocket-Version: ${req.headers["sec-websocket-version"] || "13"}`
1798
- ];
1799
- if (req.headers["sec-websocket-protocol"]) {
1800
- upgradeRequest.push(`Sec-WebSocket-Protocol: ${req.headers["sec-websocket-protocol"]}`);
1801
- }
1802
- if (req.headers["sec-websocket-extensions"]) {
1803
- upgradeRequest.push(`Sec-WebSocket-Extensions: ${req.headers["sec-websocket-extensions"]}`);
1804
- }
1805
- targetSocket.write(upgradeRequest.join("\r\n") + "\r\n\r\n");
1806
- if (head && head.length > 0) {
1807
- targetSocket.write(head);
1808
- }
1809
- });
1810
- targetSocket.on("data", (data) => {
1811
- if (socket.writable) {
1812
- socket.write(data);
1813
- }
1814
- });
1815
- socket.on("data", (data) => {
1816
- if (targetSocket.writable) {
1817
- targetSocket.write(data);
1818
- }
1819
- });
1820
- socket.on("close", () => {
1821
- console.log("[Claude Dev Server] Client WebSocket closed");
1822
- targetSocket.destroy();
1823
- });
1824
- targetSocket.on("close", () => {
1825
- console.log("[Claude Dev Server] Target WebSocket closed");
1826
- socket.end();
1827
- });
1828
- socket.on("error", (err) => {
1829
- console.error("[Claude Dev Server] Client socket error:", err.message);
1830
- targetSocket.destroy();
1831
- });
1832
- targetSocket.on("error", (err) => {
1833
- console.error("[Claude Dev Server] Target socket error:", err.message);
1834
- socket.end();
1835
- });
1836
- });
1837
- return server;
1838
- }
1839
- function injectScripts(html, wsPort, projectRoot) {
1840
- if (html.includes("claude-dev-server-container") || html.includes("__CLAUDE_ORIGINAL_HTML__")) {
1841
- console.log("[Claude Dev Server] HTML already injected, returning as-is");
1842
- return html;
1843
- }
1844
- const hasOurScripts = html.includes("CLIENT_SCRIPT") || html.includes("claude-dev-server-container");
1845
- if (hasOurScripts) {
1846
- console.log("[Claude Dev Server] Warning: Original HTML already has our scripts");
1847
- }
1848
- const modifiedHtml = html;
1849
- console.log("[Claude Dev Server] Creating split layout, original HTML length:", html.length);
1850
- const base64Html = Buffer.from(modifiedHtml, "utf-8").toString("base64");
1851
- const projectRootScript = `<script>window.__CLAUDE_PROJECT_ROOT__ = ${JSON.stringify(projectRoot)};window.__CLAUDE_ORIGINAL_HTML_BASE64__ = "${base64Html}";</script>`;
1852
- return `<!DOCTYPE html>
1853
- <html lang="en">
1854
- <head>
1855
- <meta charset="UTF-8">
1856
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1857
- <title>Claude Dev Server</title>
1858
- ${CLIENT_STYLES}
1859
- ${projectRootScript}
1860
- </head>
1861
- <body>
1862
- <script type="module">${CLIENT_SCRIPT.replace(/wsPort:\s*\d+/, `wsPort: ${wsPort}`)}</script>
1863
- </body>
1864
- </html>`;
1865
- }
1866
-
1867
- export { startUniversalServer };
1868
- //# sourceMappingURL=chunk-PAE5WTS2.js.map
1869
- //# sourceMappingURL=chunk-PAE5WTS2.js.map