@inspecto-dev/plugin 0.2.0-alpha.1 → 0.2.0-alpha.2

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 (44) hide show
  1. package/README.md +19 -0
  2. package/dist/index.cjs +428 -101
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +433 -102
  7. package/dist/index.js.map +1 -1
  8. package/dist/legacy/rspack/index.cjs +399 -97
  9. package/dist/legacy/rspack/index.cjs.map +1 -1
  10. package/dist/legacy/rspack/index.js +404 -98
  11. package/dist/legacy/rspack/index.js.map +1 -1
  12. package/dist/legacy/rspack/loader.cjs +8 -1
  13. package/dist/legacy/rspack/loader.cjs.map +1 -1
  14. package/dist/legacy/rspack/loader.js +8 -1
  15. package/dist/legacy/rspack/loader.js.map +1 -1
  16. package/dist/legacy/webpack4/index.cjs +977 -0
  17. package/dist/legacy/webpack4/index.cjs.map +1 -0
  18. package/dist/legacy/webpack4/index.d.cts +8 -0
  19. package/dist/legacy/webpack4/index.d.ts +8 -0
  20. package/dist/legacy/webpack4/index.js +953 -0
  21. package/dist/legacy/webpack4/index.js.map +1 -0
  22. package/dist/legacy/webpack4/loader.cjs +347 -0
  23. package/dist/legacy/webpack4/loader.cjs.map +1 -0
  24. package/dist/legacy/webpack4/loader.d.cts +3 -0
  25. package/dist/legacy/webpack4/loader.d.ts +3 -0
  26. package/dist/legacy/webpack4/loader.js +314 -0
  27. package/dist/legacy/webpack4/loader.js.map +1 -0
  28. package/dist/rollup.cjs +428 -101
  29. package/dist/rollup.cjs.map +1 -1
  30. package/dist/rollup.js +433 -102
  31. package/dist/rollup.js.map +1 -1
  32. package/dist/rspack.cjs +428 -101
  33. package/dist/rspack.cjs.map +1 -1
  34. package/dist/rspack.js +433 -102
  35. package/dist/rspack.js.map +1 -1
  36. package/dist/vite.cjs +428 -101
  37. package/dist/vite.cjs.map +1 -1
  38. package/dist/vite.js +433 -102
  39. package/dist/vite.js.map +1 -1
  40. package/dist/webpack.cjs +428 -101
  41. package/dist/webpack.cjs.map +1 -1
  42. package/dist/webpack.js +433 -102
  43. package/dist/webpack.js.map +1 -1
  44. package/package.json +19 -3
