vite-plugin-opencode-assistant 1.0.4 → 1.0.5

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.
Files changed (84) hide show
  1. package/es/client/index.d.ts +1 -0
  2. package/es/client/index.js +328 -0
  3. package/es/core/api.d.ts +14 -0
  4. package/es/core/api.js +294 -0
  5. package/es/core/injector.d.ts +2 -0
  6. package/es/core/injector.js +11 -0
  7. package/es/core/service.d.ts +18 -0
  8. package/es/core/service.js +163 -0
  9. package/es/endpoints/context.d.ts +3 -0
  10. package/es/endpoints/context.js +114 -0
  11. package/es/endpoints/index.d.ts +4 -0
  12. package/es/endpoints/index.js +16 -0
  13. package/es/endpoints/sessions.d.ts +3 -0
  14. package/es/endpoints/sessions.js +79 -0
  15. package/es/endpoints/sse.d.ts +3 -0
  16. package/es/endpoints/sse.js +56 -0
  17. package/es/endpoints/start.d.ts +3 -0
  18. package/es/endpoints/start.js +35 -0
  19. package/es/endpoints/types.d.ts +13 -0
  20. package/es/endpoints/widget.d.ts +3 -0
  21. package/es/endpoints/widget.js +57 -0
  22. package/{dist/vite → es}/index.d.ts +1 -1
  23. package/es/index.js +168 -0
  24. package/es/utils/paths.d.ts +3 -0
  25. package/es/utils/paths.js +38 -0
  26. package/es/utils/system.js +241 -0
  27. package/lib/client/index.d.ts +1 -0
  28. package/lib/client/index.js +328 -0
  29. package/lib/client.js +5597 -0
  30. package/lib/core/api.d.ts +14 -0
  31. package/lib/core/api.js +321 -0
  32. package/lib/core/injector.d.ts +2 -0
  33. package/lib/core/injector.js +34 -0
  34. package/lib/core/service.d.ts +18 -0
  35. package/lib/core/service.js +180 -0
  36. package/lib/endpoints/context.d.ts +3 -0
  37. package/lib/endpoints/context.js +137 -0
  38. package/lib/endpoints/index.d.ts +4 -0
  39. package/lib/endpoints/index.js +41 -0
  40. package/lib/endpoints/sessions.d.ts +3 -0
  41. package/lib/endpoints/sessions.js +102 -0
  42. package/lib/endpoints/sse.d.ts +3 -0
  43. package/lib/endpoints/sse.js +79 -0
  44. package/lib/endpoints/start.d.ts +3 -0
  45. package/lib/endpoints/start.js +58 -0
  46. package/lib/endpoints/types.d.ts +13 -0
  47. package/lib/endpoints/types.js +15 -0
  48. package/lib/endpoints/widget.d.ts +3 -0
  49. package/lib/endpoints/widget.js +90 -0
  50. package/lib/index.d.ts +3 -0
  51. package/lib/index.js +190 -0
  52. package/lib/style.css +1 -0
  53. package/lib/utils/paths.d.ts +3 -0
  54. package/lib/utils/paths.js +73 -0
  55. package/lib/utils/system.d.ts +5 -0
  56. package/lib/utils/system.js +274 -0
  57. package/package.json +28 -33
  58. package/README.md +0 -287
  59. package/dist/constants.d.ts +0 -74
  60. package/dist/constants.js +0 -75
  61. package/dist/constants.js.map +0 -1
  62. package/dist/logger.d.ts +0 -64
  63. package/dist/logger.js +0 -311
  64. package/dist/logger.js.map +0 -1
  65. package/dist/opencode/plugins/page-context.d.ts +0 -7
  66. package/dist/opencode/plugins/page-context.js +0 -372
  67. package/dist/opencode/plugins/page-context.js.map +0 -1
  68. package/dist/opencode/web.d.ts +0 -3
  69. package/dist/opencode/web.js +0 -81
  70. package/dist/opencode/web.js.map +0 -1
  71. package/dist/types.d.ts +0 -126
  72. package/dist/types.js +0 -2
  73. package/dist/types.js.map +0 -1
  74. package/dist/vite/client.js +0 -2468
  75. package/dist/vite/client.js.map +0 -1
  76. package/dist/vite/index.js +0 -697
  77. package/dist/vite/index.js.map +0 -1
  78. package/dist/vite/injector.d.ts +0 -2
  79. package/dist/vite/injector.js +0 -6
  80. package/dist/vite/injector.js.map +0 -1
  81. package/dist/vite/utils.js +0 -206
  82. package/dist/vite/utils.js.map +0 -1
  83. /package/{dist/vite/client.d.ts → es/endpoints/types.js} +0 -0
  84. /package/{dist/vite/utils.d.ts → es/utils/system.d.ts} +0 -0
