-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebContainerGitService.js
More file actions
1630 lines (1416 loc) · 62.3 KB
/
Copy pathWebContainerGitService.js
File metadata and controls
1630 lines (1416 loc) · 62.3 KB
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import git from '/lib/isomorphic-git.js';
import FS from '/lib/lightning-fs.js';
import { WebContainer } from '/lib/webcontainer-api.js';
import { FrameworkBroker } from './lib/frameworks/FrameworkBroker.js';
import { TaggerTrait } from './lib/frameworks/traits/TaggerTrait.js';
/**
* WebContainerGitService
* Orchestrates Git operations in browser-persistent storage and
* manages the WASM-based WebContainer execution engine.
*/
export class WebContainerGitService {
constructor(config = {}) {
this.repoUrl = config.repoUrl;
this.dir = config.dir || '/repo';
// Always use the internal Git proxy to preserve Auth headers and avoid browser popups
this.proxy = config.proxy || (typeof window !== 'undefined' ? window.location.origin + '/git-proxy' : 'https://cors.isomorphic-git.org');
this.token = config.token;
this.config = config;
this.fs = new FS('cms-fs').promises;
this.webcontainerInstance = null;
this.serverUrl = null; // Raw WebContainer URL (port 3001)
this.previewUrl = null; // Full URL including base path (used for iframe)
// Callbacks for UI updates
this.onStatusChange = config.onStatusChange || (() => {});
this.onServerReady = config.onServerReady || (() => {});
this.onLog = config.onLog || ((msg) => console.log(`[WC-Log] ${msg}`));
this.isBooting = false;
this.isDevMode = false;
this.serverProcess = null;
this.middlewareProc = null;
this._lastMiddlewarePort = null;
this.middlewareStarted = false;
this._isOrchestratingMiddleware = false;
// Track files actually modified by applySmartMatchChange so we know what to sync
this._modifiedFiles = new Set();
this._syncTimer = null;
this._fsBusy = false; // Mutex: prevents concurrent WASM FS operations
// Framework detection and drivers
this.broker = null;
this.activeDriver = null;
this.semanticReady = false;
this.readyPatterns = [
/ready\s-\sstarted\sserver/i, // Next.js
/compiled\ssuccessfully/i, // Webpack / Nuxt
/dev\sserver\srunning\sat/i, // Vite / Astro
/astro\s.*ready\sin/i, // Astro specific
/serving\sat/i, // Eleventy
/server\srunning\son/i, // Hugo / Zola
/listening\son/i // Generic
];
}
/**
* Formal Shutdown: Kill all processes and reset repo-specific state.
*/
async shutdown() {
this.isShuttingDown = true;
this.onLog('[Service] Shutting down current project engine...');
if (this.serverProcess) {
try { this.serverProcess.kill(); } catch (e) {}
this.serverProcess = null;
}
if (this.middlewareProc) {
try { this.middlewareProc.kill(); } catch (e) {}
this.middlewareProc = null;
}
this.serverUrl = null;
this.previewUrl = null;
this.middlewareStarted = false;
this.repoUrl = null;
this.semanticReady = false;
this._modifiedFiles.clear();
this.isBooting = false;
this.isShuttingDown = false;
this.onLog('[Service] Shutdown complete.');
}
/**
* Initialize the entire pipeline: Git -> WebContainer -> Dev Server
*/
async boot(requestedRepoUrl, manualCommand = null) {
// Reset if a different repository is requested
if (this.repoUrl && this.repoUrl !== requestedRepoUrl) {
this.onLog(`[Service] Repository changed from ${this.repoUrl} to ${requestedRepoUrl}. Performing reset...`);
await this.shutdown();
// STABILITY: Small delay to let OS release ports
await new Promise(r => setTimeout(r, 500));
await this.wipeDir(this.dir).catch(() => {});
if (this.webcontainerInstance) {
await this.wipeWebContainerFS();
}
}
if (this.serverUrl) {
this.onLog('[Service] Engine already running. Skipping boot.');
return;
}
if (this.isBooting) {
this.onLog('[Service] Engine is already initializing. Please wait...');
return;
}
this.repoUrl = requestedRepoUrl;
if (!this.repoUrl) {
this.onLog('[Service] No repository URL provided. Skipping boot initialization.');
return;
}
this.isBooting = true;
try {
this.onStatusChange('Initializing Engine...');
await this.initWebContainer();
this.onStatusChange('Cloning Repository...');
await this.fetchOrClone();
this.onStatusChange('Syncing Files...');
await this.syncToWebContainer();
this.onStatusChange('Preparing Environment...');
await this.loadSnapshot();
await this.installDependencies();
// 4. AUTO-DETECT FRAMEWORK
await this.autoDetectFramework();
// 5. START MIDDLEWARE (Now that we have the driver detected)
await this.startMiddleware();
// 6. START DEV SERVER
this.onStatusChange('Starting Dev Server...');
await this.startDevServer(manualCommand);
// Schedule background cache sync — delayed 90s to avoid race with Astro warmup
setTimeout(() => this.syncBuildCache(), 90000);
} catch (error) {
console.error('[CMS Service] Boot failed:', error);
this.onStatusChange(`Error: ${error.message}`);
throw error;
} finally {
this.isBooting = false;
}
}
async initFS() {
// Only create directory if it doesn't exist
await this.fs.mkdir(this.dir).catch(() => {});
}
async fetchOrClone() {
try {
const isGit = await this.fs.readdir(`${this.dir}/.git`).then(() => true).catch(() => false);
if (isGit) {
this.onStatusChange('Pulling latest changes...');
return await git.pull({
fs: this.fs,
http: (await import('/lib/isomorphic-git-http.js')).default,
dir: this.dir,
url: this.repoUrl,
corsProxy: this.proxy,
onAuth: () => ({ username: 'x-access-token', password: this.token }),
onAuthFailure: () => { throw new Error('GitHub authentication failed. Please check your token.'); },
singleBranch: true,
fastForwardOnly: true,
author: { name: 'CMS Sync', email: 'cms@example.com' }
});
} else {
return await this.clone();
}
} catch (e) {
if (this.isDevMode) console.warn('[CMS] Git Pull failed, attempting fresh sync:', e.message);
this.onStatusChange('Optimizing environment...');
try {
await this.wipeDir(this.dir);
return await this.clone();
} catch (wipeErr) {
console.error('[CMS] Fresh sync failed:', wipeErr);
throw new Error(`Git sync failed: ${e.message}. Is your token correct?`);
}
}
}
async wipeDir(dir) {
try {
const entries = await this.fs.readdir(dir);
for (const entry of entries) {
const path = `${dir}/${entry}`;
const stat = await this.fs.stat(path);
if (stat.isDirectory()) {
await this.wipeDir(path);
await this.fs.rmdir(path);
} else {
await this.fs.unlink(path);
}
}
} catch (e) {
// Base directory likely doesn't exist yet
}
}
async clone() {
try {
await git.clone({
fs: this.fs,
http: (await import('/lib/isomorphic-git-http.js')).default,
dir: this.dir,
url: this.repoUrl,
corsProxy: this.proxy,
onAuth: () => ({ username: 'x-access-token', password: this.token }),
onAuthFailure: () => { throw new Error('GitHub authentication failed. Please check your token.'); },
singleBranch: true,
depth: 1,
onMessage: msg => this.onStatusChange(`Git: ${msg}`)
});
} catch (e) {
console.error('[CMS] Git Clone Error:', e);
throw new Error(`Git clone failed: ${e.message}. Check your repo name and token.`);
}
}
async initWebContainer() {
if (!this.webcontainerInstance) {
this.webcontainerInstance = await WebContainer.boot();
this.broker = new FrameworkBroker(this.webcontainerInstance);
this.tagger = new TaggerTrait(this.webcontainerInstance);
}
}
/**
* Generates a FileSystemTree from LightningFS to be used with WebContainer.mount()
*/
/**
* Generates a FileSystemTree from LightningFS to be used with WebContainer.mount()
* Optimized: Parallel reading and exclusion of heavy build artifacts.
*/
async generateFileSystemTree(dir) {
const tree = {};
const entries = await this.fs.readdir(dir);
const ignoreList = ['.git', 'node_modules', 'dist', 'build', '.next', '.astro', '.svelte-kit', 'out', '.cache'];
await Promise.all(entries.map(async (entry) => {
if (ignoreList.includes(entry)) return;
const path = dir === '/' ? `/${entry}` : `${dir}/${entry}`;
const stat = await this.fs.stat(path);
if (stat.isDirectory()) {
tree[entry] = {
directory: await this.generateFileSystemTree(path)
};
} else {
const contents = await this.fs.readFile(path);
tree[entry] = {
file: { contents }
};
}
}));
return tree;
}
/**
* Turbo Boot: Syncs files using WebContainer.mount() for near-instant boot.
*/
async syncToWebContainer() {
this.onStatusChange('Syncing Files (Turbo)...');
// 1. Build the virtual tree for the repo directory
const repoTree = await this.generateFileSystemTree(this.dir);
// 2. Mount it as '/repo' in the WebContainer
await this.webcontainerInstance.mount({
repo: {
directory: repoTree
}
});
}
/**
* Idempotent Middleware Startup: Ensures the bridge is running for the correct target port.
*/
async startMiddleware(targetPort = null, basePath = '') {
const port = targetPort || this.activeDriver?.server.port || 3000;
targetPort = port; // Ensure we use the resolved port
// 0. CONCURRENCY LOCK: Prevent parallel orchestrations
if (this._isOrchestratingMiddleware) return;
// If already started for the exact same port AND base path, do nothing
if (this.middlewareStarted && this._lastMiddlewarePort === targetPort && this._lastMiddlewareBasePath === basePath) {
return;
}
this._isOrchestratingMiddleware = true;
try {
this.onLog(`[Middleware] Target updated to port ${targetPort} (Base: ${basePath}). Orchestrating bridge...`);
this._lastMiddlewarePort = targetPort;
this._lastMiddlewareBasePath = basePath;
// 1. Create the middleware proxy script
const middlewareContent = this.activeDriver?.server.getMiddlewareScript?.(targetPort) || `
const http = require('http');
const targetPort = parseInt(process.env.TARGET_PORT);
const basePath = process.env.BASE_PATH || '';
const server = http.createServer((req, res) => {
console.log('[Middleware] Request: ' + req.url);
// AUTO-REDIRECT: If root is requested but a base path exists, redirect
if (req.url === '/' && basePath && basePath !== '/') {
console.log('[Middleware] Redirecting / to ' + basePath);
res.writeHead(302, { 'Location': basePath });
res.end();
return;
}
const options = {
hostname: '127.0.0.1',
port: targetPort,
path: req.url,
method: req.method,
headers: req.headers
};
const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
proxyReq.on('error', (e) => {
res.writeHead(502);
res.end('Gateway Error: ' + e.message);
});
req.pipe(proxyReq, { end: true });
});
server.listen(3001, '0.0.0.0', () => {
console.log('[ServerTrait] Middleware Bridge running on port 3001 -> ' + targetPort + ' (Base: ' + basePath + ')');
});
`;
const bridgeResponse = await fetch('/cms.js');
const bridgeContent = await bridgeResponse.text();
await this.webcontainerInstance.fs.writeFile('zcms-bridge.js', bridgeContent);
await this.webcontainerInstance.fs.writeFile('zcms-middleware.js', middlewareContent);
// 2. Kill previous if any
if (this.middlewareProc) {
try { this.middlewareProc.kill(); } catch (e) {}
this.middlewareProc = null;
}
// 3. NUCLEAR PORT CLEANUP: Forcefully kill any zombie on 3001
try {
const killProc = await this.webcontainerInstance.spawn('npx', ['--yes', 'kill-port', '3001']);
await killProc.exit;
} catch (e) {}
await new Promise(r => setTimeout(r, 800));
// 4. RETRY LOOP
let retryCount = 0;
while (retryCount < 3) {
try {
this.middlewareProc = await this.webcontainerInstance.spawn('node', ['zcms-middleware.js'], {
env: {
TARGET_PORT: targetPort.toString(),
BASE_PATH: basePath || this.activeDriver?.routing?.base || ''
}
});
this.middlewareProc.output.pipeTo(new WritableStream({
write: (data) => {
this.onLog(`[bridge] ${data}`);
if (data.includes('EADDRINUSE')) {
this.onLog(`[Warning] Port 3001 busy (Retry ${retryCount+1}/3)...`);
}
}
}));
this.middlewareStarted = true;
return;
} catch (e) {
retryCount++;
await new Promise(r => setTimeout(r, 1000));
}
}
this.onLog('[Error] Failed to start middleware after 3 retries.');
} finally {
this._isOrchestratingMiddleware = false;
}
}
/**
* Fast middleware restart: Updates BASE_PATH without kill-port delays.
* Called when we detect the framework base path from server logs.
*/
async _fastRestartMiddleware(targetPort, basePath) {
if (!this.webcontainerInstance) return;
// Debounce: only restart once per unique base path
if (this._lastMiddlewareBasePath === basePath) return;
this._lastMiddlewareBasePath = basePath;
this.onLog(`[Middleware] Fast-updating proxy for base: ${basePath}`);
const middlewareContent = `
const http = require('http');
const targetPort = parseInt(process.env.TARGET_PORT);
const basePath = process.env.BASE_PATH || '';
const server = http.createServer((req, res) => {
console.log('[Middleware] Request: ' + req.url);
if (req.url === '/' && basePath && basePath !== '/') {
console.log('[Middleware] Redirecting / to ' + basePath);
res.writeHead(302, { 'Location': basePath });
res.end();
return;
}
const options = {
hostname: '127.0.0.1', port: targetPort,
path: req.url, method: req.method, headers: req.headers
};
const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
proxyReq.on('error', (e) => { res.writeHead(502); res.end('Gateway Error: ' + e.message); });
req.pipe(proxyReq, { end: true });
});
server.listen(3001, '0.0.0.0', () => {
console.log('[ServerTrait] Middleware Bridge running on port 3001 -> ' + targetPort + ' (Base: ' + basePath + ')');
});
`;
try {
// Kill old process
if (this.middlewareProc) {
try { this.middlewareProc.kill(); } catch(e) {}
this.middlewareProc = null;
}
// Brief pause for OS to release port
await new Promise(r => setTimeout(r, 600));
await this.webcontainerInstance.fs.writeFile('zcms-middleware.js', middlewareContent);
this.middlewareProc = await this.webcontainerInstance.spawn('node', ['zcms-middleware.js'], {
env: { TARGET_PORT: targetPort.toString(), BASE_PATH: basePath }
});
this.middlewareProc.output.pipeTo(new WritableStream({
write: (data) => this.onLog(`[bridge] ${data}`)
}));
this.onLog(`[Middleware] Proxy updated successfully with base path: ${basePath}`);
} catch(e) {
this.onLog(`[Warning] Fast middleware restart failed: ${e.message}`);
}
}
/**
* Identifies the framework by checking package.json and file signatures.
*/
async autoDetectFramework() {
this.onLog('[Auto-Detect] Scanning for framework signals using semantic drivers...');
try {
this.activeDriver = await this.broker.detect();
if (this.activeDriver) {
this.onLog(`[Auto-Detect] Matched Driver: ${this.activeDriver.name}`);
// NEW: ACTIVATE SUPER TAGGER (WASM)
await this.tagger.initWasm().catch(e => {
this.onLog(`[WebContainer] [Fallback] WASM Tagger failed to load: ${e.message}. Using JS engine.`);
});
// NEW: DETERMINISTIC INSTRUMENTATION (BATCHED)
this.onLog(`[Instrumentation] Injecting invisible Unicode breadcrumbs (Batch: ${this.tagger.activeEngine.constructor.name})...`);
const contentFiles = [];
// ROBUSTNESS: If no content paths are defined, perform a GLOBAL RECURSIVE SCAN
const targetPaths = (this.activeDriver.routing && this.activeDriver.routing.contentPaths && this.activeDriver.routing.contentPaths.length > 0)
? this.activeDriver.routing.contentPaths
: ['/repo']; // Fallback to root for universal support
this.onLog(`[Instrumentation] Scanning ${targetPaths.length} paths for content...`);
for (const dir of targetPaths) {
// Ensure we are looking inside /repo
let fullDir = dir;
if (!fullDir.startsWith('/repo')) {
fullDir = '/repo/' + (fullDir.startsWith('/') ? fullDir.slice(1) : fullDir);
}
fullDir = fullDir.replace(/\/+/g, '/');
if (fullDir.endsWith('/')) fullDir = fullDir.slice(0, -1);
try {
// RESILIENCE CHECK: Use readdir to check if path exists (since stat() is not supported)
const parts = fullDir.split('/').filter(Boolean);
const parent = '/' + parts.slice(0, -1).join('/');
const target = parts[parts.length - 1];
const exists = await this.webcontainerInstance.fs.readdir(parent)
.then(files => files.includes(target))
.catch(() => false);
if (!exists) {
this.onLog(`[Warning] Path skipped (Not Found): ${fullDir}`);
continue;
}
const files = await this.tagger.recursiveReaddir(fullDir);
const validExts = this.activeDriver.routing?.extensions || ['.md', '.mdx', '.html', '.json', '.yaml', '.yml', '.js', '.jsx', '.ts', '.tsx'];
contentFiles.push(...files.filter(f =>
validExts.some(ext => f.endsWith(ext)) &&
!f.includes('/node_modules/') &&
!f.includes('/.git/') &&
!f.includes('/dist/') &&
!f.includes('/build/')
));
} catch (e) {
this.onLog(`[Warning] Scan failed for ${fullDir}: ${e.message}`);
}
}
const startTime = performance.now();
if (contentFiles.length > 0) {
await this.tagger.instrumentBatch(contentFiles);
}
const duration = (performance.now() - startTime).toFixed(2);
this.onLog(`[Instrumentation] Completed: ${contentFiles.length} files in ${duration}ms.`);
} else {
this.onLog('[Auto-Detect] No specific driver matched. Using generic fail-safe.');
}
} catch (e) {
this.onLog(`[Warning] Framework detection failed: ${e.message}`);
}
}
async readDirRecursive(dir) {
const ignoreList = ['.git', 'node_modules', 'dist', 'build', '.next', '.astro', '.svelte-kit'];
const results = [];
const entries = await this.fs.readdir(dir);
await Promise.all(entries.map(async (entry) => {
if (ignoreList.includes(entry)) return;
const path = dir === '/' ? `/${entry}` : `${dir}/${entry}`;
const stat = await this.fs.stat(path);
if (stat.isDirectory()) {
results.push({ path, type: 'dir' });
const subResults = await this.readDirRecursive(path);
results.push(...subResults);
} else {
results.push({ path, type: 'file' });
}
}));
return results;
}
async installDependencies() {
// 1. Check if package.json exists
const hasPackageJson = await this.webcontainerInstance.fs.readFile('/repo/package.json').then(() => true).catch(() => false);
if (!hasPackageJson) {
this.onLog('[npm] No package.json found. Skipping dependency installation.');
return;
}
// 2. Reuse existing node_modules if present
const hasModules = await this.webcontainerInstance.fs.readdir('/repo/node_modules').then(e => e.length > 0).catch(() => false);
if (hasModules) {
this.onLog('Reuse existing node_modules detected.');
return;
}
this.onStatusChange('Installing Dependencies...');
this.onLog('[npm] Running optimized install...');
const installProcess = await this.webcontainerInstance.spawn('npm', ['install', '--no-audit', '--no-fund', '--quiet'], {
cwd: 'repo'
});
let lastOutput = '';
installProcess.output.pipeTo(new WritableStream({
write: (data) => {
lastOutput = data;
if (this.isDevMode) console.log('[npm install]', data);
}
}));
const exitCode = await installProcess.exit;
if (exitCode !== 0) {
this.onLog(`[Error] npm install failed (Exit: ${exitCode}). Retrying with full log...`);
// Fallback for debugging if it fails
const retryProc = await this.webcontainerInstance.spawn('npm', ['install'], { cwd: 'repo' });
retryProc.output.pipeTo(new WritableStream({ write: d => this.onLog(`[npm-retry] ${d}`) }));
if (await retryProc.exit !== 0) throw new Error('npm install failed');
}
this.onLog('[npm] Dependencies synchronized.');
}
/**
* Verified Binary Resolution: Checks if a binary exists and is valid.
* If broken or missing, falls back to npx.
*/
async resolveBin(cmd, pkgName) {
const parentDir = `/repo/node_modules/.bin`;
// 1. Check if the .bin directory exists at all
const binExists = await this.webcontainerInstance.fs.readdir('/repo/node_modules')
.then(files => files.includes('.bin'))
.catch(() => false);
if (!binExists) {
this.onLog(`[Resolver] No .bin directory found. Falling back to npx for ${cmd}`);
return `npx --yes ${pkgName}`;
}
// 2. Check if the specific command exists in .bin
const cmdExists = await this.webcontainerInstance.fs.readdir(parentDir)
.then(files => files.includes(cmd))
.catch(() => false);
if (cmdExists) {
const localPath = `${parentDir}/${cmd}`;
// 3. STABILITY CHECK: Try to 'stat' or read a bit to ensure it's not a dead symlink
// WebContainer fs.readFile is the most reliable check for existence/readability
const isReadable = await this.webcontainerInstance.fs.readFile(localPath)
.then(() => true)
.catch(() => false);
if (isReadable) {
this.onLog(`[Resolver] Verified local binary: ${cmd}`);
return localPath;
} else {
this.onLog(`[Resolver] Local binary ${cmd} is unreadable/broken. Falling back to npx.`);
return `npx --yes ${pkgName}`;
}
} else {
this.onLog(`[Resolver] Local ${cmd} missing in .bin. Using fallback: npx --yes ${pkgName}`);
return `npx --yes ${pkgName}`;
}
}
async startDevServer(manualCommand = null) {
let devCommand = manualCommand;
// 1. RESOLVE THE COMMAND SEMANTICALLY
this.onLog(`[Resolver] Aligning command for ${this.activeDriver?.name || 'Generic'} project...`);
// PRIORITY 1: package.json logic
const pkgRaw = await this.webcontainerInstance.fs.readFile('/repo/package.json', 'utf8').catch(() => null);
if (pkgRaw) {
try {
const pkg = JSON.parse(pkgRaw);
const scripts = pkg.scripts || {};
// If we have a 'dev' or 'start' script, use it. This is the absolute Node standard.
if (scripts.dev) {
devCommand = 'npm run dev';
} else if (scripts.start) {
devCommand = 'npm run start';
}
} catch (e) {}
}
// PRIORITY 2: If no npm script, or if we have a semantic driver command, resolve it intelligently
if (!devCommand) {
const semanticCmd = manualCommand || this.activeDriver?.server?.command || 'npm run dev';
if (semanticCmd.includes('npm run') || semanticCmd.includes('npx')) {
devCommand = semanticCmd;
} else {
// Fallback: try to find local bin or use npx
const binName = semanticCmd.split(' ')[0];
const localBin = await this.resolveBin(binName, binName);
devCommand = localBin + ' ' + semanticCmd.split(' ').slice(1).join(' ');
}
}
// FINAL ENFORCEMENT: For Next.js projects in WebContainers, Webpack is the only stable path.
if (this.activeDriver?.id === 'nextjs' && !devCommand.includes('--webpack')) {
this.onLog('[Optimization] Enforced Webpack for Next.js (WebContainer compatibility).');
devCommand += ' --webpack';
}
// SHADOW PACKAGE.JSON INJECTION: Satisfy npx/npm for non-Node projects
const pkgExists = (pkgRaw !== null);
if (!pkgExists && (devCommand.includes('npx') || (this.activeDriver && this.activeDriver.id !== 'generic-node'))) {
this.onLog('[Compatibility] Injecting Shadow package.json to satisfy runtime environment...');
const shadowPkg = {
name: "zerocms-runtime-shadow",
version: "1.0.0",
private: true,
description: "Temporary shadow package to satisfy strict npm/npx environment constraints."
};
await this.webcontainerInstance.fs.writeFile('/repo/package.json', JSON.stringify(shadowPkg, null, 2));
}
// Cleanup previous processes if any
if (this.serverProcess) {
this.onLog('[Cleanup] Stopping previous dev server...');
this.serverProcess.kill();
this.serverProcess = null;
}
await new Promise(r => setTimeout(r, 400));
// 1. Listen for the server-ready event of WebContainers
if (!this._serverReadyListenerAttached) {
this.webcontainerInstance.on('server-ready', async (port, url) => {
if (port === 3001) {
this.serverUrl = url;
this.onLog('[Bridge] Port 3001 ready. Initializing preview instantly...');
this.previewUrl = this._detectedBasePath
? this.serverUrl.replace(/\/$/, '') + this._detectedBasePath
: this.serverUrl;
// Delay iframe load slightly to allow WebContainer Ingress router to register the port
// Otherwise the iframe immediately hits a 404 Not Found from the WebContainer edge.
setTimeout(() => {
this.onServerReady(this.previewUrl);
}, 1500);
this.onStatusChange('Warming Up...');
}
});
this._serverReadyListenerAttached = true;
}
this.onStatusChange(`Running: ${devCommand}...`);
const cmdTokens = devCommand.split(' ');
const cmd = cmdTokens[0];
const args = cmdTokens.slice(1);
this.serverProcess = await this.webcontainerInstance.spawn(cmd, args, { cwd: 'repo' });
this.serverProcess.output.pipeTo(new WritableStream({
write: (data) => {
if (this.isDevMode) console.log(`[server] ${data}`);
this.onLog(`[server] ${data}`);
// DYNAMIC PORT SNIFFER: Detect target port from logs (Vite, Next, etc.)
const portMatch = data.match(/Local:\s+http:\/\/localhost:(\d+)/i) ||
data.match(/available at:\s+http:\/\/localhost:(\d+)/i) ||
data.match(/listening on\s+.*?:(\d+)/i);
if (portMatch) {
const detectedPort = parseInt(portMatch[1]);
if (detectedPort !== 3001 && detectedPort !== this.activeDriver?.server.port) {
this.onLog(`[Inference] Detected dev server on custom port: ${detectedPort}. Updating proxy...`);
this.startMiddleware(detectedPort);
}
}
// BASE PATH SNIFFER: Astro logs "┃ Local http://localhost:PORT/base-path" (no colon!)
const basePathMatch = data.match(/Local\s+https?:\/\/localhost:\d+(\/[^\s\n]+)/i);
if (basePathMatch && basePathMatch[1] && basePathMatch[1] !== '/') {
const newBasePath = basePathMatch[1];
if (this._detectedBasePath !== newBasePath) {
this._detectedBasePath = newBasePath;
this.onLog(`[Inference] Detected base path: ${this._detectedBasePath}. Updating proxy...`);
// Fast-restart middleware with new base path (skips kill-port for speed)
this._fastRestartMiddleware(this._lastMiddlewarePort || 4321, this._detectedBasePath);
}
}
// SEMANTIC LOG MONITORING: Detect 'Ready' string
if (!this.semanticReady && this.readyPatterns.some(p => p.test(data))) {
this.onLog('[Ready] Detected framework ready signal!');
this.semanticReady = true;
this.onStatusChange('Server Ready!');
}
}
}));
this.middlewareStarted = false;
// Return a promise that resolves when the dev server is fully booted
// We wait for BOTH the proxy URL and the semantic signal before allowing boot() to continue
// (This prevents heavy fs.readdir scans from running concurrently with framework compilation)
return new Promise((resolve) => {
const check = setInterval(() => {
if (this.serverUrl && this.semanticReady) {
clearInterval(check);
resolve(this.serverProcess);
}
}, 500);
// Safety timeout for the await (60s)
setTimeout(() => {
clearInterval(check);
if (!this.semanticReady) {
this.onLog('[Warning] Semantic ready signal not found. Resolving anyway.');
this.semanticReady = true;
}
resolve(this.serverProcess);
}, 60000);
});
}
/**
* Updates a file in the WebContainer FS. This triggers HMR in the dev server.
*/
async updateFile(filePath, content) {
await this.webcontainerInstance.fs.writeFile(filePath, content);
console.log(`[CMS] Updated: ${filePath}`);
}
/**
* Commits all changes made in the WebContainer back to Git.
* Only syncs files that were actually modified by applySmartMatchChange.
*/
async publishChanges(commitMessage = 'CMS update') {
this.onStatusChange('Syncing changes back...');
if (this._modifiedFiles.size === 0) {
this.onLog('[Publish] No files were modified via SmartMatch. Nothing to commit.');
this.onStatusChange('No changes to publish.');
setTimeout(() => this.onStatusChange('Idle'), 3000);
return { success: true, message: 'No changes' };
}
this.onLog(`[Publish] Syncing ${this._modifiedFiles.size} modified file(s) to Git FS...`);
// Only sync the files we actually changed (faster + more reliable)
for (const filePath of this._modifiedFiles) {
try {
const content = await this.webcontainerInstance.fs.readFile(filePath);
// Ensure parent directories exist in LightningFS
const parts = filePath.split('/').filter(Boolean);
let currentPath = this.dir;
for (let i = 0; i < parts.length - 1; i++) {
currentPath += '/' + parts[i];
await this.fs.mkdir(currentPath).catch(() => {});
}
await this.fs.writeFile(this.dir + filePath, content);
this.onLog(` ✓ Synced: ${filePath}`);
} catch (e) {
this.onLog(` ✗ Failed to sync ${filePath}: ${e.message}`);
}
}
// 2. Explicitly remove any CMS-internal files from the Git index if they exist
const gitFiles = await git.listFiles({ fs: this.fs, dir: this.dir });
for (const f of gitFiles) {
if (f.startsWith('zcms-') || f === 'scripts/zcms-tagger.js') {
await git.remove({ fs: this.fs, dir: this.dir, filepath: f });
}
}
// 3. Check status and add changed files
this.onStatusChange('Committing...');
const status = await git.statusMatrix({ fs: this.fs, dir: this.dir, filepath: '.' });
const changedFiles = status.filter(row => row[1] !== row[2]);
if (changedFiles.length === 0) {
this.onLog('[Publish] Git sees no diff after targeted sync. Files may already be at latest.');
this._modifiedFiles.clear();
this.onStatusChange('No changes to publish.');
setTimeout(() => this.onStatusChange('Idle'), 3000);
return { success: true, message: 'No changes' };
}
this.onLog(`[Publish] Git detected ${changedFiles.length} changed file(s). Staging...`);
// 4. STRIP BREADCRUMBS: Ensure production code is clean of invisible markers
this.onStatusChange('Sanitizing Code...');
const startTime = performance.now();
// Batch process all changed files for maximum speed
const filesToStrip = [];
for (const [file] of changedFiles) {
const fullPath = (this.dir + '/' + file).replace(/\/+/g, '/');
try {
const content = await this.fs.readFile(fullPath, 'utf8');
filesToStrip.push({ path: file, content, fullPath });
} catch (e) {}
}
if (filesToStrip.length > 0) {
const cleanedResults = await this.tagger.stripBatch(filesToStrip);
for (const res of cleanedResults) {
const original = filesToStrip.find(f => f.path === res.path);
if (original && res.content !== original.content) {
await this.fs.writeFile(original.fullPath, res.content);
this.onLog(` ✨ Sanitized: ${res.path}`);
}
}
}
// Stage all files
for (const [file] of changedFiles) {
await git.add({ fs: this.fs, dir: this.dir, filepath: file });
}
const duration = (performance.now() - startTime).toFixed(2);
this.onLog(`[Sanitization] Completed: ${changedFiles.length} files in ${duration}ms.`);
await git.commit({
fs: this.fs,
dir: this.dir,
message: commitMessage,
author: { name: 'CMS User', email: 'cms@example.com' }
});
this.onStatusChange('Pushing to GitHub...');
this.onLog(`[Push] Starting push to ${this.repoUrl} (Branch: ${await git.currentBranch({ fs: this.fs, dir: this.dir })})`);
const pushResult = await git.push({
fs: this.fs,
http: (await import('/lib/isomorphic-git-http.js')).default,
dir: this.dir,
url: this.repoUrl,
onAuth: () => ({ username: 'x-access-token', password: this.token }),
onAuthFailure: () => {
this.onLog('[Push] Authentication failed! Check that your GitHub token has the "repo" scope.');
throw new Error('GitHub authentication failed. Token may be expired or lacks "repo" scope.');
},
corsProxy: this.proxy
});
if (pushResult.ok) {
this.onLog('[Push] Push successful!');
this.onStatusChange('Published successfully!');
this._modifiedFiles.clear(); // Reset tracking after successful push
} else {
this.onLog(`[Push] Push rejected: ${JSON.stringify(pushResult.refs)}`);
throw new Error('Push rejected by GitHub.');
}
return pushResult;
}
async syncFromWebContainer() {
// This part requires a recursive read from WebContainer and write back to lightning-fs
// Avoiding node_modules is critical here.
const processEntry = async (path) => {
const names = await this.webcontainerInstance.fs.readdir(path).catch(() => []);
for (const name of names) {
if (name === 'node_modules' || name === '.git' || name.startsWith('zcms-')) continue;
const entryPath = path === '/' ? `/${name}` : `${path}/${name}`;
try {
const isDir = await this.webcontainerInstance.fs.readdir(entryPath)
.then(() => true)
.catch(() => false);
if (isDir) {
await this.fs.mkdir(`${this.dir}${entryPath}`).catch(() => {});
await processEntry(entryPath);
} else {
const content = await this.webcontainerInstance.fs.readFile(entryPath);
await this.fs.writeFile(`${this.dir}${entryPath}`, content);
}
} catch (e) {}
}
};
await processEntry('/');
}
/**
* Scans the filesystem for 'original' and replaces it with 'updated'.
* Tracks every file it writes to in this._modifiedFiles.
* Uses partial/word matching for template-composed strings.
*/
async applySmartMatchChange(original, updated, metadata = null) {
if (!original || original === updated) return false;
// Resolve deterministic source if metadata (fileId/line) is provided
let sourceFile = null;
if (metadata && metadata.fileId) {
sourceFile = this.tagger.pathMap.get(metadata.fileId);
if (sourceFile) this.onLog(`[SmartMatch] Deterministic Link: ${sourceFile} (Line: ${metadata.line || '?'})`);
}
const writeAndTrack = async (filePath, content) => {
await this.webcontainerInstance.fs.writeFile(filePath, content);
const absPath = filePath.startsWith('/') ? filePath : '/' + filePath;
// Don't track auto-generated SSG cache files - they're in .gitignore anyway
// EXCEPTION: Allow db.json if it is actually in the root, as some drivers use it
const isGenerated = absPath.includes('/.cache/') || absPath.includes('/.astro/') || absPath.includes('/public/');
if (!isGenerated) {
this._modifiedFiles.add(absPath);
this.onLog(`[SmartMatch] ✓ Wrote changes to ${filePath}`);
} else {