@synchronized-studio/cmsassets-agent 0.1.2 → 0.2.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.
@@ -0,0 +1,1706 @@
1
+ import {
2
+ WRAP_TEMPLATES,
3
+ buildCmsOptions,
4
+ findInjectionPoints,
5
+ getImportStatement,
6
+ getTransformFunctionName,
7
+ validateDiff
8
+ } from "./chunk-OJVHNQQN.js";
9
+ import {
10
+ chatCompletion,
11
+ isOpenAiError
12
+ } from "./chunk-E74TGIFQ.js";
13
+
14
+ // src/scanner/index.ts
15
+ import { resolve } from "path";
16
+
17
+ // src/scanner/detectFramework.ts
18
+ import { existsSync, readFileSync } from "fs";
19
+ import { join } from "path";
20
+ var FRAMEWORK_SIGNATURES = {
21
+ nuxt: {
22
+ packages: ["nuxt"],
23
+ configFiles: ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs"]
24
+ },
25
+ next: {
26
+ packages: ["next"],
27
+ configFiles: ["next.config.js", "next.config.mjs", "next.config.ts"]
28
+ },
29
+ remix: {
30
+ packages: ["@remix-run/react", "@remix-run/node", "@remix-run/dev"],
31
+ configFiles: ["remix.config.js", "remix.config.ts"]
32
+ },
33
+ astro: {
34
+ packages: ["astro"],
35
+ configFiles: ["astro.config.mjs", "astro.config.ts", "astro.config.js"]
36
+ },
37
+ sveltekit: {
38
+ packages: ["@sveltejs/kit"],
39
+ configFiles: ["svelte.config.js", "svelte.config.ts"]
40
+ },
41
+ hono: {
42
+ packages: ["hono"],
43
+ configFiles: []
44
+ },
45
+ fastify: {
46
+ packages: ["fastify"],
47
+ configFiles: []
48
+ },
49
+ express: {
50
+ packages: ["express"],
51
+ configFiles: []
52
+ }
53
+ };
54
+ var DETECTION_ORDER = [
55
+ "nuxt",
56
+ "next",
57
+ "remix",
58
+ "astro",
59
+ "sveltekit",
60
+ "hono",
61
+ "fastify",
62
+ "express"
63
+ ];
64
+ function readPackageJson(root) {
65
+ const pkgPath = join(root, "package.json");
66
+ if (!existsSync(pkgPath)) return null;
67
+ try {
68
+ const raw = readFileSync(pkgPath, "utf-8");
69
+ const pkg = JSON.parse(raw);
70
+ return {
71
+ dependencies: pkg.dependencies ?? {},
72
+ devDependencies: pkg.devDependencies ?? {}
73
+ };
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+ function getVersionFromPkg(allDeps, packages) {
79
+ for (const pkg of packages) {
80
+ if (allDeps[pkg]) return allDeps[pkg];
81
+ }
82
+ return "";
83
+ }
84
+ function detectFramework(root) {
85
+ const pkg = readPackageJson(root);
86
+ const allDeps = {
87
+ ...pkg?.dependencies ?? {},
88
+ ...pkg?.devDependencies ?? {}
89
+ };
90
+ for (const name of DETECTION_ORDER) {
91
+ const sig = FRAMEWORK_SIGNATURES[name];
92
+ const hasPackage = sig.packages.some((p) => p in allDeps);
93
+ const configFile = sig.configFiles.find((f) => existsSync(join(root, f))) ?? null;
94
+ if (hasPackage || configFile) {
95
+ let resolvedName = name;
96
+ const version = getVersionFromPkg(allDeps, sig.packages);
97
+ if (name === "nuxt") {
98
+ const majorVersion = parseMajorVersion(version);
99
+ if (majorVersion !== null && majorVersion < 3) {
100
+ resolvedName = "nuxt2";
101
+ }
102
+ }
103
+ return {
104
+ name: resolvedName,
105
+ version,
106
+ configFile
107
+ };
108
+ }
109
+ }
110
+ return { name: "unknown", version: "", configFile: null };
111
+ }
112
+ function parseMajorVersion(versionRange) {
113
+ const cleaned = versionRange.replace(/^[\^~>=<\s]+/, "");
114
+ const major = parseInt(cleaned, 10);
115
+ return Number.isFinite(major) ? major : null;
116
+ }
117
+
118
+ // src/scanner/detectCms.ts
119
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
120
+ import { join as join2, relative } from "path";
121
+ import fg from "fast-glob";
122
+ var CMS_SIGNATURES = {
123
+ prismic: {
124
+ packages: [
125
+ "@prismicio/client",
126
+ "@prismicio/vue",
127
+ "@prismicio/react",
128
+ "@prismicio/next",
129
+ "@prismicio/svelte",
130
+ "@nuxtjs/prismic"
131
+ ],
132
+ urlPatterns: [
133
+ /https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/gi,
134
+ /https?:\/\/images\.prismic\.io\/([a-z0-9-]+)/gi
135
+ ],
136
+ paramExtractors: {
137
+ repository: (match) => {
138
+ const m1 = match.match(/https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/);
139
+ if (m1) return m1[1];
140
+ const m2 = match.match(/https?:\/\/images\.prismic\.io\/([a-z0-9-]+)/);
141
+ if (m2) return m2[1];
142
+ return null;
143
+ }
144
+ }
145
+ },
146
+ contentful: {
147
+ packages: ["contentful"],
148
+ urlPatterns: [
149
+ /https?:\/\/images\.ctfassets\.net\/([a-z0-9]+)/gi,
150
+ /https?:\/\/videos\.ctfassets\.net\/([a-z0-9]+)/gi,
151
+ /https?:\/\/cdn\.contentful\.com\/spaces\/([a-z0-9]+)/gi
152
+ ],
153
+ paramExtractors: {
154
+ spaceId: (match) => {
155
+ const m = match.match(/ctfassets\.net\/([a-z0-9]+)/) || match.match(/spaces\/([a-z0-9]+)/);
156
+ return m?.[1] ?? null;
157
+ }
158
+ }
159
+ },
160
+ sanity: {
161
+ packages: ["@sanity/client", "next-sanity", "@nuxtjs/sanity", "sanity"],
162
+ urlPatterns: [
163
+ /https?:\/\/cdn\.sanity\.io\/(images|files)\/([a-z0-9]+)\/([a-z0-9-]+)/gi
164
+ ],
165
+ paramExtractors: {
166
+ projectId: (match) => {
167
+ const m = match.match(/cdn\.sanity\.io\/(?:images|files)\/([a-z0-9]+)/);
168
+ return m?.[1] ?? null;
169
+ },
170
+ dataset: (match) => {
171
+ const m = match.match(
172
+ /cdn\.sanity\.io\/(?:images|files)\/[a-z0-9]+\/([a-z0-9-]+)/
173
+ );
174
+ return m?.[1] ?? null;
175
+ }
176
+ }
177
+ },
178
+ shopify: {
179
+ packages: [
180
+ "@shopify/storefront-api-client",
181
+ "@shopify/hydrogen",
182
+ "@shopify/shopify-api"
183
+ ],
184
+ urlPatterns: [
185
+ /https?:\/\/([a-z0-9-]+)\.myshopify\.com\/cdn\//gi,
186
+ /https?:\/\/([a-z0-9-]+)\.myshopify\.com\/api\//gi
187
+ ],
188
+ paramExtractors: {
189
+ storeDomain: (match) => {
190
+ const m = match.match(/https?:\/\/([a-z0-9-]+\.myshopify\.com)/);
191
+ return m?.[1] ?? null;
192
+ }
193
+ }
194
+ },
195
+ cloudinary: {
196
+ packages: ["cloudinary", "@cloudinary/url-gen", "@cloudinary/react"],
197
+ urlPatterns: [/https?:\/\/res\.cloudinary\.com\/([a-z0-9_-]+)/gi],
198
+ paramExtractors: {
199
+ cloudName: (match) => {
200
+ const m = match.match(/res\.cloudinary\.com\/([a-z0-9_-]+)/);
201
+ return m?.[1] ?? null;
202
+ }
203
+ }
204
+ },
205
+ imgix: {
206
+ packages: ["@imgix/js-core", "react-imgix", "vue-imgix"],
207
+ urlPatterns: [/https?:\/\/([a-z0-9-]+)\.imgix\.net/gi],
208
+ paramExtractors: {
209
+ imgixDomain: (match) => {
210
+ const m = match.match(/https?:\/\/([a-z0-9-]+\.imgix\.net)/);
211
+ return m?.[1] ?? null;
212
+ }
213
+ }
214
+ }
215
+ };
216
+ var CMS_DETECTION_ORDER = [
217
+ "prismic",
218
+ "contentful",
219
+ "sanity",
220
+ "shopify",
221
+ "cloudinary",
222
+ "imgix"
223
+ ];
224
+ var SOURCE_GLOBS = [
225
+ "**/*.ts",
226
+ "**/*.tsx",
227
+ "**/*.js",
228
+ "**/*.jsx",
229
+ "**/*.vue",
230
+ "**/*.svelte",
231
+ "**/*.astro",
232
+ "**/*.mjs",
233
+ "**/*.mts"
234
+ ];
235
+ var IGNORE_DIRS = [
236
+ "node_modules",
237
+ ".nuxt",
238
+ ".next",
239
+ ".output",
240
+ ".svelte-kit",
241
+ "dist",
242
+ "build",
243
+ ".git",
244
+ "coverage",
245
+ ".cache"
246
+ ];
247
+ function detectCms(root) {
248
+ const pkgPath = join2(root, "package.json");
249
+ let allDeps = {};
250
+ if (existsSync2(pkgPath)) {
251
+ try {
252
+ const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
253
+ allDeps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
254
+ } catch {
255
+ }
256
+ }
257
+ for (const cmsName of CMS_DETECTION_ORDER) {
258
+ const sig = CMS_SIGNATURES[cmsName];
259
+ if (sig.packages.some((p) => p in allDeps)) {
260
+ const params = extractParamsFromSource(root, cmsName);
261
+ return {
262
+ type: cmsName,
263
+ params,
264
+ detectedFrom: ["package.json"]
265
+ };
266
+ }
267
+ }
268
+ const sourceFiles = fg.sync(SOURCE_GLOBS, {
269
+ cwd: root,
270
+ ignore: IGNORE_DIRS.map((d) => `${d}/**`),
271
+ absolute: true,
272
+ onlyFiles: true,
273
+ deep: 6
274
+ });
275
+ for (const cmsName of CMS_DETECTION_ORDER) {
276
+ const sig = CMS_SIGNATURES[cmsName];
277
+ const matchingFiles = [];
278
+ const foundParams = {};
279
+ for (const file of sourceFiles) {
280
+ let content;
281
+ try {
282
+ content = readFileSync2(file, "utf-8");
283
+ } catch {
284
+ continue;
285
+ }
286
+ for (const pattern of sig.urlPatterns) {
287
+ pattern.lastIndex = 0;
288
+ const matches = content.match(pattern);
289
+ if (matches && matches.length > 0) {
290
+ matchingFiles.push(relative(root, file));
291
+ for (const m of matches) {
292
+ for (const [paramName, extractor] of Object.entries(sig.paramExtractors)) {
293
+ if (!foundParams[paramName]) {
294
+ const val = extractor(m);
295
+ if (val) foundParams[paramName] = val;
296
+ }
297
+ }
298
+ }
299
+ }
300
+ }
301
+ }
302
+ if (matchingFiles.length > 0) {
303
+ return {
304
+ type: cmsName,
305
+ params: foundParams,
306
+ detectedFrom: [...new Set(matchingFiles)]
307
+ };
308
+ }
309
+ }
310
+ const genericPatterns = [
311
+ /https?:\/\/[a-z0-9-]+\.s3[.-][a-z0-9-]*\.amazonaws\.com/gi,
312
+ /https?:\/\/storage\.googleapis\.com\/[a-z0-9-]+/gi,
313
+ /https?:\/\/[a-z0-9-]+\.r2\.cloudflarestorage\.com/gi
314
+ ];
315
+ for (const file of sourceFiles) {
316
+ let content;
317
+ try {
318
+ content = readFileSync2(file, "utf-8");
319
+ } catch {
320
+ continue;
321
+ }
322
+ for (const pattern of genericPatterns) {
323
+ pattern.lastIndex = 0;
324
+ const m = content.match(pattern);
325
+ if (m && m.length > 0) {
326
+ return {
327
+ type: "generic",
328
+ params: { originUrl: m[0] },
329
+ detectedFrom: [relative(root, file)]
330
+ };
331
+ }
332
+ }
333
+ }
334
+ return { type: "unknown", params: {}, detectedFrom: [] };
335
+ }
336
+ var CONFIG_FILES = [
337
+ "slicemachine.config.json",
338
+ "prismicio.config.ts",
339
+ "prismicio.config.js",
340
+ "sm.json",
341
+ ".slicemachine.config.json",
342
+ "nuxt.config.ts",
343
+ "nuxt.config.js",
344
+ "next.config.js",
345
+ "next.config.mjs",
346
+ "next.config.ts",
347
+ "sanity.config.ts",
348
+ "sanity.config.js",
349
+ "sanity.cli.ts",
350
+ "sanity.cli.js"
351
+ ];
352
+ var CONFIG_PARAM_PATTERNS = {
353
+ prismic: [
354
+ { param: "repository", patterns: [
355
+ /["']?repositoryName["']?\s*[:=]\s*["']([a-z0-9-]+)["']/i,
356
+ /https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/i,
357
+ /["']?apiEndpoint["']?\s*[:=]\s*["']https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/i
358
+ ] }
359
+ ],
360
+ contentful: [
361
+ { param: "spaceId", patterns: [
362
+ /["']?space["']?\s*[:=]\s*["']([a-z0-9]+)["']/i,
363
+ /["']?spaceId["']?\s*[:=]\s*["']([a-z0-9]+)["']/i
364
+ ] }
365
+ ],
366
+ sanity: [
367
+ { param: "projectId", patterns: [
368
+ /["']?projectId["']?\s*[:=]\s*["']([a-z0-9]+)["']/i
369
+ ] },
370
+ { param: "dataset", patterns: [
371
+ /["']?dataset["']?\s*[:=]\s*["']([a-z0-9-]+)["']/i
372
+ ] }
373
+ ],
374
+ shopify: [
375
+ { param: "storeDomain", patterns: [
376
+ /["']?storeDomain["']?\s*[:=]\s*["']([a-z0-9-]+\.myshopify\.com)["']/i
377
+ ] }
378
+ ],
379
+ cloudinary: [
380
+ { param: "cloudName", patterns: [
381
+ /["']?cloud_name["']?\s*[:=]\s*["']([a-z0-9_-]+)["']/i,
382
+ /["']?cloudName["']?\s*[:=]\s*["']([a-z0-9_-]+)["']/i
383
+ ] }
384
+ ],
385
+ imgix: [
386
+ { param: "imgixDomain", patterns: [
387
+ /["']?domain["']?\s*[:=]\s*["']([a-z0-9-]+\.imgix\.net)["']/i
388
+ ] }
389
+ ]
390
+ };
391
+ function extractParamsFromSource(root, cmsName) {
392
+ const sig = CMS_SIGNATURES[cmsName];
393
+ if (!sig) return {};
394
+ const params = {};
395
+ const configPatterns = CONFIG_PARAM_PATTERNS[cmsName];
396
+ if (configPatterns) {
397
+ for (const cfgFile of CONFIG_FILES) {
398
+ const cfgPath = join2(root, cfgFile);
399
+ if (!existsSync2(cfgPath)) continue;
400
+ let content;
401
+ try {
402
+ content = readFileSync2(cfgPath, "utf-8");
403
+ } catch {
404
+ continue;
405
+ }
406
+ for (const { param, patterns } of configPatterns) {
407
+ if (params[param]) continue;
408
+ for (const pattern of patterns) {
409
+ const m = content.match(pattern);
410
+ if (m?.[1]) {
411
+ params[param] = m[1];
412
+ break;
413
+ }
414
+ }
415
+ }
416
+ }
417
+ if (Object.keys(params).length === Object.keys(sig.paramExtractors).length) {
418
+ return params;
419
+ }
420
+ }
421
+ const sourceFiles = fg.sync(SOURCE_GLOBS, {
422
+ cwd: root,
423
+ ignore: IGNORE_DIRS.map((d) => `${d}/**`),
424
+ absolute: true,
425
+ onlyFiles: true,
426
+ deep: 6
427
+ });
428
+ for (const file of sourceFiles) {
429
+ let content;
430
+ try {
431
+ content = readFileSync2(file, "utf-8");
432
+ } catch {
433
+ continue;
434
+ }
435
+ for (const pattern of sig.urlPatterns) {
436
+ pattern.lastIndex = 0;
437
+ const matches = content.match(pattern);
438
+ if (!matches) continue;
439
+ for (const m of matches) {
440
+ for (const [paramName, extractor] of Object.entries(sig.paramExtractors)) {
441
+ if (!params[paramName]) {
442
+ const val = extractor(m);
443
+ if (val) params[paramName] = val;
444
+ }
445
+ }
446
+ }
447
+ }
448
+ if (Object.keys(params).length === Object.keys(sig.paramExtractors).length) {
449
+ break;
450
+ }
451
+ }
452
+ return params;
453
+ }
454
+
455
+ // src/scanner/detectPackageManager.ts
456
+ import { existsSync as existsSync3 } from "fs";
457
+ import { join as join3 } from "path";
458
+ var LOCKFILE_MAP = [
459
+ ["bun.lockb", "bun"],
460
+ ["bun.lock", "bun"],
461
+ ["pnpm-lock.yaml", "pnpm"],
462
+ ["yarn.lock", "yarn"],
463
+ ["package-lock.json", "npm"]
464
+ ];
465
+ function detectPackageManager(root) {
466
+ for (const [lockfile, pm] of LOCKFILE_MAP) {
467
+ if (existsSync3(join3(root, lockfile))) return pm;
468
+ }
469
+ return "npm";
470
+ }
471
+
472
+ // src/scanner/index.ts
473
+ function scan(projectRoot) {
474
+ const root = resolve(projectRoot ?? process.cwd());
475
+ const framework = detectFramework(root);
476
+ const cms = detectCms(root);
477
+ const packageManager = detectPackageManager(root);
478
+ const injectionPoints = findInjectionPoints(root, framework.name, cms);
479
+ return {
480
+ framework,
481
+ cms,
482
+ injectionPoints,
483
+ packageManager,
484
+ projectRoot: root
485
+ };
486
+ }
487
+
488
+ // src/planner/index.ts
489
+ import { existsSync as existsSync4 } from "fs";
490
+ import { join as join4 } from "path";
491
+ function resolveInstallCommand(scan2) {
492
+ const pkg = "@synchronized-studio/response-transformer";
493
+ switch (scan2.packageManager) {
494
+ case "pnpm":
495
+ return `pnpm add ${pkg}`;
496
+ case "yarn":
497
+ return `yarn add ${pkg}`;
498
+ case "bun":
499
+ return `bun add ${pkg}`;
500
+ default:
501
+ return `npm install ${pkg}`;
502
+ }
503
+ }
504
+ function resolveEnvFiles(root) {
505
+ const candidates = [".env", ".env.local", ".env.example", ".env.development"];
506
+ return candidates.filter((f) => existsSync4(join4(root, f)));
507
+ }
508
+ function createPlan(scan2) {
509
+ const patches = [];
510
+ for (const candidate of scan2.injectionPoints) {
511
+ const template = WRAP_TEMPLATES[candidate.type];
512
+ if (!template) continue;
513
+ const importStatement = getImportStatement(scan2.cms.type);
514
+ const originalCode = candidate.targetCode;
515
+ if (!originalCode) continue;
516
+ if (/\.push\s*\(/.test(originalCode.trim())) continue;
517
+ const transformedCode = template.transform(
518
+ originalCode,
519
+ scan2.cms.type,
520
+ scan2.cms.params
521
+ );
522
+ if (transformedCode === originalCode) continue;
523
+ patches.push({
524
+ filePath: candidate.filePath,
525
+ description: template.description(scan2.cms.type),
526
+ importToAdd: importStatement,
527
+ wrapTarget: {
528
+ line: candidate.line,
529
+ originalCode,
530
+ transformedCode
531
+ },
532
+ confidence: candidate.confidence,
533
+ reasons: candidate.reasons
534
+ });
535
+ }
536
+ const envFiles = resolveEnvFiles(scan2.projectRoot);
537
+ return {
538
+ schemaVersion: "1.0",
539
+ scan: scan2,
540
+ install: {
541
+ package: "@synchronized-studio/response-transformer",
542
+ command: resolveInstallCommand(scan2)
543
+ },
544
+ env: {
545
+ key: "CMS_ASSETS_URL",
546
+ placeholder: "https://YOUR-SLUG.cmsassets.com",
547
+ files: envFiles
548
+ },
549
+ patches,
550
+ policies: {
551
+ maxFilesAutoApply: 20,
552
+ allowLlmFallback: false,
553
+ llmFallbackForAll: false,
554
+ llmOnly: false,
555
+ verifyProfile: "quick"
556
+ }
557
+ };
558
+ }
559
+
560
+ // src/patcher/index.ts
561
+ import { appendFileSync, existsSync as existsSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
562
+ import { join as join10 } from "path";
563
+ import consola from "consola";
564
+
565
+ // src/patcher/astPatcher.ts
566
+ import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
567
+ import { readFileSync as readFileSync4, writeFileSync } from "fs";
568
+ import { join as join6, extname as extname2 } from "path";
569
+
570
+ // src/patcher/structuralValidator.ts
571
+ import { Project, SyntaxKind, ScriptKind } from "ts-morph";
572
+ import { readFileSync as readFileSync3 } from "fs";
573
+ import { join as join5, extname } from "path";
574
+ var TRANSFORMER_PKG = "@synchronized-studio/response-transformer";
575
+ function takeSnapshot(root, filePath) {
576
+ const absPath = join5(root, filePath);
577
+ const ext = extname(filePath);
578
+ let content;
579
+ try {
580
+ content = readFileSync3(absPath, "utf-8");
581
+ } catch {
582
+ return { exports: [], functions: [], variables: [], imports: [], content: "", syntaxValid: false };
583
+ }
584
+ if ([".vue", ".svelte", ".astro"].includes(ext)) {
585
+ return takeSnapshotFromString(content, ext);
586
+ }
587
+ return takeSnapshotFromAst(content, filePath);
588
+ }
589
+ function takeSnapshotFromAst(content, filePath) {
590
+ try {
591
+ const project = new Project({ useInMemoryFileSystem: true });
592
+ const ext = extname(filePath);
593
+ const scriptKind = ext === ".tsx" || ext === ".jsx" ? ScriptKind.TSX : ScriptKind.TS;
594
+ const sourceFile = project.createSourceFile("__snapshot__.tsx", content, { scriptKind });
595
+ const exports = sourceFile.getExportedDeclarations();
596
+ const exportNames = [...exports.keys()];
597
+ const functions = sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration).map((f) => f.getName()).filter((n) => !!n);
598
+ const arrowFunctions = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration).filter((v) => v.getInitializerIfKind(SyntaxKind.ArrowFunction)).map((v) => v.getName());
599
+ const allFunctions = [.../* @__PURE__ */ new Set([...functions, ...arrowFunctions])];
600
+ const variables = sourceFile.getVariableDeclarations().map((v) => v.getName()).filter((name) => !allFunctions.includes(name));
601
+ const imports = sourceFile.getImportDeclarations().map((i) => i.getModuleSpecifierValue());
602
+ return {
603
+ exports: exportNames,
604
+ functions: allFunctions,
605
+ variables,
606
+ imports,
607
+ content,
608
+ syntaxValid: true
609
+ };
610
+ } catch {
611
+ return {
612
+ exports: [],
613
+ functions: [],
614
+ variables: [],
615
+ imports: [],
616
+ content,
617
+ syntaxValid: false
618
+ };
619
+ }
620
+ }
621
+ function takeSnapshotFromString(content, ext) {
622
+ const scriptContent = extractScriptBlock(content, ext);
623
+ if (!scriptContent) {
624
+ return { exports: [], functions: [], variables: [], imports: [], content, syntaxValid: true };
625
+ }
626
+ const exports = extractPatterns(scriptContent, /export\s+(?:default\s+)?(?:async\s+)?(?:function|const|let|var|class)\s+(\w+)/g);
627
+ const functions = extractPatterns(scriptContent, /(?:async\s+)?function\s+(\w+)\s*\(/g);
628
+ const arrowFns = extractPatterns(scriptContent, /(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>/g);
629
+ const variables = extractPatterns(scriptContent, /(?:const|let|var)\s+(\w+)\s*=/g).filter((v) => !functions.includes(v) && !arrowFns.includes(v));
630
+ const imports = extractPatterns(scriptContent, /from\s+['"]([^'"]+)['"]/g);
631
+ return {
632
+ exports,
633
+ functions: [.../* @__PURE__ */ new Set([...functions, ...arrowFns])],
634
+ variables,
635
+ imports,
636
+ content,
637
+ syntaxValid: true
638
+ };
639
+ }
640
+ function extractScriptBlock(content, ext) {
641
+ if (ext === ".astro") {
642
+ const match2 = content.match(/^---\n([\s\S]*?)\n---/);
643
+ return match2?.[1] ?? null;
644
+ }
645
+ const match = content.match(/<script[^>]*>([\s\S]*?)<\/script>/);
646
+ return match?.[1] ?? null;
647
+ }
648
+ function extractPatterns(content, pattern) {
649
+ const names = [];
650
+ let m;
651
+ while ((m = pattern.exec(content)) !== null) {
652
+ if (m[1]) names.push(m[1]);
653
+ }
654
+ return names;
655
+ }
656
+ function validateContentAgainstSnapshot(newContent, filePath, snapshot) {
657
+ const ext = extname(filePath);
658
+ const errors = [];
659
+ let newSnapshot;
660
+ if ([".vue", ".svelte", ".astro"].includes(ext)) {
661
+ newSnapshot = takeSnapshotFromString(newContent, ext);
662
+ } else {
663
+ newSnapshot = takeSnapshotFromAst(newContent, filePath);
664
+ }
665
+ if (!newSnapshot.syntaxValid) {
666
+ errors.push("Patched file has syntax errors and cannot be parsed");
667
+ return { valid: false, errors };
668
+ }
669
+ const missingExports = snapshot.exports.filter((e) => !newSnapshot.exports.includes(e));
670
+ if (missingExports.length > 0) {
671
+ errors.push(`Missing exports after patch: ${missingExports.join(", ")}`);
672
+ }
673
+ const missingFunctions = snapshot.functions.filter((f) => !newSnapshot.functions.includes(f));
674
+ if (missingFunctions.length > 0) {
675
+ errors.push(`Missing functions after patch: ${missingFunctions.join(", ")}`);
676
+ }
677
+ const missingVariables = snapshot.variables.filter((v) => !newSnapshot.variables.includes(v));
678
+ if (missingVariables.length > 0) {
679
+ errors.push(`Missing variables after patch: ${missingVariables.join(", ")}`);
680
+ }
681
+ const removedImports = snapshot.imports.filter(
682
+ (i) => i !== TRANSFORMER_PKG && !newSnapshot.imports.includes(i)
683
+ );
684
+ if (removedImports.length > 0) {
685
+ errors.push(`Removed imports after patch: ${removedImports.join(", ")}`);
686
+ }
687
+ const addedImports = newSnapshot.imports.filter((i) => !snapshot.imports.includes(i));
688
+ const unexpectedImports = addedImports.filter((i) => i !== TRANSFORMER_PKG);
689
+ if (unexpectedImports.length > 0) {
690
+ errors.push(`Unexpected new imports: ${unexpectedImports.join(", ")}`);
691
+ }
692
+ return { valid: errors.length === 0, errors };
693
+ }
694
+
695
+ // src/patcher/astPatcher.ts
696
+ function applyAstPatch(root, patch, dryRun, snapshot) {
697
+ const absPath = join6(root, patch.filePath);
698
+ const ext = extname2(patch.filePath);
699
+ if ([".vue", ".svelte", ".astro"].includes(ext)) {
700
+ return applyStringPatch(root, patch, dryRun, snapshot);
701
+ }
702
+ try {
703
+ const project = new Project2({ useInMemoryFileSystem: false });
704
+ const sourceFile = project.addSourceFileAtPath(absPath);
705
+ const originalText = sourceFile.getFullText();
706
+ const targetLine = patch.wrapTarget.line;
707
+ const original = patch.wrapTarget.originalCode.trim();
708
+ const transformed = patch.wrapTarget.transformedCode.trim();
709
+ if (original && transformed && original !== transformed) {
710
+ let patched = false;
711
+ const returnStatements = sourceFile.getDescendantsOfKind(
712
+ SyntaxKind2.ReturnStatement
713
+ );
714
+ for (const ret of returnStatements) {
715
+ const retLine = ret.getStartLineNumber();
716
+ if (retLine !== targetLine) continue;
717
+ const retText = ret.getText().trim();
718
+ if (retText.includes(original) || original.startsWith("return") && retText.startsWith("return") && normalizeReturnExpr(retText) === normalizeReturnExpr(original)) {
719
+ ret.replaceWithText(transformed);
720
+ patched = true;
721
+ break;
722
+ }
723
+ }
724
+ if (!patched) {
725
+ const expressions = sourceFile.getDescendantsOfKind(
726
+ SyntaxKind2.ExpressionStatement
727
+ );
728
+ for (const expr of expressions) {
729
+ const exprLine = expr.getStartLineNumber();
730
+ if (exprLine !== targetLine) continue;
731
+ const exprText = expr.getText().trim();
732
+ if (exprText.includes("res.json") || exprText.includes("c.json")) {
733
+ expr.replaceWithText(transformed);
734
+ patched = true;
735
+ break;
736
+ }
737
+ }
738
+ }
739
+ if (!patched) {
740
+ for (const ret of returnStatements) {
741
+ const retLine = ret.getStartLineNumber();
742
+ if (Math.abs(retLine - targetLine) > 1) continue;
743
+ const retText = ret.getText().trim();
744
+ if (original.startsWith("return") && retText.startsWith("return")) {
745
+ if (normalizeReturnExpr(retText) !== normalizeReturnExpr(original)) continue;
746
+ ret.replaceWithText(transformed);
747
+ patched = true;
748
+ break;
749
+ }
750
+ }
751
+ }
752
+ if (!patched) {
753
+ const currentText = sourceFile.getFullText();
754
+ const lines = currentText.split("\n");
755
+ const targetLineContent = lines[targetLine - 1];
756
+ if (targetLineContent && targetLineContent.trim() === original) {
757
+ const indent = targetLineContent.match(/^(\s*)/)?.[1] ?? "";
758
+ const newContent = currentText.replace(
759
+ targetLineContent,
760
+ indent + transformed
761
+ );
762
+ if (newContent !== currentText) {
763
+ sourceFile.replaceWithText(newContent);
764
+ patched = true;
765
+ }
766
+ }
767
+ }
768
+ if (!patched) {
769
+ const currentText = sourceFile.getFullText();
770
+ const lines = currentText.split("\n");
771
+ const targetIdx = Math.max(0, targetLine - 1);
772
+ const start = Math.max(0, targetIdx - 5);
773
+ const end = Math.min(lines.length - 1, targetIdx + 5);
774
+ for (let idx = start; idx <= end; idx++) {
775
+ const line = lines[idx];
776
+ const trimmed = line.trim();
777
+ if (trimmed === original || trimmed === original.replace(/;\s*$/, "")) {
778
+ const indent = line.match(/^(\s*)/)?.[1] ?? "";
779
+ lines[idx] = indent + transformed;
780
+ sourceFile.replaceWithText(lines.join("\n"));
781
+ patched = true;
782
+ break;
783
+ }
784
+ }
785
+ }
786
+ if (!patched) {
787
+ return { applied: false, reason: `Could not locate target code at line ${targetLine}` };
788
+ }
789
+ }
790
+ const existingImports = sourceFile.getImportDeclarations();
791
+ const hasImport = existingImports.some(
792
+ (i) => i.getModuleSpecifierValue() === "@synchronized-studio/response-transformer"
793
+ );
794
+ if (!hasImport && patch.importToAdd) {
795
+ const importMatch = patch.importToAdd.match(
796
+ /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/
797
+ );
798
+ if (importMatch) {
799
+ const namedImports = importMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
800
+ sourceFile.addImportDeclaration({
801
+ moduleSpecifier: importMatch[2],
802
+ namedImports
803
+ });
804
+ }
805
+ }
806
+ const newText = sourceFile.getFullText();
807
+ if (newText === originalText) {
808
+ return { applied: false, reason: "No changes needed (idempotent)" };
809
+ }
810
+ if (snapshot) {
811
+ const validation = validateContentAgainstSnapshot(newText, patch.filePath, snapshot);
812
+ if (!validation.valid) {
813
+ return {
814
+ applied: false,
815
+ validationFailed: true,
816
+ reason: `Structural validation failed: ${validation.errors.join("; ")}`
817
+ };
818
+ }
819
+ }
820
+ if (!dryRun) {
821
+ sourceFile.saveSync();
822
+ }
823
+ return { applied: true };
824
+ } catch (err) {
825
+ const msg = err instanceof Error ? err.message : String(err);
826
+ return { applied: false, reason: `AST patch failed: ${msg}` };
827
+ }
828
+ }
829
+ function normalizeReturnExpr(value) {
830
+ return value.replace(/^return\s+/, "").replace(/;$/, "").replace(/\s+/g, " ").trim();
831
+ }
832
+ function applyStringPatch(root, patch, dryRun, snapshot) {
833
+ const absPath = join6(root, patch.filePath);
834
+ let content;
835
+ try {
836
+ content = readFileSync4(absPath, "utf-8");
837
+ } catch (err) {
838
+ const msg = err instanceof Error ? err.message : String(err);
839
+ return { applied: false, reason: `Cannot read file: ${msg}` };
840
+ }
841
+ const originalContent = content;
842
+ const { originalCode, transformedCode } = patch.wrapTarget;
843
+ if (originalCode && transformedCode && originalCode !== transformedCode) {
844
+ if (content.includes(originalCode.trim())) {
845
+ content = content.replace(originalCode.trim(), transformedCode.trim());
846
+ } else {
847
+ return {
848
+ applied: false,
849
+ reason: "Original code not found in file (string match)"
850
+ };
851
+ }
852
+ }
853
+ if (patch.importToAdd && !content.includes("@synchronized-studio/response-transformer")) {
854
+ const scriptMatch = content.match(
855
+ /(<script[^>]*>)\s*\n/
856
+ );
857
+ if (scriptMatch) {
858
+ const insertAfter = scriptMatch[0];
859
+ content = content.replace(
860
+ insertAfter,
861
+ `${insertAfter}${patch.importToAdd}
862
+ `
863
+ );
864
+ } else if (patch.filePath.endsWith(".astro")) {
865
+ const fmMatch = content.match(/^(---\n)/);
866
+ if (fmMatch) {
867
+ content = content.replace(
868
+ "---\n",
869
+ `---
870
+ ${patch.importToAdd}
871
+ `
872
+ );
873
+ }
874
+ }
875
+ }
876
+ if (content === originalContent) {
877
+ return { applied: false, reason: "No changes needed (idempotent)" };
878
+ }
879
+ if (snapshot) {
880
+ const validation = validateContentAgainstSnapshot(content, patch.filePath, snapshot);
881
+ if (!validation.valid) {
882
+ return {
883
+ applied: false,
884
+ validationFailed: true,
885
+ reason: `Structural validation failed: ${validation.errors.join("; ")}`
886
+ };
887
+ }
888
+ }
889
+ if (!dryRun) {
890
+ writeFileSync(absPath, content, "utf-8");
891
+ }
892
+ return { applied: true };
893
+ }
894
+
895
+ // src/patcher/llmFallback.ts
896
+ import { readFileSync as readFileSync5 } from "fs";
897
+ import { join as join7 } from "path";
898
+ function buildPrompt(fileContent, filePath, cms, framework) {
899
+ const fn = getTransformFunctionName(cms.type);
900
+ const opts = buildCmsOptions(cms.type, cms.params);
901
+ return `You are a code integration agent. Given the following file, add the
902
+ @synchronized-studio/response-transformer to transform CMS asset URLs.
903
+
904
+ CMS: ${cms.type}
905
+ Transform function: ${fn}
906
+ Options: ${opts}
907
+ Framework: ${framework}
908
+
909
+ File: ${filePath}
910
+ \`\`\`
911
+ ${fileContent}
912
+ \`\`\`
913
+
914
+ Return ONLY a unified diff that:
915
+ 1. Adds the import: import { ${fn} } from '@synchronized-studio/response-transformer'
916
+ 2. Wraps the CMS data return/assignment with ${fn}(data, ${opts})
917
+ 3. Does NOT change any other code
918
+
919
+ Output ONLY the diff, nothing else.`;
920
+ }
921
+ async function applyLlmPatch(root, patch, cms, framework) {
922
+ const absPath = join7(root, patch.filePath);
923
+ let fileContent;
924
+ try {
925
+ fileContent = readFileSync5(absPath, "utf-8");
926
+ } catch (err) {
927
+ const msg = err instanceof Error ? err.message : String(err);
928
+ return { applied: false, reason: `Cannot read file: ${msg}`, requiresReview: true };
929
+ }
930
+ const prompt = buildPrompt(fileContent, patch.filePath, cms, framework);
931
+ const result = await chatCompletion(prompt, { model: "gpt-4o-mini", maxTokens: 2e3 });
932
+ if (isOpenAiError(result)) {
933
+ return { applied: false, reason: result.error, requiresReview: true };
934
+ }
935
+ const diff = result.content;
936
+ if (!diff) {
937
+ return { applied: false, reason: "LLM returned empty response", requiresReview: true };
938
+ }
939
+ const validation = validateDiff(diff, [patch.filePath]);
940
+ if (!validation.valid) {
941
+ return {
942
+ applied: false,
943
+ reason: `LLM diff failed validation: ${validation.errors.join("; ")}`,
944
+ diff,
945
+ requiresReview: true
946
+ };
947
+ }
948
+ return {
949
+ applied: false,
950
+ reason: "LLM patch generated, requires manual review before applying",
951
+ diff,
952
+ requiresReview: true
953
+ };
954
+ }
955
+
956
+ // src/patcher/llmCompletePatch.ts
957
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
958
+ import { join as join8 } from "path";
959
+ function buildPrompt2(fileContent, filePath, patch, cms, framework) {
960
+ const fn = getTransformFunctionName(cms.type);
961
+ const opts = buildCmsOptions(cms.type, cms.params);
962
+ const importStatement = `import { ${fn} } from '@synchronized-studio/response-transformer'`;
963
+ return `You are a precise code integration agent. Your task is to make EXACTLY TWO changes to the file below:
964
+
965
+ 1. Add this import at the top (with the other imports):
966
+ ${importStatement}
967
+
968
+ 2. Wrap the target code near line ${patch.wrapTarget.line}:
969
+ BEFORE: ${patch.wrapTarget.originalCode}
970
+ AFTER: ${patch.wrapTarget.transformedCode}
971
+
972
+ CRITICAL RULES:
973
+ - Return the COMPLETE modified file \u2014 every single line
974
+ - Do NOT change, remove, rename, or restructure ANY other code
975
+ - Do NOT add comments explaining your changes
976
+ - Do NOT change formatting, indentation, or whitespace of untouched lines
977
+ - Every function, variable, export, and import that exists in the original MUST remain
978
+ - If unsure about a change, do NOT make it \u2014 only make the two changes above
979
+
980
+ CMS: ${cms.type}
981
+ Framework: ${framework}
982
+
983
+ File: ${filePath}
984
+ \`\`\`
985
+ ${fileContent}
986
+ \`\`\`
987
+
988
+ Return ONLY the complete modified file content. No markdown fences, no explanation \u2014 just the raw file content.`;
989
+ }
990
+ async function applyLlmCompletePatch(root, patch, cms, framework, snapshot) {
991
+ const absPath = join8(root, patch.filePath);
992
+ let fileContent;
993
+ try {
994
+ fileContent = readFileSync6(absPath, "utf-8");
995
+ } catch (err) {
996
+ const msg = err instanceof Error ? err.message : String(err);
997
+ return { applied: false, reason: `Cannot read file: ${msg}` };
998
+ }
999
+ const prompt = buildPrompt2(fileContent, patch.filePath, patch, cms, framework);
1000
+ const result = await chatCompletion(prompt, {
1001
+ model: "gpt-4o",
1002
+ maxTokens: 16e3,
1003
+ temperature: 0
1004
+ });
1005
+ if (isOpenAiError(result)) {
1006
+ return { applied: false, reason: result.error };
1007
+ }
1008
+ let newContent = result.content;
1009
+ if (!newContent) {
1010
+ return { applied: false, reason: "LLM returned empty response" };
1011
+ }
1012
+ newContent = stripCodeFences(newContent);
1013
+ if (newContent.trim() === fileContent.trim()) {
1014
+ return { applied: false, reason: "LLM returned unchanged file" };
1015
+ }
1016
+ const fn = getTransformFunctionName(cms.type);
1017
+ if (!newContent.includes(fn)) {
1018
+ return { applied: false, reason: "LLM output missing transform function call" };
1019
+ }
1020
+ if (!newContent.includes("@synchronized-studio/response-transformer")) {
1021
+ return { applied: false, reason: "LLM output missing transformer import" };
1022
+ }
1023
+ const validation = validateContentAgainstSnapshot(newContent, patch.filePath, snapshot);
1024
+ if (!validation.valid) {
1025
+ return {
1026
+ applied: false,
1027
+ validationFailed: true,
1028
+ reason: `LLM output failed structural validation: ${validation.errors.join("; ")}`
1029
+ };
1030
+ }
1031
+ writeFileSync2(absPath, newContent, "utf-8");
1032
+ return { applied: true };
1033
+ }
1034
+ function stripCodeFences(content) {
1035
+ const fenceStart = /^```\w*\n/;
1036
+ const fenceEnd = /\n```\s*$/;
1037
+ if (fenceStart.test(content) && fenceEnd.test(content)) {
1038
+ return content.replace(fenceStart, "").replace(fenceEnd, "");
1039
+ }
1040
+ return content;
1041
+ }
1042
+
1043
+ // src/patcher/idempotency.ts
1044
+ import { readFileSync as readFileSync7 } from "fs";
1045
+ import { join as join9 } from "path";
1046
+ var TRANSFORMER_IMPORTS = [
1047
+ "@synchronized-studio/response-transformer",
1048
+ "transformCmsAssetUrls",
1049
+ "transformPrismicAssetUrls",
1050
+ "transformContentfulAssetUrls",
1051
+ "transformSanityAssetUrls",
1052
+ "transformShopifyAssetUrls",
1053
+ "transformCloudinaryAssetUrls",
1054
+ "transformImgixAssetUrls",
1055
+ "transformGenericAssetUrls"
1056
+ ];
1057
+ function isAlreadyTransformed(root, filePath) {
1058
+ const absPath = join9(root, filePath);
1059
+ let content;
1060
+ try {
1061
+ content = readFileSync7(absPath, "utf-8");
1062
+ } catch {
1063
+ return false;
1064
+ }
1065
+ return TRANSFORMER_IMPORTS.some((sig) => content.includes(sig));
1066
+ }
1067
+ function isTestOrFixtureFile(filePath) {
1068
+ return /\.(test|spec)\.[jt]sx?$/.test(filePath) || /__tests__\//.test(filePath) || /(^|\/)tests?\//.test(filePath) || /(^|\/)fixtures?\//.test(filePath) || /(^|\/)mocks?\//.test(filePath) || /\.stories\.[jt]sx?$/.test(filePath);
1069
+ }
1070
+ function isGeneratedFile(filePath) {
1071
+ return /\.generated\.[jt]sx?$/.test(filePath) || /\.g\.[jt]sx?$/.test(filePath) || /(^|\/)\.nuxt\//.test(filePath) || /(^|\/)\.next\//.test(filePath) || /(^|\/)\.svelte-kit\//.test(filePath) || /(^|\/)dist\//.test(filePath) || /(^|\/)build\//.test(filePath);
1072
+ }
1073
+
1074
+ // src/patcher/index.ts
1075
+ async function applyPlan(plan, opts = {}) {
1076
+ const startTime = Date.now();
1077
+ const root = plan.scan.projectRoot;
1078
+ const dryRun = opts.dryRun ?? false;
1079
+ const includeTests = opts.includeTests ?? false;
1080
+ const maxFiles = opts.maxFiles ?? plan.policies.maxFilesAutoApply;
1081
+ const files = [];
1082
+ let appliedCount = 0;
1083
+ const patchedFiles = /* @__PURE__ */ new Set();
1084
+ const alreadyTransformedAtStart = new Set(
1085
+ plan.patches.map((patch) => patch.filePath).filter((filePath, index, all) => all.indexOf(filePath) === index).filter((filePath) => isAlreadyTransformed(root, filePath))
1086
+ );
1087
+ for (const patch of plan.patches) {
1088
+ const fileStart = Date.now();
1089
+ if (alreadyTransformedAtStart.has(patch.filePath)) {
1090
+ files.push({
1091
+ filePath: patch.filePath,
1092
+ applied: false,
1093
+ method: "skipped",
1094
+ reason: "Transformer already present in file",
1095
+ durationMs: Date.now() - fileStart
1096
+ });
1097
+ continue;
1098
+ }
1099
+ if (!includeTests && isTestOrFixtureFile(patch.filePath)) {
1100
+ files.push({
1101
+ filePath: patch.filePath,
1102
+ applied: false,
1103
+ method: "skipped",
1104
+ reason: "Test/fixture file excluded (use --include-tests to include)",
1105
+ durationMs: Date.now() - fileStart
1106
+ });
1107
+ continue;
1108
+ }
1109
+ if (isGeneratedFile(patch.filePath)) {
1110
+ files.push({
1111
+ filePath: patch.filePath,
1112
+ applied: false,
1113
+ method: "skipped",
1114
+ reason: "Generated file excluded",
1115
+ durationMs: Date.now() - fileStart
1116
+ });
1117
+ continue;
1118
+ }
1119
+ if (!patchedFiles.has(patch.filePath) && appliedCount >= maxFiles) {
1120
+ files.push({
1121
+ filePath: patch.filePath,
1122
+ applied: false,
1123
+ method: "skipped",
1124
+ reason: `Max files threshold reached (${maxFiles})`,
1125
+ durationMs: Date.now() - fileStart
1126
+ });
1127
+ continue;
1128
+ }
1129
+ const snapshot = takeSnapshot(root, patch.filePath);
1130
+ if (plan.policies.llmOnly && plan.policies.allowLlmFallback) {
1131
+ consola.info(`LLM-only mode: ${patch.filePath}...`);
1132
+ const llmResult = await applyLlmCompletePatch(
1133
+ root,
1134
+ patch,
1135
+ plan.scan.cms,
1136
+ plan.scan.framework.name,
1137
+ snapshot
1138
+ );
1139
+ files.push({
1140
+ filePath: patch.filePath,
1141
+ applied: llmResult.applied,
1142
+ method: llmResult.applied ? "llm-complete" : "skipped",
1143
+ reason: llmResult.reason,
1144
+ durationMs: Date.now() - fileStart
1145
+ });
1146
+ if (llmResult.applied && !patchedFiles.has(patch.filePath)) {
1147
+ patchedFiles.add(patch.filePath);
1148
+ appliedCount++;
1149
+ }
1150
+ continue;
1151
+ }
1152
+ const astResult = applyAstPatch(root, patch, dryRun, snapshot);
1153
+ if (astResult.applied) {
1154
+ if (!patchedFiles.has(patch.filePath)) {
1155
+ patchedFiles.add(patch.filePath);
1156
+ appliedCount++;
1157
+ }
1158
+ files.push({
1159
+ filePath: patch.filePath,
1160
+ applied: true,
1161
+ method: "ast",
1162
+ durationMs: Date.now() - fileStart
1163
+ });
1164
+ continue;
1165
+ }
1166
+ const shouldTryLlmComplete = astResult.validationFailed || plan.policies.allowLlmFallback && (plan.policies.llmFallbackForAll || patch.confidence === "low");
1167
+ if (shouldTryLlmComplete) {
1168
+ const reason = astResult.validationFailed ? "AST validation failed" : "AST patch failed";
1169
+ consola.info(`${reason} for ${patch.filePath}, trying LLM complete-file fallback...`);
1170
+ if (snapshot.content) {
1171
+ const absPath = join10(root, patch.filePath);
1172
+ try {
1173
+ const currentContent = readFileSync8(absPath, "utf-8");
1174
+ if (currentContent !== snapshot.content) {
1175
+ writeFileSync3(absPath, snapshot.content, "utf-8");
1176
+ }
1177
+ } catch {
1178
+ }
1179
+ }
1180
+ const llmResult = await applyLlmCompletePatch(
1181
+ root,
1182
+ patch,
1183
+ plan.scan.cms,
1184
+ plan.scan.framework.name,
1185
+ snapshot
1186
+ );
1187
+ if (llmResult.applied) {
1188
+ if (!patchedFiles.has(patch.filePath)) {
1189
+ patchedFiles.add(patch.filePath);
1190
+ appliedCount++;
1191
+ }
1192
+ files.push({
1193
+ filePath: patch.filePath,
1194
+ applied: true,
1195
+ method: "llm-complete",
1196
+ durationMs: Date.now() - fileStart
1197
+ });
1198
+ continue;
1199
+ }
1200
+ if (plan.policies.allowLlmFallback) {
1201
+ const legacyResult = await applyLlmPatch(
1202
+ root,
1203
+ patch,
1204
+ plan.scan.cms,
1205
+ plan.scan.framework.name
1206
+ );
1207
+ files.push({
1208
+ filePath: patch.filePath,
1209
+ applied: legacyResult.applied,
1210
+ method: legacyResult.applied ? "llm" : "skipped",
1211
+ reason: legacyResult.reason,
1212
+ durationMs: Date.now() - fileStart
1213
+ });
1214
+ if (legacyResult.applied && !patchedFiles.has(patch.filePath)) {
1215
+ patchedFiles.add(patch.filePath);
1216
+ appliedCount++;
1217
+ }
1218
+ continue;
1219
+ }
1220
+ files.push({
1221
+ filePath: patch.filePath,
1222
+ applied: false,
1223
+ method: "skipped",
1224
+ reason: llmResult.reason ?? "Both AST and LLM complete-file patch failed",
1225
+ durationMs: Date.now() - fileStart
1226
+ });
1227
+ continue;
1228
+ }
1229
+ files.push({
1230
+ filePath: patch.filePath,
1231
+ applied: false,
1232
+ method: "skipped",
1233
+ reason: astResult.reason ?? "AST patch could not be applied",
1234
+ durationMs: Date.now() - fileStart
1235
+ });
1236
+ }
1237
+ let envUpdated = false;
1238
+ if (!dryRun) {
1239
+ for (const envFile of plan.env.files) {
1240
+ const envPath = join10(root, envFile);
1241
+ if (existsSync5(envPath)) {
1242
+ const content = readFileSync8(envPath, "utf-8");
1243
+ if (!content.includes(plan.env.key)) {
1244
+ appendFileSync(envPath, `
1245
+ ${plan.env.key}=${plan.env.placeholder}
1246
+ `);
1247
+ envUpdated = true;
1248
+ }
1249
+ }
1250
+ }
1251
+ if (plan.env.files.length === 0) {
1252
+ const envExamplePath = join10(root, ".env.example");
1253
+ writeFileSync3(
1254
+ envExamplePath,
1255
+ `${plan.env.key}=${plan.env.placeholder}
1256
+ `,
1257
+ "utf-8"
1258
+ );
1259
+ envUpdated = true;
1260
+ }
1261
+ }
1262
+ return {
1263
+ schemaVersion: "1.0",
1264
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1265
+ projectRoot: root,
1266
+ gitBranch: null,
1267
+ gitCommit: null,
1268
+ installed: false,
1269
+ envUpdated,
1270
+ files,
1271
+ totalDurationMs: Date.now() - startTime
1272
+ };
1273
+ }
1274
+
1275
+ // src/types.ts
1276
+ import { z } from "zod/v3";
1277
+ var FrameworkName = z.enum([
1278
+ "nuxt",
1279
+ "nuxt2",
1280
+ "next",
1281
+ "remix",
1282
+ "astro",
1283
+ "sveltekit",
1284
+ "express",
1285
+ "hono",
1286
+ "fastify",
1287
+ "unknown"
1288
+ ]);
1289
+ var CmsType = z.enum([
1290
+ "prismic",
1291
+ "contentful",
1292
+ "sanity",
1293
+ "shopify",
1294
+ "cloudinary",
1295
+ "imgix",
1296
+ "generic",
1297
+ "unknown"
1298
+ ]);
1299
+ var PackageManager = z.enum(["npm", "yarn", "pnpm", "bun"]);
1300
+ var Confidence = z.enum(["high", "medium", "low"]);
1301
+ var InjectionType = z.enum([
1302
+ "return",
1303
+ "res.json",
1304
+ "assignment",
1305
+ "useFetch-transform",
1306
+ "useAsyncData-transform",
1307
+ "loader-return",
1308
+ "getServerSideProps-return",
1309
+ "getStaticProps-return",
1310
+ "load-return",
1311
+ "frontmatter-assignment",
1312
+ "asyncData-return",
1313
+ "vuex-action-return"
1314
+ ]);
1315
+ var VerifyProfile = z.enum(["quick", "full"]);
1316
+ var FrameworkInfo = z.object({
1317
+ name: FrameworkName,
1318
+ version: z.string(),
1319
+ configFile: z.string().nullable()
1320
+ });
1321
+ var CmsInfo = z.object({
1322
+ type: CmsType,
1323
+ params: z.record(z.string()),
1324
+ detectedFrom: z.array(z.string())
1325
+ });
1326
+ var InjectionCandidate = z.object({
1327
+ filePath: z.string(),
1328
+ line: z.number(),
1329
+ type: InjectionType,
1330
+ score: z.number().min(0).max(100),
1331
+ confidence: Confidence,
1332
+ targetCode: z.string(),
1333
+ context: z.string(),
1334
+ reasons: z.array(z.string())
1335
+ });
1336
+ var ScanResult = z.object({
1337
+ framework: FrameworkInfo,
1338
+ cms: CmsInfo,
1339
+ injectionPoints: z.array(InjectionCandidate),
1340
+ packageManager: PackageManager,
1341
+ projectRoot: z.string()
1342
+ });
1343
+ var FilePatch = z.object({
1344
+ filePath: z.string(),
1345
+ description: z.string(),
1346
+ importToAdd: z.string(),
1347
+ wrapTarget: z.object({
1348
+ line: z.number(),
1349
+ originalCode: z.string(),
1350
+ transformedCode: z.string()
1351
+ }),
1352
+ confidence: Confidence,
1353
+ reasons: z.array(z.string())
1354
+ });
1355
+ var PatchPlan = z.object({
1356
+ schemaVersion: z.literal("1.0"),
1357
+ scan: ScanResult,
1358
+ install: z.object({
1359
+ package: z.literal("@synchronized-studio/response-transformer"),
1360
+ command: z.string()
1361
+ }),
1362
+ env: z.object({
1363
+ key: z.literal("CMS_ASSETS_URL"),
1364
+ placeholder: z.string(),
1365
+ files: z.array(z.string())
1366
+ }),
1367
+ patches: z.array(FilePatch),
1368
+ policies: z.object({
1369
+ maxFilesAutoApply: z.number().default(20),
1370
+ allowLlmFallback: z.boolean().default(false),
1371
+ /** When true, try LLM for any failed AST patch (not just low confidence). Useful for testing. */
1372
+ llmFallbackForAll: z.boolean().default(false),
1373
+ /** When true, skip AST entirely and use LLM for all patches (testing only). */
1374
+ llmOnly: z.boolean().default(false),
1375
+ verifyProfile: VerifyProfile.default("quick")
1376
+ })
1377
+ });
1378
+ var PatchedFileReport = z.object({
1379
+ filePath: z.string(),
1380
+ applied: z.boolean(),
1381
+ method: z.enum(["ast", "llm", "llm-complete", "skipped"]),
1382
+ reason: z.string().optional(),
1383
+ durationMs: z.number()
1384
+ });
1385
+ var ApplyReport = z.object({
1386
+ schemaVersion: z.literal("1.0"),
1387
+ timestamp: z.string(),
1388
+ projectRoot: z.string(),
1389
+ gitBranch: z.string().nullable(),
1390
+ gitCommit: z.string().nullable(),
1391
+ installed: z.boolean(),
1392
+ envUpdated: z.boolean(),
1393
+ files: z.array(PatchedFileReport),
1394
+ totalDurationMs: z.number()
1395
+ });
1396
+ var VerifyReport = z.object({
1397
+ schemaVersion: z.literal("1.0"),
1398
+ profile: VerifyProfile,
1399
+ lintPassed: z.boolean().nullable(),
1400
+ buildPassed: z.boolean().nullable(),
1401
+ testsPassed: z.boolean().nullable(),
1402
+ patchedFiles: z.array(z.string()),
1403
+ warnings: z.array(z.string()),
1404
+ durationMs: z.number()
1405
+ });
1406
+ var AiFileResult = z.object({
1407
+ filePath: z.string(),
1408
+ passed: z.boolean(),
1409
+ issues: z.array(z.string()),
1410
+ fixAttempted: z.boolean(),
1411
+ fixApplied: z.boolean(),
1412
+ iterations: z.number()
1413
+ });
1414
+ var AiReviewReport = z.object({
1415
+ schemaVersion: z.literal("1.0"),
1416
+ filesReviewed: z.number(),
1417
+ filesPassed: z.number(),
1418
+ filesFixed: z.number(),
1419
+ filesFailed: z.number(),
1420
+ results: z.array(AiFileResult),
1421
+ totalDurationMs: z.number(),
1422
+ tokensUsed: z.number()
1423
+ });
1424
+
1425
+ // src/reporting/index.ts
1426
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, existsSync as existsSync6, mkdirSync } from "fs";
1427
+ import { join as join11 } from "path";
1428
+ import consola2 from "consola";
1429
+ function createReport(parts) {
1430
+ return {
1431
+ version: "1.0",
1432
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1433
+ ...parts
1434
+ };
1435
+ }
1436
+ function saveReport(root, report) {
1437
+ const dir = join11(root, ".cmsassets-agent");
1438
+ if (!existsSync6(dir)) {
1439
+ mkdirSync(dir, { recursive: true });
1440
+ }
1441
+ const filename = `report-${Date.now()}.json`;
1442
+ const filePath = join11(dir, filename);
1443
+ writeFileSync4(filePath, JSON.stringify(report, null, 2), "utf-8");
1444
+ consola2.info(`Report saved to ${filePath}`);
1445
+ return filePath;
1446
+ }
1447
+ function savePlanFile(root, plan) {
1448
+ const filePath = join11(root, "cmsassets-agent.plan.json");
1449
+ writeFileSync4(filePath, JSON.stringify(plan, null, 2), "utf-8");
1450
+ consola2.info(`Plan saved to ${filePath}`);
1451
+ return filePath;
1452
+ }
1453
+ function loadPlanFile(filePath) {
1454
+ try {
1455
+ const raw = JSON.parse(readFileSync9(filePath, "utf-8"));
1456
+ const result = PatchPlan.safeParse(raw);
1457
+ if (result.success) return result.data;
1458
+ consola2.error("Plan file validation failed:", result.error.issues);
1459
+ return null;
1460
+ } catch (err) {
1461
+ const msg = err instanceof Error ? err.message : String(err);
1462
+ consola2.error(`Failed to load plan file: ${msg}`);
1463
+ return null;
1464
+ }
1465
+ }
1466
+
1467
+ // src/git/index.ts
1468
+ import { execSync } from "child_process";
1469
+ import consola3 from "consola";
1470
+ function exec(cmd, cwd) {
1471
+ try {
1472
+ return execSync(cmd, { cwd, encoding: "utf-8", stdio: "pipe" }).trim();
1473
+ } catch {
1474
+ return "";
1475
+ }
1476
+ }
1477
+ var gitOps = {
1478
+ isGitRepo(cwd) {
1479
+ return exec("git rev-parse --is-inside-work-tree", cwd) === "true";
1480
+ },
1481
+ isClean(cwd) {
1482
+ return exec("git diff --quiet && git diff --cached --quiet && echo clean", cwd) === "clean";
1483
+ },
1484
+ getCurrentBranch(cwd) {
1485
+ const branch = exec("git branch --show-current", cwd);
1486
+ return branch || null;
1487
+ },
1488
+ getHeadCommit(cwd) {
1489
+ const hash = exec("git rev-parse --short HEAD", cwd);
1490
+ return hash || null;
1491
+ },
1492
+ createBranch(cwd, name) {
1493
+ try {
1494
+ execSync(`git checkout -b ${name}`, { cwd, stdio: "pipe" });
1495
+ return true;
1496
+ } catch {
1497
+ consola3.warn(`Failed to create branch: ${name}`);
1498
+ return false;
1499
+ }
1500
+ },
1501
+ stageAll(cwd) {
1502
+ execSync("git add -A", { cwd, stdio: "pipe" });
1503
+ },
1504
+ commit(cwd, message) {
1505
+ try {
1506
+ execSync(`git commit -m "${message.replace(/"/g, '\\"')}"`, {
1507
+ cwd,
1508
+ stdio: "pipe"
1509
+ });
1510
+ return exec("git rev-parse --short HEAD", cwd);
1511
+ } catch {
1512
+ consola3.warn("Failed to create commit");
1513
+ return null;
1514
+ }
1515
+ },
1516
+ rollbackToCommit(cwd, commitHash) {
1517
+ try {
1518
+ execSync(`git reset --hard ${commitHash}`, { cwd, stdio: "pipe" });
1519
+ return true;
1520
+ } catch {
1521
+ consola3.error(`Failed to rollback to ${commitHash}`);
1522
+ return false;
1523
+ }
1524
+ },
1525
+ getLastCommitByAgent(cwd) {
1526
+ const log = exec(
1527
+ 'git log --oneline --all --grep="cmsassets-agent" -n 1 --format="%H"',
1528
+ cwd
1529
+ );
1530
+ return log || null;
1531
+ },
1532
+ getCommitBefore(cwd, commitHash) {
1533
+ const parent = exec(`git rev-parse ${commitHash}~1`, cwd);
1534
+ return parent || null;
1535
+ },
1536
+ push(cwd, remote = "origin") {
1537
+ try {
1538
+ const branch = exec("git branch --show-current", cwd);
1539
+ execSync(`git push -u ${remote} ${branch}`, { cwd, stdio: "pipe" });
1540
+ return true;
1541
+ } catch {
1542
+ consola3.warn("Failed to push to remote");
1543
+ return false;
1544
+ }
1545
+ }
1546
+ };
1547
+
1548
+ // src/verifier/index.ts
1549
+ import { execSync as execSync2 } from "child_process";
1550
+ import consola4 from "consola";
1551
+
1552
+ // src/verifier/profiles.ts
1553
+ function getQuickSteps(framework) {
1554
+ const steps = [];
1555
+ switch (framework) {
1556
+ case "nuxt":
1557
+ case "nuxt2":
1558
+ steps.push({
1559
+ name: "nuxt-prepare",
1560
+ command: "npx nuxt prepare",
1561
+ required: false
1562
+ });
1563
+ break;
1564
+ case "next":
1565
+ steps.push({
1566
+ name: "tsc-noEmit",
1567
+ command: "npx tsc --noEmit",
1568
+ required: false
1569
+ });
1570
+ break;
1571
+ case "astro":
1572
+ steps.push({
1573
+ name: "astro-check",
1574
+ command: "npx astro check",
1575
+ required: false
1576
+ });
1577
+ break;
1578
+ case "sveltekit":
1579
+ steps.push({
1580
+ name: "svelte-check",
1581
+ command: "npx svelte-check",
1582
+ required: false
1583
+ });
1584
+ break;
1585
+ default:
1586
+ steps.push({
1587
+ name: "tsc-noEmit",
1588
+ command: "npx tsc --noEmit",
1589
+ required: false
1590
+ });
1591
+ }
1592
+ return steps;
1593
+ }
1594
+ function getFullSteps(framework) {
1595
+ const steps = getQuickSteps(framework);
1596
+ steps.push({
1597
+ name: "lint",
1598
+ command: "npm run lint",
1599
+ required: false
1600
+ });
1601
+ switch (framework) {
1602
+ case "nuxt":
1603
+ case "nuxt2":
1604
+ steps.push({ name: "build", command: "npm run build", required: true });
1605
+ break;
1606
+ case "next":
1607
+ steps.push({ name: "build", command: "npm run build", required: true });
1608
+ break;
1609
+ case "astro":
1610
+ steps.push({ name: "build", command: "npm run build", required: true });
1611
+ break;
1612
+ case "sveltekit":
1613
+ steps.push({ name: "build", command: "npm run build", required: true });
1614
+ break;
1615
+ default:
1616
+ steps.push({ name: "build", command: "npm run build", required: false });
1617
+ }
1618
+ steps.push({
1619
+ name: "test",
1620
+ command: "npm test",
1621
+ required: false
1622
+ });
1623
+ return steps;
1624
+ }
1625
+ function getVerifySteps(profile, framework) {
1626
+ return profile === "full" ? getFullSteps(framework) : getQuickSteps(framework);
1627
+ }
1628
+
1629
+ // src/verifier/index.ts
1630
+ function verify(root, opts = {}) {
1631
+ const startTime = Date.now();
1632
+ const profile = opts.profile ?? "quick";
1633
+ const framework = opts.framework ?? "unknown";
1634
+ const patchedFiles = opts.patchedFiles ?? [];
1635
+ const warnings = [];
1636
+ const steps = getVerifySteps(profile, framework);
1637
+ let lintPassed = null;
1638
+ let buildPassed = null;
1639
+ let testsPassed = null;
1640
+ for (const step of steps) {
1641
+ consola4.info(`Running: ${step.name} (${step.command})`);
1642
+ try {
1643
+ execSync2(step.command, {
1644
+ cwd: root,
1645
+ stdio: "pipe",
1646
+ timeout: 12e4
1647
+ });
1648
+ if (step.name === "lint") lintPassed = true;
1649
+ if (step.name === "build") buildPassed = true;
1650
+ if (step.name === "test") testsPassed = true;
1651
+ consola4.success(`${step.name} passed`);
1652
+ } catch (err) {
1653
+ const message = err instanceof Error ? err.message : String(err);
1654
+ const truncated = message.substring(0, 500);
1655
+ if (step.name === "lint") lintPassed = false;
1656
+ if (step.name === "build") buildPassed = false;
1657
+ if (step.name === "test") testsPassed = false;
1658
+ if (step.required) {
1659
+ consola4.error(`${step.name} FAILED: ${truncated}`);
1660
+ warnings.push(`${step.name} failed (required): ${truncated}`);
1661
+ } else {
1662
+ consola4.warn(`${step.name} failed (optional): ${truncated}`);
1663
+ warnings.push(`${step.name} failed (optional): ${truncated}`);
1664
+ }
1665
+ }
1666
+ }
1667
+ return {
1668
+ schemaVersion: "1.0",
1669
+ profile,
1670
+ lintPassed,
1671
+ buildPassed,
1672
+ testsPassed,
1673
+ patchedFiles,
1674
+ warnings,
1675
+ durationMs: Date.now() - startTime
1676
+ };
1677
+ }
1678
+
1679
+ export {
1680
+ scan,
1681
+ createPlan,
1682
+ applyPlan,
1683
+ FrameworkName,
1684
+ CmsType,
1685
+ PackageManager,
1686
+ Confidence,
1687
+ InjectionType,
1688
+ VerifyProfile,
1689
+ FrameworkInfo,
1690
+ CmsInfo,
1691
+ InjectionCandidate,
1692
+ ScanResult,
1693
+ FilePatch,
1694
+ PatchPlan,
1695
+ PatchedFileReport,
1696
+ ApplyReport,
1697
+ VerifyReport,
1698
+ AiFileResult,
1699
+ AiReviewReport,
1700
+ createReport,
1701
+ saveReport,
1702
+ savePlanFile,
1703
+ loadPlanFile,
1704
+ gitOps,
1705
+ verify
1706
+ };