jekyll-component-mcp 1.2.2 → 1.5.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.
@@ -4,13 +4,97 @@
4
4
  import path from "node:path";
5
5
  import { assertWriteAllowed } from "../server/context.js";
6
6
  import { normalizeComponentName } from "../security/validation.js";
7
- import { safeExists, safeReadFile, safeWriteFile, safeUnlink, } from "../utils/filesystem.js";
7
+ import { safeExists, safeReadFile, safeWriteFile, safeUnlink, safeWalk, safeReadDir, } from "../utils/filesystem.js";
8
8
  import { analyzeLiquid, checkLiquidSyntax } from "../parsers/liquid-parser.js";
9
9
  import { findImportForComponent } from "../parsers/scss-parser.js";
10
10
  import { ProjectService } from "./project-service.js";
11
+ import { BuildService } from "./build-service.js";
12
+ import { ScssService } from "./scss-service.js";
11
13
  import { logger } from "../utils/logger.js";
12
- function defaultLiquidTemplate(name, variants) {
13
- const classBase = name;
14
+ import { createUnifiedDiff } from "../utils/diff.js";
15
+ const COMPONENT_FILE_KEYS = [
16
+ "liquid",
17
+ "scss",
18
+ "javascript",
19
+ "documentation",
20
+ "example",
21
+ ];
22
+ function escapeRegExp(value) {
23
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24
+ }
25
+ function replaceComponentReferences(source, oldName, newName, replacePlainName = true) {
26
+ const oldClass = `c-${oldName}`;
27
+ const newClass = `c-${newName}`;
28
+ const oldInit = componentInitFunction(oldName);
29
+ const newInit = componentInitFunction(newName);
30
+ const classPattern = new RegExp(`\\.${escapeRegExp(oldClass)}(?=__|--|[^a-zA-Z0-9_-]|$)`, "g");
31
+ const legacyClassPattern = new RegExp(`\\.${escapeRegExp(oldName)}(?=__|--|[^a-zA-Z0-9_-]|$)`, "g");
32
+ const plainPattern = new RegExp(`(^|[^a-zA-Z0-9])${escapeRegExp(oldName)}(?=$|[^a-zA-Z0-9])`, "g");
33
+ let updated = source
34
+ .replace(classPattern, `.${newClass}`)
35
+ .replace(legacyClassPattern, `.${newName}`)
36
+ .replaceAll(`_${oldName}.scss`, `_${newName}.scss`)
37
+ .replaceAll(`components/${oldName}`, `components/${newName}`)
38
+ .replaceAll(oldInit, newInit);
39
+ if (replacePlainName)
40
+ updated = updated.replace(plainPattern, `$1${newName}`);
41
+ return updated;
42
+ }
43
+ function isThicketProject(root, scssRoot) {
44
+ return (safeExists(root, path.posix.join(scssRoot, "_framework.scss")) &&
45
+ safeExists(root, path.posix.join(scssRoot, "_tokens.scss")));
46
+ }
47
+ function componentClassBase(name, thicket) {
48
+ if (!thicket)
49
+ return name;
50
+ return name.startsWith("c-") ? name : `c-${name}`;
51
+ }
52
+ function componentInitFunction(name) {
53
+ return `init${name.replace(/(^|-)(\w)/g, (_, __, c) => c.toUpperCase())}`;
54
+ }
55
+ function updateScssEntry(source, entry, scssRoot, scssPath, name) {
56
+ if (findImportForComponent(source, name).present)
57
+ return null;
58
+ const entryDir = path.posix.dirname(entry);
59
+ let importPath = path.posix.relative(entryDir, scssPath).replace(/\.scss$/, "");
60
+ if (!importPath.startsWith("."))
61
+ importPath = `./${importPath}`;
62
+ if (entry === path.posix.join(scssRoot, "_framework.scss")) {
63
+ importPath = path.posix.join("components", name);
64
+ }
65
+ importPath = importPath.replace(/\/_([^/]+)$/, "/$1");
66
+ const line = `@use "${importPath}";\n`;
67
+ return source.endsWith("\n") ? source + line : source + "\n" + line;
68
+ }
69
+ function updateThicketMainJs(source, initFunction, importPath) {
70
+ const importLine = `import { ${initFunction} } from '${importPath}';`;
71
+ let next = source;
72
+ const hasImport = next.split(/\r?\n/).some((line) => /^\s*import\b/.test(line) &&
73
+ line.includes(importPath) &&
74
+ line.includes(initFunction));
75
+ if (!hasImport) {
76
+ const lines = next.split(/\r?\n/);
77
+ let lastImport = -1;
78
+ lines.forEach((line, index) => {
79
+ if (/^\s*import\b/.test(line))
80
+ lastImport = index;
81
+ });
82
+ lines.splice(lastImport + 1, 0, importLine);
83
+ next = lines.join("\n");
84
+ }
85
+ const listener = /(document\.addEventListener\(\s*(['"])DOMContentLoaded\2\s*,\s*\(\)\s*=>\s*\{)([\s\S]*?)(\n\s*\}\s*\);)/;
86
+ const match = next.match(listener);
87
+ if (!match) {
88
+ return { warning: "Could not find a DOMContentLoaded initializer in the JavaScript entry point." };
89
+ }
90
+ if (!match[3].includes(`${initFunction}();`)) {
91
+ const body = match[3].replace(/\s*$/, "");
92
+ const updated = `${match[1]}${body}\n ${initFunction}();${match[4]}`;
93
+ next = next.replace(listener, updated);
94
+ }
95
+ return { source: next };
96
+ }
97
+ function defaultLiquidTemplate(name, variants, classBase = name) {
14
98
  const variantList = variants.length ? variants.join(", ") : "default";
15
99
  return `{% comment %}
16
100
  Component: ${name}
@@ -38,10 +122,10 @@ function defaultLiquidTemplate(name, variants) {
38
122
  </div>
39
123
  `;
40
124
  }
41
- function defaultScssTemplate(name, variants) {
125
+ function defaultScssTemplate(name, variants, classBase = name) {
42
126
  const lines = [
43
127
  `// Component: ${name}`,
44
- `.${name} {`,
128
+ `.${classBase} {`,
45
129
  ` // Base styles`,
46
130
  ``,
47
131
  ` &__label {`,
@@ -169,17 +253,7 @@ function validateComponentSchema(input) {
169
253
  return errors;
170
254
  }
171
255
  function buildUnifiedDiff(relativePath, before, after) {
172
- const beforeLines = before === "" ? [""] : before.split(/\r?\n/);
173
- const afterLines = after === "" ? [""] : after.split(/\r?\n/);
174
- const header = [`--- ${relativePath}`, `+++ ${relativePath}`];
175
- const lines = [...header, `@@ -0,0 +1,${afterLines.length} @@`];
176
- for (const line of afterLines) {
177
- lines.push(`+${line}`);
178
- }
179
- if (beforeLines.length > 0 && beforeLines.join("\n") !== afterLines.join("\n")) {
180
- lines.push(`@@ -1,${beforeLines.length} +1,${afterLines.length} @@`);
181
- }
182
- return lines.join("\n");
256
+ return createUnifiedDiff(relativePath, before, after);
183
257
  }
184
258
  function escapeHtml(value) {
185
259
  return value
@@ -192,9 +266,11 @@ function escapeHtml(value) {
192
266
  export class ComponentService {
193
267
  ctx;
194
268
  project;
269
+ build;
195
270
  constructor(ctx) {
196
271
  this.ctx = ctx;
197
272
  this.project = new ProjectService(ctx);
273
+ this.build = new BuildService(ctx);
198
274
  }
199
275
  list() {
200
276
  const scan = this.project.getScan();
@@ -335,6 +411,8 @@ export class ComponentService {
335
411
  const dryRun = input.dry_run === true;
336
412
  const paths = this.ctx.config.paths;
337
413
  const root = this.ctx.config.root;
414
+ const thicketProject = isThicketProject(root, paths.scss);
415
+ const classBase = componentClassBase(name, thicketProject);
338
416
  try {
339
417
  assertWriteAllowed(this.ctx, "create");
340
418
  }
@@ -369,17 +447,32 @@ export class ComponentService {
369
447
  planned.push({ type: "create", path: examplePath });
370
448
  if (jsPath)
371
449
  planned.push({ type: "create", path: jsPath });
372
- // Check collisions
373
450
  const warnings = [];
451
+ const integrationPreviewFiles = [];
452
+ if (dryRun) {
453
+ const scssRegistration = this.previewScssImport(name, scssPath, warnings);
454
+ if (scssRegistration) {
455
+ planned.push({ type: "update", path: scssRegistration.path });
456
+ integrationPreviewFiles.push(scssRegistration);
457
+ }
458
+ }
459
+ if (dryRun && thicketProject && jsPath) {
460
+ const jsRegistration = this.previewThicketJavascriptRegistration(name, jsPath, warnings);
461
+ if (jsRegistration) {
462
+ planned.push({ type: "update", path: jsRegistration.path });
463
+ integrationPreviewFiles.push(jsRegistration);
464
+ }
465
+ }
466
+ // Check collisions
374
467
  for (const p of planned) {
375
- if (safeExists(root, p.path)) {
468
+ if (p.type === "create" && safeExists(root, p.path)) {
376
469
  warnings.push(`File already exists and will be overwritten: ${p.path}`);
377
470
  }
378
471
  }
379
472
  if (dryRun) {
380
473
  const previewFiles = [
381
- { path: liquidPath, content: defaultLiquidTemplate(name, variants) },
382
- { path: scssPath, content: defaultScssTemplate(name, variants) },
474
+ { path: liquidPath, content: defaultLiquidTemplate(name, variants, classBase) },
475
+ { path: scssPath, content: defaultScssTemplate(name, variants, classBase) },
383
476
  ];
384
477
  if (docsPath) {
385
478
  previewFiles.push({
@@ -393,9 +486,10 @@ export class ComponentService {
393
486
  if (jsPath) {
394
487
  previewFiles.push({
395
488
  path: jsPath,
396
- content: `// Component: ${name}\nexport function init${name.replace(/(^|-)(\w)/g, (_, __, c) => c.toUpperCase())}() {\n // TODO\n}\n`,
489
+ content: `// Component: ${name}\nexport function ${componentInitFunction(name)}() {\n // TODO\n}\n`,
397
490
  });
398
491
  }
492
+ previewFiles.push(...integrationPreviewFiles);
399
493
  const diffs = previewFiles.map((entry) => ({
400
494
  path: entry.path,
401
495
  diff: buildUnifiedDiff(entry.path, "", entry.content),
@@ -414,12 +508,12 @@ export class ComponentService {
414
508
  const filesCreated = [];
415
509
  const filesModified = [];
416
510
  try {
417
- const liquidResult = safeWriteFile(root, liquidPath, defaultLiquidTemplate(name, variants), { maxSize: this.ctx.config.maxFileSize });
511
+ const liquidResult = safeWriteFile(root, liquidPath, defaultLiquidTemplate(name, variants, classBase), { maxSize: this.ctx.config.maxFileSize });
418
512
  if (liquidResult.created)
419
513
  filesCreated.push(liquidResult.path);
420
514
  else if (liquidResult.modified)
421
515
  filesModified.push(liquidResult.path);
422
- const scssResult = safeWriteFile(root, scssPath, defaultScssTemplate(name, variants), { maxSize: this.ctx.config.maxFileSize });
516
+ const scssResult = safeWriteFile(root, scssPath, defaultScssTemplate(name, variants, classBase), { maxSize: this.ctx.config.maxFileSize });
423
517
  if (scssResult.created)
424
518
  filesCreated.push(scssResult.path);
425
519
  else if (scssResult.modified)
@@ -441,14 +535,17 @@ export class ComponentService {
441
535
  filesModified.push(r.path);
442
536
  }
443
537
  if (jsPath) {
444
- const r = safeWriteFile(root, jsPath, `// Component: ${name}\nexport function init${name.replace(/(^|-)(\w)/g, (_, __, c) => c.toUpperCase())}() {\n // TODO\n}\n`, { maxSize: this.ctx.config.maxFileSize });
538
+ const r = safeWriteFile(root, jsPath, `// Component: ${name}\nexport function ${componentInitFunction(name)}() {\n // TODO\n}\n`, { maxSize: this.ctx.config.maxFileSize });
445
539
  if (r.created)
446
540
  filesCreated.push(r.path);
447
541
  else if (r.modified)
448
542
  filesModified.push(r.path);
449
543
  }
450
544
  // Try to register SCSS import in common entry points
451
- this.ensureScssImport(name, scssPath, warnings);
545
+ this.ensureScssImport(name, scssPath, warnings, filesModified);
546
+ if (thicketProject && jsPath) {
547
+ this.ensureThicketJavascriptRegistration(name, jsPath, warnings, filesModified);
548
+ }
452
549
  this.ctx.invalidateCache();
453
550
  logger.info("component_create", { name, filesCreated });
454
551
  return {
@@ -472,10 +569,572 @@ export class ComponentService {
472
569
  };
473
570
  }
474
571
  }
475
- ensureScssImport(name, scssPath, warnings) {
572
+ update(input) {
573
+ const detail = this.get(input.name);
574
+ if (!detail) {
575
+ return {
576
+ success: false,
577
+ operation: "component_update",
578
+ error: { code: "NOT_FOUND", message: `Component not found: ${input.name}` },
579
+ };
580
+ }
581
+ const updates = COMPONENT_FILE_KEYS.flatMap((key) => {
582
+ const content = input[key];
583
+ const filePath = detail[key];
584
+ return content !== undefined && filePath ? [{ key, path: filePath, content }] : [];
585
+ });
586
+ const requestedKeys = COMPONENT_FILE_KEYS.filter((key) => input[key] !== undefined);
587
+ const missingKeys = requestedKeys.filter((key) => !detail[key]);
588
+ if (missingKeys.length > 0) {
589
+ return {
590
+ success: false,
591
+ operation: "component_update",
592
+ component: detail.name,
593
+ error: {
594
+ code: "FILE_NOT_FOUND",
595
+ message: `Component does not have associated files for: ${missingKeys.join(", ")}`,
596
+ },
597
+ };
598
+ }
599
+ if (updates.length === 0) {
600
+ return {
601
+ success: false,
602
+ operation: "component_update",
603
+ component: detail.name,
604
+ error: { code: "NO_CHANGES", message: "Provide at least one component file source to update." },
605
+ };
606
+ }
607
+ const root = this.ctx.config.root;
608
+ const diffs = updates.map(({ path: filePath, content }) => ({
609
+ path: filePath,
610
+ before: safeReadFile(root, filePath, { maxSize: this.ctx.config.maxFileSize }),
611
+ content,
612
+ }));
613
+ const changed = diffs.filter((item) => item.before !== item.content);
614
+ if (input.dry_run) {
615
+ return {
616
+ success: true,
617
+ operation: "component_update",
618
+ component: detail.name,
619
+ dry_run: true,
620
+ operations: changed.map(({ path: filePath }) => ({ type: "update", path: filePath })),
621
+ diffs: changed.map(({ path: filePath, before, content }) => ({
622
+ path: filePath,
623
+ diff: createUnifiedDiff(filePath, before, content),
624
+ })),
625
+ diff: changed
626
+ .map(({ path: filePath, before, content }) => createUnifiedDiff(filePath, before, content))
627
+ .filter(Boolean)
628
+ .join("\n\n"),
629
+ };
630
+ }
631
+ const filesModified = [];
632
+ try {
633
+ assertWriteAllowed(this.ctx, "update");
634
+ for (const { path: filePath, content } of changed) {
635
+ const result = safeWriteFile(root, filePath, content, {
636
+ maxSize: this.ctx.config.maxFileSize,
637
+ });
638
+ if (result.modified)
639
+ filesModified.push(result.path);
640
+ }
641
+ this.ctx.invalidateCache();
642
+ return {
643
+ success: true,
644
+ operation: "component_update",
645
+ component: detail.name,
646
+ files_modified: filesModified,
647
+ };
648
+ }
649
+ catch (err) {
650
+ return {
651
+ success: false,
652
+ operation: "component_update",
653
+ component: detail.name,
654
+ error: {
655
+ code: err.code ?? "UPDATE_FAILED",
656
+ message: err.message,
657
+ },
658
+ files_modified: filesModified,
659
+ };
660
+ }
661
+ }
662
+ rename(input) {
663
+ const oldName = normalizeComponentName(input.name);
664
+ const newName = normalizeComponentName(input.new_name);
665
+ if (oldName === newName) {
666
+ return {
667
+ success: false,
668
+ operation: "component_rename",
669
+ error: { code: "INVALID_NAME", message: "The new name must differ from the current name." },
670
+ };
671
+ }
672
+ const detail = this.get(oldName);
673
+ if (!detail) {
674
+ return {
675
+ success: false,
676
+ operation: "component_rename",
677
+ error: { code: "NOT_FOUND", message: `Component not found: ${oldName}` },
678
+ };
679
+ }
680
+ const root = this.ctx.config.root;
681
+ const sources = COMPONENT_FILE_KEYS.flatMap((key) => {
682
+ const filePath = detail[key];
683
+ if (!filePath)
684
+ return [];
685
+ const content = safeReadFile(root, filePath, { maxSize: this.ctx.config.maxFileSize });
686
+ const newPath = filePath.replace(new RegExp(`${escapeRegExp(oldName)}(?=\\.[^./]+$)`), newName);
687
+ return [{
688
+ oldPath: filePath,
689
+ newPath,
690
+ before: content,
691
+ content: replaceComponentReferences(content, oldName, newName),
692
+ }];
693
+ });
694
+ if (sources.some(({ oldPath, newPath }) => oldPath === newPath)) {
695
+ return {
696
+ success: false,
697
+ operation: "component_rename",
698
+ component: oldName,
699
+ error: { code: "INVALID_PATH", message: "Could not derive a new path for every component file." },
700
+ };
701
+ }
702
+ const collisions = sources.filter(({ oldPath, newPath }) => newPath !== oldPath && safeExists(root, newPath));
703
+ if (collisions.length > 0) {
704
+ return {
705
+ success: false,
706
+ operation: "component_rename",
707
+ component: oldName,
708
+ error: {
709
+ code: "TARGET_EXISTS",
710
+ message: `Rename target already exists: ${collisions.map((item) => item.newPath).join(", ")}`,
711
+ },
712
+ };
713
+ }
714
+ const sourcePaths = new Set(sources.map(({ oldPath }) => oldPath));
715
+ const referenceUpdates = [];
716
+ const searchRoots = [
717
+ this.ctx.config.paths.includes,
718
+ this.ctx.config.paths.layouts,
719
+ this.ctx.config.paths.scss,
720
+ this.ctx.config.paths.js,
721
+ this.ctx.config.paths.docs,
722
+ this.ctx.config.paths.examples,
723
+ this.ctx.config.paths.posts,
724
+ "_pages",
725
+ "pages",
726
+ ];
727
+ const referencePaths = new Set();
728
+ for (const directory of searchRoots) {
729
+ for (const entry of safeWalk(root, directory, {
730
+ maxDepth: this.ctx.config.maxScanDepth,
731
+ extensions: [".html", ".liquid", ".md", ".scss", ".sass", ".css", ".js", ".mjs", ".ts"],
732
+ })) {
733
+ if (!entry.isDirectory && !sourcePaths.has(entry.relativePath)) {
734
+ referencePaths.add(entry.relativePath);
735
+ }
736
+ }
737
+ }
738
+ for (const entry of safeReadDir(root, ".", { withFileTypes: true })) {
739
+ if (entry.isFile() &&
740
+ [".html", ".liquid", ".md", ".scss", ".sass", ".css", ".js", ".mjs", ".ts"].includes(path.posix.extname(entry.name).toLowerCase())) {
741
+ referencePaths.add(entry.name);
742
+ }
743
+ }
744
+ for (const filePath of referencePaths) {
745
+ const before = safeReadFile(root, filePath, { maxSize: this.ctx.config.maxFileSize });
746
+ const content = replaceComponentReferences(before, oldName, newName, false);
747
+ if (content !== before)
748
+ referenceUpdates.push({ path: filePath, before, content });
749
+ }
750
+ const operations = [
751
+ ...sources.flatMap(({ oldPath, newPath }) => [
752
+ { type: "create", path: newPath },
753
+ { type: "delete", path: oldPath },
754
+ ]),
755
+ ...referenceUpdates.map(({ path: filePath }) => ({ type: "update", path: filePath })),
756
+ ];
757
+ const diffs = [
758
+ ...sources.map(({ newPath, content }) => ({
759
+ path: newPath,
760
+ diff: createUnifiedDiff(newPath, "", content),
761
+ })),
762
+ ...sources.map(({ oldPath, before }) => ({
763
+ path: oldPath,
764
+ diff: createUnifiedDiff(oldPath, before, ""),
765
+ })),
766
+ ...referenceUpdates.map(({ path: filePath, before, content }) => ({
767
+ path: filePath,
768
+ diff: createUnifiedDiff(filePath, before, content),
769
+ })),
770
+ ];
771
+ if (input.dry_run) {
772
+ return {
773
+ success: true,
774
+ operation: "component_rename",
775
+ component: oldName,
776
+ dry_run: true,
777
+ operations,
778
+ diffs,
779
+ diff: diffs.map((entry) => entry.diff).filter(Boolean).join("\n\n"),
780
+ };
781
+ }
782
+ if (!input.confirm) {
783
+ return {
784
+ success: false,
785
+ operation: "component_rename",
786
+ component: oldName,
787
+ error: {
788
+ code: "CONFIRMATION_REQUIRED",
789
+ message: "Renaming moves and removes source files; pass confirm: true after reviewing a dry run.",
790
+ },
791
+ };
792
+ }
793
+ const filesCreated = [];
794
+ const filesModified = [];
795
+ try {
796
+ assertWriteAllowed(this.ctx, "destructive");
797
+ for (const { newPath, content } of sources) {
798
+ const result = safeWriteFile(root, newPath, content, {
799
+ maxSize: this.ctx.config.maxFileSize,
800
+ overwrite: false,
801
+ });
802
+ if (result.created)
803
+ filesCreated.push(result.path);
804
+ }
805
+ for (const { path: filePath, content } of referenceUpdates) {
806
+ const result = safeWriteFile(root, filePath, content, {
807
+ maxSize: this.ctx.config.maxFileSize,
808
+ });
809
+ if (result.modified)
810
+ filesModified.push(result.path);
811
+ }
812
+ for (const { oldPath } of sources) {
813
+ safeUnlink(root, oldPath);
814
+ filesModified.push(oldPath);
815
+ }
816
+ this.ctx.invalidateCache();
817
+ return {
818
+ success: true,
819
+ operation: "component_rename",
820
+ component: newName,
821
+ files_created: filesCreated,
822
+ files_modified: filesModified,
823
+ };
824
+ }
825
+ catch (err) {
826
+ return {
827
+ success: false,
828
+ operation: "component_rename",
829
+ component: oldName,
830
+ error: {
831
+ code: err.code ?? "RENAME_FAILED",
832
+ message: err.message,
833
+ },
834
+ files_created: filesCreated,
835
+ files_modified: filesModified,
836
+ };
837
+ }
838
+ }
839
+ duplicate(input) {
840
+ const sourceName = normalizeComponentName(input.name);
841
+ const newName = normalizeComponentName(input.new_name);
842
+ if (sourceName === newName) {
843
+ return {
844
+ success: false,
845
+ operation: "component_duplicate",
846
+ error: { code: "INVALID_NAME", message: "The duplicate name must differ from the source name." },
847
+ };
848
+ }
849
+ const detail = this.get(sourceName);
850
+ if (!detail) {
851
+ return {
852
+ success: false,
853
+ operation: "component_duplicate",
854
+ error: { code: "NOT_FOUND", message: `Component not found: ${sourceName}` },
855
+ };
856
+ }
857
+ const root = this.ctx.config.root;
858
+ const files = COMPONENT_FILE_KEYS.flatMap((key) => {
859
+ const filePath = detail[key];
860
+ if (!filePath)
861
+ return [];
862
+ const newPath = filePath.replace(new RegExp(`${escapeRegExp(sourceName)}(?=\\.[^./]+$)`), newName);
863
+ return [{
864
+ sourcePath: filePath,
865
+ path: newPath,
866
+ content: replaceComponentReferences(safeReadFile(root, filePath, { maxSize: this.ctx.config.maxFileSize }), sourceName, newName),
867
+ }];
868
+ });
869
+ const collisions = files.filter(({ path: filePath }) => safeExists(root, filePath));
870
+ if (collisions.length > 0) {
871
+ return {
872
+ success: false,
873
+ operation: "component_duplicate",
874
+ component: sourceName,
875
+ error: {
876
+ code: "TARGET_EXISTS",
877
+ message: `Duplicate target already exists: ${collisions.map((item) => item.path).join(", ")}`,
878
+ },
879
+ };
880
+ }
881
+ const warnings = [];
882
+ const integrationFiles = [];
883
+ const scssFilePath = files.find((file) => file.sourcePath === detail.scss)?.path;
884
+ if (input.dry_run && scssFilePath) {
885
+ const registration = this.previewScssImport(newName, scssFilePath, warnings);
886
+ if (registration) {
887
+ integrationFiles.push({
888
+ ...registration,
889
+ before: safeReadFile(root, registration.path, { maxSize: this.ctx.config.maxFileSize }),
890
+ });
891
+ }
892
+ }
893
+ const jsFilePath = files.find((file) => file.sourcePath === detail.javascript)?.path;
894
+ if (input.dry_run &&
895
+ jsFilePath &&
896
+ isThicketProject(root, this.ctx.config.paths.scss)) {
897
+ const registration = this.previewThicketJavascriptRegistration(newName, jsFilePath, warnings);
898
+ if (registration) {
899
+ integrationFiles.push({
900
+ ...registration,
901
+ before: safeReadFile(root, registration.path, { maxSize: this.ctx.config.maxFileSize }),
902
+ });
903
+ }
904
+ }
905
+ const diffs = [
906
+ ...files.map(({ path: filePath, content }) => ({
907
+ path: filePath,
908
+ diff: createUnifiedDiff(filePath, "", content),
909
+ })),
910
+ ...integrationFiles.map(({ path: filePath, before, content }) => ({
911
+ path: filePath,
912
+ diff: createUnifiedDiff(filePath, before, content),
913
+ })),
914
+ ];
915
+ const operations = [
916
+ ...files.map(({ path: filePath }) => ({ type: "create", path: filePath })),
917
+ ...integrationFiles.map(({ path: filePath }) => ({ type: "update", path: filePath })),
918
+ ];
919
+ if (input.dry_run) {
920
+ return {
921
+ success: true,
922
+ operation: "component_duplicate",
923
+ component: newName,
924
+ dry_run: true,
925
+ operations,
926
+ diffs,
927
+ diff: diffs.map((entry) => entry.diff).filter(Boolean).join("\n\n"),
928
+ warnings,
929
+ };
930
+ }
931
+ const filesCreated = [];
932
+ const filesModified = [];
933
+ try {
934
+ assertWriteAllowed(this.ctx, "create");
935
+ for (const file of files) {
936
+ const result = safeWriteFile(root, file.path, file.content, {
937
+ maxSize: this.ctx.config.maxFileSize,
938
+ overwrite: false,
939
+ });
940
+ if (result.created)
941
+ filesCreated.push(result.path);
942
+ }
943
+ const scssFile = files.find((file) => file.path === detail.scss?.replace(new RegExp(`${escapeRegExp(sourceName)}(?=\\.[^./]+$)`), newName));
944
+ if (scssFile)
945
+ this.ensureScssImport(newName, scssFile.path, warnings, filesModified);
946
+ if (detail.javascript && isThicketProject(root, this.ctx.config.paths.scss)) {
947
+ const jsFile = files.find((file) => file.sourcePath === detail.javascript);
948
+ if (jsFile) {
949
+ this.ensureThicketJavascriptRegistration(newName, jsFile.path, warnings, filesModified);
950
+ }
951
+ }
952
+ this.ctx.invalidateCache();
953
+ return {
954
+ success: true,
955
+ operation: "component_duplicate",
956
+ component: newName,
957
+ files_created: filesCreated,
958
+ files_modified: filesModified,
959
+ warnings,
960
+ };
961
+ }
962
+ catch (err) {
963
+ return {
964
+ success: false,
965
+ operation: "component_duplicate",
966
+ component: newName,
967
+ error: {
968
+ code: err.code ?? "DUPLICATE_FAILED",
969
+ message: err.message,
970
+ },
971
+ files_created: filesCreated,
972
+ files_modified: filesModified,
973
+ warnings,
974
+ };
975
+ }
976
+ }
977
+ async test(name, runBuild = true) {
978
+ const validation = this.validate(name);
979
+ if (!validation.valid) {
980
+ return { success: false, component: validation.component, validation };
981
+ }
982
+ const build = runBuild ? await this.build.build() : undefined;
983
+ return {
984
+ success: validation.valid && (build?.success ?? true),
985
+ component: validation.component,
986
+ validation,
987
+ ...(build ? { build } : {}),
988
+ };
989
+ }
990
+ dependencies(name) {
991
+ const target = normalizeComponentName(name);
992
+ const components = this.list();
993
+ const targetDetail = this.get(target);
994
+ if (!targetDetail)
995
+ return null;
996
+ const referencesByComponent = new Map();
997
+ for (const component of components) {
998
+ const detail = this.get(component.name);
999
+ if (!detail)
1000
+ continue;
1001
+ const referenced = new Map();
1002
+ for (const key of COMPONENT_FILE_KEYS) {
1003
+ const filePath = detail[key];
1004
+ const source = detail[`${key}Source`];
1005
+ if (!filePath || typeof source !== "string")
1006
+ continue;
1007
+ const patterns = [
1008
+ /\{%\s*include\s+components\/([a-z0-9-]+)\.html\b/gi,
1009
+ /@(?:use|forward|import)\s+["'][^"']*components\/([a-z0-9-]+)/gi,
1010
+ /from\s+["'][^"']*components\/([a-z0-9-]+)(?:\.js)?["']/gi,
1011
+ ];
1012
+ for (const pattern of patterns) {
1013
+ let match;
1014
+ while ((match = pattern.exec(source)) !== null) {
1015
+ const dependency = match[1];
1016
+ if (dependency === component.name)
1017
+ continue;
1018
+ const paths = referenced.get(dependency) ?? [];
1019
+ if (!paths.includes(filePath))
1020
+ paths.push(filePath);
1021
+ referenced.set(dependency, paths);
1022
+ }
1023
+ }
1024
+ }
1025
+ referencesByComponent.set(component.name, referenced);
1026
+ }
1027
+ const dependencies = [...(referencesByComponent.get(target) ?? new Map()).entries()]
1028
+ .map(([dependencyName, files]) => ({ name: dependencyName, files }))
1029
+ .sort((a, b) => a.name.localeCompare(b.name));
1030
+ const dependents = [...referencesByComponent.entries()]
1031
+ .flatMap(([componentName, references]) => {
1032
+ const files = references.get(target);
1033
+ return files ? [{ name: componentName, files }] : [];
1034
+ })
1035
+ .sort((a, b) => a.name.localeCompare(b.name));
1036
+ return { component: target, dependencies, dependents };
1037
+ }
1038
+ export(name) {
1039
+ const detail = this.get(name);
1040
+ if (!detail) {
1041
+ return {
1042
+ success: false,
1043
+ format: "jekyll-component-mcp/component-export@1",
1044
+ component: normalizeComponentName(name),
1045
+ files: [],
1046
+ error: { code: "NOT_FOUND", message: `Component not found: ${name}` },
1047
+ };
1048
+ }
1049
+ const files = COMPONENT_FILE_KEYS.flatMap((key) => {
1050
+ const filePath = detail[key];
1051
+ if (!filePath)
1052
+ return [];
1053
+ return [{
1054
+ path: filePath,
1055
+ content: safeReadFile(this.ctx.config.root, filePath, {
1056
+ maxSize: this.ctx.config.maxFileSize,
1057
+ }),
1058
+ }];
1059
+ });
1060
+ const totalBytes = files.reduce((total, file) => total + Buffer.byteLength(file.content), 0);
1061
+ if (totalBytes > this.ctx.config.maxFileSize) {
1062
+ return {
1063
+ success: false,
1064
+ format: "jekyll-component-mcp/component-export@1",
1065
+ component: detail.name,
1066
+ files: [],
1067
+ error: {
1068
+ code: "EXPORT_TOO_LARGE",
1069
+ message: `Component export exceeds the configured maximum size of ${this.ctx.config.maxFileSize} bytes.`,
1070
+ },
1071
+ };
1072
+ }
1073
+ return {
1074
+ success: true,
1075
+ format: "jekyll-component-mcp/component-export@1",
1076
+ component: detail.name,
1077
+ files,
1078
+ };
1079
+ }
1080
+ previewScssImport(name, scssPath, warnings) {
1081
+ const root = this.ctx.config.root;
1082
+ const scssRoot = this.ctx.config.paths.scss;
1083
+ const candidates = [
1084
+ path.posix.join(scssRoot, "_framework.scss"),
1085
+ path.posix.join(scssRoot, "components", "_index.scss"),
1086
+ path.posix.join(scssRoot, "_components.scss"),
1087
+ path.posix.join(scssRoot, "main.scss"),
1088
+ path.posix.join(scssRoot, "app.scss"),
1089
+ path.posix.join(scssRoot, "style.scss"),
1090
+ path.posix.join(scssRoot, "styles.scss"),
1091
+ path.posix.join(scssRoot, "index.scss"),
1092
+ ];
1093
+ for (const entry of candidates) {
1094
+ if (!safeExists(root, entry))
1095
+ continue;
1096
+ try {
1097
+ const source = safeReadFile(root, entry, { maxSize: this.ctx.config.maxFileSize });
1098
+ const content = updateScssEntry(source, entry, scssRoot, scssPath, name);
1099
+ return content ? { path: entry, content } : null;
1100
+ }
1101
+ catch (err) {
1102
+ warnings.push(`Could not preview SCSS registration in ${entry}: ${err.message}`);
1103
+ return null;
1104
+ }
1105
+ }
1106
+ warnings.push("No SCSS entry point found to register the component import.");
1107
+ return null;
1108
+ }
1109
+ previewThicketJavascriptRegistration(name, jsPath, warnings) {
1110
+ const root = this.ctx.config.root;
1111
+ const entry = path.posix.join(this.ctx.config.paths.js, "main.js");
1112
+ if (!safeExists(root, entry)) {
1113
+ warnings.push(`Could not find ${entry} to register the JavaScript component.`);
1114
+ return null;
1115
+ }
1116
+ try {
1117
+ const source = safeReadFile(root, entry, { maxSize: this.ctx.config.maxFileSize });
1118
+ let importPath = path.posix.relative(path.posix.dirname(entry), jsPath);
1119
+ if (!importPath.startsWith("."))
1120
+ importPath = `./${importPath}`;
1121
+ const update = updateThicketMainJs(source, componentInitFunction(name), importPath);
1122
+ if (!update.source) {
1123
+ warnings.push(`${update.warning} Register ${componentInitFunction(name)} manually in ${entry}.`);
1124
+ return null;
1125
+ }
1126
+ return update.source === source ? null : { path: entry, content: update.source };
1127
+ }
1128
+ catch (err) {
1129
+ warnings.push(`Could not preview JavaScript registration in ${entry}: ${err.message}`);
1130
+ return null;
1131
+ }
1132
+ }
1133
+ ensureScssImport(name, scssPath, warnings, filesModified) {
476
1134
  const root = this.ctx.config.root;
477
1135
  const paths = this.ctx.config.paths;
478
1136
  const candidates = [
1137
+ path.posix.join(paths.scss, "_framework.scss"),
479
1138
  path.posix.join(paths.scss, "components", "_index.scss"),
480
1139
  path.posix.join(paths.scss, "_components.scss"),
481
1140
  path.posix.join(paths.scss, "main.scss"),
@@ -489,21 +1148,14 @@ export class ComponentService {
489
1148
  continue;
490
1149
  try {
491
1150
  const source = safeReadFile(root, entry, { maxSize: this.ctx.config.maxFileSize });
492
- const found = findImportForComponent(source, name);
493
- if (found.present) {
1151
+ const next = updateScssEntry(source, entry, paths.scss, scssPath, name);
1152
+ if (!next) {
494
1153
  logger.debug("SCSS import already present", { entry, name });
495
1154
  return;
496
1155
  }
497
- // Prefer @use with relative path from entry
498
- const entryDir = path.posix.dirname(entry);
499
- let importPath = path.posix.relative(entryDir, scssPath).replace(/\.scss$/, "");
500
- if (!importPath.startsWith("."))
501
- importPath = `./${importPath}`;
502
- // Strip leading underscore for Sass convention
503
- importPath = importPath.replace(/\/_([^/]+)$/, "/$1");
504
- const line = `@use "${importPath}";\n`;
505
- const next = source.endsWith("\n") ? source + line : source + "\n" + line;
506
- safeWriteFile(root, entry, next, { maxSize: this.ctx.config.maxFileSize });
1156
+ const result = safeWriteFile(root, entry, next, { maxSize: this.ctx.config.maxFileSize });
1157
+ if (result.modified)
1158
+ filesModified.push(result.path);
507
1159
  warnings.push(`Added SCSS import to ${entry}`);
508
1160
  return;
509
1161
  }
@@ -513,6 +1165,36 @@ export class ComponentService {
513
1165
  }
514
1166
  warnings.push("No SCSS entry point found to register the component import. Add the import manually.");
515
1167
  }
1168
+ ensureThicketJavascriptRegistration(name, jsPath, warnings, filesModified) {
1169
+ const root = this.ctx.config.root;
1170
+ const paths = this.ctx.config.paths;
1171
+ const entry = path.posix.join(paths.js, "main.js");
1172
+ if (!safeExists(root, entry)) {
1173
+ warnings.push(`Could not find ${entry} to register the JavaScript component.`);
1174
+ return;
1175
+ }
1176
+ try {
1177
+ const source = safeReadFile(root, entry, { maxSize: this.ctx.config.maxFileSize });
1178
+ const initFunction = componentInitFunction(name);
1179
+ let importPath = path.posix.relative(path.posix.dirname(entry), jsPath);
1180
+ if (!importPath.startsWith("."))
1181
+ importPath = `./${importPath}`;
1182
+ const update = updateThicketMainJs(source, initFunction, importPath);
1183
+ if (!update.source) {
1184
+ warnings.push(`${update.warning} Register ${initFunction} manually in ${entry}.`);
1185
+ return;
1186
+ }
1187
+ const next = update.source;
1188
+ if (next !== source) {
1189
+ const result = safeWriteFile(root, entry, next, { maxSize: this.ctx.config.maxFileSize });
1190
+ if (result.modified)
1191
+ filesModified.push(result.path);
1192
+ }
1193
+ }
1194
+ catch (err) {
1195
+ warnings.push(`Could not register the JavaScript component in ${entry}: ${err.message}`);
1196
+ }
1197
+ }
516
1198
  preview(name, input = {}) {
517
1199
  const detail = this.get(name);
518
1200
  if (!detail) {
@@ -532,15 +1214,18 @@ export class ComponentService {
532
1214
  const variant = input.variant && detail.variants.includes(input.variant)
533
1215
  ? input.variant
534
1216
  : detail.variants[0] ?? "default";
1217
+ const classBase = detail.classNames.some((className) => className === `c-${detail.name}` || className.startsWith(`c-${detail.name}--`))
1218
+ ? `c-${detail.name}`
1219
+ : detail.name;
535
1220
  const rawParams = input.params ?? {};
536
1221
  const params = {
537
1222
  label: rawParams.label ?? "Example",
538
1223
  variant,
539
1224
  class: rawParams.class ?? "",
540
1225
  id: rawParams.id ?? "",
541
- content: rawParams.content ?? `<span class="${detail.name}__content">Preview content</span>`,
1226
+ content: rawParams.content ?? `<span class="${classBase}__content">Preview content</span>`,
542
1227
  };
543
- const classNames = [detail.name, `${detail.name}--${variant}`];
1228
+ const classNames = [classBase, `${classBase}--${variant}`];
544
1229
  const extraClass = typeof params.class === "string" ? params.class.trim() : "";
545
1230
  if (extraClass)
546
1231
  classNames.push(extraClass);
@@ -549,7 +1234,7 @@ export class ComponentService {
549
1234
  const renderedId = typeof params.id === "string" && params.id.trim() ? ` id="${escapeHtml(params.id.trim())}"` : "";
550
1235
  const html = `
551
1236
  <div class="${classNames.join(" ")}"${renderedId}>
552
- <span class="${detail.name}__label">${escapedLabel}</span>
1237
+ <span class="${classBase}__label">${escapedLabel}</span>
553
1238
  ${contentMarkup}
554
1239
  </div>
555
1240
  `.trim();
@@ -602,6 +1287,9 @@ export class ComponentService {
602
1287
  }
603
1288
  else {
604
1289
  const expectedFilename = `_${normalized}.scss`;
1290
+ const expectedClass = normalized.startsWith("c-")
1291
+ ? escapeRegExp(normalized)
1292
+ : `(?:c-)?${escapeRegExp(normalized)}`;
605
1293
  if (path.posix.basename(detail.scss) !== expectedFilename) {
606
1294
  warnings.push({
607
1295
  file: detail.scss,
@@ -609,10 +1297,10 @@ export class ComponentService {
609
1297
  });
610
1298
  }
611
1299
  if (detail.scssSource &&
612
- !new RegExp(`\\.${normalized}(?:__[-\\w]+|--[-\\w]+)?\\s*(?:\\{|:)`).test(detail.scssSource)) {
1300
+ !new RegExp(`\\.${expectedClass}(?:__[-\\w]+|--[-\\w]+)?\\s*(?:\\{|:)`).test(detail.scssSource)) {
613
1301
  warnings.push({
614
1302
  file: detail.scss,
615
- message: `SCSS should define a BEM selector beginning with .${normalized}`,
1303
+ message: `SCSS should define a BEM selector beginning with .${normalized} or .c-${normalized.replace(/^c-/, "")}`,
616
1304
  });
617
1305
  }
618
1306
  }
@@ -626,8 +1314,8 @@ export class ComponentService {
626
1314
  warnings,
627
1315
  };
628
1316
  }
629
- delete(name, confirm) {
630
- if (!confirm) {
1317
+ delete(name, confirm, dryRun = false) {
1318
+ if (!confirm && !dryRun) {
631
1319
  return {
632
1320
  success: false,
633
1321
  operation: "component_delete",
@@ -637,19 +1325,6 @@ export class ComponentService {
637
1325
  },
638
1326
  };
639
1327
  }
640
- try {
641
- assertWriteAllowed(this.ctx, "destructive");
642
- }
643
- catch (err) {
644
- return {
645
- success: false,
646
- operation: "component_delete",
647
- error: {
648
- code: err.code ?? "WRITE_MODE_DENIED",
649
- message: err.message,
650
- },
651
- };
652
- }
653
1328
  const normalized = normalizeComponentName(name);
654
1329
  const detail = this.get(normalized);
655
1330
  if (!detail) {
@@ -660,21 +1335,97 @@ export class ComponentService {
660
1335
  };
661
1336
  }
662
1337
  const root = this.ctx.config.root;
663
- const deleted = [];
664
- for (const key of ["liquid", "scss", "javascript", "documentation", "example"]) {
1338
+ const componentFiles = COMPONENT_FILE_KEYS.flatMap((key) => {
665
1339
  const p = detail[key];
666
- if (p && safeExists(root, p)) {
667
- safeUnlink(root, p);
668
- deleted.push(p);
1340
+ return p && safeExists(root, p) ? [p] : [];
1341
+ });
1342
+ if (dryRun) {
1343
+ const scssDeletion = detail.scss
1344
+ ? new ScssService(this.ctx).delete({ path: detail.scss, dry_run: true })
1345
+ : null;
1346
+ if (scssDeletion && !scssDeletion.success) {
1347
+ return {
1348
+ success: false,
1349
+ operation: "component_delete",
1350
+ component: normalized,
1351
+ error: {
1352
+ code: scssDeletion.error?.code ?? "SCSS_DELETE_FAILED",
1353
+ message: scssDeletion.error?.message ?? "Could not preview component stylesheet deletion.",
1354
+ },
1355
+ };
669
1356
  }
1357
+ const diffs = [
1358
+ ...componentFiles
1359
+ .filter((filePath) => filePath !== detail.scss)
1360
+ .map((filePath) => ({
1361
+ path: filePath,
1362
+ diff: createUnifiedDiff(filePath, safeReadFile(root, filePath, { maxSize: this.ctx.config.maxFileSize }), ""),
1363
+ })),
1364
+ ...(scssDeletion?.diffs ?? []),
1365
+ ];
1366
+ return {
1367
+ success: true,
1368
+ operation: "component_delete",
1369
+ component: normalized,
1370
+ dry_run: true,
1371
+ operations: [
1372
+ ...componentFiles
1373
+ .filter((filePath) => filePath !== detail.scss)
1374
+ .map((filePath) => ({ type: "delete", path: filePath })),
1375
+ ...(scssDeletion?.operations ?? []),
1376
+ ],
1377
+ diffs,
1378
+ diff: diffs.map((entry) => entry.diff).filter(Boolean).join("\n\n"),
1379
+ };
1380
+ }
1381
+ const filesModified = [];
1382
+ try {
1383
+ assertWriteAllowed(this.ctx, "destructive");
1384
+ if (detail.scss) {
1385
+ const scssDeletion = new ScssService(this.ctx).delete({
1386
+ path: detail.scss,
1387
+ confirm: true,
1388
+ });
1389
+ if (!scssDeletion.success) {
1390
+ return {
1391
+ success: false,
1392
+ operation: "component_delete",
1393
+ component: normalized,
1394
+ error: {
1395
+ code: scssDeletion.error?.code ?? "SCSS_DELETE_FAILED",
1396
+ message: scssDeletion.error?.message ?? "Could not delete the component stylesheet.",
1397
+ },
1398
+ files_modified: scssDeletion.files_modified,
1399
+ };
1400
+ }
1401
+ filesModified.push(...(scssDeletion.files_modified ?? []));
1402
+ }
1403
+ for (const filePath of componentFiles) {
1404
+ if (filePath === detail.scss)
1405
+ continue;
1406
+ safeUnlink(root, filePath);
1407
+ filesModified.push(filePath);
1408
+ }
1409
+ this.ctx.invalidateCache();
1410
+ return {
1411
+ success: true,
1412
+ operation: "component_delete",
1413
+ component: normalized,
1414
+ files_modified: filesModified,
1415
+ };
1416
+ }
1417
+ catch (err) {
1418
+ return {
1419
+ success: false,
1420
+ operation: "component_delete",
1421
+ component: normalized,
1422
+ error: {
1423
+ code: err.code ?? "DELETE_FAILED",
1424
+ message: err.message,
1425
+ },
1426
+ files_modified: filesModified,
1427
+ };
670
1428
  }
671
- this.ctx.invalidateCache();
672
- return {
673
- success: true,
674
- operation: "component_delete",
675
- component: normalized,
676
- files_modified: deleted,
677
- };
678
1429
  }
679
1430
  }
680
1431
  //# sourceMappingURL=component-service.js.map