next-ai-editor 0.1.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +213 -0
  3. package/dist/AIEditorProvider-Bs9zUVrL.cjs +1722 -0
  4. package/dist/AIEditorProvider-Bs9zUVrL.cjs.map +1 -0
  5. package/dist/AIEditorProvider-D-w9-GZb.js +1723 -0
  6. package/dist/AIEditorProvider-D-w9-GZb.js.map +1 -0
  7. package/dist/client/AIEditorProvider.d.ts +52 -0
  8. package/dist/client/AIEditorProvider.d.ts.map +1 -0
  9. package/dist/client/index.d.ts +3 -0
  10. package/dist/client/index.d.ts.map +1 -0
  11. package/dist/client.cjs +6 -0
  12. package/dist/client.cjs.map +1 -0
  13. package/dist/client.js +6 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/index-BFa7H-uO.js +1145 -0
  16. package/dist/index-BFa7H-uO.js.map +1 -0
  17. package/dist/index-DnoYi4f8.cjs +1162 -0
  18. package/dist/index-DnoYi4f8.cjs.map +1 -0
  19. package/dist/index.cjs +26 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +4 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +26 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/server/handlers/absolute-path.d.ts +3 -0
  26. package/dist/server/handlers/absolute-path.d.ts.map +1 -0
  27. package/dist/server/handlers/edit.d.ts +3 -0
  28. package/dist/server/handlers/edit.d.ts.map +1 -0
  29. package/dist/server/handlers/index.d.ts +18 -0
  30. package/dist/server/handlers/index.d.ts.map +1 -0
  31. package/dist/server/handlers/read.d.ts +3 -0
  32. package/dist/server/handlers/read.d.ts.map +1 -0
  33. package/dist/server/handlers/resolve.d.ts +3 -0
  34. package/dist/server/handlers/resolve.d.ts.map +1 -0
  35. package/dist/server/handlers/undo.d.ts +3 -0
  36. package/dist/server/handlers/undo.d.ts.map +1 -0
  37. package/dist/server/handlers/validate-session.d.ts +3 -0
  38. package/dist/server/handlers/validate-session.d.ts.map +1 -0
  39. package/dist/server/index.d.ts +11 -0
  40. package/dist/server/index.d.ts.map +1 -0
  41. package/dist/server/utils/ast.d.ts +39 -0
  42. package/dist/server/utils/ast.d.ts.map +1 -0
  43. package/dist/server/utils/file-system.d.ts +24 -0
  44. package/dist/server/utils/file-system.d.ts.map +1 -0
  45. package/dist/server/utils/source-map.d.ts +29 -0
  46. package/dist/server/utils/source-map.d.ts.map +1 -0
  47. package/dist/server.cjs +24 -0
  48. package/dist/server.cjs.map +1 -0
  49. package/dist/server.js +24 -0
  50. package/dist/server.js.map +1 -0
  51. package/dist/shared/storage.d.ts +53 -0
  52. package/dist/shared/storage.d.ts.map +1 -0
  53. package/dist/shared/types.d.ts +44 -0
  54. package/dist/shared/types.d.ts.map +1 -0
  55. package/package.json +87 -0
