start.cjs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. #!/usr/bin/env node
  2. "use strict";
  3. var __create = Object.create;
  4. var __defProp = Object.defineProperty;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getProtoOf = Object.getPrototypeOf;
  8. var __hasOwnProp = Object.prototype.hasOwnProperty;
  9. var __copyProps = (to, from, except, desc) => {
  10. if (from && typeof from === "object" || typeof from === "function") {
  11. for (let key of __getOwnPropNames(from))
  12. if (!__hasOwnProp.call(to, key) && key !== except)
  13. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  14. }
  15. return to;
  16. };
  17. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  18. // If the importer is in node compatibility mode or this is not an ESM
  19. // file that has been converted to a CommonJS file using a Babel-
  20. // compatible transform (i.e. "__esModule" has not been set), then set
  21. // "default" to the CommonJS "module.exports" for node compatibility.
  22. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  23. mod
  24. ));
  25. // src/lib/index.ts
  26. var import_socket = require("socket.io");
  27. var import_child_process2 = require("child_process");
  28. var import_promises = __toESM(require("fs/promises"), 1);
  29. var import_path = __toESM(require("path"), 1);
  30. // src/lib/ServerDetector.ts
  31. var import_net = __toESM(require("net"), 1);
  32. var import_child_process = require("child_process");
  33. var import_events = require("events");
  34. var import_client = __toESM(require("@d8d-localtunnel/client"), 1);
  35. var ServerDetector = class extends import_events.EventEmitter {
  36. constructor(config) {
  37. super();
  38. this.checkInterval = null;
  39. this.workspacePath = config.workspacePath;
  40. this.intervalTime = config.checkInterval || 1e3;
  41. this.timeout = config.timeout || 5 * 60 * 1e3;
  42. this.portRange = {
  43. start: 3e3,
  44. end: 9999
  45. };
  46. }
  47. start() {
  48. if (this.checkInterval) {
  49. return;
  50. }
  51. this.checkInterval = setInterval(async () => {
  52. await this.detectServer();
  53. }, this.intervalTime);
  54. setTimeout(() => {
  55. this.stop();
  56. }, this.timeout);
  57. }
  58. stop() {
  59. if (this.checkInterval) {
  60. clearInterval(this.checkInterval);
  61. this.checkInterval = null;
  62. }
  63. }
  64. async detectServer() {
  65. try {
  66. const vitePort = await this.findVitePort();
  67. if (vitePort) {
  68. await this.handleServerFound(vitePort);
  69. return;
  70. }
  71. const commonPorts = [3e3, 8080, 4e3, 3001, 8e3];
  72. for (const port2 of commonPorts) {
  73. const isActive = await this.checkPort(port2);
  74. if (isActive && await this.isProcessFromWorkspace(port2)) {
  75. await this.handleServerFound(port2);
  76. return;
  77. }
  78. }
  79. } catch (error) {
  80. console.error("[ServerDetector] Error detecting server:", error);
  81. }
  82. }
  83. async detectServerByPid(process2) {
  84. if (!process2.pid) return;
  85. let portFromOutput = null;
  86. const outputHandler = async (data) => {
  87. const output = data.toString();
  88. console.log(`[ServerDetector] \u89E3\u6790\u8F93\u51FA: ${output}`);
  89. const portMatches = output.match(/(?:localhost|127\.0\.0\.1):(\d+)/g);
  90. if (portMatches) {
  91. for (const match of portMatches) {
  92. const port2 = parseInt(match.split(":")[1], 10);
  93. console.log(`[ServerDetector] \u4ECE\u8F93\u51FA\u4E2D\u53D1\u73B0\u7AEF\u53E3: ${port2}`);
  94. const isActive = await this.checkPort(port2);
  95. if (isActive) {
  96. console.log(`[ServerDetector] \u7AEF\u53E3 ${port2} \u53EF\u7528\uFF0C\u521B\u5EFA\u96A7\u9053...`);
  97. portFromOutput = port2;
  98. await this.handleServerFound(port2);
  99. process2.stdout?.removeListener("data", outputHandler);
  100. return;
  101. }
  102. }
  103. }
  104. };
  105. process2.stdout?.on("data", outputHandler);
  106. await new Promise((resolve) => setTimeout(resolve, 500));
  107. if (portFromOutput) {
  108. return;
  109. }
  110. const maxRetries = 5;
  111. const retryDelay = 1e3;
  112. let currentTry = 0;
  113. const checkPorts = async () => {
  114. try {
  115. const ports = await this.getProcessPorts(process2.pid);
  116. console.log(`[ServerDetector] \u8FDB\u7A0B ${process2.pid} \u7684\u7AEF\u53E3\u4FE1\u606F (\u5C1D\u8BD5 ${currentTry + 1}):`, ports);
  117. if (ports.length > 0) {
  118. for (const { port: port2, protocol } of ports) {
  119. if (protocol === "tcp") {
  120. await this.handleServerFound(port2);
  121. return true;
  122. }
  123. }
  124. }
  125. const childPorts = await this.getChildProcessPorts(process2.pid);
  126. console.log(`[ServerDetector] \u5B50\u8FDB\u7A0B\u7AEF\u53E3\u4FE1\u606F (\u5C1D\u8BD5 ${currentTry + 1}):`, childPorts);
  127. if (childPorts.length > 0) {
  128. for (const { port: port2, protocol } of childPorts) {
  129. if (protocol === "tcp") {
  130. await this.handleServerFound(port2);
  131. return true;
  132. }
  133. }
  134. }
  135. return false;
  136. } catch (error) {
  137. console.error("[ServerDetector] \u68C0\u6D4B\u7AEF\u53E3\u5931\u8D25:", error);
  138. return false;
  139. }
  140. };
  141. while (currentTry < maxRetries && !portFromOutput) {
  142. const found = await checkPorts();
  143. if (found) {
  144. process2.stdout?.removeListener("data", outputHandler);
  145. return;
  146. }
  147. currentTry++;
  148. if (currentTry < maxRetries) {
  149. console.log(`[ServerDetector] \u7B49\u5F85 ${retryDelay}ms \u540E\u8FDB\u884C\u7B2C ${currentTry + 1} \u6B21\u5C1D\u8BD5...`);
  150. await new Promise((resolve) => setTimeout(resolve, retryDelay));
  151. }
  152. }
  153. console.log("[ServerDetector] \u7AEF\u53E3\u68C0\u6D4B\u91CD\u8BD5\u7ED3\u675F\uFF0C\u7EE7\u7EED\u76D1\u542C\u8FDB\u7A0B\u8F93\u51FA...");
  154. }
  155. async getChildProcessPorts(parentPid) {
  156. return new Promise((resolve) => {
  157. (0, import_child_process.exec)(`pgrep -P ${parentPid}`, async (error, stdout) => {
  158. if (error) {
  159. console.error("[ServerDetector] pgrep \u6267\u884C\u5931\u8D25:", error);
  160. resolve([]);
  161. return;
  162. }
  163. const childPids = stdout.trim().split("\n").filter(Boolean);
  164. const allPorts = [];
  165. const portPromises = childPids.map(
  166. (childPid) => this.getProcessPorts(parseInt(childPid, 10))
  167. );
  168. try {
  169. const results = await Promise.all(portPromises);
  170. results.forEach((ports) => allPorts.push(...ports));
  171. } catch (error2) {
  172. console.error("[ServerDetector] \u68C0\u67E5\u5B50\u8FDB\u7A0B\u7AEF\u53E3\u5931\u8D25:", error2);
  173. }
  174. resolve(allPorts);
  175. });
  176. });
  177. }
  178. async getProcessPorts(pid) {
  179. return new Promise((resolve) => {
  180. (0, import_child_process.exec)(`lsof -i -P -n -p ${pid} | grep LISTEN`, (error, stdout) => {
  181. if (error) {
  182. resolve([]);
  183. return;
  184. }
  185. const ports = [];
  186. const lines = stdout.split("\n").filter(Boolean);
  187. for (const line of lines) {
  188. const match = line.match(/\s+(\w+):(\d+)\s+\(LISTEN\)$/);
  189. if (match) {
  190. ports.push({
  191. pid,
  192. port: parseInt(match[2], 10),
  193. protocol: match[1].toLowerCase()
  194. });
  195. }
  196. }
  197. resolve(ports);
  198. });
  199. });
  200. }
  201. // 抽取处理找到服务器的逻辑
  202. async handleServerFound(port2) {
  203. try {
  204. const tunnel = await (0, import_client.default)({
  205. port: port2,
  206. host: "https://pre.d8d.fun"
  207. });
  208. this.emit("server-ready", {
  209. port: port2,
  210. url: tunnel.url,
  211. localUrl: `http://localhost:${port2}`
  212. });
  213. } catch (error) {
  214. console.error("Failed to create tunnel:", error);
  215. this.emit("server-ready", {
  216. port: port2,
  217. url: `http://localhost:${port2}`
  218. });
  219. }
  220. this.stop();
  221. }
  222. async checkPort(port2) {
  223. return new Promise((resolve) => {
  224. const tester = import_net.default.createConnection({
  225. port: port2,
  226. host: "localhost",
  227. timeout: 1e3
  228. });
  229. tester.on("connect", () => {
  230. tester.end();
  231. resolve(true);
  232. });
  233. tester.on("error", () => {
  234. resolve(false);
  235. });
  236. tester.on("timeout", () => {
  237. tester.destroy();
  238. resolve(false);
  239. });
  240. });
  241. }
  242. async isProcessFromWorkspace(port2) {
  243. const maxRetries = 3;
  244. const retryDelay = 1e3;
  245. for (let i = 0; i < maxRetries; i++) {
  246. try {
  247. const controller = new AbortController();
  248. const timeoutId = setTimeout(() => controller.abort(), 5e3);
  249. const response = await fetch(`http://localhost:${port2}`, {
  250. signal: controller.signal
  251. });
  252. clearTimeout(timeoutId);
  253. return response.ok;
  254. } catch (error) {
  255. if (i === maxRetries - 1) {
  256. console.log(`[ServerDetector] Failed to check port ${port2} after ${maxRetries} retries`);
  257. return false;
  258. }
  259. await new Promise((resolve) => setTimeout(resolve, retryDelay));
  260. }
  261. }
  262. return false;
  263. }
  264. // 修改 findActualPort 方法
  265. async findActualPort() {
  266. const vitePort = await this.findVitePort();
  267. if (vitePort) {
  268. return vitePort;
  269. }
  270. return new Promise((resolve) => {
  271. (0, import_child_process.exec)(`lsof -i -P -n | grep LISTEN | grep node`, (error, stdout) => {
  272. if (error) {
  273. console.log("[ServerDetector] Error finding actual port:", error);
  274. resolve(null);
  275. return;
  276. }
  277. try {
  278. const lines = stdout.split("\n");
  279. for (const line of lines) {
  280. const match = line.match(/:51[7-9][0-9]/);
  281. if (match) {
  282. const port2 = parseInt(match[0].substring(1));
  283. if (port2 >= 5173 && port2 <= 5179) {
  284. console.log(`[ServerDetector] Found Vite server port from lsof: ${port2}`);
  285. resolve(port2);
  286. return;
  287. }
  288. }
  289. }
  290. resolve(null);
  291. } catch (parseError) {
  292. console.error("[ServerDetector] Error parsing port:", parseError);
  293. resolve(null);
  294. }
  295. });
  296. });
  297. }
  298. // 添加新方法来从 Vite 输出解析端口
  299. async findVitePort() {
  300. try {
  301. for (let port2 = 5173; port2 <= 5179; port2++) {
  302. const isActive = await this.checkPort(port2);
  303. if (isActive) {
  304. try {
  305. const controller = new AbortController();
  306. const timeoutId = setTimeout(() => controller.abort(), 3e3);
  307. const response = await fetch(`http://localhost:${port2}`, {
  308. signal: controller.signal
  309. });
  310. clearTimeout(timeoutId);
  311. const text = await response.text();
  312. if (text.includes("vite") || response.headers.get("server")?.includes("vite")) {
  313. console.log(`[ServerDetector] Found Vite server on port: ${port2}`);
  314. return port2;
  315. }
  316. } catch (error) {
  317. continue;
  318. }
  319. }
  320. }
  321. } catch (error) {
  322. console.error("[ServerDetector] Error in findVitePort:", error);
  323. }
  324. return null;
  325. }
  326. static isDevServerCommand(command, args = []) {
  327. const devCommands = [
  328. ["npm", ["run", "dev"]],
  329. ["npm", ["run", "start"]],
  330. ["npm", ["start"]],
  331. ["yarn", ["dev"]],
  332. ["yarn", ["start"]],
  333. ["pnpm", ["dev"]],
  334. ["pnpm", ["start"]],
  335. ["vite"],
  336. ["next"],
  337. ["nuxt"]
  338. ];
  339. return devCommands.some(([cmd, cmdArgs]) => {
  340. if (!cmdArgs) {
  341. return command === cmd;
  342. }
  343. return command === cmd && JSON.stringify(args) === JSON.stringify(cmdArgs);
  344. });
  345. }
  346. };
  347. // src/lib/index.ts
  348. var import_http = require("http");
  349. var import_chokidar = __toESM(require("chokidar"), 1);
  350. var import_fs = require("fs");
  351. // src/lib/constants.ts
  352. var PROCESS_CONFIG = {
  353. // 进程终止超时时间(毫秒)
  354. KILL_TIMEOUT: 5e3,
  355. // 进程清理重试次数
  356. CLEANUP_RETRIES: 3
  357. };
  358. var FS_CONFIG = {
  359. // 文件编码
  360. ENCODING: "utf-8",
  361. // 目录权限
  362. DIR_MODE: 493,
  363. // 文件权限
  364. FILE_MODE: 420
  365. };
  366. var SERVER_CONFIG = {
  367. DEFAULT_PORT: 3e3,
  368. DEFAULT_HOST: "localhost",
  369. DEFAULT_WORKSPACE_DIR: "workspaces",
  370. CORS: {
  371. origin: "*",
  372. methods: ["GET", "POST"]
  373. }
  374. };
  375. var WATCH_CONFIG = {
  376. DEFAULT_IGNORE: [
  377. "**/node_modules/**",
  378. "**/.git/**",
  379. "**/dist/**",
  380. "**/.DS_Store",
  381. "**/thumbs.db"
  382. ],
  383. WATCH_OPTIONS: {
  384. persistent: true,
  385. ignoreInitial: false,
  386. followSymlinks: false,
  387. disableGlobbing: false,
  388. usePolling: false
  389. }
  390. };
  391. // src/lib/index.ts
  392. var import_anymatch = __toESM(require("anymatch"), 1);
  393. var WebContainerServer = class {
  394. constructor(config = {}) {
  395. this.workspaces = /* @__PURE__ */ new Map();
  396. this.processes = /* @__PURE__ */ new Map();
  397. this.processHistory = /* @__PURE__ */ new Map();
  398. this.watchers = /* @__PURE__ */ new Map();
  399. this.config = {
  400. port: config.port || SERVER_CONFIG.DEFAULT_PORT,
  401. host: config.host || SERVER_CONFIG.DEFAULT_HOST,
  402. workspaceRoot: config.workspaceRoot || import_path.default.join(process.cwd(), SERVER_CONFIG.DEFAULT_WORKSPACE_DIR)
  403. };
  404. this.httpServer = (0, import_http.createServer)();
  405. this.io = new import_socket.Server(this.httpServer, {
  406. cors: SERVER_CONFIG.CORS
  407. });
  408. this.setupSocketHandlers();
  409. }
  410. async start() {
  411. try {
  412. await import_promises.default.mkdir(this.config.workspaceRoot, { recursive: true });
  413. const requiredCommands = ["git", "npm", "node"];
  414. for (const cmd of requiredCommands) {
  415. const exists = await this.checkCommandExists(cmd);
  416. if (!exists) {
  417. console.warn(`\u8B66\u544A: \u547D\u4EE4 '${cmd}' \u672A\u5B89\u88C5\uFF0C\u8FD9\u53EF\u80FD\u4F1A\u5F71\u54CD\u67D0\u4E9B\u529F\u80FD\u7684\u4F7F\u7528`);
  418. }
  419. }
  420. return new Promise((resolve) => {
  421. this.httpServer.listen(this.config.port, this.config.host, () => {
  422. console.log(
  423. `WebContainer Server is running on http://${this.config.host}:${this.config.port}`
  424. );
  425. console.log(`Workspace root: ${this.config.workspaceRoot}`);
  426. resolve();
  427. });
  428. });
  429. } catch (error) {
  430. console.error("Failed to start server:", error);
  431. process.exit(1);
  432. }
  433. }
  434. setupSocketHandlers() {
  435. this.io.on("connection", async (socket) => {
  436. const workspaceId = Math.random().toString(36).substr(2, 9);
  437. const workspacePath = import_path.default.join(this.config.workspaceRoot, workspaceId);
  438. this.workspaces.set(socket.id, workspacePath);
  439. this.processes.set(socket.id, /* @__PURE__ */ new Map());
  440. console.log(`Client connected. Workspace created at: ${workspacePath}`);
  441. try {
  442. await import_promises.default.mkdir(workspacePath, { recursive: true });
  443. } catch (error) {
  444. console.error("Failed to configure NPM mirrors:", error);
  445. }
  446. socket.on(
  447. "mount",
  448. async (files, callback) => {
  449. try {
  450. await this.handleMount(workspacePath, files);
  451. callback({ success: true });
  452. } catch (error) {
  453. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  454. callback({ error: errorMessage });
  455. }
  456. }
  457. );
  458. socket.on(
  459. "spawn",
  460. async ({ command, args = [], terminalId = "default" }, callback) => {
  461. try {
  462. const result = await this.handleSpawn(
  463. socket.id,
  464. workspacePath,
  465. command,
  466. args,
  467. terminalId
  468. );
  469. callback({ result });
  470. } catch (error) {
  471. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  472. callback({ error: errorMessage });
  473. }
  474. }
  475. );
  476. socket.on("fs:list", async (path3, callback) => {
  477. try {
  478. const result = await this.handleList(workspacePath, path3);
  479. callback({ success: true, result });
  480. } catch (error) {
  481. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  482. callback({ error: errorMessage });
  483. }
  484. });
  485. socket.on("fs:read", async (path3, callback) => {
  486. try {
  487. const result = await this.handleRead(workspacePath, path3);
  488. callback({ success: true, result });
  489. } catch (error) {
  490. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  491. callback({ error: errorMessage });
  492. }
  493. });
  494. socket.on(
  495. "fs:write",
  496. async (data, callback) => {
  497. try {
  498. await this.handleWrite(workspacePath, data.path, data.content);
  499. callback({ success: true });
  500. } catch (error) {
  501. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  502. callback({ error: errorMessage });
  503. }
  504. }
  505. );
  506. socket.on("fs:delete", async (path3, callback) => {
  507. try {
  508. await this.handleDelete(workspacePath, path3);
  509. callback({ success: true });
  510. } catch (error) {
  511. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  512. callback({ error: errorMessage });
  513. }
  514. });
  515. socket.on("fs:mkdir", async (path3, callback) => {
  516. try {
  517. await this.handleMkdir(workspacePath, path3);
  518. callback({ success: true });
  519. } catch (error) {
  520. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  521. callback({ error: errorMessage });
  522. }
  523. });
  524. socket.on(
  525. "fs:watch",
  526. async ({ glob, ignore = WATCH_CONFIG.DEFAULT_IGNORE, ignoreInitial }, callback = () => {
  527. }) => {
  528. try {
  529. console.log(`[Watch] Socket ${socket.id} \u5F00\u59CB\u76D1\u542C\u6587\u4EF6: ${glob}`);
  530. console.log(`[Watch] \u5FFD\u7565\u7684\u6587\u4EF6\u6A21\u5F0F:`, ignore);
  531. console.log(`[Watch] ignoreInitial:`, ignoreInitial);
  532. const watchPatterns = [glob, `${glob}/*`, `${glob}/**/*`];
  533. const watcher = import_chokidar.default.watch(watchPatterns, {
  534. cwd: workspacePath,
  535. ...WATCH_CONFIG.WATCH_OPTIONS,
  536. ...ignoreInitial !== void 0 ? { ignoreInitial } : {},
  537. ignored: (path3) => {
  538. const shouldIgnore = (0, import_anymatch.default)(ignore, path3);
  539. if (shouldIgnore) {
  540. console.log(`[Watch] \u5FFD\u7565\u8DEF\u5F84: ${path3}`);
  541. }
  542. return shouldIgnore;
  543. }
  544. });
  545. watcher.on("all", async (event, path3) => {
  546. const fullPath = `${workspacePath}/${path3}`;
  547. let stats = null;
  548. try {
  549. stats = await import_fs.promises.stat(fullPath).catch(() => null);
  550. } catch (error) {
  551. }
  552. socket.emit("fs:change", {
  553. type: event === "add" || event === "addDir" ? "create" : event === "change" ? "update" : event === "unlink" ? "delete" : event,
  554. path: path3,
  555. kind: stats?.isDirectory() ? "directory" : "file"
  556. });
  557. });
  558. watcher.on("error", (error) => {
  559. console.error(`[Watch] \u76D1\u542C\u9519\u8BEF:`, error);
  560. });
  561. watcher.on("ready", () => {
  562. console.log(`[Watch] \u6587\u4EF6\u76D1\u542C\u5668\u5DF2\u5C31\u7EEA`);
  563. });
  564. this.watchers.set(socket.id, watcher);
  565. if (typeof callback === "function") {
  566. callback({ success: true });
  567. }
  568. } catch (error) {
  569. console.error(`[Watch] \u8BBE\u7F6E\u76D1\u542C\u5931\u8D25:`, error);
  570. const errorMessage = error instanceof Error ? error.message : "\u8BBE\u7F6E\u76D1\u542C\u5931\u8D25";
  571. if (typeof callback === "function") {
  572. callback({ error: errorMessage });
  573. }
  574. }
  575. }
  576. );
  577. socket.on(
  578. "fs:unwatch",
  579. async ({ glob }, callback = () => {
  580. }) => {
  581. try {
  582. const watcher = this.watchers.get(socket.id);
  583. if (watcher) {
  584. await watcher.close();
  585. this.watchers.delete(socket.id);
  586. }
  587. if (typeof callback === "function") {
  588. callback({ success: true });
  589. }
  590. } catch (error) {
  591. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  592. if (typeof callback === "function") {
  593. callback({ error: errorMessage });
  594. }
  595. }
  596. }
  597. );
  598. socket.on("disconnect", async () => {
  599. console.log(`\u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5. \u5DE5\u4F5C\u533A: ${workspacePath}`);
  600. try {
  601. const watcher = this.watchers.get(socket.id);
  602. if (watcher) {
  603. await watcher.close();
  604. this.watchers.delete(socket.id);
  605. console.log(`\u6587\u4EF6\u76D1\u542C\u5668\u5DF2\u6E05\u7406: ${socket.id}`);
  606. }
  607. console.log(`\u6B63\u5728\u7EC8\u6B62\u5DE5\u4F5C\u533A\u8FDB\u7A0B: ${workspacePath}`);
  608. await this.killAllProcesses(socket.id);
  609. console.log(`\u6B63\u5728\u6E05\u7406\u5DE5\u4F5C\u533A\u76EE\u5F55: ${workspacePath}`);
  610. const exists = await import_promises.default.access(workspacePath).then(() => true).catch(() => false);
  611. if (exists) {
  612. await import_promises.default.rm(workspacePath, { recursive: true, force: true });
  613. console.log(`\u5DE5\u4F5C\u533A\u76EE\u5F55\u5DF2\u6E05\u7406: ${workspacePath}`);
  614. } else {
  615. console.log(`\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6E05\u7406: ${workspacePath}`);
  616. }
  617. this.workspaces.delete(socket.id);
  618. this.processes.delete(socket.id);
  619. console.log(`\u5BA2\u6237\u7AEF\u8D44\u6E90\u6E05\u7406\u5B8C\u6210: ${socket.id}`);
  620. } catch (error) {
  621. console.error(`\u5BA2\u6237\u7AEF\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:`, error);
  622. }
  623. });
  624. socket.on(
  625. "process:kill",
  626. async ({ pid, terminalId = "default" }, callback) => {
  627. try {
  628. await this.killProcess(socket.id, pid, terminalId);
  629. callback({ success: true });
  630. } catch (error) {
  631. const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
  632. callback({ error: errorMessage });
  633. }
  634. }
  635. );
  636. });
  637. }
  638. async killAllProcesses(socketId) {
  639. const processMap = this.processes.get(socketId);
  640. if (!processMap) {
  641. console.log(`\u6CA1\u6709\u627E\u5230 socket ${socketId} \u7684\u8FDB\u7A0B\u8BB0\u5F55`);
  642. return;
  643. }
  644. await Promise.all(
  645. Array.from(processMap.entries()).map(async ([terminalId, process2]) => {
  646. try {
  647. if (!process2.pid) {
  648. console.log(`\u8FDB\u7A0B (\u7EC8\u7AEF ${terminalId}) \u6CA1\u6709\u6709\u6548\u7684 PID`);
  649. return;
  650. }
  651. await new Promise((resolve, reject) => {
  652. const pid = process2.pid;
  653. const pkill = (0, import_child_process2.spawn)("pkill", ["-TERM", "-P", pid.toString()]);
  654. pkill.on("close", async () => {
  655. try {
  656. process2.kill("SIGINT");
  657. console.log(
  658. `\u8FDB\u7A0B ${pid} (\u7EC8\u7AEF ${terminalId}) \u5DF2\u53D1\u9001 SIGINT \u4FE1\u53F7`
  659. );
  660. await new Promise((resolveWait) => {
  661. const timeout = setTimeout(() => {
  662. try {
  663. (0, import_child_process2.spawn)("pkill", ["-KILL", "-P", pid.toString()]);
  664. process2.kill("SIGKILL");
  665. console.log(
  666. `\u8FDB\u7A0B ${pid} (\u7EC8\u7AEF ${terminalId}) \u5DF2\u5F3A\u5236\u7EC8\u6B62`
  667. );
  668. } catch (error) {
  669. console.error(
  670. `\u5F3A\u5236\u7EC8\u6B62\u8FDB\u7A0B ${pid} (\u7EC8\u7AEF ${terminalId}) \u5931\u8D25:`,
  671. error
  672. );
  673. }
  674. resolveWait();
  675. }, PROCESS_CONFIG.KILL_TIMEOUT);
  676. process2.once("exit", (code) => {
  677. clearTimeout(timeout);
  678. console.log(
  679. `\u8FDB\u7A0B ${pid} (\u7EC8\u7AEF ${terminalId}) \u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801: ${code}`
  680. );
  681. resolveWait();
  682. });
  683. });
  684. resolve();
  685. } catch (error) {
  686. reject(error);
  687. }
  688. });
  689. });
  690. } catch (error) {
  691. if (error instanceof Error && error.message.includes("ESRCH")) {
  692. console.log(`\u8FDB\u7A0B ${process2.pid} (\u7EC8\u7AEF ${terminalId}) \u5DF2\u4E0D\u5B58\u5728`);
  693. } else {
  694. console.error(
  695. `\u7EC8\u6B62\u8FDB\u7A0B ${process2.pid} (\u7EC8\u7AEF ${terminalId}) \u65F6\u53D1\u751F\u9519\u8BEF:`,
  696. error
  697. );
  698. }
  699. }
  700. })
  701. );
  702. processMap.clear();
  703. this.processHistory.set(socketId, []);
  704. console.log(`Socket ${socketId} \u7684\u6240\u6709\u8FDB\u7A0B\u5DF2\u6E05\u7406\u5B8C\u6210`);
  705. }
  706. async handleMount(workspacePath, files) {
  707. await import_promises.default.mkdir(workspacePath, { recursive: true });
  708. await this.createFiles(workspacePath, files);
  709. }
  710. async createFiles(basePath, files) {
  711. for (const [name, item] of Object.entries(files)) {
  712. const fullPath = import_path.default.join(basePath, name);
  713. if ("file" in item) {
  714. await import_promises.default.writeFile(fullPath, item.file.contents);
  715. } else if ("directory" in item) {
  716. await import_promises.default.mkdir(fullPath, { recursive: true });
  717. await this.createFiles(fullPath, item.directory.contents);
  718. }
  719. }
  720. }
  721. async checkCommandExists(command) {
  722. try {
  723. await new Promise((resolve, reject) => {
  724. const check = (0, import_child_process2.spawn)("which", [command]);
  725. check.on("close", (code) => {
  726. if (code === 0) {
  727. resolve();
  728. } else {
  729. reject();
  730. }
  731. });
  732. });
  733. return true;
  734. } catch {
  735. return false;
  736. }
  737. }
  738. async handleSpawn(socketId, workspacePath, command, args, terminalId) {
  739. const processes = this.processes.get(socketId);
  740. if (!processes) {
  741. throw new Error("No process map found for socket");
  742. }
  743. const commandExists = await this.checkCommandExists(command);
  744. if (!commandExists) {
  745. throw new Error(`\u547D\u4EE4 '${command}' \u672A\u5B89\u88C5\u3002\u8BF7\u786E\u4FDD\u7CFB\u7EDF\u5DF2\u5B89\u88C5\u8BE5\u547D\u4EE4\u5E76\u6DFB\u52A0\u5230 PATH \u73AF\u5883\u53D8\u91CF\u4E2D\u3002`);
  746. }
  747. return new Promise((resolve, reject) => {
  748. const process2 = (0, import_child_process2.spawn)(command, args, {
  749. cwd: workspacePath,
  750. stdio: ["pipe", "pipe", "pipe"],
  751. shell: true
  752. });
  753. if (!process2.pid) {
  754. reject(new Error("Failed to get process ID"));
  755. return;
  756. }
  757. const processInfo = {
  758. pid: process2.pid,
  759. command,
  760. args,
  761. timestamp: Date.now()
  762. };
  763. const history = this.processHistory.get(socketId) || [];
  764. history.push(processInfo);
  765. this.processHistory.set(socketId, history);
  766. this.io.to(socketId).emit("process:started", { ...processInfo, terminalId });
  767. if (ServerDetector.isDevServerCommand(command, args)) {
  768. console.log(
  769. `[ServerDetector] \u7B49\u5F85\u5F00\u53D1\u670D\u52A1\u5668\u542F\u52A8: ${command} ${args.join(" ")}`
  770. );
  771. const detector = new ServerDetector({ workspacePath });
  772. detector.on("server-ready", (event) => {
  773. console.log(`[ServerDetector] \u68C0\u6D4B\u5230\u670D\u52A1\u5668\u5C31\u7EEA:`, event);
  774. this.io.to(socketId).emit("server:ready", {
  775. ...event,
  776. command,
  777. args
  778. });
  779. });
  780. let detectionStarted = false;
  781. process2.stdout.on("data", () => {
  782. if (!detectionStarted) {
  783. detectionStarted = true;
  784. console.log(`[ServerDetector] \u68C0\u6D4B\u5230\u8FDB\u7A0B\u8F93\u51FA\uFF0C\u5F00\u59CB\u7AEF\u53E3\u68C0\u6D4B...`);
  785. detector.detectServerByPid(process2);
  786. }
  787. });
  788. }
  789. let stdout = "";
  790. let stderr = "";
  791. process2.on("SIGINT", () => {
  792. console.log(`Process ${process2.pid} received SIGINT`);
  793. process2.kill("SIGINT");
  794. });
  795. process2.stdout.on("data", (data) => {
  796. const output = data.toString();
  797. stdout += output;
  798. console.log(`[${command}] Process ${process2.pid} stdout:`, output);
  799. this.io.to(socketId).emit("process:output", {
  800. type: "stdout",
  801. data: output,
  802. terminalId
  803. });
  804. });
  805. process2.stderr.on("data", (data) => {
  806. const output = data.toString();
  807. stderr += output;
  808. console.error(`[${command}] stderr:`, output);
  809. this.io.to(socketId).emit("process:output", {
  810. type: "stderr",
  811. data: output,
  812. terminalId
  813. });
  814. });
  815. process2.on("close", (code) => {
  816. const processHistory = this.processHistory.get(socketId) || [];
  817. const historyIndex = processHistory.findIndex(
  818. (p) => p.pid === process2.pid
  819. );
  820. if (historyIndex > -1) {
  821. processHistory.splice(historyIndex, 1);
  822. }
  823. this.processHistory.set(socketId, processHistory);
  824. this.io.to(socketId).emit("process:ended", { pid: process2.pid, code });
  825. if (process2.pid) {
  826. processes.delete(terminalId);
  827. }
  828. if (code !== 0) {
  829. this.io.to(socketId).emit("process:output", {
  830. type: "exit",
  831. data: `Process exited with code ${code}`,
  832. terminalId
  833. });
  834. }
  835. if (code === 0 && process2.pid) {
  836. resolve({ pid: process2.pid });
  837. } else {
  838. reject(new Error(`Process exited with code ${code}`));
  839. }
  840. });
  841. process2.on("error", (error) => {
  842. processes.delete(terminalId);
  843. this.io.to(socketId).emit("process:output", {
  844. type: "stderr",
  845. data: error.message,
  846. terminalId
  847. });
  848. reject(error);
  849. });
  850. processes.set(terminalId, process2);
  851. });
  852. }
  853. async handleList(workspacePath, relativePath) {
  854. const fullPath = import_path.default.join(workspacePath, relativePath);
  855. const entries = await import_promises.default.readdir(fullPath, { withFileTypes: true });
  856. return entries.map((entry) => ({
  857. name: entry.name,
  858. type: entry.isDirectory() ? "directory" : "file"
  859. }));
  860. }
  861. async handleRead(workspacePath, relativePath) {
  862. const fullPath = import_path.default.join(workspacePath, relativePath);
  863. return import_promises.default.readFile(fullPath, "utf-8");
  864. }
  865. async handleWrite(workspacePath, relativePath, content) {
  866. const fullPath = import_path.default.join(workspacePath, relativePath);
  867. await import_promises.default.mkdir(import_path.default.dirname(fullPath), {
  868. recursive: true,
  869. mode: FS_CONFIG.DIR_MODE
  870. });
  871. await import_promises.default.writeFile(fullPath, content, {
  872. encoding: FS_CONFIG.ENCODING,
  873. mode: FS_CONFIG.FILE_MODE
  874. });
  875. }
  876. async handleDelete(workspacePath, relativePath) {
  877. const fullPath = import_path.default.join(workspacePath, relativePath);
  878. await import_promises.default.rm(fullPath, { recursive: true, force: true });
  879. }
  880. async handleMkdir(workspacePath, relativePath) {
  881. const fullPath = import_path.default.join(workspacePath, relativePath);
  882. await import_promises.default.mkdir(fullPath, { recursive: true });
  883. }
  884. stop() {
  885. return new Promise(async (resolve) => {
  886. console.log("\u6B63\u5728\u505C\u6B62 WebContainer Server...");
  887. for (const [socketId, watcher] of this.watchers.entries()) {
  888. try {
  889. await watcher.close();
  890. this.watchers.delete(socketId);
  891. console.log(`\u6587\u4EF6\u76D1\u542C\u5668\u5DF2\u6E05\u7406: ${socketId}`);
  892. } catch (error) {
  893. console.error(`\u6E05\u7406\u6587\u4EF6\u76D1\u542C\u5668\u5931\u8D25 ${socketId}:`, error);
  894. }
  895. }
  896. for (const socketId of this.processes.keys()) {
  897. this.killAllProcesses(socketId);
  898. }
  899. console.log("\u6B63\u5728\u6E05\u7406\u5DE5\u4F5C\u533A\u76EE\u5F55...");
  900. const workspaces = Array.from(this.workspaces.values());
  901. console.log(`\u9700\u8981\u6E05\u7406\u7684\u5DE5\u4F5C\u533A: ${workspaces.join(", ")}`);
  902. try {
  903. const rootExists = await import_promises.default.access(this.config.workspaceRoot).then(() => true).catch(() => false);
  904. if (rootExists) {
  905. await Promise.all(
  906. workspaces.map(async (workspacePath) => {
  907. try {
  908. const exists = await import_promises.default.access(workspacePath).then(() => true).catch(() => false);
  909. if (exists) {
  910. console.log(`\u6B63\u5728\u6E05\u7406\u5DE5\u4F5C\u533A: ${workspacePath}`);
  911. await import_promises.default.rm(workspacePath, { recursive: true, force: true });
  912. console.log(`\u5DE5\u4F5C\u533A\u5DF2\u6E05\u7406: ${workspacePath}`);
  913. } else {
  914. console.log(`\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6E05\u7406: ${workspacePath}`);
  915. }
  916. } catch (error) {
  917. console.error(`\u6E05\u7406\u5DE5\u4F5C\u533A\u5931\u8D25 ${workspacePath}:`, error);
  918. }
  919. })
  920. );
  921. try {
  922. const rootContents = await import_promises.default.readdir(this.config.workspaceRoot);
  923. if (rootContents.length === 0) {
  924. await import_promises.default.rm(this.config.workspaceRoot, {
  925. recursive: true,
  926. force: true
  927. });
  928. console.log(`\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u5DF2\u6E05\u7406: ${this.config.workspaceRoot}`);
  929. } else {
  930. console.log(
  931. `\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u975E\u7A7A\uFF0C\u4FDD\u7559: ${this.config.workspaceRoot}`
  932. );
  933. }
  934. } catch (error) {
  935. console.error("\u6E05\u7406\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u5931\u8D25:", error);
  936. }
  937. } else {
  938. console.log(`\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u4E0D\u5B58\u5728: ${this.config.workspaceRoot}`);
  939. }
  940. } catch (error) {
  941. console.error("\u6E05\u7406\u5DE5\u4F5C\u533A\u65F6\u53D1\u751F\u9519\u8BEF:", error);
  942. }
  943. this.io.close(() => {
  944. console.log("Socket.IO \u670D\u52A1\u5668\u5DF2\u5173\u95ED");
  945. this.httpServer.close(() => {
  946. console.log("HTTP \u670D\u52A1\u5668\u5DF2\u5173\u95ED");
  947. this.workspaces.clear();
  948. this.processes.clear();
  949. console.log("\u5185\u5B58\u4E2D\u7684\u5DE5\u4F5C\u533A\u8BB0\u5F55\u5DF2\u6E05\u7406");
  950. resolve();
  951. });
  952. });
  953. });
  954. }
  955. async killProcess(socketId, pid, terminalId) {
  956. const processes = this.processes.get(socketId);
  957. if (!processes) {
  958. throw new Error("No processes found for socket");
  959. }
  960. const process2 = processes.get(terminalId);
  961. if (!process2) {
  962. console.warn(`No process found for terminal ${terminalId}`);
  963. return;
  964. }
  965. try {
  966. await new Promise((resolve, reject) => {
  967. const pkill = (0, import_child_process2.spawn)("pkill", ["-TERM", "-P", pid.toString()]);
  968. pkill.on("close", async () => {
  969. try {
  970. process2.kill("SIGINT");
  971. console.log(`\u8FDB\u7A0B ${pid} \u5DF2\u53D1\u9001 SIGINT \u4FE1\u53F7`);
  972. await new Promise((resolveWait) => {
  973. const timeout = setTimeout(() => {
  974. try {
  975. (0, import_child_process2.spawn)("pkill", ["-KILL", "-P", pid.toString()]);
  976. process2.kill("SIGKILL");
  977. console.log(`\u8FDB\u7A0B ${pid} \u5DF2\u5F3A\u5236\u7EC8\u6B62`);
  978. } catch (error) {
  979. console.error(`\u5F3A\u5236\u7EC8\u6B62\u8FDB\u7A0B ${pid} \u5931\u8D25:`, error);
  980. }
  981. resolveWait();
  982. }, 5e3);
  983. process2.once("exit", (code) => {
  984. clearTimeout(timeout);
  985. console.log(`\u8FDB\u7A0B ${pid} \u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801: ${code}`);
  986. resolveWait();
  987. });
  988. });
  989. resolve();
  990. } catch (error) {
  991. reject(error);
  992. }
  993. });
  994. });
  995. processes.delete(terminalId);
  996. const history = this.processHistory.get(socketId) || [];
  997. const historyIndex = history.findIndex((p) => p.pid === pid);
  998. if (historyIndex > -1) {
  999. history.splice(historyIndex, 1);
  1000. }
  1001. this.processHistory.set(socketId, history);
  1002. this.io.to(socketId).emit("process:ended", { pid, code: 0 });
  1003. } catch (error) {
  1004. console.error(`\u7EC8\u6B62\u8FDB\u7A0B ${pid} \u5931\u8D25:`, error);
  1005. throw error;
  1006. }
  1007. }
  1008. };
  1009. // src/start.ts
  1010. var import_path2 = __toESM(require("path"), 1);
  1011. var port = parseInt(process.env.PORT || "3000", 10);
  1012. var host = process.env.HOST || "localhost";
  1013. var workspaceRoot = process.env.WORKSPACE_ROOT || import_path2.default.join(process.cwd(), "workspaces");
  1014. var server = new WebContainerServer({
  1015. port,
  1016. host,
  1017. workspaceRoot
  1018. });
  1019. var isShuttingDown = false;
  1020. server.start();
  1021. async function handleShutdown(signal) {
  1022. if (isShuttingDown) {
  1023. return;
  1024. }
  1025. isShuttingDown = true;
  1026. console.log(`
  1027. \u6536\u5230 ${signal} \u4FE1\u53F7\uFF0C\u6B63\u5728\u4F18\u96C5\u9000\u51FA...`);
  1028. try {
  1029. await server.stop();
  1030. console.log("\u670D\u52A1\u5668\u5DF2\u6210\u529F\u505C\u6B62");
  1031. setImmediate(() => process.exit(0));
  1032. } catch (error) {
  1033. console.error("\u670D\u52A1\u5668\u505C\u6B62\u65F6\u53D1\u751F\u9519\u8BEF:", error);
  1034. setImmediate(() => process.exit(1));
  1035. }
  1036. }
  1037. process.on("SIGTERM", () => handleShutdown("SIGTERM"));
  1038. process.on("SIGINT", () => handleShutdown("SIGINT"));
  1039. process.on("uncaughtException", (error) => {
  1040. console.error("\u672A\u6355\u83B7\u7684\u5F02\u5E38:", error);
  1041. handleShutdown("uncaughtException");
  1042. });
  1043. process.on("unhandledRejection", (reason) => {
  1044. console.error("\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD:", reason);
  1045. handleShutdown("unhandledRejection");
  1046. });