@pixelbyte-software/pixcode 1.40.1 → 1.40.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.
@@ -31,6 +31,162 @@ function buildUrls(req, session) {
31
31
  };
32
32
  }
33
33
 
34
+ function escapeHtml(value) {
35
+ return String(value ?? '')
36
+ .replaceAll('&', '&')
37
+ .replaceAll('<', '&lt;')
38
+ .replaceAll('>', '&gt;')
39
+ .replaceAll('"', '&quot;')
40
+ .replaceAll("'", '&#39;');
41
+ }
42
+
43
+ function latestErrorFromLogs(logs) {
44
+ return [...logs].reverse().find((line) => /error|enoent|eaddrinuse|failed|fatal|exception/i.test(line)) || null;
45
+ }
46
+
47
+ function buildLiveViewSuggestions(session, reason) {
48
+ const framework = String(session?.framework || session?.label || '').toLowerCase();
49
+ const status = String(session?.status || '').toLowerCase();
50
+ const suggestions = [];
51
+
52
+ if (framework.includes('php')) {
53
+ suggestions.push('Run `php --version` in the same machine and make sure the PHP executable is available in PATH.');
54
+ suggestions.push('If PHP is installed outside PATH, use Live View custom command with the full php executable path.');
55
+ suggestions.push('Check that the project has an index.php or a valid PHP router file in the selected project root.');
56
+ } else if (
57
+ framework.includes('javascript')
58
+ || framework.includes('vite')
59
+ || framework.includes('next')
60
+ || framework.includes('nuxt')
61
+ || framework.includes('astro')
62
+ || framework.includes('react')
63
+ || framework.includes('node')
64
+ ) {
65
+ suggestions.push('Run the project command in a terminal first and confirm it opens a local HTTP port.');
66
+ suggestions.push('Install project dependencies if node_modules is missing, then retry Live View.');
67
+ suggestions.push('If the dev server ignores PORT, set a custom command that binds to 127.0.0.1 and the chosen port.');
68
+ } else {
69
+ suggestions.push('Run the displayed command in a terminal and fix the first process error shown there.');
70
+ suggestions.push('Use a custom command if Pixcode detected the wrong runner for this project.');
71
+ }
72
+
73
+ if (status === 'starting' || reason === 'upstream_not_ready') {
74
+ suggestions.push('Wait for the app to finish booting, then press Refresh or Restart if the port never opens.');
75
+ }
76
+
77
+ if (reason === 'proxy_failed') {
78
+ suggestions.push('The Live View session exists, but Pixcode could not reach the local upstream URL.');
79
+ }
80
+
81
+ return suggestions;
82
+ }
83
+
84
+ export function buildLiveViewUnavailablePayload(session, options = {}) {
85
+ const logs = Array.isArray(session?.log) ? session.log.slice(-40) : [];
86
+ const errorDetail = options.errorMessage || session?.error || latestErrorFromLogs(logs);
87
+ const label = session?.label || session?.framework || 'Live View';
88
+ const status = session?.status || 'missing';
89
+
90
+ return {
91
+ error: 'Live View session is not available.',
92
+ message: `${label} is ${status}.`,
93
+ reason: options.reason || status,
94
+ status,
95
+ framework: session?.framework || null,
96
+ label,
97
+ projectName: session?.projectName || null,
98
+ shareId: session?.shareId || options.shareId || null,
99
+ sharePath: session?.sharePath || null,
100
+ upstreamUrl: session?.upstreamUrl || null,
101
+ port: session?.port || null,
102
+ errorDetail,
103
+ diagnostics: {
104
+ command: session?.command?.displayCommand || null,
105
+ upstreamUrl: session?.upstreamUrl || null,
106
+ port: session?.port || null,
107
+ startedAt: session?.startedAt || null,
108
+ stoppedAt: session?.stoppedAt || null,
109
+ exitCode: session?.exitCode ?? null,
110
+ exitSignal: session?.exitSignal ?? null,
111
+ logs,
112
+ },
113
+ suggestions: buildLiveViewSuggestions(session, options.reason),
114
+ };
115
+ }
116
+
117
+ export function renderLiveViewDiagnosticHtml(payload) {
118
+ const suggestions = payload.suggestions?.length
119
+ ? payload.suggestions.map((item) => `<li>${escapeHtml(item)}</li>`).join('')
120
+ : '<li>Open the Live View panel, check the latest logs, and restart the session.</li>';
121
+ const logs = payload.diagnostics?.logs?.length
122
+ ? payload.diagnostics.logs.map((line) => escapeHtml(line)).join('\n')
123
+ : 'No process logs were captured yet.';
124
+
125
+ return `<!doctype html>
126
+ <html lang="en">
127
+ <head>
128
+ <meta charset="utf-8">
129
+ <meta name="viewport" content="width=device-width, initial-scale=1">
130
+ <title>Pixcode Live View diagnostics</title>
131
+ <style>
132
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
133
+ body { margin: 0; min-height: 100vh; background: #0b0f14; color: #e5edf5; }
134
+ main { box-sizing: border-box; max-width: 980px; margin: 0 auto; padding: 32px 20px; }
135
+ .eyebrow { color: #f97316; font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
136
+ h1 { margin: 8px 0 10px; font-size: clamp(26px, 5vw, 44px); line-height: 1.05; }
137
+ p { color: #a8b3c2; line-height: 1.6; }
138
+ section { margin-top: 18px; border: 1px solid rgba(148, 163, 184, .24); border-radius: 12px; background: rgba(15, 23, 42, .72); padding: 16px; }
139
+ dl { display: grid; grid-template-columns: minmax(110px, 180px) minmax(0, 1fr); gap: 10px 14px; margin: 0; }
140
+ dt { color: #94a3b8; font-size: 12px; text-transform: uppercase; }
141
+ dd { margin: 0; overflow-wrap: anywhere; }
142
+ pre { margin: 0; max-height: 280px; overflow: auto; white-space: pre-wrap; color: #dbeafe; background: #020617; border-radius: 10px; padding: 14px; }
143
+ code { color: #bfdbfe; }
144
+ li { margin: 8px 0; color: #d0d8e4; }
145
+ </style>
146
+ </head>
147
+ <body>
148
+ <main>
149
+ <div class="eyebrow">Pixcode Live View</div>
150
+ <h1>${escapeHtml(payload.message)}</h1>
151
+ <p>${escapeHtml(payload.errorDetail || 'The preview link is active, but the local runner is not ready.')}</p>
152
+ <section>
153
+ <dl>
154
+ <dt>Status</dt><dd>${escapeHtml(payload.status)}</dd>
155
+ <dt>Framework</dt><dd>${escapeHtml(payload.framework || 'Unknown')}</dd>
156
+ <dt>Command</dt><dd><code>${escapeHtml(payload.diagnostics?.command || 'No command captured')}</code></dd>
157
+ <dt>Upstream</dt><dd>${escapeHtml(payload.upstreamUrl || 'Not ready')}</dd>
158
+ <dt>Share ID</dt><dd>${escapeHtml(payload.shareId || 'Unknown')}</dd>
159
+ </dl>
160
+ </section>
161
+ <section>
162
+ <h2>What to check</h2>
163
+ <ul>${suggestions}</ul>
164
+ </section>
165
+ <section>
166
+ <h2>Process logs</h2>
167
+ <pre>${logs}</pre>
168
+ </section>
169
+ </main>
170
+ </body>
171
+ </html>`;
172
+ }
173
+
174
+ function requestPrefersHtml(req) {
175
+ const accept = req.header('accept') || '';
176
+ return accept.includes('text/html') || (!accept.includes('application/json') && accept.includes('*/*'));
177
+ }
178
+
179
+ function sendLiveViewDiagnostic(req, res, session, statusCode, options = {}) {
180
+ const payload = buildLiveViewUnavailablePayload(session, options);
181
+ res.status(statusCode);
182
+ if (requestPrefersHtml(req)) {
183
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
184
+ res.type('html').send(renderLiveViewDiagnosticHtml(payload));
185
+ return;
186
+ }
187
+ res.json(payload);
188
+ }
189
+
34
190
  async function resolveProjectPath(projectName) {
35
191
  const projectPath = await extractProjectDirectory(projectName);
36
192
  if (!projectPath || typeof projectPath !== 'string') {
@@ -139,7 +295,10 @@ async function sendStaticLiveView(req, res, session) {
139
295
 
140
296
  async function proxyLiveView(req, res, session) {
141
297
  if (!session.upstreamUrl) {
142
- res.status(503).json({ error: 'Live View upstream is not ready yet.' });
298
+ sendLiveViewDiagnostic(req, res, session, 503, {
299
+ reason: 'upstream_not_ready',
300
+ errorMessage: 'Live View upstream is not ready yet.',
301
+ });
143
302
  return;
144
303
  }
145
304
 
@@ -161,7 +320,10 @@ async function proxyLiveView(req, res, session) {
161
320
  });
162
321
  res.send(Buffer.from(await upstream.arrayBuffer()));
163
322
  } catch (error) {
164
- res.status(502).json({ error: error.message || 'Live View proxy failed' });
323
+ sendLiveViewDiagnostic(req, res, session, 502, {
324
+ reason: 'proxy_failed',
325
+ errorMessage: error.message || 'Live View proxy failed',
326
+ });
165
327
  }
166
328
  }
167
329
 
@@ -170,8 +332,31 @@ export function createLiveViewPublicRouter() {
170
332
 
171
333
  publicRouter.use('/:shareId', async (req, res) => {
172
334
  const session = getLiveViewSessionByShareId(req.params.shareId);
173
- if (!session || session.status === 'stopped' || session.status === 'error') {
174
- res.status(404).json({ error: 'Live View session not found.' });
335
+ if (!session) {
336
+ sendLiveViewDiagnostic(req, res, {
337
+ shareId: req.params.shareId,
338
+ status: 'missing',
339
+ label: 'Live View session',
340
+ log: [],
341
+ }, 404, {
342
+ reason: 'missing_session',
343
+ errorMessage: 'This preview link does not match an active Live View session on this Pixcode server.',
344
+ });
345
+ return;
346
+ }
347
+
348
+ if (session.status === 'error') {
349
+ sendLiveViewDiagnostic(req, res, session, 502, { reason: 'session_error' });
350
+ return;
351
+ }
352
+
353
+ if (session.status === 'stopped') {
354
+ sendLiveViewDiagnostic(req, res, session, 410, { reason: 'session_stopped' });
355
+ return;
356
+ }
357
+
358
+ if (session.status === 'starting') {
359
+ sendLiveViewDiagnostic(req, res, session, 202, { reason: 'upstream_not_ready' });
175
360
  return;
176
361
  }
177
362
 
@@ -8,6 +8,7 @@ const sessionsByProject = new Map();
8
8
  const sessionsByShareId = new Map();
9
9
  const READY_TIMEOUT_MS = 12000;
10
10
  const LOG_LIMIT = 200;
11
+ const RUNTIME_CHECK_TIMEOUT_MS = 1800;
11
12
 
12
13
  const localUrlRegex = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[[^\]]+\])(?::(\d+))?[^\s"'<>]*/i;
13
14
 
@@ -78,6 +79,88 @@ function buildDisplayCommand(command, args) {
78
79
  return [command, ...args].join(' ');
79
80
  }
80
81
 
82
+ function quoteForPosixShell(value) {
83
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
84
+ }
85
+
86
+ function quoteForWindowsShell(value) {
87
+ return `"${String(value).replaceAll('"', '""')}"`;
88
+ }
89
+
90
+ function isPathLikeCommand(command) {
91
+ return path.isAbsolute(command) || command.includes('/') || command.includes('\\');
92
+ }
93
+
94
+ function runtimeMissingReason(command, framework) {
95
+ const base = `${command} executable was not found in PATH.`;
96
+ if (framework === 'PHP' || command === 'php') {
97
+ return `${base} Install PHP and add php.exe to PATH, or use a custom command with the full PHP executable path.`;
98
+ }
99
+ if (command === 'npm' || command === 'pnpm' || command === 'yarn' || command === 'bun') {
100
+ return `${base} Install Node.js/package manager support or use a custom command with the full executable path.`;
101
+ }
102
+ if (command === 'python' || command === 'python3') {
103
+ return `${base} Install Python and add it to PATH, or use a custom command with the full Python executable path.`;
104
+ }
105
+ return `${base} Install ${framework || command} or use a custom command with the full executable path.`;
106
+ }
107
+
108
+ async function checkCommandAvailability(command, env = process.env) {
109
+ if (!command || command.includes('\n') || command.includes('\r')) return true;
110
+
111
+ if (isPathLikeCommand(command)) {
112
+ try {
113
+ await fs.access(command);
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ const checker = process.platform === 'win32'
121
+ ? {
122
+ command: process.env.ComSpec || 'cmd.exe',
123
+ args: ['/d', '/s', '/c', `where ${quoteForWindowsShell(command)}`],
124
+ }
125
+ : {
126
+ command: '/bin/sh',
127
+ args: ['-lc', `command -v ${quoteForPosixShell(command)}`],
128
+ };
129
+
130
+ return new Promise((resolve) => {
131
+ let settled = false;
132
+ let child = null;
133
+ const finish = (available) => {
134
+ if (settled) return;
135
+ settled = true;
136
+ clearTimeout(timer);
137
+ resolve(available);
138
+ };
139
+
140
+ const timer = setTimeout(() => {
141
+ try {
142
+ child?.kill();
143
+ } catch {
144
+ // Ignore a raced process exit.
145
+ }
146
+ finish(true);
147
+ }, RUNTIME_CHECK_TIMEOUT_MS);
148
+
149
+ child = spawn(checker.command, checker.args, {
150
+ env,
151
+ stdio: 'ignore',
152
+ windowsHide: true,
153
+ });
154
+
155
+ child.on('error', (error) => {
156
+ finish(error?.code === 'ENOENT' ? false : true);
157
+ });
158
+ child.on('exit', (code) => {
159
+ finish(code === 0);
160
+ });
161
+ });
162
+ }
163
+
81
164
  function buildPackageCommand(packageManager, scriptName, id, label, framework, extraArgs = []) {
82
165
  const args = packageRunArgs(packageManager, scriptName, extraArgs);
83
166
  return {
@@ -286,7 +369,7 @@ async function detectProcessCommand(projectPath) {
286
369
  return null;
287
370
  }
288
371
 
289
- export async function detectLiveViewTarget(projectPath) {
372
+ export async function detectLiveViewTarget(projectPath, options = {}) {
290
373
  if (!projectPath || !(await dirExists(projectPath))) {
291
374
  return {
292
375
  available: false,
@@ -297,6 +380,19 @@ export async function detectLiveViewTarget(projectPath) {
297
380
 
298
381
  const processCommand = await detectProcessCommand(projectPath);
299
382
  if (processCommand) {
383
+ const runtimeAvailable = await checkCommandAvailability(processCommand.command, options.env || process.env);
384
+ if (!runtimeAvailable) {
385
+ return {
386
+ available: false,
387
+ kind: 'process',
388
+ label: processCommand.label,
389
+ framework: processCommand.framework,
390
+ command: processCommand,
391
+ missingRuntime: processCommand.command,
392
+ reason: runtimeMissingReason(processCommand.command, processCommand.framework),
393
+ };
394
+ }
395
+
300
396
  return {
301
397
  available: true,
302
398
  kind: 'process',
@@ -391,6 +487,9 @@ function publicSession(session) {
391
487
  upstreamUrl: session.upstreamUrl,
392
488
  startedAt: session.startedAt,
393
489
  stoppedAt: session.stoppedAt,
490
+ exitCode: session.exitCode ?? null,
491
+ exitSignal: session.exitSignal ?? null,
492
+ spawnErrorCode: session.spawnErrorCode ?? null,
394
493
  error: session.error,
395
494
  log: session.log.slice(-40),
396
495
  };
@@ -453,6 +552,9 @@ export async function startLiveView(projectName, projectPath, options = {}) {
453
552
  upstreamUrl: null,
454
553
  startedAt: new Date().toISOString(),
455
554
  stoppedAt: null,
555
+ exitCode: null,
556
+ exitSignal: null,
557
+ spawnErrorCode: null,
456
558
  error: null,
457
559
  log: [`Serving static files from ${path.relative(projectPath, target.staticRoot) || '.'}`],
458
560
  };
@@ -477,6 +579,9 @@ export async function startLiveView(projectName, projectPath, options = {}) {
477
579
  upstreamUrl: `http://127.0.0.1:${port}`,
478
580
  startedAt: new Date().toISOString(),
479
581
  stoppedAt: null,
582
+ exitCode: null,
583
+ exitSignal: null,
584
+ spawnErrorCode: null,
480
585
  error: null,
481
586
  log: [`$ ${command.displayCommand}`],
482
587
  child: null,
@@ -511,11 +616,14 @@ export async function startLiveView(projectName, projectPath, options = {}) {
511
616
  child.on('error', (error) => {
512
617
  session.status = 'error';
513
618
  session.error = error.message;
619
+ session.spawnErrorCode = error.code || null;
514
620
  appendLog(session, `process error: ${error.message}`);
515
621
  });
516
622
  child.on('exit', (code, signal) => {
517
623
  session.status = code === 0 ? 'stopped' : 'error';
518
624
  session.stoppedAt = new Date().toISOString();
625
+ session.exitCode = code;
626
+ session.exitSignal = signal;
519
627
  session.error = code === 0 ? null : `Process exited with ${signal || `code ${code}`}`;
520
628
  appendLog(session, session.error || 'Process stopped.');
521
629
  });