package/es/index.js ADDED
@@ -0,0 +1,168 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+ import Inspector from "unplugin-vue-inspector/vite";
38
+ import {
39
+ CONTEXT_API_PATH,
40
+ DEFAULT_CONFIG,
41
+ createLogger,
42
+ setVerbose
43
+ } from "@vite-plugin-opencode-assistant/shared";
44
+ import { setupMiddlewares } from "./endpoints/index.js";
45
+ import { injectWidget } from "./core/injector.js";
46
+ import { OpenCodeAPI } from "./core/api.js";
47
+ import { OpenCodeService } from "./core/service.js";
48
+ import { resolveWidgetPath, resolveWidgetStylePath } from "./utils/paths.js";
49
+ function opencodePlugin(options = {}) {
50
+ const plugins = [];
51
+ plugins.push(
52
+ ...Inspector({
53
+ enabled: false,
54
+ toggleButtonVisibility: "never",
55
+ toggleComboKey: false
56
+ })
57
+ );
58
+ plugins.push(createOpenCodePlugin(options));
59
+ return plugins;
60
+ }
61
+ function createOpenCodePlugin(options = {}) {
62
+ const config = __spreadValues(__spreadValues({}, DEFAULT_CONFIG), options);
63
+ setVerbose(config.verbose);
64
+ const log = createLogger("Plugin");
65
+ let actualWebPort = config.webPort;
66
+ let pageContext = { url: "", title: "" };
67
+ const sseClients = /* @__PURE__ */ new Set();
68
+ const api = new OpenCodeAPI(config.hostname, () => actualWebPort, config.warmupChromeMcp);
69
+ const service = new OpenCodeService(config, api, sseClients, (port) => {
70
+ actualWebPort = port;
71
+ });
72
+ return {
73
+ name: "vite-plugin-opencode",
74
+ apply(_viteConfig, env) {
75
+ if (!config.enabled) return false;
76
+ return env.command === "serve" && process.env.NODE_ENV !== "test";
77
+ },
78
+ configureServer(server) {
79
+ return __async(this, null, function* () {
80
+ var _a2, _b;
81
+ const timer = log.timer("configureServer");
82
+ setupMiddlewares(server, {
83
+ get sessionUrl() {
84
+ return service.sessionUrl;
85
+ },
86
+ get sseClients() {
87
+ return sseClients;
88
+ },
89
+ get pageContext() {
90
+ return pageContext;
91
+ },
92
+ set pageContext(ctx) {
93
+ pageContext = ctx;
94
+ },
95
+ getSessions: () => api.getSessions(),
96
+ createSession: () => api.createSession(),
97
+ deleteSession: (id) => api.deleteSession(id),
98
+ resolveWidgetPath,
99
+ resolveWidgetStylePath
100
+ });
101
+ (_a2 = server.httpServer) == null ? void 0 : _a2.on("listening", () => __async(null, null, function* () {
102
+ var _a3;
103
+ log.debug("Vite server listening event fired");
104
+ const address = (_a3 = server.httpServer) == null ? void 0 : _a3.address();
105
+ let vitePort;
106
+ let viteHost;
107
+ if (address && typeof address === "object") {
108
+ vitePort = address.port;
109
+ const addr = address.address;
110
+ if (addr === "::" || addr === "::1" || addr === "0.0.0.0" || !addr) {
111
+ viteHost = "localhost";
112
+ } else {
113
+ viteHost = addr;
114
+ }
115
+ } else {
116
+ const host = server.config.server.host;
117
+ vitePort = server.config.server.port || 5173;
118
+ viteHost = typeof host === "string" && host !== "0.0.0.0" && host !== "::" && host !== "::1" ? host : "localhost";
119
+ }
120
+ const viteOrigin = `http://${viteHost}:${vitePort}`;
121
+ const contextApiUrl = `http://${viteHost}:${vitePort}${CONTEXT_API_PATH}`;
122
+ log.debug("Vite server ready", {
123
+ vitePort,
124
+ viteHost,
125
+ viteOrigin,
126
+ contextApiUrl
127
+ });
128
+ try {
129
+ yield service.start([viteOrigin], contextApiUrl, viteOrigin);
130
+ } catch (e) {
131
+ log.error("Failed to start services", { error: e });
132
+ }
133
+ }));
134
+ (_b = server.httpServer) == null ? void 0 : _b.on("close", () => {
135
+ log.debug("HTTP server closing");
136
+ service.stop();
137
+ });
138
+ const cleanup = () => __async(null, null, function* () {
139
+ log.debug("Process cleanup triggered");
140
+ yield service.stop();
141
+ process.exit(0);
142
+ });
143
+ process.on("SIGINT", cleanup);
144
+ process.on("SIGTERM", cleanup);
145
+ timer.end("\u2713 Server configured");
146
+ });
147
+ },
148
+ transformIndexHtml(html) {
149
+ const timer = log.timer("transformIndexHtml");
150
+ const widget = injectWidget({
151
+ webUrl: `http://${config.hostname}:${actualWebPort}`,
152
+ serverUrl: `http://${config.hostname}:${actualWebPort}`,
153
+ position: config.position,
154
+ theme: config.theme,
155
+ open: config.open,
156
+ autoReload: config.autoReload,
157
+ cwd: process.cwd(),
158
+ sessionUrl: service.sessionUrl || void 0,
159
+ hotkey: config.hotkey
160
+ });
161
+ timer.end();
162
+ return html.replace("</body>", `${widget}</body>`);
163
+ }
164
+ };
165
+ }
166
+ export {
167
+ opencodePlugin as default
168
+ };
@@ -0,0 +1,3 @@
1
+ export declare function resolvePackageDir(): string;
2
+ export declare function resolveWidgetPath(): string;
3
+ export declare function resolveWidgetStylePath(): string;
@@ -0,0 +1,38 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { createRequire } from "module";
4
+ const require2 = createRequire(path.join(process.cwd(), "package.json"));
5
+ const packageDir = resolvePackageDir();
6
+ function resolvePackageDir() {
7
+ const entryPath = require2.resolve("vite-plugin-opencode-assistant");
8
+ return path.resolve(path.dirname(entryPath), "..");
9
+ }
10
+ function resolveWidgetPath() {
11
+ const candidatePaths = [
12
+ path.join(packageDir, "es", "client.js"),
13
+ path.join(packageDir, "lib", "client.js")
14
+ ];
15
+ for (const candidatePath of candidatePaths) {
16
+ if (fs.existsSync(candidatePath)) {
17
+ return candidatePath;
18
+ }
19
+ }
20
+ return candidatePaths[0];
21
+ }
22
+ function resolveWidgetStylePath() {
23
+ const candidatePaths = [
24
+ path.join(packageDir, "es", "style.css"),
25
+ path.join(packageDir, "lib", "style.css")
26
+ ];
27
+ for (const candidatePath of candidatePaths) {
28
+ if (fs.existsSync(candidatePath)) {
29
+ return candidatePath;
30
+ }
31
+ }
32
+ return candidatePaths[0];
33
+ }
34
+ export {
35
+ resolvePackageDir,
36
+ resolveWidgetPath,
37
+ resolveWidgetStylePath
38
+ };
@@ -0,0 +1,241 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { spawn } from "child_process";
22
+ import http from "http";
23
+ import net from "net";
24
+ import {
25
+ DEFAULT_HOSTNAME,
26
+ MAX_PORT_TRIES,
27
+ SERVER_CHECK_INTERVAL
28
+ } from "@vite-plugin-opencode-assistant/shared";
29
+ import { PerformanceTimer, createLogger } from "@vite-plugin-opencode-assistant/shared";
30
+ const log = createLogger("Utils");
31
+ function waitForServer(url, timeout = 1e4) {
32
+ const timer = new PerformanceTimer("waitForServer", { url, timeout });
33
+ return new Promise((resolve, reject) => {
34
+ const startTime = Date.now();
35
+ let attempts = 0;
36
+ const check = () => {
37
+ attempts++;
38
+ log.debug(`Checking server availability (attempt ${attempts})`, { url });
39
+ const req = http.get(url, (res) => {
40
+ if (res.statusCode && res.statusCode < 500) {
41
+ timer.end(`\u2713 Server ready after ${attempts} attempts`);
42
+ resolve();
43
+ } else {
44
+ log.debug(`Server returned status ${res.statusCode}, retrying...`);
45
+ retryOrReject();
46
+ }
47
+ });
48
+ req.on("error", (err) => {
49
+ log.debug(`Server check failed: ${err.message}`);
50
+ retryOrReject();
51
+ });
52
+ };
53
+ const retryOrReject = () => {
54
+ const elapsed = Date.now() - startTime;
55
+ if (elapsed < timeout) {
56
+ setTimeout(check, SERVER_CHECK_INTERVAL);
57
+ } else {
58
+ timer.end("\u274C Timeout");
59
+ reject(new Error(`Server not ready after ${timeout}ms (${attempts} attempts)`));
60
+ }
61
+ };
62
+ check();
63
+ });
64
+ }
65
+ function checkOpenCodeInstalled() {
66
+ return __async(this, null, function* () {
67
+ const timer = log.timer("checkOpenCodeInstalled");
68
+ return new Promise((resolve) => {
69
+ log.debug("Checking if OpenCode is installed...");
70
+ const proc = spawn("opencode", ["--version"], { stdio: "ignore" });
71
+ proc.on("close", (code) => {
72
+ const installed = code === 0;
73
+ timer.end(installed ? "\u2713 OpenCode is installed" : "\u274C OpenCode not found");
74
+ resolve(installed);
75
+ });
76
+ proc.on("error", (err) => {
77
+ log.debug("Failed to check OpenCode installation", { error: err.message });
78
+ timer.end("\u274C Check failed");
79
+ resolve(false);
80
+ });
81
+ });
82
+ });
83
+ }
84
+ function isPortAvailable(_0) {
85
+ return __async(this, arguments, function* (port, hostname = DEFAULT_HOSTNAME) {
86
+ return new Promise((resolve) => {
87
+ const server = net.createServer();
88
+ server.once("error", (err) => {
89
+ log.debug(`Port ${port} is not available`, { error: err.message });
90
+ resolve(false);
91
+ });
92
+ server.once("listening", () => {
93
+ server.close();
94
+ log.debug(`Port ${port} is available`);
95
+ resolve(true);
96
+ });
97
+ server.listen(port, hostname);
98
+ });
99
+ });
100
+ }
101
+ function findAvailablePort(_0) {
102
+ return __async(this, arguments, function* (startPort, hostname = DEFAULT_HOSTNAME, maxTries = MAX_PORT_TRIES) {
103
+ const timer = log.timer("findAvailablePort", { startPort, hostname, maxTries });
104
+ log.debug(`Looking for available port starting from ${startPort}`);
105
+ for (let port = startPort; port < startPort + maxTries; port++) {
106
+ if (yield isPortAvailable(port, hostname)) {
107
+ timer.end(`\u2713 Found available port: ${port}`);
108
+ return port;
109
+ }
110
+ log.debug(`Port ${port} is in use, trying next...`);
111
+ }
112
+ timer.end("\u274C No available port found");
113
+ throw new Error(`No available port found after ${maxTries} tries starting from ${startPort}`);
114
+ });
115
+ }
116
+ function killOrphanOpenCodeProcesses() {
117
+ return __async(this, null, function* () {
118
+ const timer = log.timer("killOrphanOpenCodeProcesses");
119
+ log.debug("Looking for orphan OpenCode processes (PPID=1)");
120
+ return new Promise((resolve) => {
121
+ if (process.platform === "win32") {
122
+ killOrphanProcessesOnWindows(resolve, timer);
123
+ } else {
124
+ killOrphanProcessesOnUnix(resolve, timer);
125
+ }
126
+ });
127
+ });
128
+ }
129
+ function killOrphanProcessesOnWindows(resolve, timer) {
130
+ var _a;
131
+ log.debug("Using Windows method to find orphan processes");
132
+ const proc = spawn(
133
+ "wmic",
134
+ ["process", "where", 'name="opencode.exe"', "get", "processid,parentprocessid"],
135
+ { stdio: "pipe" }
136
+ );
137
+ let output = "";
138
+ (_a = proc.stdout) == null ? void 0 : _a.on("data", (data) => {
139
+ output += data.toString();
140
+ });
141
+ proc.on("close", () => {
142
+ const lines = output.split("\n").filter((line) => line.trim());
143
+ const pidsToKill = [];
144
+ lines.forEach((line) => {
145
+ const parts = line.trim().split(/\s+/);
146
+ if (parts.length >= 2) {
147
+ const ppid = parts[0];
148
+ const pid = parts[1];
149
+ if (ppid === "1" && pid && !isNaN(Number(pid))) {
150
+ pidsToKill.push(pid);
151
+ }
152
+ }
153
+ });
154
+ if (pidsToKill.length > 0) {
155
+ log.debug(`Found ${pidsToKill.length} orphan processes`, { pids: pidsToKill });
156
+ let killedCount = 0;
157
+ let completedCount = 0;
158
+ pidsToKill.forEach((pid) => {
159
+ const killProc = spawn("taskkill", ["/F", "/PID", pid], { stdio: "ignore" });
160
+ killProc.on("close", (code) => {
161
+ completedCount++;
162
+ if (code === 0) {
163
+ killedCount++;
164
+ log.debug(`Killed orphan process ${pid}`);
165
+ }
166
+ if (completedCount === pidsToKill.length) {
167
+ timer.end(`\u2713 Killed ${killedCount} orphan processes`);
168
+ resolve(killedCount);
169
+ }
170
+ });
171
+ });
172
+ } else {
173
+ log.debug("No orphan processes found");
174
+ timer.end("No orphan processes found");
175
+ resolve(0);
176
+ }
177
+ });
178
+ proc.on("error", (err) => {
179
+ log.debug("Failed to find orphan processes", { error: err.message });
180
+ timer.end("\u274C Failed to find orphan processes");
181
+ resolve(0);
182
+ });
183
+ }
184
+ function killOrphanProcessesOnUnix(resolve, timer) {
185
+ var _a;
186
+ log.debug("Using Unix method to find orphan processes");
187
+ const proc = spawn("ps", ["-e", "-o", "pid,ppid,comm"], { stdio: "pipe" });
188
+ let output = "";
189
+ (_a = proc.stdout) == null ? void 0 : _a.on("data", (data) => {
190
+ output += data.toString();
191
+ });
192
+ proc.on("close", () => {
193
+ const lines = output.split("\n");
194
+ const pidsToKill = [];
195
+ lines.forEach((line) => {
196
+ const trimmed = line.trim();
197
+ if (trimmed.includes("opencode")) {
198
+ const parts = trimmed.split(/\s+/);
199
+ if (parts.length >= 3) {
200
+ const pid = parts[0];
201
+ const ppid = parts[1];
202
+ const comm = parts.slice(2).join(" ");
203
+ if (ppid === "1" && comm.includes("opencode")) {
204
+ pidsToKill.push(pid);
205
+ }
206
+ }
207
+ }
208
+ });
209
+ if (pidsToKill.length > 0) {
210
+ log.debug(`Found ${pidsToKill.length} orphan processes`, { pids: pidsToKill });
211
+ const killProc = spawn("kill", ["-9", ...pidsToKill], { stdio: "ignore" });
212
+ killProc.on("close", (code) => {
213
+ const killedCount = code === 0 ? pidsToKill.length : 0;
214
+ timer.end(
215
+ killedCount > 0 ? `\u2713 Killed ${killedCount} orphan processes` : "\u274C Failed to kill processes"
216
+ );
217
+ resolve(killedCount);
218
+ });
219
+ killProc.on("error", () => {
220
+ timer.end("\u274C Failed to kill processes");
221
+ resolve(0);
222
+ });
223
+ } else {
224
+ log.debug("No orphan processes found");
225
+ timer.end("No orphan processes found");
226
+ resolve(0);
227
+ }
228
+ });
229
+ proc.on("error", (err) => {
230
+ log.debug("Failed to find orphan processes", { error: err.message });
231
+ timer.end("\u274C Failed to find orphan processes");
232
+ resolve(0);
233
+ });
234
+ }
235
+ export {
236
+ checkOpenCodeInstalled,
237
+ findAvailablePort,
238
+ isPortAvailable,
239
+ killOrphanOpenCodeProcesses,
240
+ waitForServer
241
+ };
@@ -0,0 +1 @@
1
+ import "@vite-plugin-opencode-assistant/components/style.css";