@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
package/dist/vite.js ADDED
@@ -0,0 +1,1058 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/index.ts
9
+ import { createUnplugin } from "unplugin";
10
+
11
+ // src/transform/utils.ts
12
+ var DEFAULT_ESCAPE_TAGS = /* @__PURE__ */ new Set([
13
+ "template",
14
+ "script",
15
+ "style",
16
+ // React special elements
17
+ "Fragment",
18
+ "React.Fragment",
19
+ "StrictMode",
20
+ "React.StrictMode",
21
+ "Suspense",
22
+ "React.Suspense",
23
+ "Profiler",
24
+ "React.Profiler",
25
+ // React transitions
26
+ "Transition",
27
+ "TransitionGroup",
28
+ // Vue built-in components
29
+ "KeepAlive",
30
+ "Teleport",
31
+ "Suspense",
32
+ // Vue router built-ins
33
+ "RouterView",
34
+ "RouterLink",
35
+ "NuxtPage",
36
+ "NuxtLink"
37
+ ]);
38
+ var JSX_EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx", ".js", ".ts", ".mjs", ".mts"]);
39
+ function shouldTransform(filePath, options) {
40
+ if (process.env["NODE_ENV"] === "production") return false;
41
+ if (filePath.includes("node_modules")) return false;
42
+ if (filePath.startsWith("\0")) return false;
43
+ if (/[/\\](dist|build|\.next|\.nuxt)[/\\]/.test(filePath)) return false;
44
+ return true;
45
+ }
46
+ function buildEscapeTagsSet(escapeTags) {
47
+ const merged = new Set(DEFAULT_ESCAPE_TAGS);
48
+ if (escapeTags) {
49
+ for (const tag of escapeTags) {
50
+ merged.add(tag);
51
+ }
52
+ }
53
+ return merged;
54
+ }
55
+ function formatAttrValue(file, line, column) {
56
+ return `${file}:${line}:${column}`;
57
+ }
58
+
59
+ // src/transform/index.ts
60
+ import path3 from "path";
61
+
62
+ // src/transform/transform-jsx.ts
63
+ import * as parser from "@babel/parser";
64
+ import traverse_ from "@babel/traverse";
65
+ import MagicString from "magic-string";
66
+ import path from "path";
67
+ var traverse = typeof traverse_ === "function" ? traverse_ : traverse_.default || traverse_;
68
+ function transformJsx(options) {
69
+ const {
70
+ filePath,
71
+ source,
72
+ projectRoot,
73
+ escapeTags,
74
+ pathType = "absolute",
75
+ attributeName = "data-inspecto"
76
+ } = options;
77
+ const escapeTagsSet = buildEscapeTagsSet(escapeTags);
78
+ const resolvedPath = pathType === "absolute" ? path.resolve(filePath) : path.relative(projectRoot, path.resolve(filePath));
79
+ const normalizedPath = resolvedPath.replace(/\\/g, "/");
80
+ let ast;
81
+ try {
82
+ ast = parser.parse(source, {
83
+ sourceType: "module",
84
+ plugins: [
85
+ "jsx",
86
+ "typescript",
87
+ "decorators-legacy",
88
+ "classProperties",
89
+ "optionalChaining",
90
+ "nullishCoalescingOperator",
91
+ "importMeta"
92
+ ],
93
+ errorRecovery: true
94
+ });
95
+ } catch {
96
+ return { code: source, map: null, changed: false };
97
+ }
98
+ const ms = new MagicString(source);
99
+ let changed = false;
100
+ traverse(ast, {
101
+ JSXOpeningElement(nodePath) {
102
+ const node = nodePath.node;
103
+ const alreadyHasAttr = node.attributes.some(
104
+ (attr) => attr.type === "JSXAttribute" && attr.name.type === "JSXIdentifier" && attr.name.name === attributeName
105
+ );
106
+ if (alreadyHasAttr) return;
107
+ const nameNode = node.name;
108
+ let tagName;
109
+ if (nameNode.type === "JSXIdentifier") {
110
+ tagName = nameNode.name;
111
+ } else if (nameNode.type === "JSXMemberExpression") {
112
+ const objName = nameNode.object.type === "JSXIdentifier" ? nameNode.object.name : "";
113
+ const propName = nameNode.property.type === "JSXIdentifier" ? nameNode.property.name : "";
114
+ tagName = objName && propName ? `${objName}.${propName}` : objName;
115
+ } else {
116
+ tagName = "";
117
+ }
118
+ if (escapeTagsSet.has(tagName)) return;
119
+ const loc = node.loc;
120
+ if (!loc) return;
121
+ const { line, column } = loc.start;
122
+ const attrValue = formatAttrValue(normalizedPath, line, column + 1);
123
+ let insertPos = null;
124
+ if (node.attributes && node.attributes.length > 0) {
125
+ const firstAttr = node.attributes[0];
126
+ if (firstAttr && firstAttr.start != null) {
127
+ insertPos = firstAttr.start;
128
+ }
129
+ }
130
+ if (insertPos == null) {
131
+ if (node.typeParameters && node.typeParameters.end != null) {
132
+ insertPos = node.typeParameters.end;
133
+ } else if (node.name.end != null) {
134
+ insertPos = node.name.end;
135
+ }
136
+ }
137
+ if (insertPos == null) return;
138
+ ms.appendLeft(
139
+ insertPos,
140
+ ` ${attributeName}="${attrValue}"${node.attributes && node.attributes.length > 0 ? "" : " "}`
141
+ );
142
+ changed = true;
143
+ }
144
+ });
145
+ if (!changed) {
146
+ return { code: source, map: null, changed: false };
147
+ }
148
+ return {
149
+ code: ms.toString(),
150
+ map: ms.generateMap({ hires: true, source: filePath }),
151
+ changed: true
152
+ };
153
+ }
154
+
155
+ // src/transform/transform-vue.ts
156
+ import * as vueCompiler from "@vue/compiler-dom";
157
+ import { parse as parseSFC } from "@vue/compiler-sfc";
158
+ import { NodeTypes } from "@vue/compiler-core";
159
+ import MagicString2 from "magic-string";
160
+ import path2 from "path";
161
+ function transformVue(options) {
162
+ const {
163
+ filePath,
164
+ source,
165
+ projectRoot,
166
+ escapeTags,
167
+ pathType = "absolute",
168
+ attributeName = "data-inspecto"
169
+ } = options;
170
+ const escapeTagsSet = buildEscapeTagsSet(escapeTags);
171
+ const resolvedPath = pathType === "absolute" ? path2.resolve(filePath) : path2.relative(projectRoot, path2.resolve(filePath));
172
+ const normalizedPath = resolvedPath.replace(/\\/g, "/");
173
+ const { descriptor, errors } = parseSFC(source, {
174
+ filename: filePath,
175
+ sourceMap: false,
176
+ ignoreEmpty: true
177
+ });
178
+ if (errors.length > 0 || !descriptor.template) {
179
+ return { code: source, map: null, changed: false };
180
+ }
181
+ const templateContent = descriptor.template.content;
182
+ const templateBlockStart = descriptor.template.loc.start.offset;
183
+ let ast;
184
+ try {
185
+ ast = vueCompiler.parse(templateContent, {
186
+ parseMode: "html",
187
+ // Preserve source locations relative to templateContent
188
+ onError: () => {
189
+ }
190
+ });
191
+ } catch {
192
+ return { code: source, map: null, changed: false };
193
+ }
194
+ const ms = new MagicString2(source);
195
+ let changed = false;
196
+ walkElement(ast, (node) => {
197
+ if (node.type !== NodeTypes.ELEMENT) return;
198
+ const tagName = node.tag;
199
+ if (escapeTagsSet.has(tagName)) return;
200
+ if (tagName === "template" && node === ast.children[0]) return;
201
+ const alreadyHasAttr = node.props.some(
202
+ (p) => p.type === NodeTypes.ATTRIBUTE && p.name === attributeName
203
+ );
204
+ if (alreadyHasAttr) return;
205
+ const loc = node.loc;
206
+ if (!loc) return;
207
+ const { line, column } = loc.start;
208
+ const attrValue = formatAttrValue(normalizedPath, line, column + 1);
209
+ const tagNameEnd = loc.start.offset + tagName.length + 1;
210
+ const absoluteOffset = templateBlockStart + tagNameEnd;
211
+ ms.appendLeft(absoluteOffset, ` ${attributeName}="${attrValue}"`);
212
+ changed = true;
213
+ });
214
+ if (!changed) {
215
+ return { code: source, map: null, changed: false };
216
+ }
217
+ return {
218
+ code: ms.toString(),
219
+ map: ms.generateMap({ hires: true, source: filePath }),
220
+ changed: true
221
+ };
222
+ }
223
+ function walkElement(node, visitor) {
224
+ if (node.type === NodeTypes.ELEMENT) {
225
+ visitor(node);
226
+ for (const child of node.children) {
227
+ walkElement(child, visitor);
228
+ }
229
+ } else if ("children" in node && Array.isArray(node.children)) {
230
+ for (const child of node.children) {
231
+ walkElement(child, visitor);
232
+ }
233
+ }
234
+ }
235
+
236
+ // src/transform/index.ts
237
+ function transformRouter(options) {
238
+ const { filePath, source, projectRoot, pluginOptions } = options;
239
+ const ext = path3.extname(filePath).toLowerCase();
240
+ if (JSX_EXTENSIONS.has(ext)) {
241
+ return transformJsx({
242
+ filePath,
243
+ source,
244
+ projectRoot,
245
+ escapeTags: pluginOptions.escapeTags,
246
+ pathType: pluginOptions.pathType,
247
+ attributeName: pluginOptions.attributeName
248
+ });
249
+ }
250
+ if (ext === ".vue") {
251
+ return transformVue({
252
+ filePath,
253
+ source,
254
+ projectRoot,
255
+ escapeTags: pluginOptions.escapeTags,
256
+ pathType: pluginOptions.pathType,
257
+ attributeName: pluginOptions.attributeName
258
+ });
259
+ }
260
+ return null;
261
+ }
262
+
263
+ // src/server/index.ts
264
+ import http from "http";
265
+ import fs3 from "fs";
266
+ import path6 from "path";
267
+ import os2 from "os";
268
+ import { execSync, execFileSync } from "child_process";
269
+ import portfinder from "portfinder";
270
+ import { launchIDE } from "launch-ide";
271
+
272
+ // src/server/snippet.ts
273
+ import * as fs from "fs";
274
+ import * as path4 from "path";
275
+ import * as parser2 from "@babel/parser";
276
+ import traverse_2 from "@babel/traverse";
277
+ var traverse2 = typeof traverse_2 === "function" ? traverse_2 : traverse_2.default || traverse_2;
278
+ var snippetCache = /* @__PURE__ */ new Map();
279
+ var DEFAULT_MAX_LINES = 100;
280
+ var DEFAULT_CONTEXT_LINES_BEFORE = 5;
281
+ async function extractSnippet(req) {
282
+ const { file, line, column, maxLines = DEFAULT_MAX_LINES } = req;
283
+ const absolutePath = path4.resolve(file);
284
+ let stat;
285
+ try {
286
+ stat = await fs.promises.stat(absolutePath);
287
+ } catch {
288
+ throw new Error(`FILE_NOT_FOUND: ${absolutePath}`);
289
+ }
290
+ const mtime = stat.mtimeMs;
291
+ let lines;
292
+ const cached = snippetCache.get(absolutePath);
293
+ if (cached && cached.mtime === mtime) {
294
+ lines = cached.lines;
295
+ } else {
296
+ const source = await fs.promises.readFile(absolutePath, "utf-8");
297
+ lines = source.split("\n");
298
+ snippetCache.set(absolutePath, { mtime, lines });
299
+ }
300
+ let snippetLines;
301
+ let startLine;
302
+ let componentName;
303
+ try {
304
+ const result = extractComponentBoundary(lines.join("\n"), line, column, maxLines);
305
+ snippetLines = result.lines;
306
+ startLine = result.startLine;
307
+ componentName = result.name;
308
+ } catch {
309
+ const before = Math.max(0, line - 1 - DEFAULT_CONTEXT_LINES_BEFORE);
310
+ const after = Math.min(lines.length, before + maxLines);
311
+ snippetLines = lines.slice(before, after);
312
+ startLine = before + 1;
313
+ }
314
+ if (snippetLines.length > maxLines) {
315
+ snippetLines = snippetLines.slice(0, maxLines);
316
+ }
317
+ return {
318
+ snippet: snippetLines.join("\n"),
319
+ startLine,
320
+ file: absolutePath,
321
+ ...componentName ? { name: componentName } : {}
322
+ };
323
+ }
324
+ function extractComponentBoundary(source, targetLine, _targetColumn, maxLines) {
325
+ const ast = parser2.parse(source, {
326
+ sourceType: "module",
327
+ plugins: ["jsx", "typescript", "decorators-legacy", "classProperties"],
328
+ errorRecovery: true
329
+ });
330
+ const allLines = source.split("\n");
331
+ let bestStart = 0;
332
+ let bestEnd = allLines.length - 1;
333
+ let bestName;
334
+ traverse2(ast, {
335
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ClassMethod"(nodePath) {
336
+ const node = nodePath.node;
337
+ if (!node.loc) return;
338
+ const nodeStart = node.loc.start.line;
339
+ const nodeEnd = node.loc.end.line;
340
+ if (targetLine < nodeStart || targetLine > nodeEnd) return;
341
+ if (nodeEnd - nodeStart < bestEnd - bestStart) {
342
+ bestStart = nodeStart - 1;
343
+ bestEnd = nodeEnd - 1;
344
+ bestName = extractFunctionName(nodePath);
345
+ }
346
+ }
347
+ });
348
+ let sliceStart = bestStart;
349
+ let sliceEnd = bestEnd + 1;
350
+ if (sliceEnd - sliceStart > maxLines) {
351
+ const targetIdx = targetLine - 1;
352
+ sliceStart = Math.max(bestStart, targetIdx - Math.floor(maxLines / 3));
353
+ sliceEnd = sliceStart + maxLines;
354
+ if (sliceEnd > bestEnd + 1) {
355
+ sliceEnd = bestEnd + 1;
356
+ sliceStart = Math.max(0, sliceEnd - maxLines);
357
+ }
358
+ }
359
+ return {
360
+ lines: allLines.slice(sliceStart, sliceEnd),
361
+ startLine: sliceStart + 1,
362
+ ...bestName ? { name: bestName } : {}
363
+ };
364
+ }
365
+ function extractFunctionName(nodePath) {
366
+ const node = nodePath.node;
367
+ if (node.type === "FunctionDeclaration" && node.id) {
368
+ return node.id.name;
369
+ }
370
+ const parent = nodePath.parent;
371
+ if ((node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && parent.type === "VariableDeclarator" && parent.id.type === "Identifier") {
372
+ return parent.id.name;
373
+ }
374
+ if (node.type === "ClassMethod" && node.key.type === "Identifier") {
375
+ return node.key.name;
376
+ }
377
+ return void 0;
378
+ }
379
+
380
+ // src/config.ts
381
+ import fs2 from "fs";
382
+ import path5 from "path";
383
+ import os from "os";
384
+ import { createDefu } from "defu";
385
+ import { DEFAULT_TOOL_MODE, VALID_MODES } from "@inspecto-dev/types";
386
+ var loadedConfig = null;
387
+ var loadedPrompts = null;
388
+ var isWatching = false;
389
+ var arrayReplaceMerge = createDefu((obj, key, val) => {
390
+ if (Array.isArray(val)) {
391
+ obj[key] = val;
392
+ return true;
393
+ }
394
+ });
395
+ function resolveConfigRoots(cwd, gitRoot) {
396
+ const roots = [];
397
+ let current = cwd;
398
+ const isUnderOrEqual = current === gitRoot || current.startsWith(gitRoot + path5.sep);
399
+ if (!isUnderOrEqual) {
400
+ if (fs2.existsSync(path5.join(cwd, ".inspecto"))) roots.push(cwd);
401
+ return roots;
402
+ }
403
+ while (true) {
404
+ if (fs2.existsSync(path5.join(current, ".inspecto"))) {
405
+ roots.push(current);
406
+ }
407
+ if (current === gitRoot) break;
408
+ const parent = path5.dirname(current);
409
+ if (parent === current) break;
410
+ current = parent;
411
+ }
412
+ return roots;
413
+ }
414
+ function loadUserConfigSync(force = false, cwd = process.cwd(), gitRoot) {
415
+ if (loadedConfig && !force) return loadedConfig;
416
+ loadedConfig = null;
417
+ const layers = [];
418
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
419
+ for (const root of roots) {
420
+ layers.push(readJsonSafely(path5.join(root, ".inspecto", "settings.local.json")));
421
+ layers.push(readJsonSafely(path5.join(root, ".inspecto", "settings.json")));
422
+ }
423
+ layers.push(readJsonSafely(path5.join(os.homedir(), ".inspecto", "settings.json")));
424
+ layers.push({ providers: {} });
425
+ const validLayers = layers.filter((l) => l !== null);
426
+ loadedConfig = arrayReplaceMerge(...validLayers);
427
+ return loadedConfig;
428
+ }
429
+ async function loadPromptsConfig(force = false, cwd = process.cwd(), gitRoot) {
430
+ if (loadedPrompts && !force) return loadedPrompts;
431
+ const layers = [];
432
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
433
+ for (const root of roots) {
434
+ const localPath = path5.join(root, ".inspecto", "prompts.local.json");
435
+ const jsonPath = path5.join(root, ".inspecto", "prompts.json");
436
+ layers.push(readJsonSafely(localPath));
437
+ layers.push(readJsonSafely(jsonPath));
438
+ }
439
+ layers.push(readJsonSafely(path5.join(os.homedir(), ".inspecto", "prompts.json")));
440
+ let finalPrompts = [];
441
+ for (const layer of layers) {
442
+ if (Array.isArray(layer) && layer.length > 0) {
443
+ finalPrompts = layer;
444
+ break;
445
+ }
446
+ if (layer && typeof layer === "object" && layer.$replace === true && Array.isArray(layer.items)) {
447
+ finalPrompts = layer;
448
+ break;
449
+ }
450
+ }
451
+ loadedPrompts = finalPrompts;
452
+ return loadedPrompts;
453
+ }
454
+ function readJsonSafely(filePath) {
455
+ try {
456
+ if (fs2.existsSync(filePath)) {
457
+ const content = fs2.readFileSync(filePath, "utf-8").trim();
458
+ if (!content) return null;
459
+ const parsed = JSON.parse(content);
460
+ if (!Array.isArray(parsed) && parsed.prompts && Array.isArray(parsed.prompts)) {
461
+ return parsed.prompts;
462
+ }
463
+ return parsed;
464
+ }
465
+ } catch (e) {
466
+ if (e instanceof SyntaxError) {
467
+ console.warn(`[inspecto] Failed to parse config at ${filePath}: Invalid JSON`);
468
+ } else {
469
+ console.warn(`[inspecto] Failed to read config at ${filePath}:`, e);
470
+ }
471
+ }
472
+ return null;
473
+ }
474
+ function resolveTargetTool(config) {
475
+ if (config.prefer) {
476
+ return config.prefer;
477
+ }
478
+ if (config.providers && Object.keys(config.providers).length > 0) {
479
+ return Object.keys(config.providers)[0];
480
+ }
481
+ return "github-copilot";
482
+ }
483
+ function resolveToolMode(tool, ide, config) {
484
+ let requestedType = void 0;
485
+ if (config.providers && config.providers[tool] && config.providers[tool].type) {
486
+ const type = config.providers[tool].type;
487
+ if (type === "plugin" || type === "cli") {
488
+ requestedType = type;
489
+ }
490
+ }
491
+ requestedType = requestedType ?? DEFAULT_TOOL_MODE[tool];
492
+ const valid = VALID_MODES[tool] || [DEFAULT_TOOL_MODE[tool]];
493
+ return requestedType && valid.includes(requestedType) ? requestedType : valid[0];
494
+ }
495
+ function extractToolOverrides(ide, config) {
496
+ const result = {};
497
+ if (!config.providers) return result;
498
+ for (const [tool, cfg] of Object.entries(config.providers)) {
499
+ if (!cfg) continue;
500
+ const overrides = {
501
+ type: cfg.type || DEFAULT_TOOL_MODE[tool] || "plugin"
502
+ };
503
+ if (cfg.bin) overrides.binaryPath = cfg.bin;
504
+ if (cfg.args) overrides.args = cfg.args;
505
+ if (cfg.cwd) overrides.cwd = cfg.cwd;
506
+ if (cfg.autoSend !== void 0) overrides.autoSend = cfg.autoSend;
507
+ result[tool] = overrides;
508
+ }
509
+ return result;
510
+ }
511
+ var watchers = [];
512
+ function watchConfig(onReload, cwd = process.cwd(), gitRoot) {
513
+ if (isWatching) return;
514
+ isWatching = true;
515
+ const watchDirs = [path5.join(os.homedir(), ".inspecto")];
516
+ const roots = resolveConfigRoots(cwd, gitRoot ?? cwd);
517
+ for (const root of roots) {
518
+ watchDirs.push(path5.join(root, ".inspecto"));
519
+ }
520
+ const CONFIG_FILES = /* @__PURE__ */ new Set([
521
+ "settings.json",
522
+ "settings.local.json",
523
+ "prompts.json",
524
+ "prompts.local.json"
525
+ ]);
526
+ for (const dir of watchDirs) {
527
+ if (!fs2.existsSync(dir)) continue;
528
+ try {
529
+ const watcher = fs2.watch(dir, async (eventType, filename) => {
530
+ if (!filename || !CONFIG_FILES.has(filename)) return;
531
+ loadedConfig = null;
532
+ loadedPrompts = null;
533
+ loadUserConfigSync(true, cwd, gitRoot);
534
+ await loadPromptsConfig(true, cwd, gitRoot);
535
+ onReload();
536
+ });
537
+ watcher.unref();
538
+ watchers.push(watcher);
539
+ } catch (e) {
540
+ }
541
+ }
542
+ }
543
+
544
+ // src/server/index.ts
545
+ var serverState = {
546
+ port: null,
547
+ running: false,
548
+ projectRoot: "",
549
+ configRoot: "",
550
+ cwd: process.cwd()
551
+ };
552
+ var serverInstance = null;
553
+ function resolveProjectRoot() {
554
+ let gitRoot;
555
+ try {
556
+ gitRoot = execSync("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();
557
+ } catch {
558
+ gitRoot = process.cwd();
559
+ }
560
+ let current = gitRoot;
561
+ while (true) {
562
+ if (fs3.existsSync(path6.join(current, ".inspecto"))) return current;
563
+ const parent = path6.dirname(current);
564
+ if (parent === current) break;
565
+ current = parent;
566
+ }
567
+ return gitRoot;
568
+ }
569
+ function launchURI(uri) {
570
+ try {
571
+ if (process.platform === "darwin") {
572
+ execFileSync("open", [uri]);
573
+ } else if (process.platform === "win32") {
574
+ execFileSync("cmd", ["/c", "start", '""', uri]);
575
+ } else {
576
+ execFileSync("xdg-open", [uri]);
577
+ }
578
+ } catch (e) {
579
+ console.error("[inspecto] Failed to launch URI via execFileSync, falling back to launchIDE:", e);
580
+ launchIDE({ file: uri });
581
+ }
582
+ }
583
+ async function startServer() {
584
+ if (serverState.running && serverState.port !== null) {
585
+ return serverState.port;
586
+ }
587
+ serverState.projectRoot = resolveProjectRoot();
588
+ serverState.configRoot = serverState.projectRoot;
589
+ serverState.cwd = process.cwd();
590
+ portfinder.basePort = 5678;
591
+ const port = await portfinder.getPortPromise();
592
+ watchConfig(
593
+ () => {
594
+ console.log("[inspecto] user config reloaded.");
595
+ },
596
+ serverState.cwd,
597
+ serverState.configRoot
598
+ );
599
+ serverInstance = http.createServer((req, res) => {
600
+ res.setHeader("Access-Control-Allow-Origin", "*");
601
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
602
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
603
+ if (req.method === "OPTIONS") {
604
+ res.writeHead(204);
605
+ res.end();
606
+ return;
607
+ }
608
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
609
+ handleRequest(url, req, res).catch((err) => {
610
+ console.error("[inspecto] server error:", err);
611
+ res.writeHead(500, { "Content-Type": "application/json" });
612
+ res.end(JSON.stringify({ success: false, error: String(err) }));
613
+ });
614
+ });
615
+ await new Promise((resolve2, reject) => {
616
+ serverInstance.listen(port, "127.0.0.1", () => {
617
+ serverInstance.unref();
618
+ resolve2();
619
+ });
620
+ serverInstance.once("error", reject);
621
+ });
622
+ serverInstance.on("error", (err) => {
623
+ console.error("[inspecto] persistent server error:", err);
624
+ });
625
+ serverState.port = port;
626
+ serverState.running = true;
627
+ const portFile = path6.join(os2.tmpdir(), "inspecto.port");
628
+ try {
629
+ fs3.writeFileSync(portFile, String(port), "utf-8");
630
+ } catch {
631
+ }
632
+ process.once("exit", () => {
633
+ try {
634
+ fs3.unlinkSync(portFile);
635
+ } catch {
636
+ }
637
+ });
638
+ console.log(`[inspecto] server running at http://127.0.0.1:${port}`);
639
+ return port;
640
+ }
641
+ async function readBody(req) {
642
+ return new Promise((resolve2, reject) => {
643
+ const chunks = [];
644
+ req.on("data", (chunk) => chunks.push(chunk));
645
+ req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
646
+ req.on("error", reject);
647
+ });
648
+ }
649
+ async function handleRequest(url, req, res) {
650
+ const pathname = url.pathname;
651
+ if (pathname === "/health" && req.method === "GET") {
652
+ res.writeHead(200, { "Content-Type": "application/json" });
653
+ res.end(JSON.stringify({ ok: true, port: serverState.port }));
654
+ return;
655
+ }
656
+ if (pathname === "/config" && req.method === "GET") {
657
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
658
+ const promptsConfig = await loadPromptsConfig(false, serverState.cwd, serverState.configRoot);
659
+ const effectiveIde = userConfig.ide ?? "vscode";
660
+ let info;
661
+ if (!serverState.ideInfo) {
662
+ const fallbackTargets = userConfig.providers ? Object.keys(userConfig.providers) : ["claude-code", "gemini", "coco", "codex"];
663
+ info = {
664
+ ide: effectiveIde,
665
+ providers: fallbackTargets.reduce(
666
+ (acc, target) => {
667
+ acc[target] = {
668
+ mode: resolveToolMode(target, effectiveIde, userConfig),
669
+ installed: false
670
+ };
671
+ return acc;
672
+ },
673
+ {}
674
+ )
675
+ };
676
+ } else {
677
+ const { scheme: _scheme, ...rest } = serverState.ideInfo;
678
+ info = rest;
679
+ }
680
+ const resolvedProviders = { ...info.providers };
681
+ for (const tool in resolvedProviders) {
682
+ resolvedProviders[tool].mode = resolveToolMode(tool, info.ide, userConfig);
683
+ }
684
+ const config = {
685
+ ...info,
686
+ providers: resolvedProviders,
687
+ providerOverrides: extractToolOverrides(info.ide, userConfig),
688
+ prompts: promptsConfig,
689
+ hotKeys: userConfig.hotKeys,
690
+ includeSnippet: userConfig.includeSnippet
691
+ };
692
+ res.writeHead(200, { "Content-Type": "application/json" });
693
+ res.end(JSON.stringify(config));
694
+ return;
695
+ }
696
+ if (pathname === "/config" && req.method === "POST") {
697
+ try {
698
+ const body = JSON.parse(await readBody(req));
699
+ serverState.ideInfo = body;
700
+ console.log(`[inspecto] Received IDE info from extension:`, body);
701
+ res.writeHead(200, { "Content-Type": "application/json" });
702
+ res.end(JSON.stringify({ success: true }));
703
+ } catch (e) {
704
+ console.error("[inspecto] Error parsing /config POST request:", e);
705
+ res.writeHead(400, { "Content-Type": "application/json" });
706
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
707
+ }
708
+ return;
709
+ }
710
+ if (pathname === "/open" && req.method === "POST") {
711
+ let body;
712
+ try {
713
+ body = JSON.parse(await readBody(req));
714
+ } catch (e) {
715
+ res.writeHead(400, { "Content-Type": "application/json" });
716
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
717
+ return;
718
+ }
719
+ const absolutePath = path6.isAbsolute(body.file) ? body.file : path6.resolve(serverState.cwd, body.file);
720
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
721
+ const ide = userConfig.ide ?? "vscode";
722
+ const editorHint = "code";
723
+ launchIDE({
724
+ file: absolutePath,
725
+ line: body.line,
726
+ column: body.column,
727
+ editor: editorHint,
728
+ type: process.platform === "darwin" ? "open" : "exec"
729
+ });
730
+ res.writeHead(200, { "Content-Type": "application/json" });
731
+ res.end(JSON.stringify({ success: true }));
732
+ return;
733
+ }
734
+ if (pathname === "/snippet" && req.method === "GET") {
735
+ const file = url.searchParams.get("file") ?? "";
736
+ const line = parseInt(url.searchParams.get("line") ?? "1", 10);
737
+ const column = parseInt(url.searchParams.get("column") ?? "1", 10);
738
+ const maxLines = parseInt(url.searchParams.get("maxLines") ?? "100", 10);
739
+ try {
740
+ const absolutePath = path6.isAbsolute(file) ? file : path6.resolve(serverState.cwd, file);
741
+ const result = await extractSnippet({ file: absolutePath, line, column, maxLines });
742
+ res.writeHead(200, { "Content-Type": "application/json" });
743
+ res.end(JSON.stringify(result));
744
+ } catch (err) {
745
+ const message = String(err.message || err);
746
+ const errorCode = message.startsWith("FILE_NOT_FOUND") ? "FILE_NOT_FOUND" : "UNKNOWN";
747
+ res.writeHead(404, { "Content-Type": "application/json" });
748
+ res.end(JSON.stringify({ success: false, error: message, errorCode }));
749
+ }
750
+ return;
751
+ }
752
+ if (pathname === "/send-to-ai" && req.method === "POST") {
753
+ try {
754
+ const rawBody = await readBody(req);
755
+ const body = JSON.parse(rawBody);
756
+ const result = await dispatchToAi(body);
757
+ res.writeHead(result.success ? 200 : 500, { "Content-Type": "application/json" });
758
+ res.end(JSON.stringify(result));
759
+ } catch (e) {
760
+ console.error("[inspecto] Error parsing /send-to-ai request:", e);
761
+ res.writeHead(500, { "Content-Type": "application/json" });
762
+ res.end(JSON.stringify({ success: false, error: String(e), errorCode: "INTERNAL_ERROR" }));
763
+ }
764
+ return;
765
+ }
766
+ res.writeHead(404, { "Content-Type": "application/json" });
767
+ res.end(JSON.stringify({ error: "not found" }));
768
+ }
769
+ async function dispatchToAi(req) {
770
+ const { location, snippet, prompt } = req;
771
+ const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot);
772
+ const ide = userConfig.ide ?? "vscode";
773
+ const resolvedTarget = resolveTargetTool(userConfig);
774
+ const formattedPrompt = prompt ?? `Please help me with this code from \`${location.file}\` (line ${location.line}):
775
+
776
+ \`\`\`
777
+ ${snippet}
778
+ \`\`\`
779
+ `;
780
+ const params = new URLSearchParams();
781
+ params.set("target", resolvedTarget);
782
+ const overrides = extractToolOverrides(ide, userConfig)[resolvedTarget];
783
+ if (overrides) {
784
+ params.set("overrides", JSON.stringify(overrides));
785
+ }
786
+ params.set("prompt", formattedPrompt);
787
+ params.set("file", location.file);
788
+ params.set("line", String(location.line));
789
+ params.set("col", String(location.column));
790
+ params.set("snippet", snippet);
791
+ const scheme = serverState.ideInfo?.scheme || "vscode";
792
+ const uri = `${scheme}://inspecto.inspecto/send?${params.toString()}`;
793
+ console.log(`[inspecto] dispatchToAi: Generated URI: ${uri}`);
794
+ launchURI(uri);
795
+ return { success: true };
796
+ }
797
+
798
+ // src/injectors/utils.ts
799
+ import { createRequire } from "module";
800
+ var resolveClientModule = () => {
801
+ try {
802
+ return createRequire(import.meta.url).resolve("@inspecto-dev/core");
803
+ } catch {
804
+ try {
805
+ return __require.resolve("@inspecto-dev/core");
806
+ } catch {
807
+ console.warn("[inspecto] Could not resolve @inspecto-dev/core \u2014 falling back to bare specifier");
808
+ return "@inspecto-dev/core";
809
+ }
810
+ }
811
+ };
812
+
813
+ // src/injectors/webpack.ts
814
+ function getWebpackHtmlScript(serverPort) {
815
+ return `
816
+ window.__AI_INSPECTOR_PORT__ = ${serverPort};
817
+ window.addEventListener('load', () => {
818
+ if (window.InspectoClient) {
819
+ window.InspectoClient.mountInspector({
820
+ serverUrl: 'http://127.0.0.1:' + window.__AI_INSPECTOR_PORT__,
821
+ });
822
+ }
823
+ });
824
+ `;
825
+ }
826
+ function getWebpackAssetScript(serverPort) {
827
+ return `
828
+ if (typeof window !== 'undefined') {
829
+ window.__AI_INSPECTOR_PORT__ = ${serverPort};
830
+ const _initInspecto = () => {
831
+ if (window.InspectoClient) {
832
+ window.InspectoClient.mountInspector({
833
+ serverUrl: 'http://127.0.0.1:' + window.__AI_INSPECTOR_PORT__,
834
+ });
835
+ } else {
836
+ setTimeout(_initInspecto, 100);
837
+ }
838
+ };
839
+ if (document.readyState === 'complete') {
840
+ _initInspecto();
841
+ } else {
842
+ window.addEventListener('load', _initInspecto);
843
+ }
844
+ }
845
+ `;
846
+ }
847
+ function injectWebpack(compiler, serverPortFn, resolveClientModule2) {
848
+ const inspectoClientPath = resolveClientModule2();
849
+ new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, { name: void 0 }).apply(
850
+ compiler
851
+ );
852
+ compiler.hooks.compilation.tap("inspecto-overlay", (compilation) => {
853
+ const HtmlWebpackPlugin = compiler.options.plugins.find(
854
+ (p) => p && p.constructor && p.constructor.name === "HtmlWebpackPlugin"
855
+ );
856
+ if (HtmlWebpackPlugin) {
857
+ const hooks = HtmlWebpackPlugin.constructor.getHooks(compilation);
858
+ hooks.alterAssetTagGroups.tapPromise("inspecto-overlay", async (data) => {
859
+ const port = await serverPortFn();
860
+ data.headTags.unshift({
861
+ tagName: "script",
862
+ voidTag: false,
863
+ meta: { plugin: "inspecto-overlay" },
864
+ innerHTML: getWebpackHtmlScript(port)
865
+ });
866
+ return data;
867
+ });
868
+ } else {
869
+ compilation.hooks.processAssets.tapPromise(
870
+ {
871
+ name: "inspecto-overlay",
872
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
873
+ },
874
+ async (assets) => {
875
+ const port = await serverPortFn();
876
+ const mainAssetKey = Object.keys(assets).find(
877
+ (key) => key.endsWith(".js") && (key.includes("main") || key.includes("app"))
878
+ );
879
+ if (!mainAssetKey) return;
880
+ const originalSource = assets[mainAssetKey].source();
881
+ assets[mainAssetKey] = new compiler.webpack.sources.RawSource(
882
+ getWebpackAssetScript(port) + "\n" + originalSource
883
+ );
884
+ }
885
+ );
886
+ }
887
+ });
888
+ }
889
+
890
+ // src/injectors/rspack.ts
891
+ function injectRspack(compiler, serverPortFn, resolveClientModule2) {
892
+ const inspectoClientPath = resolveClientModule2();
893
+ new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, {}).apply(compiler);
894
+ compiler.hooks.compilation.tap("inspecto-overlay", (compilation) => {
895
+ const HtmlRspackPlugin = compiler.options.plugins.find(
896
+ (p) => p && p.constructor && p.constructor.name === "HtmlRspackPlugin"
897
+ );
898
+ if (HtmlRspackPlugin) {
899
+ const hooks = HtmlRspackPlugin.constructor.getHooks(compilation);
900
+ hooks.alterAssetTagGroups.tapPromise("inspecto-overlay", async (data) => {
901
+ const port = await serverPortFn();
902
+ data.headTags.unshift({
903
+ tagName: "script",
904
+ voidTag: false,
905
+ meta: { plugin: "inspecto-overlay" },
906
+ innerHTML: getWebpackHtmlScript(port)
907
+ });
908
+ return data;
909
+ });
910
+ }
911
+ });
912
+ }
913
+
914
+ // src/injectors/vite.ts
915
+ function getViteVirtualModuleScript(serverPort) {
916
+ return `
917
+ import { mountInspector } from '@inspecto-dev/core';
918
+ window.__AI_INSPECTOR_PORT__ = ${serverPort};
919
+ mountInspector({
920
+ serverUrl: 'http://127.0.0.1:' + window.__AI_INSPECTOR_PORT__,
921
+ });
922
+ `;
923
+ }
924
+ var VITE_VIRTUAL_MODULE_ID = "\0virtual:inspecto-client";
925
+ var VITE_VIRTUAL_IMPORT_ID = "/@id/__x00__virtual:inspecto-client";
926
+
927
+ // src/index.ts
928
+ var DEFAULT_OPTIONS = {
929
+ include: [],
930
+ exclude: [],
931
+ escapeTags: [],
932
+ pathType: "absolute",
933
+ attributeName: "data-inspecto"
934
+ };
935
+ var DEFAULT_PORT = 5678;
936
+ var getCleanId = (id) => id.split("?")[0];
937
+ var InspectoPlugin = createUnplugin((userOptions = {}) => {
938
+ const options = {
939
+ ...DEFAULT_OPTIONS,
940
+ ...userOptions
941
+ };
942
+ const isProduction = process.env["NODE_ENV"] === "production";
943
+ let projectRoot = process.cwd();
944
+ let serverPort = null;
945
+ const ensureServer = async () => {
946
+ if (serverPort === null) {
947
+ serverPort = await startServer();
948
+ }
949
+ return serverPort;
950
+ };
951
+ return {
952
+ name: "inspecto-overlay",
953
+ enforce: "pre",
954
+ buildStart() {
955
+ if (isProduction) return;
956
+ projectRoot = serverState.cwd || process.cwd();
957
+ ensureServer().catch(console.error);
958
+ },
959
+ buildEnd() {
960
+ },
961
+ webpack: (compiler) => {
962
+ if (isProduction) return;
963
+ injectWebpack(compiler, ensureServer, resolveClientModule);
964
+ },
965
+ rspack: (compiler) => {
966
+ if (isProduction) return;
967
+ injectRspack(compiler, ensureServer, resolveClientModule);
968
+ },
969
+ vite: {
970
+ config(config) {
971
+ if (isProduction) return config;
972
+ return {
973
+ ...config,
974
+ define: {
975
+ ...config.define,
976
+ __AI_INSPECTOR_PORT__: JSON.stringify(DEFAULT_PORT)
977
+ // Placeholder, rewritten in configureServer
978
+ }
979
+ };
980
+ },
981
+ resolveId(id) {
982
+ if (id === "virtual:inspecto-client") {
983
+ return VITE_VIRTUAL_MODULE_ID;
984
+ }
985
+ return null;
986
+ },
987
+ load(id) {
988
+ if (id === VITE_VIRTUAL_MODULE_ID) {
989
+ return getViteVirtualModuleScript(serverPort ?? DEFAULT_PORT);
990
+ }
991
+ return null;
992
+ },
993
+ async configureServer(server) {
994
+ if (isProduction) return;
995
+ const port = await ensureServer();
996
+ if (!server.config.define) {
997
+ ;
998
+ server.config.define = {};
999
+ }
1000
+ ;
1001
+ server.config.define["__AI_INSPECTOR_PORT__"] = JSON.stringify(port);
1002
+ const mod = server.moduleGraph.getModuleById(VITE_VIRTUAL_MODULE_ID);
1003
+ if (mod) server.moduleGraph.invalidateModule(mod);
1004
+ },
1005
+ transformIndexHtml(html) {
1006
+ if (isProduction || !serverPort) return html;
1007
+ return {
1008
+ html,
1009
+ tags: [
1010
+ {
1011
+ tag: "script",
1012
+ attrs: { type: "module" },
1013
+ children: `import '${VITE_VIRTUAL_IMPORT_ID}';`
1014
+ }
1015
+ ]
1016
+ };
1017
+ }
1018
+ },
1019
+ transformInclude(id) {
1020
+ if (isProduction || !id) return false;
1021
+ const cleanId = getCleanId(id);
1022
+ return shouldTransform(cleanId, options);
1023
+ },
1024
+ transform(code, id) {
1025
+ if (isProduction || !id) return null;
1026
+ const cleanId = getCleanId(id);
1027
+ const result = transformRouter({
1028
+ filePath: cleanId,
1029
+ source: code,
1030
+ projectRoot,
1031
+ pluginOptions: options
1032
+ });
1033
+ if (!result || !result.changed) return null;
1034
+ return {
1035
+ code: result.code,
1036
+ map: result.map
1037
+ };
1038
+ }
1039
+ };
1040
+ });
1041
+ var unplugin = InspectoPlugin;
1042
+ var vitePlugin = InspectoPlugin.vite;
1043
+ var webpackPlugin = InspectoPlugin.webpack;
1044
+ var rspackPlugin = InspectoPlugin.rspack;
1045
+ var rollupPlugin = InspectoPlugin.rollup;
1046
+ var esbuildPlugin = InspectoPlugin.esbuild;
1047
+ var src_default = InspectoPlugin;
1048
+ export {
1049
+ src_default as default,
1050
+ esbuildPlugin,
1051
+ rollupPlugin,
1052
+ rspackPlugin,
1053
+ transformJsx,
1054
+ unplugin,
1055
+ vitePlugin,
1056
+ webpackPlugin
1057
+ };
1058
+ //# sourceMappingURL=vite.js.map