@inspecto-dev/plugin 0.2.0-alpha.0

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -0
  3. package/dist/index.cjs +1098 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +34 -0
  6. package/dist/index.d.ts +34 -0
  7. package/dist/index.js +1058 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/legacy/rspack/index.cjs +696 -0
  10. package/dist/legacy/rspack/index.cjs.map +1 -0
  11. package/dist/legacy/rspack/index.d.cts +10 -0
  12. package/dist/legacy/rspack/index.d.ts +10 -0
  13. package/dist/legacy/rspack/index.js +668 -0
  14. package/dist/legacy/rspack/index.js.map +1 -0
  15. package/dist/legacy/rspack/loader.cjs +310 -0
  16. package/dist/legacy/rspack/loader.cjs.map +1 -0
  17. package/dist/legacy/rspack/loader.d.cts +3 -0
  18. package/dist/legacy/rspack/loader.d.ts +3 -0
  19. package/dist/legacy/rspack/loader.js +277 -0
  20. package/dist/legacy/rspack/loader.js.map +1 -0
  21. package/dist/rollup.cjs +1098 -0
  22. package/dist/rollup.cjs.map +1 -0
  23. package/dist/rollup.d.cts +5 -0
  24. package/dist/rollup.d.ts +5 -0
  25. package/dist/rollup.js +1058 -0
  26. package/dist/rollup.js.map +1 -0
  27. package/dist/rspack.cjs +1098 -0
  28. package/dist/rspack.cjs.map +1 -0
  29. package/dist/rspack.d.cts +5 -0
  30. package/dist/rspack.d.ts +5 -0
  31. package/dist/rspack.js +1058 -0
  32. package/dist/rspack.js.map +1 -0
  33. package/dist/vite.cjs +1098 -0
  34. package/dist/vite.cjs.map +1 -0
  35. package/dist/vite.d.cts +5 -0
  36. package/dist/vite.d.ts +5 -0
  37. package/dist/vite.js +1058 -0
  38. package/dist/vite.js.map +1 -0
  39. package/dist/webpack.cjs +1098 -0
  40. package/dist/webpack.cjs.map +1 -0
  41. package/dist/webpack.d.cts +5 -0
  42. package/dist/webpack.d.ts +5 -0
  43. package/dist/webpack.js +1058 -0
  44. package/dist/webpack.js.map +1 -0
  45. package/legacy/rspack/index.cjs +1 -0
  46. package/legacy/rspack/index.d.ts +1 -0
  47. package/legacy/rspack/index.js +2 -0
  48. package/legacy/rspack/package.json +5 -0
  49. package/package.json +97 -0
