@vite-plugin-opencode-assistant/shared 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.
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @fileoverview OpenCode 插件常量定义
3
+ */
4
+ /** ==================== 网络相关 ==================== */
5
+ /** 默认主机名 */
6
+ export declare const DEFAULT_HOSTNAME = "127.0.0.1";
7
+ /** 默认 Web 服务端口 */
8
+ export declare const DEFAULT_WEB_PORT = 4097;
9
+ /** 服务器启动超时时间(毫秒) */
10
+ export declare const SERVER_START_TIMEOUT = 300000;
11
+ /** 服务器检查间隔(毫秒) */
12
+ export declare const SERVER_CHECK_INTERVAL = 100;
13
+ /** ==================== 重试相关 ==================== */
14
+ /** 默认重试次数 */
15
+ export declare const DEFAULT_RETRIES = 5;
16
+ /** 重试延迟(毫秒) */
17
+ export declare const RETRY_DELAY = 500;
18
+ /** ==================== 端口查找 ==================== */
19
+ /** 最大端口尝试次数 */
20
+ export declare const MAX_PORT_TRIES = 10;
21
+ /** ==================== 日志相关 ==================== */
22
+ /** 插件日志前缀 */
23
+ export declare const LOG_PREFIX = "[vite-plugin-opencode]";
24
+ /** OpenCode Web 日志前缀 */
25
+ export declare const WEB_LOG_PREFIX = "[OpenCode Web]";
26
+ /** OpenCode Web 错误日志前缀 */
27
+ export declare const WEB_ERROR_PREFIX = "[OpenCode Web Error]";
28
+ /** ==================== 挂件相关 ==================== */
29
+ /** 挂件脚本路径 */
30
+ export declare const WIDGET_SCRIPT_PATH = "/__opencode_widget__.js";
31
+ /** 配置数据属性名 */
32
+ export declare const CONFIG_DATA_ATTR = "data-opencode-config";
33
+ /** 上下文 API 路径 */
34
+ export declare const CONTEXT_API_PATH = "/__opencode_context__";
35
+ /** 启动 API 路径 */
36
+ export declare const START_API_PATH = "/__opencode_start__";
37
+ /** 会话列表 API 路径 */
38
+ export declare const SESSIONS_API_PATH = "/__opencode_sessions__";
39
+ /** SSE 事件流路径 */
40
+ export declare const SSE_EVENTS_PATH = "/__opencode_events__";
41
+ /** 上下文更新间隔(毫秒) */
42
+ export declare const CONTEXT_UPDATE_INTERVAL = 500;
43
+ /** 服务器同步间隔(毫秒) */
44
+ export declare const SERVER_SYNC_INTERVAL = 2000;
45
+ /** Vue Inspector 检查间隔(毫秒) */
46
+ export declare const INSPECTOR_CHECK_INTERVAL = 500;
47
+ /** 自动打开延迟(毫秒) */
48
+ export declare const AUTO_OPEN_DELAY = 1000;
49
+ /** 通知显示时间(毫秒) */
50
+ export declare const NOTIFICATION_DURATION = 3000;
51
+ /** ==================== 存储相关 ==================== */
52
+ /** 初始化标记 */
53
+ export declare const INIT_MARKER = "__OPENCODE_INITIALIZED__";
54
+ /** 选中元素存储键 */
55
+ export declare const SELECTED_ELEMENTS_KEY = "__opencode_selected_elements__";
56
+ /** ==================== 文本处理 ==================== */
57
+ /** 元素文本最大显示长度 */
58
+ export declare const MAX_TEXT_LENGTH = 100;
59
+ /** 元素上下文标记 */
60
+ export declare const CONTEXT_MARKER = "[\u5143\u7D20\u4E0A\u4E0B\u6587]";
61
+ /** ==================== 默认配置 ==================== */
62
+ /** 默认插件配置 */
63
+ export declare const DEFAULT_CONFIG: {
64
+ enabled: boolean;
65
+ webPort: number;
66
+ hostname: string;
67
+ position: "bottom-right";
68
+ theme: "auto";
69
+ open: boolean;
70
+ autoReload: boolean;
71
+ verbose: boolean;
72
+ hotkey: string;
73
+ warmupChromeMcp: boolean;
74
+ };
@@ -0,0 +1,65 @@
1
+ const DEFAULT_HOSTNAME = "127.0.0.1";
2
+ const DEFAULT_WEB_PORT = 4097;
3
+ const SERVER_START_TIMEOUT = 3e5;
4
+ const SERVER_CHECK_INTERVAL = 100;
5
+ const DEFAULT_RETRIES = 5;
6
+ const RETRY_DELAY = 500;
7
+ const MAX_PORT_TRIES = 10;
8
+ const LOG_PREFIX = "[vite-plugin-opencode]";
9
+ const WEB_LOG_PREFIX = "[OpenCode Web]";
10
+ const WEB_ERROR_PREFIX = "[OpenCode Web Error]";
11
+ const WIDGET_SCRIPT_PATH = "/__opencode_widget__.js";
12
+ const CONFIG_DATA_ATTR = "data-opencode-config";
13
+ const CONTEXT_API_PATH = "/__opencode_context__";
14
+ const START_API_PATH = "/__opencode_start__";
15
+ const SESSIONS_API_PATH = "/__opencode_sessions__";
16
+ const SSE_EVENTS_PATH = "/__opencode_events__";
17
+ const CONTEXT_UPDATE_INTERVAL = 500;
18
+ const SERVER_SYNC_INTERVAL = 2e3;
19
+ const INSPECTOR_CHECK_INTERVAL = 500;
20
+ const AUTO_OPEN_DELAY = 1e3;
21
+ const NOTIFICATION_DURATION = 3e3;
22
+ const INIT_MARKER = "__OPENCODE_INITIALIZED__";
23
+ const SELECTED_ELEMENTS_KEY = "__opencode_selected_elements__";
24
+ const MAX_TEXT_LENGTH = 100;
25
+ const CONTEXT_MARKER = "[\u5143\u7D20\u4E0A\u4E0B\u6587]";
26
+ const DEFAULT_CONFIG = {
27
+ enabled: true,
28
+ webPort: DEFAULT_WEB_PORT,
29
+ hostname: DEFAULT_HOSTNAME,
30
+ position: "bottom-right",
31
+ theme: "auto",
32
+ open: false,
33
+ autoReload: true,
34
+ verbose: false,
35
+ hotkey: "ctrl+k",
36
+ warmupChromeMcp: true
37
+ };
38
+ export {
39
+ AUTO_OPEN_DELAY,
40
+ CONFIG_DATA_ATTR,
41
+ CONTEXT_API_PATH,
42
+ CONTEXT_MARKER,
43
+ CONTEXT_UPDATE_INTERVAL,
44
+ DEFAULT_CONFIG,
45
+ DEFAULT_HOSTNAME,
46
+ DEFAULT_RETRIES,
47
+ DEFAULT_WEB_PORT,
48
+ INIT_MARKER,
49
+ INSPECTOR_CHECK_INTERVAL,
50
+ LOG_PREFIX,
51
+ MAX_PORT_TRIES,
52
+ MAX_TEXT_LENGTH,
53
+ NOTIFICATION_DURATION,
54
+ RETRY_DELAY,
55
+ SELECTED_ELEMENTS_KEY,
56
+ SERVER_CHECK_INTERVAL,
57
+ SERVER_START_TIMEOUT,
58
+ SERVER_SYNC_INTERVAL,
59
+ SESSIONS_API_PATH,
60
+ SSE_EVENTS_PATH,
61
+ START_API_PATH,
62
+ WEB_ERROR_PREFIX,
63
+ WEB_LOG_PREFIX,
64
+ WIDGET_SCRIPT_PATH
65
+ };
package/es/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./constants.js";
2
+ export * from "./logger.js";
3
+ export * from "./types.js";
package/es/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./constants.js";
2
+ export * from "./logger.js";
3
+ export * from "./types.js";
package/es/logger.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ export declare enum LogLevel {
2
+ DEBUG = 0,
3
+ INFO = 1,
4
+ WARN = 2,
5
+ ERROR = 3,
6
+ NONE = 4
7
+ }
8
+ export interface LogContext {
9
+ module?: string;
10
+ operation?: string;
11
+ traceId?: string;
12
+ duration?: number;
13
+ error?: Error | unknown;
14
+ [key: string]: unknown;
15
+ }
16
+ interface LoggerConfig {
17
+ verbose: boolean;
18
+ level: LogLevel;
19
+ showTimestamp: boolean;
20
+ showCaller: boolean;
21
+ showTrace: boolean;
22
+ indent: string;
23
+ }
24
+ export declare function configureLogger(options: Partial<LoggerConfig>): void;
25
+ export declare function setVerbose(verbose: boolean): void;
26
+ export declare const logger: {
27
+ debug(message: string, context?: LogContext, ...args: unknown[]): void;
28
+ info(message: string, context?: LogContext, ...args: unknown[]): void;
29
+ warn(message: string, context?: LogContext, ...args: unknown[]): void;
30
+ error(message: string, context?: LogContext, ...args: unknown[]): void;
31
+ group(label: string, context?: LogContext): void;
32
+ groupEnd(): void;
33
+ };
34
+ export declare function generateTraceId(): string;
35
+ export declare class PerformanceTimer {
36
+ private startTime;
37
+ private context;
38
+ private operation;
39
+ constructor(operation: string, context?: LogContext);
40
+ end(message?: string): number;
41
+ checkpoint(label: string): number;
42
+ }
43
+ export declare class RequestContext {
44
+ traceId: string;
45
+ method: string;
46
+ path: string;
47
+ startTime: number;
48
+ private checkpoints;
49
+ constructor(method: string, path: string);
50
+ checkpoint(label: string): void;
51
+ end(statusCode: number): void;
52
+ error(error: Error | unknown): void;
53
+ }
54
+ export declare function createLogger(module: string): {
55
+ debug(message: string, context?: Omit<LogContext, "module">, ...args: unknown[]): void;
56
+ info(message: string, context?: Omit<LogContext, "module">, ...args: unknown[]): void;
57
+ warn(message: string, context?: Omit<LogContext, "module">, ...args: unknown[]): void;
58
+ error(message: string, context?: Omit<LogContext, "module">, ...args: unknown[]): void;
59
+ timer(operation: string, context?: Omit<LogContext, "module">): PerformanceTimer;
60
+ };
61
+ export declare function logMethod(target: unknown, propertyKey: string, descriptor: PropertyDescriptor): PropertyDescriptor;
62
+ export declare function formatBytes(bytes: number): string;
63
+ export declare function formatDuration(ms: number): string;
64
+ export {};
package/es/logger.js ADDED
@@ -0,0 +1,353 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+ var __async = (__this, __arguments, generator) => {
22
+ return new Promise((resolve, reject) => {
23
+ var fulfilled = (value) => {
24
+ try {
25
+ step(generator.next(value));
26
+ } catch (e) {
27
+ reject(e);
28
+ }
29
+ };
30
+ var rejected = (value) => {
31
+ try {
32
+ step(generator.throw(value));
33
+ } catch (e) {
34
+ reject(e);
35
+ }
36
+ };
37
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
38
+ step((generator = generator.apply(__this, __arguments)).next());
39
+ });
40
+ };
41
+ import { LOG_PREFIX } from "./constants.js";
42
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
43
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
44
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
45
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
46
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
47
+ LogLevel2[LogLevel2["NONE"] = 4] = "NONE";
48
+ return LogLevel2;
49
+ })(LogLevel || {});
50
+ const COLORS = {
51
+ reset: "\x1B[0m",
52
+ dim: "\x1B[2m",
53
+ bright: "\x1B[1m",
54
+ red: "\x1B[31m",
55
+ green: "\x1B[32m",
56
+ yellow: "\x1B[33m",
57
+ blue: "\x1B[34m",
58
+ magenta: "\x1B[35m",
59
+ cyan: "\x1B[36m",
60
+ white: "\x1B[37m"
61
+ };
62
+ const LEVEL_COLORS = {
63
+ [0 /* DEBUG */]: COLORS.cyan,
64
+ [1 /* INFO */]: COLORS.green,
65
+ [2 /* WARN */]: COLORS.yellow,
66
+ [3 /* ERROR */]: COLORS.red,
67
+ [4 /* NONE */]: COLORS.reset
68
+ };
69
+ const LEVEL_NAMES = {
70
+ [0 /* DEBUG */]: "DEBUG",
71
+ [1 /* INFO */]: "INFO",
72
+ [2 /* WARN */]: "WARN",
73
+ [3 /* ERROR */]: "ERROR",
74
+ [4 /* NONE */]: "NONE"
75
+ };
76
+ let globalConfig = {
77
+ verbose: false,
78
+ level: 1 /* INFO */,
79
+ showTimestamp: true,
80
+ showCaller: true,
81
+ showTrace: false,
82
+ indent: " "
83
+ };
84
+ let traceCounter = 0;
85
+ function configureLogger(options) {
86
+ globalConfig = __spreadValues(__spreadValues({}, globalConfig), options);
87
+ }
88
+ function setVerbose(verbose) {
89
+ globalConfig.verbose = verbose;
90
+ globalConfig.level = verbose ? 0 /* DEBUG */ : 1 /* INFO */;
91
+ }
92
+ function getTimestamp() {
93
+ const now = /* @__PURE__ */ new Date();
94
+ const hours = String(now.getHours()).padStart(2, "0");
95
+ const minutes = String(now.getMinutes()).padStart(2, "0");
96
+ const seconds = String(now.getSeconds()).padStart(2, "0");
97
+ const ms = String(now.getMilliseconds()).padStart(3, "0");
98
+ return `${hours}:${minutes}:${seconds}.${ms}`;
99
+ }
100
+ function getCallerInfo(depth = 3) {
101
+ const stack = new Error().stack;
102
+ if (!stack) return "";
103
+ const lines = stack.split("\n");
104
+ const targetLine = lines[depth];
105
+ if (!targetLine) return "";
106
+ const match = targetLine.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?/);
107
+ if (!match) return "";
108
+ const [, funcName, filePath, line] = match;
109
+ const fileName = filePath.split("/").pop() || filePath;
110
+ const func = funcName || "<anonymous>";
111
+ return `${fileName}:${line} ${func}`;
112
+ }
113
+ function formatValue(value, depth = 0) {
114
+ if (depth > 3) return "...";
115
+ if (value === null) return "null";
116
+ if (value === void 0) return "undefined";
117
+ if (typeof value === "string") return depth > 0 ? `"${value}"` : value;
118
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
119
+ if (value instanceof Error) {
120
+ return `${value.name}: ${value.message}${value.stack ? `
121
+ ${value.stack}` : ""}`;
122
+ }
123
+ if (Array.isArray(value)) {
124
+ if (value.length === 0) return "[]";
125
+ if (value.length > 5) {
126
+ const items2 = value.slice(0, 3).map((v) => formatValue(v, depth + 1));
127
+ return `[${items2.join(", ")}, ... ${value.length - 3} more items]`;
128
+ }
129
+ const items = value.map((v) => formatValue(v, depth + 1));
130
+ return `[${items.join(", ")}]`;
131
+ }
132
+ if (typeof value === "object") {
133
+ const entries = Object.entries(value);
134
+ if (entries.length === 0) return "{}";
135
+ if (entries.length > 5) {
136
+ const shown = entries.slice(0, 3).map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`);
137
+ return `{${shown.join(", ")}, ... ${entries.length - 3} more keys}`;
138
+ }
139
+ const formatted = entries.map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`);
140
+ return `{${formatted.join(", ")}}`;
141
+ }
142
+ return String(value);
143
+ }
144
+ function formatContext(context) {
145
+ if (!context || Object.keys(context).length === 0) return "";
146
+ const parts = [];
147
+ if (context.module) parts.push(`[${context.module}]`);
148
+ if (context.operation) parts.push(`(${context.operation})`);
149
+ if (context.traceId) parts.push(`trace:${context.traceId}`);
150
+ if (context.duration !== void 0) parts.push(`${context.duration}ms`);
151
+ const extraKeys = Object.keys(context).filter(
152
+ (k) => !["module", "operation", "traceId", "duration", "error"].includes(k)
153
+ );
154
+ if (extraKeys.length > 0) {
155
+ const extra = {};
156
+ extraKeys.forEach((k) => extra[k] = context[k]);
157
+ parts.push(formatValue(extra));
158
+ }
159
+ return parts.join(" ");
160
+ }
161
+ function log(level, message, context, ...args) {
162
+ if (level < globalConfig.level) return;
163
+ const parts = [];
164
+ parts.push(`${COLORS.dim}[${process.pid}]${COLORS.reset}`);
165
+ if (globalConfig.showTimestamp) {
166
+ parts.push(`${COLORS.dim}${getTimestamp()}${COLORS.reset}`);
167
+ }
168
+ const levelColor = LEVEL_COLORS[level];
169
+ const levelName = LEVEL_NAMES[level].padEnd(5);
170
+ parts.push(`${levelColor}${levelName}${COLORS.reset}`);
171
+ parts.push(`${COLORS.bright}${LOG_PREFIX}${COLORS.reset}`);
172
+ const contextStr = formatContext(context);
173
+ if (contextStr) {
174
+ parts.push(`${COLORS.magenta}${contextStr}${COLORS.reset}`);
175
+ }
176
+ parts.push(message);
177
+ if (globalConfig.showCaller && level >= 2 /* WARN */) {
178
+ const caller = getCallerInfo(4);
179
+ if (caller) {
180
+ parts.push(`${COLORS.dim}(${caller})${COLORS.reset}`);
181
+ }
182
+ }
183
+ const formattedArgs = args.map((a) => formatValue(a)).join(" ");
184
+ if (formattedArgs) {
185
+ parts.push(formattedArgs);
186
+ }
187
+ const output = parts.join(" ");
188
+ if (level >= 3 /* ERROR */) {
189
+ console.error(output);
190
+ } else if (level === 2 /* WARN */) {
191
+ console.warn(output);
192
+ } else {
193
+ console.log(output);
194
+ }
195
+ if ((context == null ? void 0 : context.error) && level >= 3 /* ERROR */ && globalConfig.showTrace) {
196
+ const err = context.error;
197
+ if (err instanceof Error && err.stack) {
198
+ console.error(`${COLORS.dim}${err.stack}${COLORS.reset}`);
199
+ }
200
+ }
201
+ }
202
+ const logger = {
203
+ debug(message, context, ...args) {
204
+ log(0 /* DEBUG */, message, context, ...args);
205
+ },
206
+ info(message, context, ...args) {
207
+ log(1 /* INFO */, message, context, ...args);
208
+ },
209
+ warn(message, context, ...args) {
210
+ log(2 /* WARN */, message, context, ...args);
211
+ },
212
+ error(message, context, ...args) {
213
+ log(3 /* ERROR */, message, context, ...args);
214
+ },
215
+ group(label, context) {
216
+ if (!globalConfig.verbose) return;
217
+ const contextStr = formatContext(context);
218
+ console.log(
219
+ `${COLORS.dim}[${process.pid}]${COLORS.reset} ${COLORS.bright}${LOG_PREFIX}${COLORS.reset} ${COLORS.blue}\u25BC${COLORS.reset} ${label}${contextStr ? ` ${contextStr}` : ""}`
220
+ );
221
+ },
222
+ groupEnd() {
223
+ if (!globalConfig.verbose) return;
224
+ }
225
+ };
226
+ function generateTraceId() {
227
+ traceCounter++;
228
+ const timestamp = Date.now().toString(36);
229
+ const counter = traceCounter.toString(36).padStart(4, "0");
230
+ return `${timestamp}-${counter}`;
231
+ }
232
+ class PerformanceTimer {
233
+ constructor(operation, context) {
234
+ __publicField(this, "startTime");
235
+ __publicField(this, "context");
236
+ __publicField(this, "operation");
237
+ this.operation = operation;
238
+ this.context = context || {};
239
+ this.startTime = performance.now();
240
+ logger.debug(`\u23F1\uFE0F Starting: ${operation}`, this.context);
241
+ }
242
+ end(message) {
243
+ const duration = Math.round(performance.now() - this.startTime);
244
+ const msg = message || `\u2713 Completed: ${this.operation}`;
245
+ logger.debug(msg, __spreadProps(__spreadValues({}, this.context), { duration }));
246
+ return duration;
247
+ }
248
+ checkpoint(label) {
249
+ const elapsed = Math.round(performance.now() - this.startTime);
250
+ logger.debug(` \u21B3 ${label}`, __spreadProps(__spreadValues({}, this.context), { duration: elapsed }));
251
+ return elapsed;
252
+ }
253
+ }
254
+ class RequestContext {
255
+ constructor(method, path) {
256
+ __publicField(this, "traceId");
257
+ __publicField(this, "method");
258
+ __publicField(this, "path");
259
+ __publicField(this, "startTime");
260
+ __publicField(this, "checkpoints", []);
261
+ this.traceId = generateTraceId();
262
+ this.method = method;
263
+ this.path = path;
264
+ this.startTime = performance.now();
265
+ logger.debug(`\u2192 ${method} ${path}`, { traceId: this.traceId, module: "HTTP" });
266
+ }
267
+ checkpoint(label) {
268
+ const elapsed = Math.round(performance.now() - this.startTime);
269
+ this.checkpoints.push({ time: elapsed, label });
270
+ logger.debug(` \u2192 ${label}`, { traceId: this.traceId, duration: elapsed });
271
+ }
272
+ end(statusCode) {
273
+ const duration = Math.round(performance.now() - this.startTime);
274
+ const statusColor = statusCode < 400 ? COLORS.green : COLORS.red;
275
+ logger.debug(`\u2190 ${this.method} ${this.path} ${statusColor}${statusCode}${COLORS.reset}`, {
276
+ traceId: this.traceId,
277
+ duration,
278
+ checkpoints: this.checkpoints.length
279
+ });
280
+ }
281
+ error(error) {
282
+ const duration = Math.round(performance.now() - this.startTime);
283
+ logger.error(`\u2717 ${this.method} ${this.path}`, {
284
+ traceId: this.traceId,
285
+ duration,
286
+ error
287
+ });
288
+ }
289
+ }
290
+ function createLogger(module) {
291
+ return {
292
+ debug(message, context, ...args) {
293
+ logger.debug(message, __spreadProps(__spreadValues({}, context), { module }), ...args);
294
+ },
295
+ info(message, context, ...args) {
296
+ logger.info(message, __spreadProps(__spreadValues({}, context), { module }), ...args);
297
+ },
298
+ warn(message, context, ...args) {
299
+ logger.warn(message, __spreadProps(__spreadValues({}, context), { module }), ...args);
300
+ },
301
+ error(message, context, ...args) {
302
+ logger.error(message, __spreadProps(__spreadValues({}, context), { module }), ...args);
303
+ },
304
+ timer(operation, context) {
305
+ return new PerformanceTimer(operation, __spreadProps(__spreadValues({}, context), { module }));
306
+ }
307
+ };
308
+ }
309
+ function logMethod(target, propertyKey, descriptor) {
310
+ const originalMethod = descriptor.value;
311
+ const className = target.constructor.name;
312
+ descriptor.value = function(...args) {
313
+ return __async(this, null, function* () {
314
+ const timer = new PerformanceTimer(`${className}.${propertyKey}`);
315
+ try {
316
+ const result = yield originalMethod.apply(this, args);
317
+ timer.end();
318
+ return result;
319
+ } catch (error) {
320
+ timer.end("\u274C Failed");
321
+ throw error;
322
+ }
323
+ });
324
+ };
325
+ return descriptor;
326
+ }
327
+ function formatBytes(bytes) {
328
+ if (bytes === 0) return "0B";
329
+ const k = 1024;
330
+ const sizes = ["B", "KB", "MB", "GB"];
331
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
332
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))}${sizes[i]}`;
333
+ }
334
+ function formatDuration(ms) {
335
+ if (ms < 1e3) return `${ms}ms`;
336
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(2)}s`;
337
+ const minutes = Math.floor(ms / 6e4);
338
+ const seconds = Math.round(ms % 6e4 / 1e3);
339
+ return `${minutes}m ${seconds}s`;
340
+ }
341
+ export {
342
+ LogLevel,
343
+ PerformanceTimer,
344
+ RequestContext,
345
+ configureLogger,
346
+ createLogger,
347
+ formatBytes,
348
+ formatDuration,
349
+ generateTraceId,
350
+ logMethod,
351
+ logger,
352
+ setVerbose
353
+ };
package/es/types.d.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * OpenCode Vite 插件配置选项
3
+ */
4
+ export interface OpenCodeOptions {
5
+ /** 是否启用插件,默认 true */
6
+ enabled?: boolean;
7
+ /** Web 服务端口,默认 4097 */
8
+ webPort?: number;
9
+ /** 服务主机名,默认 '127.0.0.1' */
10
+ hostname?: string;
11
+ /** 挂件位置,默认 'bottom-right' */
12
+ position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
13
+ /** 主题模式,默认 'auto' */
14
+ theme?: "light" | "dark" | "auto";
15
+ /** 是否自动打开面板,默认 false */
16
+ open?: boolean;
17
+ /** 是否自动重载,默认 true */
18
+ autoReload?: boolean;
19
+ /** 是否输出详细日志,默认 false */
20
+ verbose?: boolean;
21
+ /** 快捷键配置,默认 'ctrl+k' */
22
+ hotkey?: string;
23
+ /** 服务启动后是否立即预热 Chrome MCP,默认 true */
24
+ warmupChromeMcp?: boolean;
25
+ }
26
+ /**
27
+ * OpenCode Web 服务启动选项
28
+ */
29
+ export interface WebOptions {
30
+ /** 服务端口 */
31
+ port: number;
32
+ /** 服务主机名 */
33
+ hostname: string;
34
+ /** 服务器 URL */
35
+ serverUrl: string;
36
+ /** 工作目录 */
37
+ cwd: string;
38
+ /** 配置目录路径 */
39
+ configDir?: string;
40
+ /** CORS 允许的源 */
41
+ corsOrigins?: string[];
42
+ /** 上下文 API URL */
43
+ contextApiUrl?: string;
44
+ }
45
+ /**
46
+ * 挂件注入配置选项
47
+ */
48
+ export interface WidgetOptions {
49
+ /** Web 服务 URL */
50
+ webUrl: string;
51
+ /** 服务器 URL */
52
+ serverUrl: string;
53
+ /** 挂件位置 */
54
+ position: string;
55
+ /** 主题模式 */
56
+ theme: string;
57
+ /** 是否自动打开 */
58
+ open: boolean;
59
+ /** 是否自动重载 */
60
+ autoReload: boolean;
61
+ /** 工作目录 */
62
+ cwd: string;
63
+ /** 会话 URL */
64
+ sessionUrl?: string;
65
+ /** 快捷键配置 */
66
+ hotkey?: string;
67
+ }
68
+ /**
69
+ * OpenCode 会话信息
70
+ */
71
+ export interface SessionInfo {
72
+ /** 会话 ID */
73
+ id: string;
74
+ /** 会话标识符 */
75
+ slug: string;
76
+ /** 项目 ID */
77
+ projectID: string;
78
+ /** 项目目录 */
79
+ directory: string;
80
+ /** 会话标题 */
81
+ title: string;
82
+ /** 版本号 */
83
+ version: string;
84
+ /** 代码变更统计 */
85
+ summary: {
86
+ /** 新增行数 */
87
+ additions: number;
88
+ /** 删除行数 */
89
+ deletions: number;
90
+ /** 修改文件数 */
91
+ files: number;
92
+ };
93
+ /** 时间信息 */
94
+ time: {
95
+ /** 创建时间戳 */
96
+ created: number;
97
+ /** 更新时间戳 */
98
+ updated: number;
99
+ };
100
+ }
101
+ /**
102
+ * 选中的元素信息
103
+ */
104
+ export interface SelectedElement {
105
+ /** 文件路径 */
106
+ filePath: string | null;
107
+ /** 行号 */
108
+ line: number | null;
109
+ /** 列号 */
110
+ column: number | null;
111
+ /** 元素内部文本 */
112
+ innerText: string;
113
+ /** 元素描述(标签名+选择器) */
114
+ description?: string;
115
+ }
116
+ /**
117
+ * 页面上下文数据
118
+ */
119
+ export interface PageContext {
120
+ /** 当前页面 URL */
121
+ url: string;
122
+ /** 当前页面标题 */
123
+ title: string;
124
+ /** 选中的元素列表 */
125
+ selectedElements?: SelectedElement[];
126
+ }
package/es/types.js ADDED
File without changes