@@ -0,0 +1,1722 @@
1
+ "use client";
2
+ "use strict";
3
+ const jsxRuntime = require("react/jsx-runtime");
4
+ const react = require("react");
5
+ const reactSyntaxHighlighter = require("react-syntax-highlighter");
6
+ const prism = require("react-syntax-highlighter/dist/esm/styles/prism");
7
+ const _AIEditorStorage = class _AIEditorStorage {
8
+ // 5MB
9
+ /**
10
+ * Generate storage key from file path and component name
11
+ * Format: "ai-editor:session:components/Header.tsx#Header"
12
+ */
13
+ static getSessionKey(filePath, componentName) {
14
+ const normalizedPath = filePath.replace(/\\/g, "/");
15
+ return `${this.STORAGE_PREFIX}${normalizedPath}#${componentName}`;
16
+ }
17
+ /**
18
+ * Save session to localStorage
19
+ */
20
+ static saveSession(session) {
21
+ try {
22
+ const key = this.getSessionKey(
23
+ session.sourceLocation.filePath,
24
+ session.sourceLocation.componentName
25
+ );
26
+ if (this.getStorageSize() > this.MAX_STORAGE_SIZE) {
27
+ console.warn("Storage size exceeded, pruning old sessions...");
28
+ this.pruneOldSessions(7 * 24 * 60 * 60 * 1e3);
29
+ }
30
+ const serialized = JSON.stringify(session);
31
+ localStorage.setItem(key, serialized);
32
+ return true;
33
+ } catch (e) {
34
+ if (e instanceof Error && e.name === "QuotaExceededError") {
35
+ console.error("localStorage quota exceeded");
36
+ this.pruneOldSessions(7 * 24 * 60 * 60 * 1e3);
37
+ try {
38
+ const key = this.getSessionKey(
39
+ session.sourceLocation.filePath,
40
+ session.sourceLocation.componentName
41
+ );
42
+ const serialized = JSON.stringify(session);
43
+ localStorage.setItem(key, serialized);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+ console.error("Failed to save session:", e);
50
+ return false;
51
+ }
52
+ }
53
+ /**
54
+ * Load session by filePath + componentName
55
+ */
56
+ static loadSession(filePath, componentName) {
57
+ try {
58
+ const key = this.getSessionKey(filePath, componentName);
59
+ const stored = localStorage.getItem(key);
60
+ if (!stored) return null;
61
+ const session = JSON.parse(stored);
62
+ if (!session.version || !session.sourceLocation || !session.editHistory) {
63
+ console.warn("Invalid session schema, removing corrupted data");
64
+ localStorage.removeItem(key);
65
+ return null;
66
+ }
67
+ return session;
68
+ } catch (e) {
69
+ console.error("Failed to load session:", e);
70
+ const key = this.getSessionKey(filePath, componentName);
71
+ localStorage.removeItem(key);
72
+ return null;
73
+ }
74
+ }
75
+ /**
76
+ * Delete specific session
77
+ */
78
+ static deleteSession(filePath, componentName) {
79
+ try {
80
+ const key = this.getSessionKey(filePath, componentName);
81
+ localStorage.removeItem(key);
82
+ } catch (e) {
83
+ console.error("Failed to delete session:", e);
84
+ }
85
+ }
86
+ /**
87
+ * Get all session keys
88
+ */
89
+ static getAllSessionKeys() {
90
+ const keys = [];
91
+ try {
92
+ for (let i = 0; i < localStorage.length; i++) {
93
+ const key = localStorage.key(i);
94
+ if (key && key.startsWith(this.STORAGE_PREFIX)) {
95
+ keys.push(key);
96
+ }
97
+ }
98
+ } catch (e) {
99
+ console.error("Failed to get session keys:", e);
100
+ }
101
+ return keys;
102
+ }
103
+ /**
104
+ * Clear all sessions
105
+ */
106
+ static clearAllSessions() {
107
+ try {
108
+ const keys = this.getAllSessionKeys();
109
+ keys.forEach((key) => localStorage.removeItem(key));
110
+ console.log(`Cleared ${keys.length} session(s)`);
111
+ } catch (e) {
112
+ console.error("Failed to clear sessions:", e);
113
+ }
114
+ }
115
+ /**
116
+ * Get total storage usage in bytes
117
+ */
118
+ static getStorageSize() {
119
+ let total = 0;
120
+ try {
121
+ for (let i = 0; i < localStorage.length; i++) {
122
+ const key = localStorage.key(i);
123
+ if (key && key.startsWith(this.STORAGE_PREFIX)) {
124
+ const value = localStorage.getItem(key);
125
+ if (value) {
126
+ total += (key.length + value.length) * 2;
127
+ }
128
+ }
129
+ }
130
+ } catch (e) {
131
+ console.error("Failed to calculate storage size:", e);
132
+ }
133
+ return total;
134
+ }
135
+ /**
136
+ * Remove sessions older than maxAge milliseconds
137
+ */
138
+ static pruneOldSessions(maxAge) {
139
+ try {
140
+ const now = Date.now();
141
+ const keys = this.getAllSessionKeys();
142
+ keys.forEach((key) => {
143
+ const value = localStorage.getItem(key);
144
+ if (!value) return;
145
+ try {
146
+ const session = JSON.parse(value);
147
+ const age = now - session.lastModified;
148
+ if (age > maxAge) {
149
+ console.log(`Pruning old session: ${key} (age: ${Math.round(age / (24 * 60 * 60 * 1e3))} days)`);
150
+ localStorage.removeItem(key);
151
+ }
152
+ } catch (e) {
153
+ console.warn(`Removing corrupted session: ${key}`);
154
+ localStorage.removeItem(key);
155
+ }
156
+ });
157
+ } catch (e) {
158
+ console.error("Failed to prune sessions:", e);
159
+ }
160
+ }
161
+ /**
162
+ * Compute SHA-256 hash of file content using Web Crypto API
163
+ */
164
+ static async hashFileContent(content) {
165
+ try {
166
+ const encoder = new TextEncoder();
167
+ const data = encoder.encode(content);
168
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
169
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
170
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
171
+ return hashHex;
172
+ } catch (e) {
173
+ console.error("Failed to hash content:", e);
174
+ return this.simpleHash(content);
175
+ }
176
+ }
177
+ /**
178
+ * Simple hash fallback (for environments without Web Crypto API)
179
+ */
180
+ static simpleHash(str) {
181
+ let hash = 0;
182
+ for (let i = 0; i < str.length; i++) {
183
+ const char = str.charCodeAt(i);
184
+ hash = (hash << 5) - hash + char;
185
+ hash = hash & hash;
186
+ }
187
+ return hash.toString(16);
188
+ }
189
+ /**
190
+ * Get most recently modified session
191
+ */
192
+ static getLastActiveSession() {
193
+ try {
194
+ const keys = this.getAllSessionKeys();
195
+ if (keys.length === 0) return null;
196
+ let latestSession = null;
197
+ let latestTime = 0;
198
+ keys.forEach((key) => {
199
+ const value = localStorage.getItem(key);
200
+ if (!value) return;
201
+ try {
202
+ const session = JSON.parse(value);
203
+ if (!session.version || !session.sourceLocation || !session.editHistory) {
204
+ console.warn(`Skipping invalid session: ${key}`);
205
+ return;
206
+ }
207
+ if (session.lastModified > latestTime) {
208
+ latestTime = session.lastModified;
209
+ latestSession = session;
210
+ }
211
+ } catch (e) {
212
+ console.warn(`Skipping corrupted session: ${key}`);
213
+ }
214
+ });
215
+ return latestSession;
216
+ } catch (e) {
217
+ console.error("Failed to get last active session:", e);
218
+ return null;
219
+ }
220
+ }
221
+ };
222
+ _AIEditorStorage.STORAGE_PREFIX = "ai-editor:session:";
223
+ _AIEditorStorage.VERSION = "1.0.0";
224
+ _AIEditorStorage.MAX_STORAGE_SIZE = 5 * 1024 * 1024;
225
+ let AIEditorStorage = _AIEditorStorage;
226
+ const ENABLE_SESSION_PERSISTENCE = false;
227
+ const sourceResolutionCache = /* @__PURE__ */ new Map();
228
+ const inflightSourceResolutions = /* @__PURE__ */ new Map();
229
+ function inferComponentNameFromPath(filePath) {
230
+ const fileName = filePath.split("/").pop() || "";
231
+ const nameWithoutExt = fileName.replace(/\.(tsx?|jsx?)$/, "");
232
+ return nameWithoutExt.charAt(0).toUpperCase() + nameWithoutExt.slice(1);
233
+ }
234
+ async function resolveSourceLocation(source) {
235
+ if (typeof window === "undefined" || process.env.NODE_ENV !== "development") {
236
+ return null;
237
+ }
238
+ if (!source.debugStack) {
239
+ console.warn("No debugStack available for resolution:", source);
240
+ return null;
241
+ }
242
+ const cacheKey = source.debugStack;
243
+ const cached = sourceResolutionCache.get(cacheKey);
244
+ if (cached) {
245
+ const resolved2 = { ...source, ...cached };
246
+ if (resolved2.componentName === "Unknown" && resolved2.filePath) {
247
+ resolved2.componentName = inferComponentNameFromPath(resolved2.filePath);
248
+ }
249
+ return resolved2;
250
+ }
251
+ let inflight = inflightSourceResolutions.get(cacheKey);
252
+ if (!inflight) {
253
+ inflight = fetch("/api/ai-editor/resolve", {
254
+ method: "POST",
255
+ headers: { "Content-Type": "application/json" },
256
+ body: JSON.stringify({ debugStack: cacheKey })
257
+ }).then(async (res) => {
258
+ if (!res.ok) {
259
+ const errorText = await res.text();
260
+ console.error(
261
+ `Resolve API error ${res.status}:`,
262
+ errorText,
263
+ "for stack:",
264
+ cacheKey.substring(0, 200)
265
+ );
266
+ return inferFilePathFromComponentName(source.componentName);
267
+ }
268
+ const data = await res.json();
269
+ if ((data == null ? void 0 : data.success) && data.filePath && data.lineNumber) {
270
+ const resolved2 = {
271
+ filePath: data.filePath,
272
+ lineNumber: data.lineNumber,
273
+ columnNumber: typeof data.columnNumber === "number" ? data.columnNumber : source.columnNumber
274
+ };
275
+ sourceResolutionCache.set(cacheKey, resolved2);
276
+ return resolved2;
277
+ }
278
+ console.warn("Resolve API returned unsuccessful response:", data);
279
+ return inferFilePathFromComponentName(source.componentName);
280
+ }).catch((err) => {
281
+ console.error("Error calling resolve API:", err);
282
+ return inferFilePathFromComponentName(source.componentName);
283
+ }).finally(() => {
284
+ inflightSourceResolutions.delete(cacheKey);
285
+ });
286
+ inflightSourceResolutions.set(cacheKey, inflight);
287
+ }
288
+ const resolvedInfo = await inflight;
289
+ if (!resolvedInfo) return null;
290
+ const resolved = {
291
+ ...source,
292
+ filePath: resolvedInfo.filePath,
293
+ lineNumber: resolvedInfo.lineNumber,
294
+ columnNumber: resolvedInfo.columnNumber
295
+ };
296
+ if (resolved.componentName === "Unknown" && resolved.filePath) {
297
+ resolved.componentName = inferComponentNameFromPath(resolved.filePath);
298
+ }
299
+ return resolved;
300
+ }
301
+ async function inferFilePathFromComponentName(componentName) {
302
+ if (!componentName || componentName === "Unknown") return null;
303
+ const possiblePaths = [
304
+ `components/${componentName}.tsx`,
305
+ `components/${componentName}.jsx`,
306
+ `app/${componentName}.tsx`,
307
+ `app/${componentName}.jsx`,
308
+ `src/components/${componentName}.tsx`,
309
+ `src/components/${componentName}.jsx`
310
+ ];
311
+ for (const tryPath of possiblePaths) {
312
+ try {
313
+ const response = await fetch(
314
+ `/api/ai-editor/absolute-path?path=${encodeURIComponent(tryPath)}`
315
+ );
316
+ if (response.ok) {
317
+ const data = await response.json();
318
+ if (data.success) {
319
+ console.log(
320
+ `Inferred file path for ${componentName}: ${tryPath}`
321
+ );
322
+ return {
323
+ filePath: tryPath,
324
+ lineNumber: 1,
325
+ columnNumber: 0
326
+ };
327
+ }
328
+ }
329
+ } catch (err) {
330
+ }
331
+ }
332
+ console.warn(`Could not infer file path for component: ${componentName}`);
333
+ return null;
334
+ }
335
+ const EditorContext = react.createContext(null);
336
+ function useAIEditor() {
337
+ const ctx = react.useContext(EditorContext);
338
+ if (!ctx) throw new Error("useAIEditor must be used within AIEditorProvider");
339
+ return ctx;
340
+ }
341
+ function getFiberFromElement(element) {
342
+ const key = Object.keys(element).find(
343
+ (k) => k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$")
344
+ );
345
+ return key ? element[key] : null;
346
+ }
347
+ function getComponentName(fiber) {
348
+ var _a;
349
+ if (!fiber) return "Unknown";
350
+ const type = fiber.type;
351
+ if (typeof type === "string") return type;
352
+ if (typeof type === "function")
353
+ return type.displayName || type.name || "Anonymous";
354
+ if (type == null ? void 0 : type.displayName) return type.displayName;
355
+ if ((_a = type == null ? void 0 : type.render) == null ? void 0 : _a.name) return type.render.name;
356
+ return "Unknown";
357
+ }
358
+ function isUserComponent(fiber) {
359
+ if (fiber.tag === 5 || fiber.tag === 6 || fiber.tag === 3) return false;
360
+ const type = fiber.type;
361
+ if (!type || typeof type === "string") return false;
362
+ return true;
363
+ }
364
+ function captureElementContext(element, fiber) {
365
+ const tagName = element.tagName.toLowerCase();
366
+ let textContent;
367
+ const directText = Array.from(element.childNodes).filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => {
368
+ var _a;
369
+ return (_a = n.textContent) == null ? void 0 : _a.trim();
370
+ }).filter(Boolean).join(" ");
371
+ if (directText) {
372
+ textContent = directText.slice(0, 50);
373
+ } else if (element.textContent) {
374
+ textContent = element.textContent.trim().slice(0, 50);
375
+ }
376
+ const className = typeof element.className === "string" ? element.className.slice(0, 100) : void 0;
377
+ const nthOfType = countNthOfType(element, tagName);
378
+ const key = (fiber == null ? void 0 : fiber.key) ? String(fiber.key) : void 0;
379
+ const props = extractProps(fiber);
380
+ return { tagName, textContent, className, key, nthOfType, props };
381
+ }
382
+ function countNthOfType(element, tagName) {
383
+ let boundary = element.parentElement;
384
+ while (boundary) {
385
+ const fiber = getFiberFromElement(boundary);
386
+ if (fiber && isUserComponent(fiber)) break;
387
+ boundary = boundary.parentElement;
388
+ }
389
+ if (!boundary) boundary = element.parentElement;
390
+ if (!boundary) return 1;
391
+ const sameTagElements = [];
392
+ if (boundary.tagName.toLowerCase() === tagName.toLowerCase()) {
393
+ sameTagElements.push(boundary);
394
+ }
395
+ sameTagElements.push(...Array.from(boundary.querySelectorAll(tagName)));
396
+ let count = 1;
397
+ for (const el of sameTagElements) {
398
+ if (el === element) break;
399
+ count++;
400
+ }
401
+ console.log(
402
+ `[countNthOfType] tagName=${tagName}, found ${sameTagElements.length} elements (including boundary), this is #${count}`
403
+ );
404
+ return count;
405
+ }
406
+ function extractProps(fiber) {
407
+ if (!fiber) return void 0;
408
+ const fiberProps = fiber.memoizedProps || fiber.pendingProps;
409
+ if (!fiberProps || typeof fiberProps !== "object") return void 0;
410
+ const props = {};
411
+ const identifyingKeys = [
412
+ "id",
413
+ "name",
414
+ "type",
415
+ "href",
416
+ "src",
417
+ "alt",
418
+ "role",
419
+ "aria-label",
420
+ "data-testid"
421
+ ];
422
+ for (const key of identifyingKeys) {
423
+ if (key in fiberProps && typeof fiberProps[key] === "string") {
424
+ props[key] = fiberProps[key];
425
+ }
426
+ }
427
+ if (fiberProps.style && typeof fiberProps.style === "object") {
428
+ props._styleKeys = Object.keys(fiberProps.style).slice(0, 5);
429
+ }
430
+ return Object.keys(props).length > 0 ? props : void 0;
431
+ }
432
+ function findSourceFromFiber(fiber) {
433
+ if (!fiber) return null;
434
+ let current = fiber;
435
+ const visited = /* @__PURE__ */ new Set();
436
+ while (current && !visited.has(current)) {
437
+ visited.add(current);
438
+ const sourceData = current._debugSource || extractFromDebugStack(current) || extractFromDebugOwner(current);
439
+ if (sourceData == null ? void 0 : sourceData.fileName) {
440
+ const filePath = cleanPath(sourceData.fileName);
441
+ if (!shouldSkip(filePath)) {
442
+ let componentFiber = current;
443
+ while (componentFiber) {
444
+ if (isUserComponent(componentFiber)) {
445
+ const componentName = getComponentName(componentFiber);
446
+ const isNextJSInternal = [
447
+ "Segment",
448
+ "Boundary",
449
+ "Router",
450
+ "Handler",
451
+ "Context",
452
+ "Layout",
453
+ "Template",
454
+ "Scroll",
455
+ "Focus",
456
+ "Loading",
457
+ "Error"
458
+ ].some((pattern) => componentName.includes(pattern));
459
+ if (!isNextJSInternal) {
460
+ const rawDebugStack = current._debugStack ? String(current._debugStack.stack || current._debugStack) : void 0;
461
+ return {
462
+ filePath,
463
+ lineNumber: sourceData.lineNumber || 1,
464
+ columnNumber: sourceData.columnNumber || 0,
465
+ componentName,
466
+ debugStack: rawDebugStack
467
+ };
468
+ }
469
+ }
470
+ componentFiber = componentFiber.return || componentFiber._debugOwner || null;
471
+ }
472
+ }
473
+ }
474
+ current = current.return || current._debugOwner || null;
475
+ }
476
+ return null;
477
+ }
478
+ function extractFromDebugStack(fiber) {
479
+ const stack = fiber._debugStack;
480
+ if (!stack) return null;
481
+ const stackStr = stack.stack || String(stack);
482
+ const frames = stackStr.split("\n");
483
+ const skipPatterns = [
484
+ "node_modules",
485
+ "SegmentViewNode",
486
+ "LayoutRouter",
487
+ "ErrorBoundary",
488
+ "fakeJSXCallSite"
489
+ ];
490
+ for (const frame of frames) {
491
+ if (skipPatterns.some((p) => frame.includes(p))) continue;
492
+ const match = frame.match(/at\s+(\w+)\s+\((.+?):(\d+):(\d+)\)?$/);
493
+ if (match) {
494
+ const fileName = cleanPath(match[2].replace(/\?[^:]*$/, ""));
495
+ if (!shouldSkip(fileName)) {
496
+ return {
497
+ fileName,
498
+ lineNumber: parseInt(match[3], 10),
499
+ columnNumber: parseInt(match[4], 10)
500
+ };
501
+ }
502
+ }
503
+ }
504
+ return null;
505
+ }
506
+ function extractFromDebugOwner(fiber) {
507
+ var _a, _b;
508
+ const owner = fiber._debugOwner;
509
+ if (!owner) return null;
510
+ if ((_a = owner._debugSource) == null ? void 0 : _a.fileName) {
511
+ return owner._debugSource;
512
+ }
513
+ const stack = owner.stack;
514
+ if (Array.isArray(stack) && ((_b = stack[0]) == null ? void 0 : _b.fileName)) {
515
+ return stack[0];
516
+ }
517
+ return null;
518
+ }
519
+ function cleanPath(p) {
520
+ let cleaned = p;
521
+ if (cleaned.startsWith("file://")) {
522
+ cleaned = cleaned.replace(/^file:\/\//, "");
523
+ }
524
+ try {
525
+ if (cleaned.includes("%")) {
526
+ cleaned = decodeURIComponent(cleaned);
527
+ }
528
+ } catch (e) {
529
+ }
530
+ cleaned = cleaned.replace(/^webpack-internal:\/\/\/\([^)]+\)\/\.\//, "").replace(/^webpack-internal:\/\/\/\([^)]+\)\//, "").replace(/^webpack-internal:\/\//, "").replace(/^webpack:\/\/[^/]*\//, "").replace(/^about:\/\/React\/Server\//, "").replace(/^\([^)]+\)\//, "").replace(/^\.\//, "").replace(/\?.*$/, "");
531
+ return cleaned;
532
+ }
533
+ function shouldSkip(p) {
534
+ if (!p) return true;
535
+ return ["node_modules", "next/dist", "react-dom", "ai-editor-provider"].some(
536
+ (s) => p.includes(s)
537
+ );
538
+ }
539
+ function getSourceFromElement(element) {
540
+ let current = element;
541
+ let fiber = null;
542
+ while (current && current !== document.body) {
543
+ fiber = getFiberFromElement(current);
544
+ if (fiber) break;
545
+ current = current.parentElement;
546
+ }
547
+ if (!fiber) return null;
548
+ const source = findSourceFromFiber(fiber);
549
+ if (!source) return null;
550
+ const elementContext = captureElementContext(element, fiber);
551
+ return { ...source, elementContext };
552
+ }
553
+ if (typeof window !== "undefined") {
554
+ window.__getSource = getSourceFromElement;
555
+ }
556
+ function AIEditorProvider({
557
+ children,
558
+ theme = "dark"
559
+ }) {
560
+ const [isEnabled, setEnabled] = react.useState(false);
561
+ const [selectedSource, setSelectedSource] = react.useState(
562
+ null
563
+ );
564
+ const [selectedDOMElement, setSelectedDOMElement] = react.useState(
565
+ null
566
+ );
567
+ const [isLoading, setIsLoading] = react.useState(false);
568
+ const [editHistory, setEditHistory] = react.useState([]);
569
+ const [showStaleWarning, setShowStaleWarning] = react.useState(false);
570
+ const [staleSession, setStaleSession] = react.useState(null);
571
+ const [hasActiveSession, setHasActiveSession] = react.useState(false);
572
+ react.useEffect(() => {
573
+ const handleKey = (e) => {
574
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "e") {
575
+ e.preventDefault();
576
+ setEnabled((p) => !p);
577
+ }
578
+ };
579
+ window.addEventListener("keydown", handleKey);
580
+ return () => window.removeEventListener("keydown", handleKey);
581
+ }, []);
582
+ react.useEffect(() => {
583
+ return;
584
+ }, []);
585
+ const restoreSession = react.useCallback(async (session) => {
586
+ const sourceLocation = session.sourceLocation;
587
+ setSelectedSource(sourceLocation);
588
+ setEditHistory(session.editHistory);
589
+ if (sourceLocation.debugStack) {
590
+ const resolved = await resolveSourceLocation(sourceLocation);
591
+ if (resolved) {
592
+ setSelectedSource(resolved);
593
+ }
594
+ }
595
+ }, []);
596
+ const handleClearSession = react.useCallback(() => {
597
+ if (selectedSource) {
598
+ AIEditorStorage.deleteSession(
599
+ selectedSource.filePath,
600
+ selectedSource.componentName
601
+ );
602
+ setHasActiveSession(false);
603
+ setSelectedSource(null);
604
+ setEditHistory([]);
605
+ }
606
+ }, [selectedSource]);
607
+ const submitEdit = react.useCallback(
608
+ async (suggestion) => {
609
+ if (!selectedSource)
610
+ return { success: false, error: "No element selected" };
611
+ setIsLoading(true);
612
+ try {
613
+ const res = await fetch("/api/ai-editor/edit", {
614
+ method: "POST",
615
+ headers: { "Content-Type": "application/json" },
616
+ body: JSON.stringify({
617
+ filePath: selectedSource.filePath,
618
+ lineNumber: selectedSource.lineNumber,
619
+ componentName: selectedSource.componentName,
620
+ suggestion,
621
+ // NEW: Pass element context for precise matching
622
+ elementContext: selectedSource.elementContext,
623
+ // Pass debugStack for server-side source map resolution
624
+ debugStack: selectedSource.debugStack,
625
+ // Pass edit history for context
626
+ editHistory: editHistory.map((item) => ({
627
+ suggestion: item.suggestion,
628
+ success: item.success
629
+ }))
630
+ })
631
+ });
632
+ const result = await res.json();
633
+ const editId = Date.now().toString(36) + Math.random().toString(36).substring(2);
634
+ const newHistoryItem = {
635
+ id: editId,
636
+ suggestion,
637
+ success: result.success,
638
+ error: result.error,
639
+ timestamp: Date.now(),
640
+ fileSnapshot: result.fileSnapshot,
641
+ generatedCode: result.generatedCode,
642
+ modifiedLines: result.modifiedLines
643
+ };
644
+ setEditHistory((prev) => [...prev, newHistoryItem]);
645
+ if (ENABLE_SESSION_PERSISTENCE && selectedSource && result.fileSnapshot) ;
646
+ return result;
647
+ } catch (err) {
648
+ const error = String(err);
649
+ const editId = Date.now().toString(36) + Math.random().toString(36).substring(2);
650
+ setEditHistory((prev) => [
651
+ ...prev,
652
+ {
653
+ id: editId,
654
+ suggestion,
655
+ success: false,
656
+ error,
657
+ timestamp: Date.now()
658
+ }
659
+ ]);
660
+ return { success: false, error };
661
+ } finally {
662
+ setIsLoading(false);
663
+ }
664
+ },
665
+ [selectedSource, editHistory]
666
+ );
667
+ const handleSelect = react.useCallback(
668
+ (element, source) => {
669
+ setSelectedDOMElement(element);
670
+ setSelectedSource(source);
671
+ setEditHistory([]);
672
+ resolveSourceLocation(source).then((resolved) => {
673
+ if (resolved) {
674
+ setSelectedSource((prev) => prev === source ? resolved : prev);
675
+ }
676
+ });
677
+ },
678
+ [setSelectedDOMElement, setSelectedSource]
679
+ );
680
+ if (process.env.NODE_ENV !== "development") {
681
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children });
682
+ }
683
+ return /* @__PURE__ */ jsxRuntime.jsxs(
684
+ EditorContext.Provider,
685
+ {
686
+ value: {
687
+ isEnabled,
688
+ setEnabled,
689
+ selectedSource,
690
+ setSelectedSource,
691
+ selectedDOMElement,
692
+ isLoading,
693
+ setIsLoading,
694
+ editHistory,
695
+ setEditHistory,
696
+ submitEdit
697
+ },
698
+ children: [
699
+ children,
700
+ isEnabled && /* @__PURE__ */ jsxRuntime.jsx(
701
+ EditorOverlay,
702
+ {
703
+ theme,
704
+ onSelect: handleSelect,
705
+ showStaleWarning,
706
+ staleSession,
707
+ hasActiveSession,
708
+ setShowStaleWarning,
709
+ setStaleSession,
710
+ setHasActiveSession,
711
+ restoreSession,
712
+ handleClearSession
713
+ }
714
+ )
715
+ ]
716
+ }
717
+ );
718
+ }
719
+ function EditorOverlay({
720
+ theme,
721
+ onSelect,
722
+ showStaleWarning,
723
+ staleSession,
724
+ hasActiveSession,
725
+ setShowStaleWarning,
726
+ setStaleSession,
727
+ setHasActiveSession,
728
+ restoreSession,
729
+ handleClearSession
730
+ }) {
731
+ var _a;
732
+ const {
733
+ selectedSource,
734
+ setSelectedSource,
735
+ submitEdit,
736
+ isLoading,
737
+ setIsLoading,
738
+ setEnabled,
739
+ selectedDOMElement,
740
+ editHistory,
741
+ setEditHistory
742
+ } = useAIEditor();
743
+ const [hoveredSource, setHoveredSource] = react.useState(
744
+ null
745
+ );
746
+ const [hoveredElement, setHoveredElement] = react.useState(null);
747
+ const [hoveredRect, setHoveredRect] = react.useState(null);
748
+ const [mousePos, setMousePos] = react.useState({ x: 0, y: 0 });
749
+ const [isResolvingSource, setIsResolvingSource] = react.useState(false);
750
+ const [suggestion, setSuggestion] = react.useState("");
751
+ const [result, setResult] = react.useState(null);
752
+ const [code, setCode] = react.useState("");
753
+ const [codeLineStart, setCodeLineStart] = react.useState(1);
754
+ const [targetStartLine, setTargetStartLine] = react.useState(null);
755
+ const [targetEndLine, setTargetEndLine] = react.useState(null);
756
+ const [absolutePath, setAbsolutePath] = react.useState(null);
757
+ const [parsedComponentName, setParsedComponentName] = react.useState(
758
+ null
759
+ );
760
+ const isDark = theme === "dark";
761
+ react.useEffect(() => {
762
+ var _a2, _b, _c, _d;
763
+ if (selectedSource) {
764
+ const params = {
765
+ path: selectedSource.filePath,
766
+ line: String(selectedSource.lineNumber),
767
+ tagName: ((_a2 = selectedSource.elementContext) == null ? void 0 : _a2.tagName) || "",
768
+ nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
769
+ textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
770
+ className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
771
+ };
772
+ if (selectedSource.debugStack) {
773
+ params.debugStack = selectedSource.debugStack;
774
+ }
775
+ fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
776
+ if (d.success) {
777
+ console.log("[AI Editor] Read response:", {
778
+ lineStart: d.lineStart,
779
+ targetStartLine: d.targetStartLine,
780
+ targetEndLine: d.targetEndLine,
781
+ componentName: d.componentName
782
+ });
783
+ setCode(d.content);
784
+ setCodeLineStart(d.lineStart || 1);
785
+ setTargetStartLine(d.targetStartLine || null);
786
+ setTargetEndLine(d.targetEndLine || null);
787
+ if (d.componentName) {
788
+ setParsedComponentName(d.componentName);
789
+ }
790
+ }
791
+ }).catch(() => {
792
+ setCode("// Could not load");
793
+ setCodeLineStart(1);
794
+ setTargetStartLine(null);
795
+ setTargetEndLine(null);
796
+ });
797
+ fetch(
798
+ `/api/ai-editor/absolute-path?` + new URLSearchParams({ path: selectedSource.filePath })
799
+ ).then((r) => r.json()).then((d) => d.success && setAbsolutePath(d.absolutePath)).catch(() => setAbsolutePath(null));
800
+ } else {
801
+ setAbsolutePath(null);
802
+ setParsedComponentName(null);
803
+ }
804
+ }, [selectedSource]);
805
+ react.useEffect(() => {
806
+ let lastEl = null;
807
+ let raf;
808
+ const onMove = (e) => {
809
+ setMousePos({ x: e.clientX, y: e.clientY });
810
+ if (selectedSource) return;
811
+ cancelAnimationFrame(raf);
812
+ raf = requestAnimationFrame(() => {
813
+ const el = document.elementFromPoint(e.clientX, e.clientY);
814
+ if (!el || el.closest(".ai-editor-ui") || el === lastEl) return;
815
+ lastEl = el;
816
+ const source = getSourceFromElement(el);
817
+ if (source) {
818
+ setHoveredElement(el);
819
+ setHoveredRect(el.getBoundingClientRect());
820
+ const isCompiledPath = source.filePath.includes(".next/") || source.filePath.includes("/chunks/") || source.filePath.startsWith("file://") || source.filePath.endsWith(".js") && (source.filePath.includes("/server/") || source.filePath.includes("/static/"));
821
+ if (isCompiledPath && source.debugStack) {
822
+ setIsResolvingSource(true);
823
+ resolveSourceLocation(source).then((resolved) => {
824
+ setIsResolvingSource(false);
825
+ if (resolved) {
826
+ console.log("Resolved source location:", resolved);
827
+ setHoveredSource(resolved);
828
+ } else {
829
+ console.warn(
830
+ "Failed to resolve source location for:",
831
+ source
832
+ );
833
+ setHoveredSource(source);
834
+ }
835
+ }).catch((err) => {
836
+ console.error("Error resolving source location:", err);
837
+ setIsResolvingSource(false);
838
+ setHoveredSource(source);
839
+ });
840
+ } else if (isCompiledPath && !source.debugStack) {
841
+ console.warn("Compiled path but no debugStack:", source);
842
+ setIsResolvingSource(false);
843
+ setHoveredSource(source);
844
+ } else {
845
+ setIsResolvingSource(false);
846
+ setHoveredSource(source);
847
+ }
848
+ } else {
849
+ setHoveredSource(null);
850
+ setHoveredElement(null);
851
+ setHoveredRect(null);
852
+ setIsResolvingSource(false);
853
+ }
854
+ });
855
+ };
856
+ const onClick = (e) => {
857
+ if (e.target.closest(".ai-editor-ui")) return;
858
+ if (hoveredSource && hoveredElement) {
859
+ e.preventDefault();
860
+ e.stopPropagation();
861
+ onSelect(hoveredElement, hoveredSource);
862
+ setSuggestion("");
863
+ setResult(null);
864
+ }
865
+ };
866
+ document.addEventListener("mousemove", onMove, { passive: true });
867
+ document.addEventListener("click", onClick, true);
868
+ return () => {
869
+ document.removeEventListener("mousemove", onMove);
870
+ document.removeEventListener("click", onClick, true);
871
+ cancelAnimationFrame(raf);
872
+ };
873
+ }, [hoveredSource, hoveredElement, selectedSource, onSelect]);
874
+ const handleSubmit = async () => {
875
+ var _a2, _b, _c, _d;
876
+ if (!suggestion.trim()) return;
877
+ const res = await submitEdit(suggestion);
878
+ setResult(res);
879
+ if (res.success) {
880
+ setSuggestion("");
881
+ if (selectedSource) {
882
+ const params = {
883
+ path: selectedSource.filePath,
884
+ line: String(selectedSource.lineNumber),
885
+ tagName: ((_a2 = selectedSource.elementContext) == null ? void 0 : _a2.tagName) || "",
886
+ nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
887
+ textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
888
+ className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
889
+ };
890
+ if (selectedSource.debugStack) {
891
+ params.debugStack = selectedSource.debugStack;
892
+ }
893
+ fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
894
+ if (d.success) {
895
+ setCode(d.content);
896
+ setCodeLineStart(d.lineStart || 1);
897
+ setTargetStartLine(d.targetStartLine || null);
898
+ setTargetEndLine(d.targetEndLine || null);
899
+ if (d.componentName) {
900
+ setParsedComponentName(d.componentName);
901
+ }
902
+ }
903
+ }).catch(console.error);
904
+ }
905
+ setTimeout(() => setResult(null), 3e3);
906
+ }
907
+ };
908
+ const handleUndo = async () => {
909
+ var _a2, _b, _c, _d;
910
+ if (editHistory.length === 0 || !selectedSource) return;
911
+ const lastSuccessfulEdit = [...editHistory].reverse().find((edit) => edit.success && edit.fileSnapshot);
912
+ if (!lastSuccessfulEdit) {
913
+ console.warn("No successful edit with snapshot found to undo");
914
+ return;
915
+ }
916
+ setIsLoading(true);
917
+ try {
918
+ const response = await fetch("/api/ai-editor/undo", {
919
+ method: "POST",
920
+ headers: { "Content-Type": "application/json" },
921
+ body: JSON.stringify({
922
+ filePath: selectedSource.filePath,
923
+ content: lastSuccessfulEdit.fileSnapshot
924
+ })
925
+ });
926
+ const result2 = await response.json();
927
+ if (!result2.success) {
928
+ throw new Error(result2.error || "Undo failed");
929
+ }
930
+ setEditHistory((prev) => {
931
+ const lastIndex = prev.lastIndexOf(lastSuccessfulEdit);
932
+ return prev.filter((_, idx) => idx !== lastIndex);
933
+ });
934
+ const params = {
935
+ path: selectedSource.filePath,
936
+ line: String(selectedSource.lineNumber),
937
+ tagName: ((_a2 = selectedSource.elementContext) == null ? void 0 : _a2.tagName) || "",
938
+ nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
939
+ textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
940
+ className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
941
+ };
942
+ if (selectedSource.debugStack) {
943
+ params.debugStack = selectedSource.debugStack;
944
+ }
945
+ fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
946
+ if (d.success) {
947
+ setCode(d.content);
948
+ setCodeLineStart(d.lineStart || 1);
949
+ setTargetStartLine(d.targetStartLine || null);
950
+ setTargetEndLine(d.targetEndLine || null);
951
+ if (d.componentName) {
952
+ setParsedComponentName(d.componentName);
953
+ }
954
+ }
955
+ }).catch(console.error);
956
+ setResult({ success: true, error: void 0 });
957
+ setTimeout(() => setResult(null), 3e3);
958
+ } catch (error) {
959
+ console.error("Undo error:", error);
960
+ setResult({ success: false, error: String(error) });
961
+ } finally {
962
+ setIsLoading(false);
963
+ }
964
+ };
965
+ const handleRetry = async (editIndex) => {
966
+ var _a2, _b, _c, _d;
967
+ const editToRetry = editHistory[editIndex];
968
+ if (!editToRetry) return;
969
+ const res = await submitEdit(editToRetry.suggestion);
970
+ if (res.success && selectedSource) {
971
+ const params = {
972
+ path: selectedSource.filePath,
973
+ line: String(selectedSource.lineNumber),
974
+ tagName: ((_a2 = selectedSource.elementContext) == null ? void 0 : _a2.tagName) || "",
975
+ nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
976
+ textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
977
+ className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
978
+ };
979
+ if (selectedSource.debugStack) {
980
+ params.debugStack = selectedSource.debugStack;
981
+ }
982
+ fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
983
+ if (d.success) {
984
+ setCode(d.content);
985
+ setCodeLineStart(d.lineStart || 1);
986
+ setTargetStartLine(d.targetStartLine || null);
987
+ setTargetEndLine(d.targetEndLine || null);
988
+ if (d.componentName) {
989
+ setParsedComponentName(d.componentName);
990
+ }
991
+ }
992
+ }).catch(console.error);
993
+ }
994
+ };
995
+ const handleUndoAndRetry = async () => {
996
+ var _a2, _b, _c, _d;
997
+ if (editHistory.length === 0 || !selectedSource) return;
998
+ const lastSuccessfulEdit = [...editHistory].reverse().find((edit) => edit.success && edit.fileSnapshot);
999
+ if (!lastSuccessfulEdit) {
1000
+ console.warn("No successful edit with snapshot found to undo and retry");
1001
+ return;
1002
+ }
1003
+ setIsLoading(true);
1004
+ try {
1005
+ const undoResponse = await fetch("/api/ai-editor/undo", {
1006
+ method: "POST",
1007
+ headers: { "Content-Type": "application/json" },
1008
+ body: JSON.stringify({
1009
+ filePath: selectedSource.filePath,
1010
+ content: lastSuccessfulEdit.fileSnapshot
1011
+ })
1012
+ });
1013
+ const undoResult = await undoResponse.json();
1014
+ if (!undoResult.success) {
1015
+ throw new Error(undoResult.error || "Undo failed");
1016
+ }
1017
+ setEditHistory((prev) => {
1018
+ const lastIndex = prev.lastIndexOf(lastSuccessfulEdit);
1019
+ return prev.filter((_, idx) => idx !== lastIndex);
1020
+ });
1021
+ const params = {
1022
+ path: selectedSource.filePath,
1023
+ line: String(selectedSource.lineNumber),
1024
+ tagName: ((_a2 = selectedSource.elementContext) == null ? void 0 : _a2.tagName) || "",
1025
+ nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
1026
+ textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
1027
+ className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
1028
+ };
1029
+ if (selectedSource.debugStack) {
1030
+ params.debugStack = selectedSource.debugStack;
1031
+ }
1032
+ await fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
1033
+ if (d.success) {
1034
+ setCode(d.content);
1035
+ setCodeLineStart(d.lineStart || 1);
1036
+ setTargetStartLine(d.targetStartLine || null);
1037
+ setTargetEndLine(d.targetEndLine || null);
1038
+ if (d.componentName) {
1039
+ setParsedComponentName(d.componentName);
1040
+ }
1041
+ }
1042
+ }).catch(console.error);
1043
+ setIsLoading(true);
1044
+ const retryResult = await submitEdit(lastSuccessfulEdit.suggestion);
1045
+ if (retryResult.success && selectedSource) {
1046
+ await fetch(`/api/ai-editor/read?` + new URLSearchParams(params)).then((r) => r.json()).then((d) => {
1047
+ if (d.success) {
1048
+ setCode(d.content);
1049
+ setCodeLineStart(d.lineStart || 1);
1050
+ setTargetStartLine(d.targetStartLine || null);
1051
+ setTargetEndLine(d.targetEndLine || null);
1052
+ if (d.componentName) {
1053
+ setParsedComponentName(d.componentName);
1054
+ }
1055
+ }
1056
+ }).catch(console.error);
1057
+ }
1058
+ if (retryResult.success) {
1059
+ setResult({ success: true, error: void 0 });
1060
+ } else {
1061
+ setResult({ success: false, error: retryResult.error });
1062
+ }
1063
+ setTimeout(() => setResult(null), 3e3);
1064
+ } catch (error) {
1065
+ console.error("Undo and retry error:", error);
1066
+ setResult({ success: false, error: String(error) });
1067
+ } finally {
1068
+ setIsLoading(false);
1069
+ }
1070
+ };
1071
+ const handleDone = () => {
1072
+ window.location.reload();
1073
+ };
1074
+ const c = {
1075
+ bg: isDark ? "#0d0d14" : "#fff",
1076
+ bgAlt: isDark ? "#16162a" : "#f5f5f5",
1077
+ text: isDark ? "#e4e4e7" : "#18181b",
1078
+ muted: isDark ? "#71717a" : "#a1a1aa",
1079
+ accent: "#818cf8",
1080
+ border: isDark ? "#27273f" : "#e4e4e7",
1081
+ success: "#34d399",
1082
+ error: "#f87171"
1083
+ };
1084
+ const elCtx = selectedSource == null ? void 0 : selectedSource.elementContext;
1085
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1086
+ "div",
1087
+ {
1088
+ className: "ai-editor-ui",
1089
+ style: { fontFamily: "system-ui, sans-serif" },
1090
+ children: [
1091
+ hoveredRect && !selectedSource && /* @__PURE__ */ jsxRuntime.jsx(
1092
+ "div",
1093
+ {
1094
+ style: {
1095
+ position: "fixed",
1096
+ left: hoveredRect.left - 2,
1097
+ top: hoveredRect.top - 2,
1098
+ width: hoveredRect.width + 4,
1099
+ height: hoveredRect.height + 4,
1100
+ border: `2px solid ${c.accent}`,
1101
+ borderRadius: 6,
1102
+ background: `${c.accent}15`,
1103
+ pointerEvents: "none",
1104
+ zIndex: 99998
1105
+ }
1106
+ }
1107
+ ),
1108
+ hoveredSource && !selectedSource && !isResolvingSource && /* @__PURE__ */ jsxRuntime.jsxs(
1109
+ "div",
1110
+ {
1111
+ style: {
1112
+ position: "fixed",
1113
+ left: Math.min(mousePos.x + 14, window.innerWidth - 340),
1114
+ top: mousePos.y + 14,
1115
+ background: c.bg,
1116
+ color: c.text,
1117
+ border: `1px solid ${c.border}`,
1118
+ borderRadius: 10,
1119
+ padding: "12px 16px",
1120
+ fontSize: 12,
1121
+ fontFamily: "ui-monospace, monospace",
1122
+ zIndex: 99999,
1123
+ boxShadow: `0 8px 30px rgba(0,0,0,${isDark ? 0.5 : 0.15})`,
1124
+ maxWidth: 320,
1125
+ pointerEvents: "none"
1126
+ },
1127
+ children: [
1128
+ /* @__PURE__ */ jsxRuntime.jsxs(
1129
+ "div",
1130
+ {
1131
+ style: {
1132
+ fontWeight: 700,
1133
+ color: c.accent,
1134
+ marginBottom: 4,
1135
+ fontSize: 14
1136
+ },
1137
+ children: [
1138
+ "<",
1139
+ hoveredSource.componentName,
1140
+ " />"
1141
+ ]
1142
+ }
1143
+ ),
1144
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { color: c.muted, fontSize: 11 }, children: [
1145
+ hoveredSource.filePath,
1146
+ ":",
1147
+ hoveredSource.lineNumber
1148
+ ] }),
1149
+ ((_a = hoveredSource.elementContext) == null ? void 0 : _a.textContent) && /* @__PURE__ */ jsxRuntime.jsxs(
1150
+ "div",
1151
+ {
1152
+ style: {
1153
+ color: c.muted,
1154
+ fontSize: 10,
1155
+ marginTop: 4,
1156
+ fontStyle: "italic"
1157
+ },
1158
+ children: [
1159
+ '"',
1160
+ hoveredSource.elementContext.textContent,
1161
+ '"'
1162
+ ]
1163
+ }
1164
+ )
1165
+ ]
1166
+ }
1167
+ ),
1168
+ ENABLE_SESSION_PERSISTENCE,
1169
+ selectedSource && /* @__PURE__ */ jsxRuntime.jsxs(
1170
+ "div",
1171
+ {
1172
+ style: {
1173
+ position: "fixed",
1174
+ bottom: 20,
1175
+ right: 20,
1176
+ background: c.bg,
1177
+ color: c.text,
1178
+ borderRadius: 16,
1179
+ padding: 24,
1180
+ width: 560,
1181
+ maxWidth: "calc(100vw - 40px)",
1182
+ maxHeight: "calc(100vh - 40px)",
1183
+ overflowY: "auto",
1184
+ overflowX: "hidden",
1185
+ zIndex: 1e5,
1186
+ boxShadow: `0 24px 80px rgba(0,0,0,${isDark ? 0.6 : 0.25})`,
1187
+ border: `1px solid ${c.border}`
1188
+ },
1189
+ children: [
1190
+ /* @__PURE__ */ jsxRuntime.jsxs(
1191
+ "div",
1192
+ {
1193
+ style: {
1194
+ display: "flex",
1195
+ justifyContent: "space-between",
1196
+ marginBottom: 20
1197
+ },
1198
+ children: [
1199
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1200
+ /* @__PURE__ */ jsxRuntime.jsx(
1201
+ "div",
1202
+ {
1203
+ style: {
1204
+ fontSize: 11,
1205
+ textTransform: "uppercase",
1206
+ letterSpacing: 1,
1207
+ color: c.muted
1208
+ },
1209
+ children: "Editing"
1210
+ }
1211
+ ),
1212
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { fontSize: 20, fontWeight: 700, color: c.accent }, children: [
1213
+ "<",
1214
+ parsedComponentName || selectedSource.componentName,
1215
+ " />"
1216
+ ] }),
1217
+ /* @__PURE__ */ jsxRuntime.jsx(
1218
+ "div",
1219
+ {
1220
+ style: {
1221
+ fontSize: 12,
1222
+ color: c.muted,
1223
+ fontFamily: "monospace",
1224
+ marginTop: 4
1225
+ },
1226
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
1227
+ "a",
1228
+ {
1229
+ href: absolutePath ? `cursor://file/${absolutePath}:${selectedSource.lineNumber}` : `cursor://file/${selectedSource.filePath}:${selectedSource.lineNumber}`,
1230
+ onClick: (e) => {
1231
+ e.preventDefault();
1232
+ e.stopPropagation();
1233
+ const path = absolutePath || selectedSource.filePath;
1234
+ const cursorPath = path.startsWith("/") ? path : `/${path}`;
1235
+ window.location.href = `cursor://file${cursorPath}:${selectedSource.lineNumber}`;
1236
+ },
1237
+ style: {
1238
+ color: c.accent,
1239
+ textDecoration: "none",
1240
+ cursor: "pointer",
1241
+ borderBottom: `1px solid ${c.accent}40`
1242
+ },
1243
+ onMouseEnter: (e) => {
1244
+ e.currentTarget.style.borderBottomColor = c.accent;
1245
+ },
1246
+ onMouseLeave: (e) => {
1247
+ e.currentTarget.style.borderBottomColor = `${c.accent}40`;
1248
+ },
1249
+ children: [
1250
+ selectedSource.filePath,
1251
+ ":",
1252
+ selectedSource.lineNumber
1253
+ ]
1254
+ }
1255
+ )
1256
+ }
1257
+ ),
1258
+ (elCtx == null ? void 0 : elCtx.textContent) && /* @__PURE__ */ jsxRuntime.jsxs(
1259
+ "div",
1260
+ {
1261
+ style: {
1262
+ fontSize: 11,
1263
+ color: c.muted,
1264
+ marginTop: 4,
1265
+ fontStyle: "italic"
1266
+ },
1267
+ children: [
1268
+ 'Element text: "',
1269
+ elCtx.textContent,
1270
+ '"'
1271
+ ]
1272
+ }
1273
+ )
1274
+ ] }),
1275
+ /* @__PURE__ */ jsxRuntime.jsx(
1276
+ "button",
1277
+ {
1278
+ onClick: () => setSelectedSource(null),
1279
+ style: {
1280
+ width: 36,
1281
+ height: 36,
1282
+ borderRadius: 10,
1283
+ border: "none",
1284
+ background: c.bgAlt,
1285
+ color: c.muted,
1286
+ fontSize: 20,
1287
+ cursor: "pointer"
1288
+ },
1289
+ children: "×"
1290
+ }
1291
+ )
1292
+ ]
1293
+ }
1294
+ ),
1295
+ code && /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: 20 }, children: [
1296
+ /* @__PURE__ */ jsxRuntime.jsx(
1297
+ "div",
1298
+ {
1299
+ style: {
1300
+ fontSize: 11,
1301
+ fontWeight: 600,
1302
+ marginBottom: 8,
1303
+ color: c.muted,
1304
+ textTransform: "uppercase"
1305
+ },
1306
+ children: "Source Preview"
1307
+ }
1308
+ ),
1309
+ /* @__PURE__ */ jsxRuntime.jsx(
1310
+ reactSyntaxHighlighter.Prism,
1311
+ {
1312
+ language: "tsx",
1313
+ style: isDark ? prism.vscDarkPlus : prism.vs,
1314
+ showLineNumbers: true,
1315
+ startingLineNumber: codeLineStart,
1316
+ customStyle: {
1317
+ background: c.bgAlt,
1318
+ borderRadius: 10,
1319
+ fontSize: 14,
1320
+ margin: 0,
1321
+ maxHeight: 180,
1322
+ overflowX: "auto",
1323
+ border: `1px solid ${c.border}`
1324
+ },
1325
+ lineNumberStyle: {
1326
+ minWidth: "2.5em",
1327
+ paddingRight: "1em",
1328
+ color: c.muted,
1329
+ textAlign: "right",
1330
+ userSelect: "none"
1331
+ },
1332
+ wrapLines: true,
1333
+ lineProps: (lineNumber) => {
1334
+ const isHighlighted = targetStartLine !== null && targetEndLine !== null && lineNumber >= targetStartLine && lineNumber <= targetEndLine;
1335
+ return {
1336
+ style: {
1337
+ backgroundColor: isHighlighted ? isDark ? "rgba(102, 126, 234, 0.15)" : "rgba(147, 197, 253, 0.3)" : "transparent"
1338
+ }
1339
+ };
1340
+ },
1341
+ children: code
1342
+ }
1343
+ )
1344
+ ] }),
1345
+ editHistory.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: 20 }, children: [
1346
+ /* @__PURE__ */ jsxRuntime.jsxs(
1347
+ "div",
1348
+ {
1349
+ style: {
1350
+ fontSize: 11,
1351
+ fontWeight: 600,
1352
+ marginBottom: 8,
1353
+ color: c.muted,
1354
+ textTransform: "uppercase"
1355
+ },
1356
+ children: [
1357
+ "Edit History (",
1358
+ editHistory.length,
1359
+ ")"
1360
+ ]
1361
+ }
1362
+ ),
1363
+ /* @__PURE__ */ jsxRuntime.jsx(
1364
+ "div",
1365
+ {
1366
+ style: {
1367
+ background: c.bgAlt,
1368
+ borderRadius: 10,
1369
+ border: `1px solid ${c.border}`,
1370
+ maxHeight: 200,
1371
+ overflow: "auto"
1372
+ },
1373
+ children: editHistory.map((item, idx) => {
1374
+ const isLastEdit = idx === editHistory.length - 1;
1375
+ const hasSnapshot = item.success && item.fileSnapshot;
1376
+ return /* @__PURE__ */ jsxRuntime.jsx(
1377
+ "div",
1378
+ {
1379
+ style: {
1380
+ padding: "10px 14px",
1381
+ borderBottom: idx < editHistory.length - 1 ? `1px solid ${c.border}` : "none"
1382
+ },
1383
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
1384
+ "div",
1385
+ {
1386
+ style: {
1387
+ display: "flex",
1388
+ alignItems: "flex-start",
1389
+ gap: 8
1390
+ },
1391
+ children: [
1392
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { flex: 1 }, children: [
1393
+ /* @__PURE__ */ jsxRuntime.jsxs(
1394
+ "div",
1395
+ {
1396
+ style: {
1397
+ display: "flex",
1398
+ alignItems: "center",
1399
+ gap: 8,
1400
+ marginBottom: 4
1401
+ },
1402
+ children: [
1403
+ /* @__PURE__ */ jsxRuntime.jsx(
1404
+ "span",
1405
+ {
1406
+ style: {
1407
+ color: item.success ? c.success : c.error,
1408
+ fontSize: 16
1409
+ },
1410
+ children: item.success ? "✓" : "✗"
1411
+ }
1412
+ ),
1413
+ /* @__PURE__ */ jsxRuntime.jsxs(
1414
+ "span",
1415
+ {
1416
+ style: {
1417
+ fontSize: 11,
1418
+ color: c.muted
1419
+ },
1420
+ children: [
1421
+ "Edit ",
1422
+ idx + 1
1423
+ ]
1424
+ }
1425
+ )
1426
+ ]
1427
+ }
1428
+ ),
1429
+ /* @__PURE__ */ jsxRuntime.jsx(
1430
+ "div",
1431
+ {
1432
+ style: {
1433
+ fontSize: 13,
1434
+ color: c.text,
1435
+ marginLeft: 24
1436
+ },
1437
+ children: item.suggestion
1438
+ }
1439
+ ),
1440
+ item.error && /* @__PURE__ */ jsxRuntime.jsx(
1441
+ "div",
1442
+ {
1443
+ style: {
1444
+ fontSize: 11,
1445
+ color: c.error,
1446
+ marginLeft: 24,
1447
+ marginTop: 4
1448
+ },
1449
+ children: item.error
1450
+ }
1451
+ )
1452
+ ] }),
1453
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: 6, flexWrap: "wrap" }, children: [
1454
+ isLastEdit && hasSnapshot && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1455
+ /* @__PURE__ */ jsxRuntime.jsx(
1456
+ "button",
1457
+ {
1458
+ onClick: handleUndo,
1459
+ disabled: isLoading,
1460
+ style: {
1461
+ padding: "4px 10px",
1462
+ fontSize: 11,
1463
+ borderRadius: 6,
1464
+ border: "none",
1465
+ background: isLoading ? c.muted : "#f59e0b",
1466
+ color: "#fff",
1467
+ fontWeight: 600,
1468
+ cursor: isLoading ? "wait" : "pointer",
1469
+ whiteSpace: "nowrap"
1470
+ },
1471
+ title: "Undo this edit",
1472
+ onMouseEnter: (e) => {
1473
+ if (!isLoading)
1474
+ e.currentTarget.style.background = "#d97706";
1475
+ },
1476
+ onMouseLeave: (e) => {
1477
+ if (!isLoading)
1478
+ e.currentTarget.style.background = "#f59e0b";
1479
+ },
1480
+ children: "↶ Undo"
1481
+ }
1482
+ ),
1483
+ /* @__PURE__ */ jsxRuntime.jsx(
1484
+ "button",
1485
+ {
1486
+ onClick: handleUndoAndRetry,
1487
+ disabled: isLoading,
1488
+ style: {
1489
+ padding: "4px 10px",
1490
+ fontSize: 11,
1491
+ borderRadius: 6,
1492
+ border: "none",
1493
+ background: isLoading ? c.muted : "#8b5cf6",
1494
+ color: "#fff",
1495
+ fontWeight: 600,
1496
+ cursor: isLoading ? "wait" : "pointer",
1497
+ whiteSpace: "nowrap"
1498
+ },
1499
+ title: "Undo and retry with AI",
1500
+ onMouseEnter: (e) => {
1501
+ if (!isLoading)
1502
+ e.currentTarget.style.background = "#7c3aed";
1503
+ },
1504
+ onMouseLeave: (e) => {
1505
+ if (!isLoading)
1506
+ e.currentTarget.style.background = "#8b5cf6";
1507
+ },
1508
+ children: "↶↻ Undo & Retry"
1509
+ }
1510
+ )
1511
+ ] }),
1512
+ /* @__PURE__ */ jsxRuntime.jsx(
1513
+ "button",
1514
+ {
1515
+ onClick: () => handleRetry(idx),
1516
+ disabled: isLoading,
1517
+ style: {
1518
+ padding: "4px 10px",
1519
+ fontSize: 11,
1520
+ borderRadius: 6,
1521
+ border: "none",
1522
+ background: isLoading ? c.muted : c.accent,
1523
+ color: "#fff",
1524
+ fontWeight: 600,
1525
+ cursor: isLoading ? "wait" : "pointer",
1526
+ whiteSpace: "nowrap"
1527
+ },
1528
+ title: "Retry this edit",
1529
+ onMouseEnter: (e) => {
1530
+ if (!isLoading)
1531
+ e.currentTarget.style.background = "#6366f1";
1532
+ },
1533
+ onMouseLeave: (e) => {
1534
+ if (!isLoading)
1535
+ e.currentTarget.style.background = c.accent;
1536
+ },
1537
+ children: "↻ Retry"
1538
+ }
1539
+ )
1540
+ ] })
1541
+ ]
1542
+ }
1543
+ )
1544
+ },
1545
+ idx
1546
+ );
1547
+ })
1548
+ }
1549
+ )
1550
+ ] }),
1551
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: 20 }, children: [
1552
+ /* @__PURE__ */ jsxRuntime.jsx(
1553
+ "div",
1554
+ {
1555
+ style: {
1556
+ fontSize: 11,
1557
+ fontWeight: 600,
1558
+ marginBottom: 8,
1559
+ color: c.muted,
1560
+ textTransform: "uppercase"
1561
+ },
1562
+ children: "Describe Changes"
1563
+ }
1564
+ ),
1565
+ /* @__PURE__ */ jsxRuntime.jsx(
1566
+ "textarea",
1567
+ {
1568
+ value: suggestion,
1569
+ onChange: (e) => setSuggestion(e.target.value),
1570
+ placeholder: `e.g., Make this ${(elCtx == null ? void 0 : elCtx.tagName) || "element"} blue with rounded corners...`,
1571
+ autoFocus: true,
1572
+ style: {
1573
+ width: "100%",
1574
+ height: 100,
1575
+ padding: 14,
1576
+ borderRadius: 10,
1577
+ border: `1px solid ${c.border}`,
1578
+ background: c.bgAlt,
1579
+ color: c.text,
1580
+ fontSize: 14,
1581
+ resize: "vertical",
1582
+ fontFamily: "inherit",
1583
+ boxSizing: "border-box"
1584
+ },
1585
+ onKeyDown: (e) => {
1586
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
1587
+ e.preventDefault();
1588
+ handleSubmit();
1589
+ }
1590
+ }
1591
+ }
1592
+ )
1593
+ ] }),
1594
+ result && /* @__PURE__ */ jsxRuntime.jsx(
1595
+ "div",
1596
+ {
1597
+ style: {
1598
+ marginBottom: 20,
1599
+ padding: 14,
1600
+ borderRadius: 10,
1601
+ background: result.success ? `${c.success}15` : `${c.error}15`,
1602
+ color: result.success ? c.success : c.error,
1603
+ fontWeight: 500
1604
+ },
1605
+ children: result.success ? "✓ Applied!" : `✗ ${result.error}`
1606
+ }
1607
+ ),
1608
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: 12, flexWrap: "wrap" }, children: [
1609
+ /* @__PURE__ */ jsxRuntime.jsx(
1610
+ "button",
1611
+ {
1612
+ onClick: () => setSelectedSource(null),
1613
+ style: {
1614
+ flex: "1 1 auto",
1615
+ padding: "12px 20px",
1616
+ borderRadius: 10,
1617
+ border: `1px solid ${c.border}`,
1618
+ background: "transparent",
1619
+ color: c.text,
1620
+ cursor: "pointer"
1621
+ },
1622
+ children: "Cancel"
1623
+ }
1624
+ ),
1625
+ ENABLE_SESSION_PERSISTENCE,
1626
+ editHistory.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(
1627
+ "button",
1628
+ {
1629
+ onClick: handleDone,
1630
+ style: {
1631
+ flex: "1 1 auto",
1632
+ padding: "12px 20px",
1633
+ borderRadius: 10,
1634
+ border: `1px solid ${c.success}`,
1635
+ background: "transparent",
1636
+ color: c.success,
1637
+ fontWeight: 600,
1638
+ cursor: "pointer"
1639
+ },
1640
+ children: "Finish & Reload"
1641
+ }
1642
+ ),
1643
+ /* @__PURE__ */ jsxRuntime.jsx(
1644
+ "button",
1645
+ {
1646
+ onClick: handleSubmit,
1647
+ disabled: isLoading || !suggestion.trim(),
1648
+ style: {
1649
+ flex: "2 1 auto",
1650
+ padding: "12px 20px",
1651
+ borderRadius: 10,
1652
+ border: "none",
1653
+ background: isLoading ? c.muted : c.accent,
1654
+ color: "#fff",
1655
+ fontWeight: 600,
1656
+ cursor: isLoading ? "wait" : "pointer",
1657
+ opacity: !suggestion.trim() ? 0.5 : 1
1658
+ },
1659
+ children: isLoading ? "Applying..." : "Apply Changes ⌘↵"
1660
+ }
1661
+ )
1662
+ ] })
1663
+ ]
1664
+ }
1665
+ ),
1666
+ !selectedSource && /* @__PURE__ */ jsxRuntime.jsxs(
1667
+ "div",
1668
+ {
1669
+ style: {
1670
+ position: "fixed",
1671
+ bottom: 20,
1672
+ right: 20,
1673
+ background: c.bg,
1674
+ color: c.success,
1675
+ padding: "10px 16px",
1676
+ borderRadius: 20,
1677
+ fontSize: 13,
1678
+ fontWeight: 600,
1679
+ zIndex: 99997,
1680
+ display: "flex",
1681
+ alignItems: "center",
1682
+ gap: 8,
1683
+ border: `1px solid ${c.border}`,
1684
+ boxShadow: `0 4px 20px rgba(0,0,0,${isDark ? 0.4 : 0.1})`
1685
+ },
1686
+ children: [
1687
+ /* @__PURE__ */ jsxRuntime.jsx(
1688
+ "span",
1689
+ {
1690
+ style: {
1691
+ width: 8,
1692
+ height: 8,
1693
+ borderRadius: "50%",
1694
+ background: c.success
1695
+ }
1696
+ }
1697
+ ),
1698
+ "AI Editor",
1699
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: { color: c.muted, fontSize: 11 }, children: "⌘⇧E" }),
1700
+ ENABLE_SESSION_PERSISTENCE,
1701
+ /* @__PURE__ */ jsxRuntime.jsx(
1702
+ "button",
1703
+ {
1704
+ onClick: () => setEnabled(false),
1705
+ style: {
1706
+ background: "none",
1707
+ border: "none",
1708
+ color: c.muted,
1709
+ cursor: "pointer"
1710
+ },
1711
+ children: "×"
1712
+ }
1713
+ )
1714
+ ]
1715
+ }
1716
+ )
1717
+ ]
1718
+ }
1719
+ );
1720
+ }
1721
+ exports.AIEditorProvider = AIEditorProvider;
1722
+ //# sourceMappingURL=AIEditorProvider-Bs9zUVrL.cjs.map