@@ -0,0 +1,977 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/legacy/webpack4/index.ts
31
+ var webpack4_exports = {};
32
+ __export(webpack4_exports, {
33
+ InspectoWebpack4Plugin: () => InspectoWebpack4Plugin,
34
+ webpack4Plugin: () => webpack4Plugin
35
+ });
36
+ module.exports = __toCommonJS(webpack4_exports);
37
+
38
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.8_typescript@5.9.3_yaml@2.8.3/node_modules/tsup/assets/cjs_shims.js
39
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
40
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
41
+
42
+ // src/injectors/webpack.ts
43
+ function getWebpackHtmlScript(serverPort) {
44
+ return `
45
+ window.__AI_INSPECTOR_PORT__ = ${serverPort};
46
+ window.addEventListener('load', () => {
47
+ if (window.InspectoClient) {
48
+ window.InspectoClient.mountInspector({
49
+ serverUrl: 'http://127.0.0.1:' + window.__AI_INSPECTOR_PORT__,
50
+ });
51
+ }
52
+ });
53
+ `;
54
+ }
55
+
56
+ // src/injectors/utils.ts
57
+ var import_node_module = require("module");
58
+ var resolveClientModule = () => {
59
+ try {
60
+ return (0, import_node_module.createRequire)(importMetaUrl).resolve("@inspecto-dev/core");
61
+ } catch {
62
+ try {
63
+ return require.resolve("@inspecto-dev/core");
64
+ } catch {
65
+ console.warn(
66
+ "[inspecto] Could not resolve @inspecto-dev/core \u2014 falling back to bare specifier"
67
+ );
68
+ return "@inspecto-dev/core";
69
+ }
70
+ }
71
+ };
72
+
73
+ // src/server/index.ts
74
+ var import_node_http = __toESM(require("http"), 1);
75
+ var import_node_fs2 = __toESM(require("fs"), 1);
76
+ var import_node_path2 = __toESM(require("path"), 1);
77
+ var import_node_os2 = __toESM(require("os"), 1);
78
+ var import_node_crypto = __toESM(require("crypto"), 1);
79
+ var import_node_child_process = require("child_process");
80
+ var import_portfinder = __toESM(require("portfinder"), 1);
81
+ var import_launch_ide = require("launch-ide");
82
+ var import_types2 = require("@inspecto-dev/types");
83
+
84
+ // src/server/snippet.ts
85
+ var fs = __toESM(require("fs"), 1);
86
+ var path = __toESM(require("path"), 1);
87
+ var parser = __toESM(require("@babel/parser"), 1);
88
+ var import_traverse = __toESM(require("@babel/traverse"), 1);
89
+ var traverse = typeof import_traverse.default === "function" ? import_traverse.default : import_traverse.default.default || import_traverse.default;
90
+ var snippetCache = /* @__PURE__ */ new Map();
91
+ var DEFAULT_MAX_LINES = 100;
92
+ var DEFAULT_CONTEXT_LINES_BEFORE = 5;
93
+ async function extractSnippet(req) {
94
+ const { file, line, column, maxLines = DEFAULT_MAX_LINES } = req;
95
+ const absolutePath = path.resolve(file);
96
+ let stat;
97
+ try {
98
+ stat = await fs.promises.stat(absolutePath);
99
+ } catch {
100
+ throw new Error(`FILE_NOT_FOUND: ${absolutePath}`);
101
+ }
102
+ const mtime = stat.mtimeMs;
103
+ let lines;
104
+ const cached = snippetCache.get(absolutePath);
105
+ if (cached && cached.mtime === mtime) {
106
+ lines = cached.lines;
107
+ } else {
108
+ const source = await fs.promises.readFile(absolutePath, "utf-8");
109
+ lines = source.split("\n");
110
+ snippetCache.set(absolutePath, { mtime, lines });
111
+ }
112
+ let snippetLines;
113
+ let startLine;
114
+ let componentName;
115
+ try {
116
+ const result = extractComponentBoundary(lines.join("\n"), line, column, maxLines);
117
+ snippetLines = result.lines;
118
+ startLine = result.startLine;
119
+ componentName = result.name;
120
+ } catch {
121
+ const before = Math.max(0, line - 1 - DEFAULT_CONTEXT_LINES_BEFORE);
122
+ const after = Math.min(lines.length, before + maxLines);
123
+ snippetLines = lines.slice(before, after);
124
+ startLine = before + 1;
125
+ }
126
+ if (snippetLines.length > maxLines) {
127
+ snippetLines = snippetLines.slice(0, maxLines);
128
+ }
129
+ return {
130
+ snippet: snippetLines.join("\n"),
131
+ startLine,
132
+ file: absolutePath,
133
+ ...componentName ? { name: componentName } : {}
134
+ };
135
+ }
136
+ function extractComponentBoundary(source, targetLine, _targetColumn, maxLines) {
137
+ const ast = parser.parse(source, {
138
+ sourceType: "module",
139
+ plugins: ["jsx", "typescript", "decorators-legacy", "classProperties"],
140
+ errorRecovery: true
141
+ });
142
+ const allLines = source.split("\n");
143
+ let bestStart = 0;
144
+ let bestEnd = allLines.length - 1;
145
+ let bestName;
146
+ traverse(ast, {
147
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ClassMethod"(nodePath) {
148
+ const node = nodePath.node;
149
+ if (!node.loc) return;
150
+ const nodeStart = node.loc.start.line;
151
+ const nodeEnd = node.loc.end.line;
152
+ if (targetLine < nodeStart || targetLine > nodeEnd) return;
153
+ if (nodeEnd - nodeStart < bestEnd - bestStart) {
154
+ bestStart = nodeStart - 1;
155
+ bestEnd = nodeEnd - 1;
156
+ bestName = extractFunctionName(nodePath);
157
+ }
158
+ }
159
+ });
160
+ let sliceStart = bestStart;
161
+ let sliceEnd = bestEnd + 1;
162
+ if (sliceEnd - sliceStart > maxLines) {
163
+ const targetIdx = targetLine - 1;
164
+ sliceStart = Math.max(bestStart, targetIdx - Math.floor(maxLines / 3));
165
+ sliceEnd = sliceStart + maxLines;
166
+ if (sliceEnd > bestEnd + 1) {
167
+ sliceEnd = bestEnd + 1;
168
+ sliceStart = Math.max(0, sliceEnd - maxLines);
169
+ }
170
+ }
171
+ return {
172
+ lines: allLines.slice(sliceStart, sliceEnd),
173
+ startLine: sliceStart + 1,
174
+ ...bestName ? { name: bestName } : {}
175
+ };
176
+ }
177
+ function extractFunctionName(nodePath) {
178
+ const node = nodePath.node;
179
+ if (node.type === "FunctionDeclaration" && node.id) {
180
+ return node.id.name;
181
+ }
182
+ const parent = nodePath.parent;
183
+ if ((node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && parent.type === "VariableDeclarator" && parent.id.type === "Identifier") {
184
+ return parent.id.name;
185
+ }
186
+ if (node.type === "ClassMethod" && node.key.type === "Identifier") {
187
+ return node.key.name;
188
+ }
189
+ return void 0;
190
+ }
191
+
192
+ // src/config.ts
193
+ var import_node_fs = __toESM(require("fs"), 1);
194
+ var import_node_path = __toESM(require("path"), 1);
195
+ var import_node_os = __toESM(require("os"), 1);
196
+ var import_defu = require("defu");
197
+ var import_types = require("@inspecto-dev/types");
198
+
199
+ // src/utils/logger.ts
200
+ var LOG_LEVELS = {
201
+ silent: 0,
202
+ error: 1,
203
+ warn: 2,
204
+ info: 3
205
+ };
206
+ function isDebugEnabled(namespace) {
207
+ if (typeof process === "undefined" || !process.env) return false;
208
+ const debugEnv = process.env.DEBUG;
209
+ if (!debugEnv) return false;
210
+ const namespaces = debugEnv.split(",").map((s) => s.trim());
211
+ for (const ns of namespaces) {
212
+ if (ns === "*") return true;
213
+ if (ns.endsWith("*")) {
214
+ const prefix = ns.slice(0, -1);
215
+ if (namespace.startsWith(prefix)) return true;
216
+ } else if (ns === namespace) {
217
+ return true;
218
+ }
219
+ }
220
+ return false;
221
+ }
222
+ var globalLevel = "warn";
223
+ var registeredLoggers = /* @__PURE__ */ new Set();
224
+ function createLogger(namespace, options) {
225
+ let currentLevel = options?.logLevel ?? globalLevel;
226
+ let numericLevel = LOG_LEVELS[currentLevel] ?? 2;
227
+ const debugEnabled = isDebugEnabled(namespace);
228
+ const logger = {
229
+ setLevel(level) {
230
+ currentLevel = level;
231
+ numericLevel = LOG_LEVELS[level] ?? 2;
232
+ },
233
+ info(msg, ...args) {
234
+ if (numericLevel >= LOG_LEVELS.info) {
235
+ console.log(`\x1B[36m[inspecto]\x1B[0m ${msg}`, ...args);
236
+ }
237
+ },
238
+ warn(msg, ...args) {
239
+ if (numericLevel >= LOG_LEVELS.warn) {
240
+ console.warn(`\x1B[33m[inspecto] WARN:\x1B[0m ${msg}`, ...args);
241
+ }
242
+ },
243
+ error(msg, ...args) {
244
+ if (numericLevel >= LOG_LEVELS.error) {
245
+ console.error(`\x1B[31m[inspecto] ERROR:\x1B[0m ${msg}`, ...args);
246
+ }
247
+ },
248
+ debug(msg, ...args) {
249
+ if (debugEnabled) {
250
+ console.log(`\x1B[90m[${namespace}]\x1B[0m ${msg}`, ...args);
251
+ }
252
+ }
253
+ };
254
+ registeredLoggers.add(logger);
255
+ return logger;
256
+ }
257
+
258
+ // src/config.ts
259
+ var configLogger = createLogger("inspecto:config");
260
+ var loadedConfig = null;
261
+ var loadedPrompts = null;
262
+ var globalLogLevel = "warn";
263
+ var isWatching = false;
264
+ var arrayReplaceMerge = (0, import_defu.createDefu)((obj, key, val) => {
265
+ if (Array.isArray(val)) {
266
+ obj[key] = val;
267
+ return true;
268
+ }
269
+ });
270
+ function getGlobalLogLevel() {
271
+ return globalLogLevel;
272
+ }
273
+ function resolveConfigRoots(cwd, gitRoot) {
274
+ const roots = [];
275
+ let current = cwd;
276
+ const isUnderOrEqual = current === gitRoot || current.startsWith(gitRoot + import_node_path.default.sep);
277
+ if (!isUnderOrEqual) {
278
+ if (import_node_fs.default.existsSync(import_node_path.default.join(cwd, ".inspecto"))) roots.push(cwd);
279
+ return roots;
280
+ }
281
+ while (true) {
282
+ if (import_node_fs.default.existsSync(import_node_path.default.join(current, ".inspecto"))) {
283
+ roots.push(current);
284
+ }
285
+ if (current === gitRoot) break;
286
+ const parent = import_node_path.default.dirname(current);
287
+ if (parent === current) break;
288
+ current = parent;
289
+ }
290
+ return roots;
291
+ }
292
+ function loadUserConfigSync(force = false, cwd = process.cwd(), gitRoot) {
293
+ if (loadedConfig && !force) return loadedConfig;
294
+ loadedConfig = null;
295
+ const layers = [];
296
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
297
+ for (const root of roots) {
298
+ layers.push(readJsonSafely(import_node_path.default.join(root, ".inspecto", "settings.local.json")));
299
+ layers.push(readJsonSafely(import_node_path.default.join(root, ".inspecto", "settings.json")));
300
+ }
301
+ layers.push(readJsonSafely(import_node_path.default.join(import_node_os.default.homedir(), ".inspecto", "settings.json")));
302
+ layers.push({});
303
+ const validLayers = layers.filter((l) => l !== null);
304
+ loadedConfig = arrayReplaceMerge(...validLayers);
305
+ return loadedConfig;
306
+ }
307
+ async function loadPromptsConfig(force = false, cwd = process.cwd(), gitRoot) {
308
+ if (loadedPrompts && !force) return loadedPrompts;
309
+ const layers = [];
310
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
311
+ for (const root of roots) {
312
+ const localPath = import_node_path.default.join(root, ".inspecto", "prompts.local.json");
313
+ const jsonPath = import_node_path.default.join(root, ".inspecto", "prompts.json");
314
+ layers.push(readJsonSafely(localPath));
315
+ layers.push(readJsonSafely(jsonPath));
316
+ }
317
+ layers.push(readJsonSafely(import_node_path.default.join(import_node_os.default.homedir(), ".inspecto", "prompts.json")));
318
+ let finalPrompts = [];
319
+ for (const layer of layers) {
320
+ if (Array.isArray(layer) && layer.length > 0) {
321
+ finalPrompts = layer;
322
+ break;
323
+ }
324
+ if (layer && typeof layer === "object" && layer.$replace === true && Array.isArray(layer.items)) {
325
+ finalPrompts = layer;
326
+ break;
327
+ }
328
+ }
329
+ loadedPrompts = finalPrompts;
330
+ return loadedPrompts;
331
+ }
332
+ function readJsonSafely(filePath) {
333
+ try {
334
+ if (import_node_fs.default.existsSync(filePath)) {
335
+ const content = import_node_fs.default.readFileSync(filePath, "utf-8").trim();
336
+ if (!content) return null;
337
+ const parsed = JSON.parse(content);
338
+ if (!Array.isArray(parsed) && parsed.prompts && Array.isArray(parsed.prompts)) {
339
+ return parsed.prompts;
340
+ }
341
+ return parsed;
342
+ }
343
+ } catch (e) {
344
+ if (e instanceof SyntaxError) {
345
+ configLogger.warn(`Failed to parse config at ${filePath}: Invalid JSON`);
346
+ } else {
347
+ configLogger.warn(`Failed to read config at ${filePath}:`, e);
348
+ }
349
+ }
350
+ return null;
351
+ }
352
+ function resolveTargetTool(config, ide = "vscode") {
353
+ const defaultProvider = config["provider.default"];
354
+ if (defaultProvider) {
355
+ const tool = defaultProvider.split(".")[0];
356
+ return tool;
357
+ }
358
+ return "copilot";
359
+ }
360
+ function resolveProviderMode(tool, ide, config) {
361
+ let requestedType = void 0;
362
+ const defaultProvider = config["provider.default"];
363
+ if (defaultProvider && defaultProvider.startsWith(`${tool}.`)) {
364
+ const mode = defaultProvider.split(".")[1];
365
+ if (mode === "extension") requestedType = "extension";
366
+ if (mode === "cli") requestedType = "cli";
367
+ }
368
+ requestedType = requestedType ?? import_types.DEFAULT_PROVIDER_MODE[tool];
369
+ const valid = import_types.VALID_MODES[tool] || [import_types.DEFAULT_PROVIDER_MODE[tool]];
370
+ return requestedType && valid.includes(requestedType) ? requestedType : valid[0];
371
+ }
372
+ function extractToolOverrides(ide, config) {
373
+ const result = {};
374
+ if (!config) return result;
375
+ for (const [key, value] of Object.entries(config)) {
376
+ if (!key.startsWith("provider.")) continue;
377
+ if (key === "provider.default") continue;
378
+ const toolIndex = 1;
379
+ const modeIndex = 2;
380
+ const propIndex = 3;
381
+ const parts = key.split(".");
382
+ if (parts.length >= propIndex + 1) {
383
+ const tool = parts[toolIndex];
384
+ const mode = parts[modeIndex];
385
+ const prop = parts[propIndex];
386
+ if (!result[tool]) {
387
+ result[tool] = { type: mode };
388
+ }
389
+ const overrides = result[tool];
390
+ if (prop === "bin") overrides.binaryPath = value;
391
+ if (prop === "args") overrides.args = value;
392
+ if (prop === "cwd") overrides.cwd = value;
393
+ if (prop === "coldStartDelay") overrides.coldStartDelay = value;
394
+ }
395
+ }
396
+ return result;
397
+ }
398
+ function resolveIntents(serverPrompts) {
399
+ const baseMap = /* @__PURE__ */ new Map();
400
+ for (const intent of import_types.DEFAULT_INTENTS) {
401
+ if (intent.id) baseMap.set(intent.id, { ...intent });
402
+ }
403
+ const defaults = () => ensureOpenInEditorLast(Array.from(baseMap.values()));
404
+ if (!serverPrompts) return defaults();
405
+ const isReplace = !Array.isArray(serverPrompts) && typeof serverPrompts === "object" && serverPrompts.$replace === true;
406
+ const promptsArray = Array.isArray(serverPrompts) ? serverPrompts : isReplace ? serverPrompts.items : [];
407
+ if (!promptsArray || promptsArray.length === 0) return defaults();
408
+ if (isReplace) {
409
+ const result = [];
410
+ for (const item of promptsArray) {
411
+ if (typeof item === "string") {
412
+ if (baseMap.has(item)) {
413
+ result.push(baseMap.get(item));
414
+ } else {
415
+ configLogger.warn(
416
+ `Unknown built-in intent id: "${item}". Available: ${[...baseMap.keys()].join(", ")}`
417
+ );
418
+ }
419
+ } else if (typeof item === "object") {
420
+ if (!item.id) {
421
+ configLogger.warn('Intent object missing required "id" field, skipping.');
422
+ continue;
423
+ }
424
+ if (item.enabled === false) {
425
+ configLogger.warn(
426
+ `Intent "${item.id}" is listed in $replace but has enabled:false \u2014 it will be excluded.`
427
+ );
428
+ continue;
429
+ }
430
+ if (item.isAction && item.id !== "open-in-editor") {
431
+ configLogger.warn(
432
+ `isAction is reserved for built-in actions. Ignoring intent "${item.id}".`
433
+ );
434
+ continue;
435
+ }
436
+ result.push(baseMap.has(item.id) ? { ...baseMap.get(item.id), ...item } : item);
437
+ }
438
+ }
439
+ return ensureOpenInEditorLast(result);
440
+ }
441
+ const merged = Array.from(baseMap.values());
442
+ for (const item of promptsArray) {
443
+ if (typeof item === "string") {
444
+ if (!baseMap.has(item)) {
445
+ configLogger.warn(
446
+ `Unknown built-in intent id: "${item}". In append mode, strings have no effect on ordering \u2014 use $replace to control order.`
447
+ );
448
+ }
449
+ continue;
450
+ }
451
+ if (typeof item === "object") {
452
+ if (!item.id) {
453
+ configLogger.warn('Intent object missing required "id" field, skipping.');
454
+ continue;
455
+ }
456
+ if (item.isAction && item.id !== "open-in-editor") {
457
+ configLogger.warn(
458
+ `isAction is reserved for built-in actions. Ignoring intent "${item.id}".`
459
+ );
460
+ continue;
461
+ }
462
+ const existingIdx = merged.findIndex((i) => i.id === item.id);
463
+ if (existingIdx !== -1) {
464
+ if (item.enabled === false) {
465
+ merged.splice(existingIdx, 1);
466
+ } else {
467
+ merged[existingIdx] = { ...merged[existingIdx], ...item };
468
+ }
469
+ } else {
470
+ if (item.enabled !== false) {
471
+ merged.push(item);
472
+ }
473
+ }
474
+ }
475
+ }
476
+ return ensureOpenInEditorLast(merged);
477
+ }
478
+ function ensureOpenInEditorLast(intents) {
479
+ const idx = intents.findIndex((i) => i.id === "open-in-editor");
480
+ if (idx === -1 || idx === intents.length - 1) return intents;
481
+ const result = [...intents];
482
+ const item = result.splice(idx, 1)[0];
483
+ result.push(item);
484
+ return result;
485
+ }
486
+ var watchers = [];
487
+ function watchConfig(onReload, cwd = process.cwd(), gitRoot) {
488
+ if (isWatching) return;
489
+ isWatching = true;
490
+ const watchDirs = [import_node_path.default.join(import_node_os.default.homedir(), ".inspecto")];
491
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
492
+ for (const root of roots) {
493
+ watchDirs.push(import_node_path.default.join(root, ".inspecto"));
494
+ }
495
+ const CONFIG_FILES = /* @__PURE__ */ new Set([
496
+ "settings.json",
497
+ "settings.local.json",
498
+ "prompts.json",
499
+ "prompts.local.json"
500
+ ]);
501
+ for (const dir of watchDirs) {
502
+ if (!import_node_fs.default.existsSync(dir)) continue;
503
+ try {
504
+ const watcher = import_node_fs.default.watch(dir, async (eventType, filename) => {
505
+ if (!filename || !CONFIG_FILES.has(filename)) return;
506
+ loadedConfig = null;
507
+ loadedPrompts = null;
508
+ loadUserConfigSync(true, cwd, gitRoot);
509
+ await loadPromptsConfig(true, cwd, gitRoot);
510
+ onReload();
511
+ });
512
+ watcher.unref();
513
+ watchers.push(watcher);
514
+ } catch (e) {
515
+ }
516
+ }
517
+ }
518
+
519
+ // src/server/index.ts
520
+ var serverLogger = createLogger("inspecto:server", { logLevel: getGlobalLogLevel() });
521
+ var payloadTickets = /* @__PURE__ */ new Map();
522
+ function createTicket(payload) {
523
+ const ticketId = import_node_crypto.default.randomUUID();
524
+ payloadTickets.set(ticketId, JSON.stringify(payload));
525
+ setTimeout(
526
+ () => {
527
+ payloadTickets.delete(ticketId);
528
+ },
529
+ 5 * 60 * 1e3
530
+ );
531
+ return ticketId;
532
+ }
533
+ var serverState = {
534
+ port: null,
535
+ running: false,
536
+ projectRoot: "",
537
+ configRoot: "",
538
+ cwd: process.cwd()
539
+ };
540
+ var serverInstance = null;
541
+ function resolveProjectRoot() {
542
+ let gitRoot;
543
+ try {
544
+ serverLogger.info("Resolving project root...");
545
+ gitRoot = (0, import_node_child_process.execSync)("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();
546
+ serverLogger.info("Resolved project root: " + gitRoot);
547
+ } catch (e) {
548
+ serverLogger.error("Failed to resolve project root:", e);
549
+ gitRoot = process.cwd();
550
+ }
551
+ let current = gitRoot;
552
+ while (true) {
553
+ if (import_node_fs2.default.existsSync(import_node_path2.default.join(current, ".inspecto"))) return current;
554
+ const parent = import_node_path2.default.dirname(current);
555
+ if (parent === current) break;
556
+ current = parent;
557
+ }
558
+ return gitRoot;
559
+ }
560
+ function launchURI(uri) {
561
+ try {
562
+ if (process.platform === "darwin") {
563
+ (0, import_node_child_process.execFileSync)("open", [uri]);
564
+ } else if (process.platform === "win32") {
565
+ (0, import_node_child_process.execFileSync)("cmd", ["/c", "start", '""', uri]);
566
+ } else {
567
+ (0, import_node_child_process.execFileSync)("xdg-open", [uri]);
568
+ }
569
+ } catch (e) {
570
+ serverLogger.error("Failed to launch URI via execFileSync, falling back to launchIDE:", e);
571
+ (0, import_launch_ide.launchIDE)({ file: uri });
572
+ }
573
+ }
574
+ async function startServer() {
575
+ if (serverState.running && serverState.port !== null) {
576
+ return serverState.port;
577
+ }
578
+ serverState.projectRoot = resolveProjectRoot();
579
+ serverState.configRoot = serverState.projectRoot;
580
+ serverState.cwd = process.cwd();
581
+ import_portfinder.default.basePort = 5678;
582
+ const port = await import_portfinder.default.getPortPromise();
583
+ watchConfig(
584
+ () => {
585
+ serverLogger.info("user config reloaded.");
586
+ },
587
+ serverState.cwd,
588
+ serverState.configRoot
589
+ );
590
+ serverInstance = import_node_http.default.createServer((req, res) => {
591
+ res.setHeader("Access-Control-Allow-Origin", "*");
592
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
593
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
594
+ if (req.method === "OPTIONS") {
595
+ res.writeHead(204);
596
+ res.end();
597
+ return;
598
+ }
599
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
600
+ handleRequest(url, req, res).catch((err) => {
601
+ serverLogger.error("server error:", err);
602
+ res.writeHead(500, { "Content-Type": "application/json" });
603
+ res.end(JSON.stringify({ success: false, error: String(err) }));
604
+ });
605
+ });
606
+ await new Promise((resolve2, reject) => {
607
+ serverInstance.listen(port, "127.0.0.1", () => {
608
+ serverInstance.unref();
609
+ resolve2();
610
+ });
611
+ serverInstance.once("error", reject);
612
+ });
613
+ serverInstance.on("error", (err) => {
614
+ serverLogger.error("persistent server error:", err);
615
+ });
616
+ serverState.port = port;
617
+ serverState.running = true;
618
+ const portFile = import_node_path2.default.join(import_node_os2.default.tmpdir(), "inspecto.port.json");
619
+ try {
620
+ let portData = {};
621
+ if (import_node_fs2.default.existsSync(portFile)) {
622
+ try {
623
+ portData = JSON.parse(import_node_fs2.default.readFileSync(portFile, "utf-8"));
624
+ } catch (e) {
625
+ }
626
+ }
627
+ const rootHash = import_node_crypto.default.createHash("md5").update(serverState.projectRoot).digest("hex");
628
+ portData[rootHash] = port;
629
+ import_node_fs2.default.writeFileSync(portFile, JSON.stringify(portData, null, 2), "utf-8");
630
+ } catch (e) {
631
+ serverLogger.warn("Failed to write port file:", e);
632
+ }
633
+ process.once("exit", () => {
634
+ try {
635
+ if (import_node_fs2.default.existsSync(portFile)) {
636
+ const portData = JSON.parse(import_node_fs2.default.readFileSync(portFile, "utf-8"));
637
+ const rootHash = import_node_crypto.default.createHash("md5").update(serverState.projectRoot).digest("hex");
638
+ delete portData[rootHash];
639
+ if (Object.keys(portData).length === 0) {
640
+ import_node_fs2.default.unlinkSync(portFile);
641
+ } else {
642
+ import_node_fs2.default.writeFileSync(portFile, JSON.stringify(portData, null, 2), "utf-8");
643
+ }
644
+ }
645
+ } catch {
646
+ }
647
+ });
648
+ serverLogger.info(`server running at http://127.0.0.1:${port}`);
649
+ return port;
650
+ }
651
+ async function readBody(req) {
652
+ return new Promise((resolve2, reject) => {
653
+ const chunks = [];
654
+ req.on("data", (chunk) => chunks.push(chunk));
655
+ req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
656
+ req.on("error", reject);
657
+ });
658
+ }
659
+ async function handleRequest(url, req, res) {
660
+ const pathname = url.pathname;
661
+ if ((pathname === "/health" || pathname === import_types2.INSPECTO_API_PATHS.HEALTH) && req.method === "GET") {
662
+ res.writeHead(200, { "Content-Type": "application/json" });
663
+ res.end(JSON.stringify({ ok: true, port: serverState.port }));
664
+ return;
665
+ }
666
+ if (pathname === import_types2.INSPECTO_API_PATHS.CLIENT_CONFIG && req.method === "GET") {
667
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
668
+ const promptsConfig = await loadPromptsConfig(false, serverState.cwd, serverState.configRoot);
669
+ const effectiveIde = userConfig.ide ?? "vscode";
670
+ let info;
671
+ if (!serverState.ideInfo) {
672
+ info = {
673
+ ide: effectiveIde
674
+ };
675
+ } else {
676
+ const { scheme: _scheme, ...rest } = serverState.ideInfo;
677
+ info = rest;
678
+ }
679
+ const config = {
680
+ ...info,
681
+ prompts: resolveIntents(promptsConfig),
682
+ hotKeys: userConfig["inspector.hotKey"] ?? "alt",
683
+ theme: userConfig["inspector.theme"] ?? "auto",
684
+ includeSnippet: userConfig["prompt.includeSnippet"] ?? false,
685
+ autoSend: userConfig["prompt.autoSend"] ?? false
686
+ };
687
+ delete config.providers;
688
+ res.writeHead(200, { "Content-Type": "application/json" });
689
+ res.end(JSON.stringify(config));
690
+ return;
691
+ }
692
+ if (pathname === import_types2.INSPECTO_API_PATHS.IDE_INFO && req.method === "POST") {
693
+ try {
694
+ const body = JSON.parse(await readBody(req));
695
+ const ideWorkspace = body.workspaceRoot || "";
696
+ const serverProjectRoot = serverState.projectRoot || "";
697
+ const isSameProject = !ideWorkspace || !serverProjectRoot || ideWorkspace === serverProjectRoot || serverProjectRoot.startsWith(ideWorkspace);
698
+ if (isSameProject) {
699
+ serverState.ideInfo = body;
700
+ serverLogger.debug(
701
+ `Accepted IDE info from matched workspace (ide-${body.ide} / schema-${body.scheme})`
702
+ );
703
+ } else {
704
+ serverLogger.debug(
705
+ `Ignored IDE info from unrelated workspace (IDE Workspace: ${ideWorkspace}, Server: ${serverProjectRoot}, Scheme: ${body.scheme}, IDE: ${body.ide})`
706
+ );
707
+ }
708
+ res.writeHead(200, { "Content-Type": "application/json" });
709
+ res.end(JSON.stringify({ success: true }));
710
+ } catch (e) {
711
+ serverLogger.error(`Error parsing ${import_types2.INSPECTO_API_PATHS.IDE_INFO} POST request:`, e);
712
+ res.writeHead(400, { "Content-Type": "application/json" });
713
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
714
+ }
715
+ return;
716
+ }
717
+ if (pathname === import_types2.INSPECTO_API_PATHS.IDE_OPEN && req.method === "POST") {
718
+ let body;
719
+ try {
720
+ body = JSON.parse(await readBody(req));
721
+ } catch (e) {
722
+ res.writeHead(400, { "Content-Type": "application/json" });
723
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
724
+ return;
725
+ }
726
+ const absolutePath = import_node_path2.default.isAbsolute(body.file) ? import_node_path2.default.resolve(body.file) : import_node_path2.default.resolve(serverState.cwd, body.file);
727
+ const relativeToRoot = import_node_path2.default.relative(serverState.projectRoot, absolutePath);
728
+ if (relativeToRoot.startsWith("..") || import_node_path2.default.isAbsolute(relativeToRoot)) {
729
+ serverLogger.warn(`Security: Blocked path traversal attempt in IDE_OPEN: ${body.file}`);
730
+ res.writeHead(403, { "Content-Type": "application/json" });
731
+ res.end(JSON.stringify({ error: "Access denied: File is outside of project workspace" }));
732
+ return;
733
+ }
734
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
735
+ const configuredIde = userConfig.ide;
736
+ const activeIde = serverState.ideInfo?.ide;
737
+ const activeIdeScheme = serverState.ideInfo?.scheme;
738
+ const rawEditorHint = configuredIde || activeIde || activeIdeScheme || "code";
739
+ if (configuredIde && activeIdeScheme && !activeIdeScheme.includes(configuredIde)) {
740
+ serverLogger.warn(
741
+ `Active IDE is ${activeIdeScheme}, but config forces ${configuredIde}. Using configured IDE.`
742
+ );
743
+ }
744
+ let editorHint = rawEditorHint;
745
+ if (rawEditorHint === "vscode") editorHint = "code";
746
+ else if (rawEditorHint === "vscode-insiders") editorHint = "code-insiders";
747
+ else if (rawEditorHint === "vscodium") editorHint = "codium";
748
+ else if (rawEditorHint === "trae-cn" || rawEditorHint === "trae") editorHint = "trae";
749
+ serverLogger.debug(
750
+ `IDE_OPEN: activeIde=${activeIde}, activeIdeScheme=${activeIdeScheme}, configuredIde=${configuredIde} -> rawEditorHint=${rawEditorHint}, finalEditorHint=${editorHint}`
751
+ );
752
+ const VSCODE_FAMILY_SCHEMES = [
753
+ "vscode",
754
+ "vscode-insiders",
755
+ "cursor",
756
+ "windsurf",
757
+ "trae",
758
+ "trae-cn",
759
+ "vscodium",
760
+ "codebuddy",
761
+ "codebuddy-cn",
762
+ "antigravity"
763
+ ];
764
+ if (VSCODE_FAMILY_SCHEMES.includes(rawEditorHint)) {
765
+ const uri = `${rawEditorHint}://file${absolutePath}:${body.line}:${body.column}`;
766
+ serverLogger.debug(`IDE_OPEN: Bypassing launchIDE, using URI scheme directly: ${uri}`);
767
+ try {
768
+ if (process.platform === "darwin") {
769
+ (0, import_node_child_process.execFileSync)("open", [uri]);
770
+ } else if (process.platform === "win32") {
771
+ (0, import_node_child_process.execFileSync)("cmd", ["/c", "start", '""', uri]);
772
+ } else {
773
+ (0, import_node_child_process.execFileSync)("xdg-open", [uri]);
774
+ }
775
+ } catch (e) {
776
+ serverLogger.error(`Failed to launch URI for IDE_OPEN (${uri}):`, e);
777
+ (0, import_launch_ide.launchIDE)({
778
+ file: absolutePath,
779
+ line: body.line,
780
+ column: body.column,
781
+ editor: editorHint,
782
+ type: process.platform === "darwin" ? "open" : "exec"
783
+ });
784
+ }
785
+ } else {
786
+ (0, import_launch_ide.launchIDE)({
787
+ file: absolutePath,
788
+ line: body.line,
789
+ column: body.column,
790
+ editor: editorHint,
791
+ type: process.platform === "darwin" ? "open" : "exec"
792
+ });
793
+ }
794
+ res.writeHead(200, { "Content-Type": "application/json" });
795
+ res.end(JSON.stringify({ success: true }));
796
+ return;
797
+ }
798
+ if (pathname === import_types2.INSPECTO_API_PATHS.PROJECT_SNIPPET && req.method === "GET") {
799
+ const file = url.searchParams.get("file") ?? "";
800
+ const line = parseInt(url.searchParams.get("line") ?? "1", 10);
801
+ const column = parseInt(url.searchParams.get("column") ?? "1", 10);
802
+ const maxLines = parseInt(url.searchParams.get("maxLines") ?? "100", 10);
803
+ try {
804
+ const absolutePath = import_node_path2.default.isAbsolute(file) ? import_node_path2.default.resolve(file) : import_node_path2.default.resolve(serverState.cwd, file);
805
+ const relativeToRoot = import_node_path2.default.relative(serverState.projectRoot, absolutePath);
806
+ if (relativeToRoot.startsWith("..") || import_node_path2.default.isAbsolute(relativeToRoot)) {
807
+ serverLogger.warn(`Security: Blocked path traversal attempt in PROJECT_SNIPPET: ${file}`);
808
+ res.writeHead(403, { "Content-Type": "application/json" });
809
+ res.end(
810
+ JSON.stringify({
811
+ success: false,
812
+ error: "Access denied: File is outside of project workspace",
813
+ errorCode: "FORBIDDEN"
814
+ })
815
+ );
816
+ return;
817
+ }
818
+ const result = await extractSnippet({ file: absolutePath, line, column, maxLines });
819
+ res.writeHead(200, { "Content-Type": "application/json" });
820
+ res.end(JSON.stringify(result));
821
+ } catch (err) {
822
+ const message = String(err.message || err);
823
+ const errorCode = message.startsWith("FILE_NOT_FOUND") ? "FILE_NOT_FOUND" : "UNKNOWN";
824
+ res.writeHead(404, { "Content-Type": "application/json" });
825
+ res.end(JSON.stringify({ success: false, error: message, errorCode }));
826
+ }
827
+ return;
828
+ }
829
+ if (pathname === import_types2.INSPECTO_API_PATHS.AI_DISPATCH && req.method === "POST") {
830
+ try {
831
+ const rawBody = await readBody(req);
832
+ const body = JSON.parse(rawBody);
833
+ const result = await dispatchToAi(body);
834
+ res.writeHead(result.success ? 200 : 500, { "Content-Type": "application/json" });
835
+ res.end(JSON.stringify(result));
836
+ } catch (e) {
837
+ serverLogger.error(`Error parsing ${import_types2.INSPECTO_API_PATHS.AI_DISPATCH} request:`, e);
838
+ res.writeHead(500, { "Content-Type": "application/json" });
839
+ res.end(JSON.stringify({ success: false, error: String(e), errorCode: "INTERNAL_ERROR" }));
840
+ }
841
+ return;
842
+ }
843
+ if (pathname.startsWith(`${import_types2.INSPECTO_API_PATHS.AI_TICKET}/`) && req.method === "GET") {
844
+ const ticketId = pathname.substring(import_types2.INSPECTO_API_PATHS.AI_TICKET.length + 1);
845
+ const payloadStr = payloadTickets.get(ticketId);
846
+ if (!payloadStr) {
847
+ res.writeHead(404, { "Content-Type": "application/json" });
848
+ res.end(JSON.stringify({ success: false, error: "Ticket not found or expired" }));
849
+ return;
850
+ }
851
+ res.writeHead(200, { "Content-Type": "application/json" });
852
+ res.end(payloadStr);
853
+ return;
854
+ }
855
+ res.writeHead(404, { "Content-Type": "application/json" });
856
+ res.end(JSON.stringify({ error: "not found" }));
857
+ }
858
+ async function dispatchToAi(req) {
859
+ const { location, snippet, prompt } = req;
860
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
861
+ const resolvedTarget = resolveTargetTool(userConfig);
862
+ const formattedPrompt = prompt ?? `Please help me with this code from \`${location.file}\` (line ${location.line}):
863
+
864
+ \`\`\`
865
+ ${snippet}
866
+ \`\`\`
867
+ `;
868
+ const ideReportedMode = serverState.ideInfo?.providers[resolvedTarget]?.mode;
869
+ const configuredIde = userConfig.ide;
870
+ const activeIde = serverState.ideInfo?.ide;
871
+ const activeIdeScheme = serverState.ideInfo?.scheme;
872
+ const finalIde = configuredIde || activeIdeScheme || activeIde || "vscode";
873
+ if (configuredIde && activeIdeScheme && !activeIdeScheme.includes(configuredIde)) {
874
+ serverLogger.warn(
875
+ `dispatchToAi: Active IDE is ${activeIdeScheme}, but config forces ${configuredIde}. Using configured IDE.`
876
+ );
877
+ }
878
+ const mode = resolveProviderMode(resolvedTarget, finalIde, userConfig);
879
+ const overrides = extractToolOverrides(finalIde, userConfig)[resolvedTarget] || {};
880
+ overrides.type = mode;
881
+ const fullPayload = {
882
+ ide: finalIde,
883
+ target: resolvedTarget,
884
+ targetType: mode,
885
+ prompt: formattedPrompt,
886
+ filePath: location.file,
887
+ line: location.line,
888
+ column: location.column,
889
+ snippet,
890
+ overrides: Object.keys(overrides).length > 0 ? overrides : void 0,
891
+ autoSend: userConfig["prompt.autoSend"] !== void 0 ? Boolean(userConfig["prompt.autoSend"]) : void 0
892
+ };
893
+ const ticketId = createTicket(fullPayload);
894
+ const params = new URLSearchParams();
895
+ params.set("ticket", ticketId);
896
+ params.set("target", resolvedTarget);
897
+ const uri = `${finalIde}://inspecto.inspecto/send?${params.toString()}`;
898
+ serverLogger.debug(`dispatchToAi: Generated URI: ${uri}`);
899
+ launchURI(uri);
900
+ return {
901
+ success: true,
902
+ fallbackPayload: {
903
+ prompt: formattedPrompt,
904
+ file: location.file
905
+ }
906
+ };
907
+ }
908
+
909
+ // src/legacy/webpack4/index.ts
910
+ var import_node_path3 = __toESM(require("path"), 1);
911
+ var InspectoWebpack4Plugin = class {
912
+ constructor(options = {}) {
913
+ this.options = options;
914
+ }
915
+ apply(compiler) {
916
+ const clientPath = resolveClientModule();
917
+ compiler.hooks.afterEnvironment.tap("InspectoWebpack4Plugin", () => {
918
+ const inspectoLoader = import_node_path3.default.resolve(__dirname, "loader.cjs");
919
+ compiler.options.module.rules.push({
920
+ test: /\.[jt]sx?$/,
921
+ enforce: "pre",
922
+ exclude: /node_modules/,
923
+ use: [
924
+ {
925
+ loader: inspectoLoader,
926
+ options: {
927
+ ...this.options,
928
+ clientPath
929
+ }
930
+ }
931
+ ]
932
+ });
933
+ });
934
+ compiler.hooks.compilation.tap("InspectoWebpack4Plugin", (compilation) => {
935
+ const htmlPlugin = compiler.options.plugins.find(
936
+ (p) => p && p.constructor && p.constructor.name === "HtmlWebpackPlugin"
937
+ );
938
+ const HtmlWebpackPlugin = htmlPlugin ? htmlPlugin.constructor : null;
939
+ if (HtmlWebpackPlugin && HtmlWebpackPlugin.getHooks) {
940
+ HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(
941
+ "InspectoWebpack4Plugin",
942
+ async (data, cb) => {
943
+ const port = await startServer();
944
+ data.headTags.unshift({
945
+ tagName: "script",
946
+ voidTag: false,
947
+ attributes: { "data-plugin": "inspecto-overlay" },
948
+ innerHTML: getWebpackHtmlScript(port)
949
+ });
950
+ cb(null, data);
951
+ }
952
+ );
953
+ } else if (compilation.hooks.htmlWebpackPluginAlterAssetTags) {
954
+ compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(
955
+ "InspectoWebpack4Plugin",
956
+ async (data, cb) => {
957
+ const port = await startServer();
958
+ data.head.unshift({
959
+ tagName: "script",
960
+ voidTag: false,
961
+ attributes: { "data-plugin": "inspecto-overlay" },
962
+ innerHTML: getWebpackHtmlScript(port)
963
+ });
964
+ cb(null, data);
965
+ }
966
+ );
967
+ }
968
+ });
969
+ }
970
+ };
971
+ var webpack4Plugin = (options) => new InspectoWebpack4Plugin(options);
972
+ // Annotate the CommonJS export names for ESM import in node:
973
+ 0 && (module.exports = {
974
+ InspectoWebpack4Plugin,
975
+ webpack4Plugin
976
+ });
977
+ //# sourceMappingURL=index.cjs.map