@@ -0,0 +1,696 @@
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/rspack/index.ts
31
+ var rspack_exports = {};
32
+ __export(rspack_exports, {
33
+ InspectoRspackLegacyPlugin: () => InspectoRspackLegacyPlugin,
34
+ default: () => rspack_default,
35
+ rspackPlugin: () => rspackPlugin
36
+ });
37
+ module.exports = __toCommonJS(rspack_exports);
38
+
39
+ // ../../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
40
+ 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;
41
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
42
+
43
+ // src/server/index.ts
44
+ var import_node_http = __toESM(require("http"), 1);
45
+ var import_node_fs2 = __toESM(require("fs"), 1);
46
+ var import_node_path2 = __toESM(require("path"), 1);
47
+ var import_node_os2 = __toESM(require("os"), 1);
48
+ var import_node_child_process = require("child_process");
49
+ var import_portfinder = __toESM(require("portfinder"), 1);
50
+ var import_launch_ide = require("launch-ide");
51
+
52
+ // src/server/snippet.ts
53
+ var fs = __toESM(require("fs"), 1);
54
+ var path = __toESM(require("path"), 1);
55
+ var parser = __toESM(require("@babel/parser"), 1);
56
+ var import_traverse = __toESM(require("@babel/traverse"), 1);
57
+ var traverse = typeof import_traverse.default === "function" ? import_traverse.default : import_traverse.default.default || import_traverse.default;
58
+ var snippetCache = /* @__PURE__ */ new Map();
59
+ var DEFAULT_MAX_LINES = 100;
60
+ var DEFAULT_CONTEXT_LINES_BEFORE = 5;
61
+ async function extractSnippet(req) {
62
+ const { file, line, column, maxLines = DEFAULT_MAX_LINES } = req;
63
+ const absolutePath = path.resolve(file);
64
+ let stat;
65
+ try {
66
+ stat = await fs.promises.stat(absolutePath);
67
+ } catch {
68
+ throw new Error(`FILE_NOT_FOUND: ${absolutePath}`);
69
+ }
70
+ const mtime = stat.mtimeMs;
71
+ let lines;
72
+ const cached = snippetCache.get(absolutePath);
73
+ if (cached && cached.mtime === mtime) {
74
+ lines = cached.lines;
75
+ } else {
76
+ const source = await fs.promises.readFile(absolutePath, "utf-8");
77
+ lines = source.split("\n");
78
+ snippetCache.set(absolutePath, { mtime, lines });
79
+ }
80
+ let snippetLines;
81
+ let startLine;
82
+ let componentName;
83
+ try {
84
+ const result = extractComponentBoundary(lines.join("\n"), line, column, maxLines);
85
+ snippetLines = result.lines;
86
+ startLine = result.startLine;
87
+ componentName = result.name;
88
+ } catch {
89
+ const before = Math.max(0, line - 1 - DEFAULT_CONTEXT_LINES_BEFORE);
90
+ const after = Math.min(lines.length, before + maxLines);
91
+ snippetLines = lines.slice(before, after);
92
+ startLine = before + 1;
93
+ }
94
+ if (snippetLines.length > maxLines) {
95
+ snippetLines = snippetLines.slice(0, maxLines);
96
+ }
97
+ return {
98
+ snippet: snippetLines.join("\n"),
99
+ startLine,
100
+ file: absolutePath,
101
+ ...componentName ? { name: componentName } : {}
102
+ };
103
+ }
104
+ function extractComponentBoundary(source, targetLine, _targetColumn, maxLines) {
105
+ const ast = parser.parse(source, {
106
+ sourceType: "module",
107
+ plugins: ["jsx", "typescript", "decorators-legacy", "classProperties"],
108
+ errorRecovery: true
109
+ });
110
+ const allLines = source.split("\n");
111
+ let bestStart = 0;
112
+ let bestEnd = allLines.length - 1;
113
+ let bestName;
114
+ traverse(ast, {
115
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ClassMethod"(nodePath) {
116
+ const node = nodePath.node;
117
+ if (!node.loc) return;
118
+ const nodeStart = node.loc.start.line;
119
+ const nodeEnd = node.loc.end.line;
120
+ if (targetLine < nodeStart || targetLine > nodeEnd) return;
121
+ if (nodeEnd - nodeStart < bestEnd - bestStart) {
122
+ bestStart = nodeStart - 1;
123
+ bestEnd = nodeEnd - 1;
124
+ bestName = extractFunctionName(nodePath);
125
+ }
126
+ }
127
+ });
128
+ let sliceStart = bestStart;
129
+ let sliceEnd = bestEnd + 1;
130
+ if (sliceEnd - sliceStart > maxLines) {
131
+ const targetIdx = targetLine - 1;
132
+ sliceStart = Math.max(bestStart, targetIdx - Math.floor(maxLines / 3));
133
+ sliceEnd = sliceStart + maxLines;
134
+ if (sliceEnd > bestEnd + 1) {
135
+ sliceEnd = bestEnd + 1;
136
+ sliceStart = Math.max(0, sliceEnd - maxLines);
137
+ }
138
+ }
139
+ return {
140
+ lines: allLines.slice(sliceStart, sliceEnd),
141
+ startLine: sliceStart + 1,
142
+ ...bestName ? { name: bestName } : {}
143
+ };
144
+ }
145
+ function extractFunctionName(nodePath) {
146
+ const node = nodePath.node;
147
+ if (node.type === "FunctionDeclaration" && node.id) {
148
+ return node.id.name;
149
+ }
150
+ const parent = nodePath.parent;
151
+ if ((node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && parent.type === "VariableDeclarator" && parent.id.type === "Identifier") {
152
+ return parent.id.name;
153
+ }
154
+ if (node.type === "ClassMethod" && node.key.type === "Identifier") {
155
+ return node.key.name;
156
+ }
157
+ return void 0;
158
+ }
159
+
160
+ // src/config.ts
161
+ var import_node_fs = __toESM(require("fs"), 1);
162
+ var import_node_path = __toESM(require("path"), 1);
163
+ var import_node_os = __toESM(require("os"), 1);
164
+ var import_defu = require("defu");
165
+ var import_types = require("@inspecto-dev/types");
166
+ var loadedConfig = null;
167
+ var loadedPrompts = null;
168
+ var isWatching = false;
169
+ var arrayReplaceMerge = (0, import_defu.createDefu)((obj, key, val) => {
170
+ if (Array.isArray(val)) {
171
+ obj[key] = val;
172
+ return true;
173
+ }
174
+ });
175
+ function resolveConfigRoots(cwd, gitRoot) {
176
+ const roots = [];
177
+ let current = cwd;
178
+ const isUnderOrEqual = current === gitRoot || current.startsWith(gitRoot + import_node_path.default.sep);
179
+ if (!isUnderOrEqual) {
180
+ if (import_node_fs.default.existsSync(import_node_path.default.join(cwd, ".inspecto"))) roots.push(cwd);
181
+ return roots;
182
+ }
183
+ while (true) {
184
+ if (import_node_fs.default.existsSync(import_node_path.default.join(current, ".inspecto"))) {
185
+ roots.push(current);
186
+ }
187
+ if (current === gitRoot) break;
188
+ const parent = import_node_path.default.dirname(current);
189
+ if (parent === current) break;
190
+ current = parent;
191
+ }
192
+ return roots;
193
+ }
194
+ function loadUserConfigSync(force = false, cwd = process.cwd(), gitRoot) {
195
+ if (loadedConfig && !force) return loadedConfig;
196
+ loadedConfig = null;
197
+ const layers = [];
198
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
199
+ for (const root of roots) {
200
+ layers.push(readJsonSafely(import_node_path.default.join(root, ".inspecto", "settings.local.json")));
201
+ layers.push(readJsonSafely(import_node_path.default.join(root, ".inspecto", "settings.json")));
202
+ }
203
+ layers.push(readJsonSafely(import_node_path.default.join(import_node_os.default.homedir(), ".inspecto", "settings.json")));
204
+ layers.push({ providers: {} });
205
+ const validLayers = layers.filter((l) => l !== null);
206
+ loadedConfig = arrayReplaceMerge(...validLayers);
207
+ return loadedConfig;
208
+ }
209
+ async function loadPromptsConfig(force = false, cwd = process.cwd(), gitRoot) {
210
+ if (loadedPrompts && !force) return loadedPrompts;
211
+ const layers = [];
212
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
213
+ for (const root of roots) {
214
+ const localPath = import_node_path.default.join(root, ".inspecto", "prompts.local.json");
215
+ const jsonPath = import_node_path.default.join(root, ".inspecto", "prompts.json");
216
+ layers.push(readJsonSafely(localPath));
217
+ layers.push(readJsonSafely(jsonPath));
218
+ }
219
+ layers.push(readJsonSafely(import_node_path.default.join(import_node_os.default.homedir(), ".inspecto", "prompts.json")));
220
+ let finalPrompts = [];
221
+ for (const layer of layers) {
222
+ if (Array.isArray(layer) && layer.length > 0) {
223
+ finalPrompts = layer;
224
+ break;
225
+ }
226
+ if (layer && typeof layer === "object" && layer.$replace === true && Array.isArray(layer.items)) {
227
+ finalPrompts = layer;
228
+ break;
229
+ }
230
+ }
231
+ loadedPrompts = finalPrompts;
232
+ return loadedPrompts;
233
+ }
234
+ function readJsonSafely(filePath) {
235
+ try {
236
+ if (import_node_fs.default.existsSync(filePath)) {
237
+ const content = import_node_fs.default.readFileSync(filePath, "utf-8").trim();
238
+ if (!content) return null;
239
+ const parsed = JSON.parse(content);
240
+ if (!Array.isArray(parsed) && parsed.prompts && Array.isArray(parsed.prompts)) {
241
+ return parsed.prompts;
242
+ }
243
+ return parsed;
244
+ }
245
+ } catch (e) {
246
+ if (e instanceof SyntaxError) {
247
+ console.warn(`[inspecto] Failed to parse config at ${filePath}: Invalid JSON`);
248
+ } else {
249
+ console.warn(`[inspecto] Failed to read config at ${filePath}:`, e);
250
+ }
251
+ }
252
+ return null;
253
+ }
254
+ function resolveTargetTool(config) {
255
+ if (config.prefer) {
256
+ return config.prefer;
257
+ }
258
+ if (config.providers && Object.keys(config.providers).length > 0) {
259
+ return Object.keys(config.providers)[0];
260
+ }
261
+ return "github-copilot";
262
+ }
263
+ function resolveToolMode(tool, ide, config) {
264
+ let requestedType = void 0;
265
+ if (config.providers && config.providers[tool] && config.providers[tool].type) {
266
+ const type = config.providers[tool].type;
267
+ if (type === "plugin" || type === "cli") {
268
+ requestedType = type;
269
+ }
270
+ }
271
+ requestedType = requestedType ?? import_types.DEFAULT_TOOL_MODE[tool];
272
+ const valid = import_types.VALID_MODES[tool] || [import_types.DEFAULT_TOOL_MODE[tool]];
273
+ return requestedType && valid.includes(requestedType) ? requestedType : valid[0];
274
+ }
275
+ function extractToolOverrides(ide, config) {
276
+ const result = {};
277
+ if (!config.providers) return result;
278
+ for (const [tool, cfg] of Object.entries(config.providers)) {
279
+ if (!cfg) continue;
280
+ const overrides = {
281
+ type: cfg.type || import_types.DEFAULT_TOOL_MODE[tool] || "plugin"
282
+ };
283
+ if (cfg.bin) overrides.binaryPath = cfg.bin;
284
+ if (cfg.args) overrides.args = cfg.args;
285
+ if (cfg.cwd) overrides.cwd = cfg.cwd;
286
+ if (cfg.autoSend !== void 0) overrides.autoSend = cfg.autoSend;
287
+ result[tool] = overrides;
288
+ }
289
+ return result;
290
+ }
291
+ var watchers = [];
292
+ function watchConfig(onReload, cwd = process.cwd(), gitRoot) {
293
+ if (isWatching) return;
294
+ isWatching = true;
295
+ const watchDirs = [import_node_path.default.join(import_node_os.default.homedir(), ".inspecto")];
296
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
297
+ for (const root of roots) {
298
+ watchDirs.push(import_node_path.default.join(root, ".inspecto"));
299
+ }
300
+ const CONFIG_FILES = /* @__PURE__ */ new Set([
301
+ "settings.json",
302
+ "settings.local.json",
303
+ "prompts.json",
304
+ "prompts.local.json"
305
+ ]);
306
+ for (const dir of watchDirs) {
307
+ if (!import_node_fs.default.existsSync(dir)) continue;
308
+ try {
309
+ const watcher = import_node_fs.default.watch(dir, async (eventType, filename) => {
310
+ if (!filename || !CONFIG_FILES.has(filename)) return;
311
+ loadedConfig = null;
312
+ loadedPrompts = null;
313
+ loadUserConfigSync(true, cwd, gitRoot);
314
+ await loadPromptsConfig(true, cwd, gitRoot);
315
+ onReload();
316
+ });
317
+ watcher.unref();
318
+ watchers.push(watcher);
319
+ } catch (e) {
320
+ }
321
+ }
322
+ }
323
+
324
+ // src/server/index.ts
325
+ var serverState = {
326
+ port: null,
327
+ running: false,
328
+ projectRoot: "",
329
+ configRoot: "",
330
+ cwd: process.cwd()
331
+ };
332
+ var serverInstance = null;
333
+ function resolveProjectRoot() {
334
+ let gitRoot;
335
+ try {
336
+ gitRoot = (0, import_node_child_process.execSync)("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();
337
+ } catch {
338
+ gitRoot = process.cwd();
339
+ }
340
+ let current = gitRoot;
341
+ while (true) {
342
+ if (import_node_fs2.default.existsSync(import_node_path2.default.join(current, ".inspecto"))) return current;
343
+ const parent = import_node_path2.default.dirname(current);
344
+ if (parent === current) break;
345
+ current = parent;
346
+ }
347
+ return gitRoot;
348
+ }
349
+ function launchURI(uri) {
350
+ try {
351
+ if (process.platform === "darwin") {
352
+ (0, import_node_child_process.execFileSync)("open", [uri]);
353
+ } else if (process.platform === "win32") {
354
+ (0, import_node_child_process.execFileSync)("cmd", ["/c", "start", '""', uri]);
355
+ } else {
356
+ (0, import_node_child_process.execFileSync)("xdg-open", [uri]);
357
+ }
358
+ } catch (e) {
359
+ console.error("[inspecto] Failed to launch URI via execFileSync, falling back to launchIDE:", e);
360
+ (0, import_launch_ide.launchIDE)({ file: uri });
361
+ }
362
+ }
363
+ async function startServer() {
364
+ if (serverState.running && serverState.port !== null) {
365
+ return serverState.port;
366
+ }
367
+ serverState.projectRoot = resolveProjectRoot();
368
+ serverState.configRoot = serverState.projectRoot;
369
+ serverState.cwd = process.cwd();
370
+ import_portfinder.default.basePort = 5678;
371
+ const port = await import_portfinder.default.getPortPromise();
372
+ watchConfig(
373
+ () => {
374
+ console.log("[inspecto] user config reloaded.");
375
+ },
376
+ serverState.cwd,
377
+ serverState.configRoot
378
+ );
379
+ serverInstance = import_node_http.default.createServer((req, res) => {
380
+ res.setHeader("Access-Control-Allow-Origin", "*");
381
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
382
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
383
+ if (req.method === "OPTIONS") {
384
+ res.writeHead(204);
385
+ res.end();
386
+ return;
387
+ }
388
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
389
+ handleRequest(url, req, res).catch((err) => {
390
+ console.error("[inspecto] server error:", err);
391
+ res.writeHead(500, { "Content-Type": "application/json" });
392
+ res.end(JSON.stringify({ success: false, error: String(err) }));
393
+ });
394
+ });
395
+ await new Promise((resolve2, reject) => {
396
+ serverInstance.listen(port, "127.0.0.1", () => {
397
+ serverInstance.unref();
398
+ resolve2();
399
+ });
400
+ serverInstance.once("error", reject);
401
+ });
402
+ serverInstance.on("error", (err) => {
403
+ console.error("[inspecto] persistent server error:", err);
404
+ });
405
+ serverState.port = port;
406
+ serverState.running = true;
407
+ const portFile = import_node_path2.default.join(import_node_os2.default.tmpdir(), "inspecto.port");
408
+ try {
409
+ import_node_fs2.default.writeFileSync(portFile, String(port), "utf-8");
410
+ } catch {
411
+ }
412
+ process.once("exit", () => {
413
+ try {
414
+ import_node_fs2.default.unlinkSync(portFile);
415
+ } catch {
416
+ }
417
+ });
418
+ console.log(`[inspecto] server running at http://127.0.0.1:${port}`);
419
+ return port;
420
+ }
421
+ async function readBody(req) {
422
+ return new Promise((resolve2, reject) => {
423
+ const chunks = [];
424
+ req.on("data", (chunk) => chunks.push(chunk));
425
+ req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
426
+ req.on("error", reject);
427
+ });
428
+ }
429
+ async function handleRequest(url, req, res) {
430
+ const pathname = url.pathname;
431
+ if (pathname === "/health" && req.method === "GET") {
432
+ res.writeHead(200, { "Content-Type": "application/json" });
433
+ res.end(JSON.stringify({ ok: true, port: serverState.port }));
434
+ return;
435
+ }
436
+ if (pathname === "/config" && req.method === "GET") {
437
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
438
+ const promptsConfig = await loadPromptsConfig(false, serverState.cwd, serverState.configRoot);
439
+ const effectiveIde = userConfig.ide ?? "vscode";
440
+ let info;
441
+ if (!serverState.ideInfo) {
442
+ const fallbackTargets = userConfig.providers ? Object.keys(userConfig.providers) : ["claude-code", "gemini", "coco", "codex"];
443
+ info = {
444
+ ide: effectiveIde,
445
+ providers: fallbackTargets.reduce(
446
+ (acc, target) => {
447
+ acc[target] = {
448
+ mode: resolveToolMode(target, effectiveIde, userConfig),
449
+ installed: false
450
+ };
451
+ return acc;
452
+ },
453
+ {}
454
+ )
455
+ };
456
+ } else {
457
+ const { scheme: _scheme, ...rest } = serverState.ideInfo;
458
+ info = rest;
459
+ }
460
+ const resolvedProviders = { ...info.providers };
461
+ for (const tool in resolvedProviders) {
462
+ resolvedProviders[tool].mode = resolveToolMode(tool, info.ide, userConfig);
463
+ }
464
+ const config = {
465
+ ...info,
466
+ providers: resolvedProviders,
467
+ providerOverrides: extractToolOverrides(info.ide, userConfig),
468
+ prompts: promptsConfig,
469
+ hotKeys: userConfig.hotKeys,
470
+ includeSnippet: userConfig.includeSnippet
471
+ };
472
+ res.writeHead(200, { "Content-Type": "application/json" });
473
+ res.end(JSON.stringify(config));
474
+ return;
475
+ }
476
+ if (pathname === "/config" && req.method === "POST") {
477
+ try {
478
+ const body = JSON.parse(await readBody(req));
479
+ serverState.ideInfo = body;
480
+ console.log(`[inspecto] Received IDE info from extension:`, body);
481
+ res.writeHead(200, { "Content-Type": "application/json" });
482
+ res.end(JSON.stringify({ success: true }));
483
+ } catch (e) {
484
+ console.error("[inspecto] Error parsing /config POST request:", e);
485
+ res.writeHead(400, { "Content-Type": "application/json" });
486
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
487
+ }
488
+ return;
489
+ }
490
+ if (pathname === "/open" && req.method === "POST") {
491
+ let body;
492
+ try {
493
+ body = JSON.parse(await readBody(req));
494
+ } catch (e) {
495
+ res.writeHead(400, { "Content-Type": "application/json" });
496
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
497
+ return;
498
+ }
499
+ const absolutePath = import_node_path2.default.isAbsolute(body.file) ? body.file : import_node_path2.default.resolve(serverState.cwd, body.file);
500
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
501
+ const ide = userConfig.ide ?? "vscode";
502
+ const editorHint = "code";
503
+ (0, import_launch_ide.launchIDE)({
504
+ file: absolutePath,
505
+ line: body.line,
506
+ column: body.column,
507
+ editor: editorHint,
508
+ type: process.platform === "darwin" ? "open" : "exec"
509
+ });
510
+ res.writeHead(200, { "Content-Type": "application/json" });
511
+ res.end(JSON.stringify({ success: true }));
512
+ return;
513
+ }
514
+ if (pathname === "/snippet" && req.method === "GET") {
515
+ const file = url.searchParams.get("file") ?? "";
516
+ const line = parseInt(url.searchParams.get("line") ?? "1", 10);
517
+ const column = parseInt(url.searchParams.get("column") ?? "1", 10);
518
+ const maxLines = parseInt(url.searchParams.get("maxLines") ?? "100", 10);
519
+ try {
520
+ const absolutePath = import_node_path2.default.isAbsolute(file) ? file : import_node_path2.default.resolve(serverState.cwd, file);
521
+ const result = await extractSnippet({ file: absolutePath, line, column, maxLines });
522
+ res.writeHead(200, { "Content-Type": "application/json" });
523
+ res.end(JSON.stringify(result));
524
+ } catch (err) {
525
+ const message = String(err.message || err);
526
+ const errorCode = message.startsWith("FILE_NOT_FOUND") ? "FILE_NOT_FOUND" : "UNKNOWN";
527
+ res.writeHead(404, { "Content-Type": "application/json" });
528
+ res.end(JSON.stringify({ success: false, error: message, errorCode }));
529
+ }
530
+ return;
531
+ }
532
+ if (pathname === "/send-to-ai" && req.method === "POST") {
533
+ try {
534
+ const rawBody = await readBody(req);
535
+ const body = JSON.parse(rawBody);
536
+ const result = await dispatchToAi(body);
537
+ res.writeHead(result.success ? 200 : 500, { "Content-Type": "application/json" });
538
+ res.end(JSON.stringify(result));
539
+ } catch (e) {
540
+ console.error("[inspecto] Error parsing /send-to-ai request:", e);
541
+ res.writeHead(500, { "Content-Type": "application/json" });
542
+ res.end(JSON.stringify({ success: false, error: String(e), errorCode: "INTERNAL_ERROR" }));
543
+ }
544
+ return;
545
+ }
546
+ res.writeHead(404, { "Content-Type": "application/json" });
547
+ res.end(JSON.stringify({ error: "not found" }));
548
+ }
549
+ async function dispatchToAi(req) {
550
+ const { location, snippet, prompt } = req;
551
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
552
+ const ide = userConfig.ide ?? "vscode";
553
+ const resolvedTarget = resolveTargetTool(userConfig);
554
+ const formattedPrompt = prompt ?? `Please help me with this code from \`${location.file}\` (line ${location.line}):
555
+
556
+ \`\`\`
557
+ ${snippet}
558
+ \`\`\`
559
+ `;
560
+ const params = new URLSearchParams();
561
+ params.set("target", resolvedTarget);
562
+ const overrides = extractToolOverrides(ide, userConfig)[resolvedTarget];
563
+ if (overrides) {
564
+ params.set("overrides", JSON.stringify(overrides));
565
+ }
566
+ params.set("prompt", formattedPrompt);
567
+ params.set("file", location.file);
568
+ params.set("line", String(location.line));
569
+ params.set("col", String(location.column));
570
+ params.set("snippet", snippet);
571
+ const scheme = serverState.ideInfo?.scheme || "vscode";
572
+ const uri = `${scheme}://inspecto.inspecto/send?${params.toString()}`;
573
+ console.log(`[inspecto] dispatchToAi: Generated URI: ${uri}`);
574
+ launchURI(uri);
575
+ return { success: true };
576
+ }
577
+
578
+ // src/injectors/utils.ts
579
+ var import_node_module = require("module");
580
+ var resolveClientModule = () => {
581
+ try {
582
+ return (0, import_node_module.createRequire)(importMetaUrl).resolve("@inspecto-dev/core");
583
+ } catch {
584
+ try {
585
+ return require.resolve("@inspecto-dev/core");
586
+ } catch {
587
+ console.warn("[inspecto] Could not resolve @inspecto-dev/core \u2014 falling back to bare specifier");
588
+ return "@inspecto-dev/core";
589
+ }
590
+ }
591
+ };
592
+
593
+ // src/injectors/webpack.ts
594
+ function getWebpackHtmlScript(serverPort2) {
595
+ return `
596
+ window.__AI_INSPECTOR_PORT__ = ${serverPort2};
597
+ window.addEventListener('load', () => {
598
+ if (window.InspectoClient) {
599
+ window.InspectoClient.mountInspector({
600
+ serverUrl: 'http://127.0.0.1:' + window.__AI_INSPECTOR_PORT__,
601
+ });
602
+ }
603
+ });
604
+ `;
605
+ }
606
+
607
+ // src/legacy/rspack/index.ts
608
+ var import_node_path3 = __toESM(require("path"), 1);
609
+ var _dirname = typeof __dirname !== "undefined" ? __dirname : __dirname;
610
+ var DEFAULT_OPTIONS = {
611
+ include: [],
612
+ exclude: [],
613
+ escapeTags: [],
614
+ pathType: "absolute",
615
+ attributeName: "data-inspecto"
616
+ };
617
+ var serverPort = null;
618
+ var ensureServer = async () => {
619
+ if (serverPort === null) {
620
+ serverPort = await startServer();
621
+ }
622
+ return serverPort;
623
+ };
624
+ var InspectoRspackLegacyPlugin = class {
625
+ constructor(options = {}) {
626
+ this.options = { ...DEFAULT_OPTIONS, ...options };
627
+ }
628
+ apply(compiler) {
629
+ if (process.env["NODE_ENV"] === "production") return;
630
+ compiler.hooks.beforeCompile.tapPromise("inspecto-overlay", async () => {
631
+ await ensureServer().catch(console.error);
632
+ });
633
+ const clientPath = resolveClientModule();
634
+ new compiler.webpack.EntryPlugin(compiler.context, clientPath, {}).apply(compiler);
635
+ compiler.hooks.compilation.tap("inspecto-overlay", (compilation) => {
636
+ const HtmlRspackPlugin = compiler.options.plugins.find(
637
+ (p) => p && p.constructor && p.constructor.name === "HtmlRspackPlugin"
638
+ );
639
+ if (HtmlRspackPlugin && HtmlRspackPlugin.constructor.getHooks) {
640
+ const hooks = HtmlRspackPlugin.constructor.getHooks(compilation);
641
+ hooks.alterAssetTagGroups.tapPromise("inspecto-overlay", async (data) => {
642
+ const port = await ensureServer();
643
+ data.headTags.unshift({
644
+ tagName: "script",
645
+ voidTag: false,
646
+ meta: { plugin: "inspecto-overlay" },
647
+ innerHTML: getWebpackHtmlScript(port)
648
+ });
649
+ return data;
650
+ });
651
+ } else {
652
+ compilation.hooks.processAssets.tapPromise(
653
+ {
654
+ name: "inspecto-overlay",
655
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
656
+ },
657
+ async (assets) => {
658
+ const port = await ensureServer();
659
+ const scriptTag = `<script>${getWebpackHtmlScript(port)}</script>`;
660
+ for (const filename of Object.keys(assets)) {
661
+ if (filename.endsWith(".html")) {
662
+ const source = assets[filename].source();
663
+ if (typeof source === "string") {
664
+ const newSource = source.replace("</head>", `${scriptTag}</head>`);
665
+ assets[filename] = new compiler.webpack.sources.RawSource(newSource);
666
+ } else if (Buffer.isBuffer(source)) {
667
+ const sourceStr = source.toString("utf-8");
668
+ const newSource = sourceStr.replace("</head>", `${scriptTag}</head>`);
669
+ assets[filename] = new compiler.webpack.sources.RawSource(newSource);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ );
675
+ }
676
+ });
677
+ const loaderPath = import_node_path3.default.resolve(_dirname, "./loader.cjs");
678
+ compiler.options.module.rules.push({
679
+ test: /\.[jt]sx?$/,
680
+ use: [
681
+ {
682
+ loader: loaderPath,
683
+ options: this.options
684
+ }
685
+ ]
686
+ });
687
+ }
688
+ };
689
+ var rspackPlugin = (options) => new InspectoRspackLegacyPlugin(options);
690
+ var rspack_default = rspackPlugin;
691
+ // Annotate the CommonJS export names for ESM import in node:
692
+ 0 && (module.exports = {
693
+ InspectoRspackLegacyPlugin,
694
+ rspackPlugin
695
+ });
696
+ //# sourceMappingURL=index.cjs.map