@naseej/blox 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/run.js +2587 -816
  2. package/dist/sdk.js +44 -4
  3. package/package.json +5 -2
  4. package/readme.md +28 -1
package/dist/run.js CHANGED
@@ -94,7 +94,11 @@ var setBloxCliVersion = (version2) => {
94
94
  };
95
95
  var getBloxCliVersion = () => bloxCliVersion;
96
96
  var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
97
- var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
97
+ var forceMinimalMode = false;
98
+ var setMinimalMode = (value) => {
99
+ forceMinimalMode = value;
100
+ };
101
+ var isMinimalMode = () => forceMinimalMode || !!import_extra_typings2.program.opts()?.minimal;
98
102
 
99
103
  // src/services/cliVersion.ts
100
104
  var import_node_https = __toESM(require("https"));
@@ -128,14 +132,14 @@ var fmt = import_ansis.default;
128
132
 
129
133
  // src/shared/logger.ts
130
134
  var import_prompts2 = require("@clack/prompts");
131
- var debug = (message) => {
135
+ var debug = (message3) => {
132
136
  if (!isDebugMode()) {
133
137
  return;
134
138
  }
135
- if (typeof message === "string") {
136
- import_prompts.log.warn(message.trim());
139
+ if (typeof message3 === "string") {
140
+ import_prompts.log.warn(message3.trim());
137
141
  } else {
138
- console2.log(JSON.stringify(message));
142
+ console2.log(JSON.stringify(message3));
139
143
  }
140
144
  };
141
145
  var logWarningSection = (title, content) => {
@@ -235,8 +239,10 @@ var _getInvokedCommand = (argv) => {
235
239
  }
236
240
  return null;
237
241
  };
242
+ var SKIP_UPDATE_CHECK_COMMANDS = /* @__PURE__ */ new Set(["upgrade", "mcp"]);
238
243
  var checkForCliUpdate = async (currentVersion, argv = []) => {
239
- if (_getInvokedCommand(argv) === "upgrade") {
244
+ const invokedCommand = _getInvokedCommand(argv);
245
+ if (invokedCommand && SKIP_UPDATE_CHECK_COMMANDS.has(invokedCommand)) {
240
246
  return;
241
247
  }
242
248
  if (argv.includes("--json")) {
@@ -262,7 +268,7 @@ var checkForCliUpdate = async (currentVersion, argv = []) => {
262
268
  };
263
269
 
264
270
  // package.json
265
- var version = "1.12.0";
271
+ var version = "1.14.0";
266
272
 
267
273
  // src/migrations/index.ts
268
274
  var import_node_path15 = __toESM(require("path"));
@@ -327,21 +333,21 @@ async function replacePlaceholders(dir, context) {
327
333
  }
328
334
  }
329
335
  }
330
- function getTemplateDef(cwd = ".") {
336
+ function getTemplateDef(cwd2 = ".") {
331
337
  debug("Get template def");
332
- const def = getBloxFile(cwd).definition;
338
+ const def = getBloxFile(cwd2).definition;
333
339
  debug(def);
334
340
  return def;
335
341
  }
336
- function getBlockDef(cwd = ".") {
342
+ function getBlockDef(cwd2 = ".") {
337
343
  debug("Get block def");
338
- const def = getBloxFile(cwd).definition;
344
+ const def = getBloxFile(cwd2).definition;
339
345
  def && debug(def);
340
346
  return def;
341
347
  }
342
- function getBloxFile(cwd = ".") {
348
+ function getBloxFile(cwd2 = ".") {
343
349
  try {
344
- const file = import_fs_extra3.default.readJSONSync(import_node_path3.default.join(cwd, bloxFilePath));
350
+ const file = import_fs_extra3.default.readJSONSync(import_node_path3.default.join(cwd2, bloxFilePath));
345
351
  if (!file.checkpoints) {
346
352
  file.checkpoints = {};
347
353
  }
@@ -350,17 +356,17 @@ function getBloxFile(cwd = ".") {
350
356
  return {};
351
357
  }
352
358
  }
353
- function saveBloxFile(info, cwd = ".") {
359
+ function saveBloxFile(info, cwd2 = ".") {
354
360
  debug("Save info");
355
- import_fs_extra3.default.writeFileSync(import_node_path3.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
361
+ import_fs_extra3.default.writeFileSync(import_node_path3.default.join(cwd2, bloxFilePath), JSON.stringify(info, null, 2));
356
362
  }
357
- function updateCheckpoint(name, checkpoint, cwd = ".") {
358
- const info = getBloxFile(cwd);
363
+ function updateCheckpoint(name, checkpoint, cwd2 = ".") {
364
+ const info = getBloxFile(cwd2);
359
365
  if (!info.checkpoints) {
360
366
  info.checkpoints = {};
361
367
  }
362
368
  info.checkpoints[name] = checkpoint;
363
- saveBloxFile(info, cwd);
369
+ saveBloxFile(info, cwd2);
364
370
  }
365
371
  function getBlockPath(name, projectDir = ".") {
366
372
  const blocksPath = import_node_path3.default.join(projectDir, blocksDir);
@@ -376,8 +382,8 @@ function getBlockPath(name, projectDir = ".") {
376
382
  function getUsedBlocksDef(projectDir = ".") {
377
383
  return getUsedBlocks(projectDir).map((b) => b.definition);
378
384
  }
379
- function getUsedBlocks(projectDir = ".") {
380
- debug("Get used blocks");
385
+ function getUsedBlockEntries(projectDir = ".") {
386
+ debug("Get used block entries");
381
387
  const blocks = [];
382
388
  const blocksPath = import_node_path3.default.join(projectDir, blocksDir);
383
389
  if (import_fs_extra3.default.existsSync(blocksPath)) {
@@ -385,15 +391,19 @@ function getUsedBlocks(projectDir = ".") {
385
391
  if (!file.isDirectory()) {
386
392
  return;
387
393
  }
388
- const blockDef = getBloxFile(import_node_path3.default.join(blocksPath, file.name));
394
+ const dir = import_node_path3.default.join(blocksPath, file.name);
395
+ const blockDef = getBloxFile(dir);
389
396
  if (blockDef && blockDef.definition) {
390
- blocks.push(blockDef);
397
+ blocks.push({ dir, file: blockDef });
391
398
  }
392
399
  });
393
400
  }
394
401
  debug(blocks);
395
402
  return blocks;
396
403
  }
404
+ function getUsedBlocks(projectDir = ".") {
405
+ return getUsedBlockEntries(projectDir).map((entry) => entry.file);
406
+ }
397
407
 
398
408
  // src/shared/errors.ts
399
409
  var exitCodes = {
@@ -406,8 +416,8 @@ var exitCodes = {
406
416
  APPROVAL_REQUIRED: 6
407
417
  };
408
418
  var CliError = class extends Error {
409
- constructor(message, code, exitCode = exitCodes.GENERAL, suggestion, details) {
410
- super(message);
419
+ constructor(message3, code, exitCode = exitCodes.GENERAL, suggestion, details) {
420
+ super(message3);
411
421
  this.code = code;
412
422
  this.exitCode = exitCode;
413
423
  this.suggestion = suggestion;
@@ -431,12 +441,12 @@ Provide the missing arguments to continue.`,
431
441
  }
432
442
  };
433
443
  var ApprovalRequiredError = class extends CliError {
434
- constructor(message, suggestion) {
435
- super(message, "APPROVAL_REQUIRED", exitCodes.APPROVAL_REQUIRED, suggestion);
444
+ constructor(message3, suggestion) {
445
+ super(message3, "APPROVAL_REQUIRED", exitCodes.APPROVAL_REQUIRED, suggestion);
436
446
  this.name = "ApprovalRequiredError";
437
447
  }
438
448
  };
439
- var formatCommitMessage = (message) => message.split("\n").map((line) => ` ${line}`).join("\n");
449
+ var formatCommitMessage = (message3) => message3.split("\n").map((line) => ` ${line}`).join("\n");
440
450
  var ContributionConflictError = class extends CliError {
441
451
  constructor(conflict) {
442
452
  super(
@@ -525,9 +535,16 @@ var handleCommandError = (e) => {
525
535
  };
526
536
 
527
537
  // src/services/context.ts
528
- var hasBloxFile = (dir) => import_fs_extra4.default.existsSync(import_node_path4.default.join(dir, bloxFilePath));
529
- function findProjectDir(cwd = ".") {
530
- let dir = import_node_path4.default.resolve(cwd);
538
+ var hasBloxFile = (dir) => {
539
+ const file = import_node_path4.default.join(dir, bloxFilePath);
540
+ try {
541
+ return import_fs_extra4.default.statSync(file).isFile();
542
+ } catch {
543
+ return false;
544
+ }
545
+ };
546
+ function findProjectDir(cwd2 = ".") {
547
+ let dir = import_node_path4.default.resolve(cwd2);
531
548
  for (; ; ) {
532
549
  if (hasBloxFile(dir)) {
533
550
  const parent2 = import_node_path4.default.dirname(dir);
@@ -559,15 +576,15 @@ function listApps(workspaceRoot = ".") {
559
576
  ).map((entry) => {
560
577
  const dir = import_node_path4.default.join(root, entry.name);
561
578
  return { key: entry.name, dir, def: getBloxFile(dir).definition };
562
- }).filter((app) => !!app.def?.name);
579
+ }).filter((app2) => !!app2.def?.name);
563
580
  }
564
- function resolveContext(cwd = ".", appKey) {
565
- const found = findProjectDir(cwd) ?? import_node_path4.default.resolve(cwd);
581
+ function resolveContext(cwd2 = ".", appKey) {
582
+ const found = findProjectDir(cwd2) ?? import_node_path4.default.resolve(cwd2);
566
583
  const workspaceRoot = findWorkspaceRoot(found);
567
584
  if (appKey) {
568
585
  const apps = listApps(workspaceRoot);
569
- const app = apps.find((a) => a.key === appKey);
570
- if (!app) {
586
+ const app2 = apps.find((a) => a.key === appKey);
587
+ if (!app2) {
571
588
  throw new CliError(
572
589
  `Application not found: ${appKey}`,
573
590
  "NOT_FOUND",
@@ -575,8 +592,8 @@ function resolveContext(cwd = ".", appKey) {
575
592
  apps.length ? `Available applications: ${apps.map((a) => a.key).join(", ")}` : `No applications found under ${appsDir}/`
576
593
  );
577
594
  }
578
- debug(`Resolved app context: ${app.dir}`);
579
- return { workspaceRoot, projectDir: app.dir, app: app.key };
595
+ debug(`Resolved app context: ${app2.dir}`);
596
+ return { workspaceRoot, projectDir: app2.dir, app: app2.key };
580
597
  }
581
598
  const context = { workspaceRoot, projectDir: found };
582
599
  if (found !== workspaceRoot) {
@@ -594,13 +611,13 @@ function parseQualifiedRef(arg) {
594
611
  }
595
612
 
596
613
  // src/migrations/updateSchemaUrls.ts
597
- async function updateSchemaUrls(cwd = ".") {
614
+ async function updateSchemaUrls(cwd2 = ".") {
598
615
  const locations = [
599
- { filePath: import_node_path5.default.join(cwd, bloxFilePath), type: "template" },
600
- ...readBlockPaths(cwd).map((filePath) => ({ filePath, type: "block" })),
601
- ...listApps(cwd).flatMap((app) => [
602
- { filePath: import_node_path5.default.join(app.dir, bloxFilePath), type: "template" },
603
- ...readBlockPaths(app.dir).map((filePath) => ({
616
+ { filePath: import_node_path5.default.join(cwd2, bloxFilePath), type: "template" },
617
+ ...readBlockPaths(cwd2).map((filePath) => ({ filePath, type: "block" })),
618
+ ...listApps(cwd2).flatMap((app2) => [
619
+ { filePath: import_node_path5.default.join(app2.dir, bloxFilePath), type: "template" },
620
+ ...readBlockPaths(app2.dir).map((filePath) => ({
604
621
  filePath,
605
622
  type: "block"
606
623
  }))
@@ -616,8 +633,8 @@ async function updateSchemaUrls(cwd = ".") {
616
633
  }
617
634
  return anyChanged;
618
635
  }
619
- function readBlockPaths(cwd) {
620
- const dir = import_node_path5.default.join(cwd, blocksDir);
636
+ function readBlockPaths(cwd2) {
637
+ const dir = import_node_path5.default.join(cwd2, blocksDir);
621
638
  if (!import_fs_extra5.default.existsSync(dir)) return [];
622
639
  return import_fs_extra5.default.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => import_node_path5.default.join(dir, e.name, bloxFilePath));
623
640
  }
@@ -694,10 +711,10 @@ var import_fs_extra9 = __toESM(require("fs-extra"));
694
711
 
695
712
  // src/services/shell.ts
696
713
  var import_cross_spawn = __toESM(require("cross-spawn"));
697
- var $ = async (bin, options = [], { cwd, onStdout, shell = false } = {}) => {
698
- debug(`Command executed: "${bin} ${options.join(" ")}" with cwd = ${cwd}`);
714
+ var $ = async (bin, options = [], { cwd: cwd2, onStdout, shell = false } = {}) => {
715
+ debug(`Command executed: "${bin} ${options.join(" ")}" with cwd = ${cwd2}`);
699
716
  return new Promise(function(resolve, reject) {
700
- const child = (0, import_cross_spawn.default)(bin, options, { cwd, shell, stdio: ["pipe", "pipe", "pipe"] });
717
+ const child = (0, import_cross_spawn.default)(bin, options, { cwd: cwd2, shell, stdio: ["pipe", "pipe", "pipe"] });
701
718
  let stdout = "";
702
719
  let stderr = "";
703
720
  child.stdout?.on("data", (data) => {
@@ -846,15 +863,54 @@ function isBlockDirectory(blockDir) {
846
863
 
847
864
  // src/shared/spinner.ts
848
865
  var import_prompts3 = require("@clack/prompts");
866
+ var import_string_width = __toESM(require("string-width"));
867
+ var SPINNER_RESERVED_COLUMNS = 7;
868
+ var ANSI_PATTERN = /\u001B\[[0-9;]*[A-Za-z]/y;
869
+ var segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
870
+ var fitToTerminal = (msg, columns = process.stdout.columns) => {
871
+ if (!columns) return msg;
872
+ const max = Math.max(columns - SPINNER_RESERVED_COLUMNS, 10);
873
+ if ((0, import_string_width.default)(msg) <= max) return msg;
874
+ let out = "";
875
+ let visible = 0;
876
+ let hasAnsi = false;
877
+ for (let i = 0; i < msg.length; ) {
878
+ ANSI_PATTERN.lastIndex = i;
879
+ const match = ANSI_PATTERN.exec(msg);
880
+ if (match) {
881
+ out += match[0];
882
+ i += match[0].length;
883
+ hasAnsi = true;
884
+ continue;
885
+ }
886
+ const next = msg.indexOf("\x1B", i + 1);
887
+ const chunk = msg.slice(i, next === -1 ? void 0 : next);
888
+ let consumed = 0;
889
+ let full = true;
890
+ for (const { segment } of segmenter.segment(chunk)) {
891
+ const w = (0, import_string_width.default)(segment);
892
+ if (visible + w > max - 1) {
893
+ full = false;
894
+ break;
895
+ }
896
+ out += segment;
897
+ visible += w;
898
+ consumed += segment.length;
899
+ }
900
+ if (!full) break;
901
+ i += consumed;
902
+ }
903
+ return `${out}${hasAnsi ? "\x1B[0m" : ""}\u2026`;
904
+ };
849
905
  var spinner = () => {
850
- const s = (0, import_prompts3.spinner)();
851
906
  const minimal = isMinimalMode() || isDebugMode();
907
+ const s = minimal ? void 0 : (0, import_prompts3.spinner)();
852
908
  const stop = (msg = "error", code) => {
853
909
  minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
854
910
  };
855
911
  return {
856
912
  start: (msg) => {
857
- minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
913
+ minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg && fitToTerminal(msg));
858
914
  },
859
915
  stop,
860
916
  success: (msg = "success") => {
@@ -867,13 +923,13 @@ var spinner = () => {
867
923
  stop(msg, 0);
868
924
  },
869
925
  message: (msg) => {
870
- minimal ? import_prompts2.log.message(msg) : s.message(msg);
926
+ minimal ? import_prompts2.log.message(msg) : s.message(fitToTerminal(msg));
871
927
  }
872
928
  };
873
929
  };
874
- async function runTask(message, task) {
875
- const startMessage = typeof message === "string" ? message : message.start;
876
- const endMessage = typeof message === "string" ? message : message.end;
930
+ async function runTask(message3, task) {
931
+ const startMessage = typeof message3 === "string" ? message3 : message3.start;
932
+ const endMessage = typeof message3 === "string" ? message3 : message3.end;
877
933
  const taskSpinner = spinner();
878
934
  taskSpinner.start(startMessage);
879
935
  try {
@@ -887,32 +943,32 @@ async function runTask(message, task) {
887
943
  }
888
944
 
889
945
  // src/shared/utils/runLifecycleHook.ts
890
- function getLifecycleHookScript(cwd, hook) {
891
- const definition = getTemplateDef(cwd);
946
+ function getLifecycleHookScript(cwd2, hook) {
947
+ const definition = getTemplateDef(cwd2);
892
948
  const script = definition[hook];
893
949
  if (typeof script !== "string" || !script.trim()) {
894
950
  return void 0;
895
951
  }
896
952
  return script.trim();
897
953
  }
898
- async function runLifecycleHookScript(cwd, script) {
954
+ async function runLifecycleHookScript(cwd2, script) {
899
955
  const isWin = process.platform === "win32";
900
956
  const onStdout = (data) => {
901
957
  process.stdout.write(data);
902
958
  };
903
959
  if (isWin) {
904
- await $("cmd.exe", ["/d", "/s", "/c", script], { cwd, onStdout });
960
+ await $("cmd.exe", ["/d", "/s", "/c", script], { cwd: cwd2, onStdout });
905
961
  return;
906
962
  }
907
- await $("/bin/sh", ["-lc", script], { cwd, onStdout });
963
+ await $("/bin/sh", ["-lc", script], { cwd: cwd2, onStdout });
908
964
  }
909
- async function runLifecycleHookWithTask(cwd, hook, message) {
910
- const script = getLifecycleHookScript(cwd, hook);
965
+ async function runLifecycleHookWithTask(cwd2, hook, message3) {
966
+ const script = getLifecycleHookScript(cwd2, hook);
911
967
  if (!script) {
912
968
  return;
913
969
  }
914
- debug(`Run lifecycle hook ${hook} in: ${cwd}`);
915
- await runTask(message, async () => runLifecycleHookScript(cwd, script));
970
+ debug(`Run lifecycle hook ${hook} in: ${cwd2}`);
971
+ await runTask(message3, async () => runLifecycleHookScript(cwd2, script));
916
972
  }
917
973
 
918
974
  // src/shared/utils/componentCheckpoint.ts
@@ -927,15 +983,15 @@ var BloxComponentType = /* @__PURE__ */ ((BloxComponentType2) => {
927
983
  })(BloxComponentType || {});
928
984
 
929
985
  // src/shared/utils/componentCheckpoint.ts
930
- function getComponentCheckpoint(cwd, component) {
931
- const bloxDir = getBloxDirForComponent(cwd, component);
986
+ function getComponentCheckpoint(cwd2, component) {
987
+ const bloxDir = getBloxDirForComponent(cwd2, component);
932
988
  const blox = getBloxFile(bloxDir);
933
989
  const cp = blox.checkpoints?.[component.name];
934
990
  return { commit: cp?.commit, branch: cp?.branch };
935
991
  }
936
- function getBloxDirForComponent(cwd, component) {
992
+ function getBloxDirForComponent(cwd2, component) {
937
993
  const projectRoot = import_node_path9.default.join(
938
- cwd,
994
+ cwd2,
939
995
  component.projectDir && component.projectDir !== "." ? component.projectDir : ""
940
996
  );
941
997
  if (component.type === "block" /* BLOCK */) {
@@ -960,8 +1016,8 @@ var getConfiguredRegistryDirs = () => {
960
1016
  dir: import_node_path10.default.isAbsolute(registry) ? registry : import_node_path10.default.join(registriesDataPath, cacheDirNameForRegistry(registry))
961
1017
  }));
962
1018
  };
963
- var syncRegistries = async (branch) => {
964
- if (upeToDate) return;
1019
+ var syncRegistries = async (branch, options = {}) => {
1020
+ if (upeToDate && !options.force) return;
965
1021
  upeToDate = true;
966
1022
  debug("Sync registries");
967
1023
  import_fs_extra7.default.ensureDirSync(registriesDataPath);
@@ -1029,8 +1085,8 @@ var getAvailableTemplates = async () => {
1029
1085
  }
1030
1086
  });
1031
1087
  const appRefs = {};
1032
- for (const app of template.apps || []) {
1033
- appRefs[app.name ?? app.template] = app;
1088
+ for (const app2 of template.apps || []) {
1089
+ appRefs[app2.name ?? app2.template] = app2;
1034
1090
  }
1035
1091
  const resolvedTemplate = {
1036
1092
  ...template,
@@ -1161,11 +1217,11 @@ async function resolveRemoteHead(repoUrl, remoteBranch) {
1161
1217
  }
1162
1218
 
1163
1219
  // src/shared/utils/findOutdatedComponents.ts
1164
- async function findOutdatedComponents(cwd, components) {
1220
+ async function findOutdatedComponents(cwd2, components) {
1165
1221
  const results = await Promise.all(
1166
1222
  components.map(async (component) => {
1167
1223
  try {
1168
- const checkpoint = getComponentCheckpoint(cwd, component);
1224
+ const checkpoint = getComponentCheckpoint(cwd2, component);
1169
1225
  if (!checkpoint.commit) return void 0;
1170
1226
  const repoUrl = await getComponentRepoUrl(component);
1171
1227
  const remoteCommit = await resolveRemoteHead(
@@ -1202,8 +1258,8 @@ var normalizePath = (_path) => {
1202
1258
  };
1203
1259
 
1204
1260
  // src/shared/utils/discoverBloxComponents.ts
1205
- var readBloxFileIfExists = (cwd) => {
1206
- const p = import_node_path12.default.join(cwd, bloxFilePath);
1261
+ var readBloxFileIfExists = (cwd2) => {
1262
+ const p = import_node_path12.default.join(cwd2, bloxFilePath);
1207
1263
  if (!import_fs_extra8.default.existsSync(p)) return;
1208
1264
  try {
1209
1265
  return import_fs_extra8.default.readJSONSync(p);
@@ -1211,7 +1267,7 @@ var readBloxFileIfExists = (cwd) => {
1211
1267
  return;
1212
1268
  }
1213
1269
  };
1214
- var collectProjectComponents = (projectDirAbs, projectDirRel, app, rootTemplateName, components) => {
1270
+ var collectProjectComponents = (projectDirAbs, projectDirRel, app2, rootTemplateName, components) => {
1215
1271
  const rootBlox = readBloxFileIfExists(projectDirAbs);
1216
1272
  const appTemplateName = rootBlox?.definition?.name;
1217
1273
  const appTemplateDef = rootBlox?.definition;
@@ -1223,7 +1279,7 @@ var collectProjectComponents = (projectDirAbs, projectDirRel, app, rootTemplateN
1223
1279
  templateDef: appTemplateDef,
1224
1280
  version: rootBlox.definition.version,
1225
1281
  projectDir: projectDirRel,
1226
- app,
1282
+ app: app2,
1227
1283
  rootTemplateName
1228
1284
  });
1229
1285
  for (const base of rootBlox.definition.bases || []) {
@@ -1233,7 +1289,7 @@ var collectProjectComponents = (projectDirAbs, projectDirRel, app, rootTemplateN
1233
1289
  templateDef: appTemplateDef,
1234
1290
  version: base.version,
1235
1291
  projectDir: projectDirRel,
1236
- app,
1292
+ app: app2,
1237
1293
  rootTemplateName
1238
1294
  });
1239
1295
  }
@@ -1254,30 +1310,30 @@ var collectProjectComponents = (projectDirAbs, projectDirRel, app, rootTemplateN
1254
1310
  templateDef: appTemplateDef,
1255
1311
  version: blockBlox.definition.version,
1256
1312
  projectDir: projectDirRel,
1257
- app,
1313
+ app: app2,
1258
1314
  rootTemplateName
1259
1315
  });
1260
1316
  }
1261
1317
  }
1262
1318
  };
1263
- var discoverBloxComponents = (cwd, options = {}) => {
1319
+ var discoverBloxComponents = (cwd2, options = {}) => {
1264
1320
  const components = [];
1265
- const projectDir = findProjectDir(cwd) ?? cwd;
1321
+ const projectDir = findProjectDir(cwd2) ?? cwd2;
1266
1322
  const workspaceRoot = findWorkspaceRoot(projectDir);
1267
1323
  const rootTemplateName = readBloxFileIfExists(workspaceRoot)?.definition?.name;
1268
1324
  if (options.scope === "project") {
1269
- const app = projectDir === workspaceRoot ? void 0 : import_node_path12.default.basename(projectDir);
1270
- collectProjectComponents(projectDir, ".", app, rootTemplateName, components);
1325
+ const app2 = projectDir === workspaceRoot ? void 0 : import_node_path12.default.basename(projectDir);
1326
+ collectProjectComponents(projectDir, ".", app2, rootTemplateName, components);
1271
1327
  return components;
1272
1328
  }
1273
1329
  collectProjectComponents(workspaceRoot, ".", void 0, rootTemplateName, components);
1274
1330
  const appsRoot = import_node_path12.default.join(workspaceRoot, appsDir);
1275
- for (const app of listApps(workspaceRoot)) {
1276
- const rel = normalizePath(import_node_path12.default.relative(appsRoot, app.dir));
1331
+ for (const app2 of listApps(workspaceRoot)) {
1332
+ const rel = normalizePath(import_node_path12.default.relative(appsRoot, app2.dir));
1277
1333
  collectProjectComponents(
1278
- app.dir,
1334
+ app2.dir,
1279
1335
  normalizePath(import_node_path12.default.join(appsDir, rel)),
1280
- app.key,
1336
+ app2.key,
1281
1337
  rootTemplateName,
1282
1338
  components
1283
1339
  );
@@ -1297,7 +1353,7 @@ var buildRefConflictError = (remote, cause) => {
1297
1353
  )
1298
1354
  )
1299
1355
  ];
1300
- const message = [
1356
+ const message3 = [
1301
1357
  `Unable to update remote "${remote}" because Git encountered conflicting remote-tracking references.`,
1302
1358
  ...conflicts.length ? ["", "Conflicts detected:", ...conflicts] : [],
1303
1359
  "",
@@ -1309,12 +1365,12 @@ var buildRefConflictError = (remote, cause) => {
1309
1365
  "Git output:",
1310
1366
  cause.message
1311
1367
  ].join("\n");
1312
- return new Error(message, { cause });
1368
+ return new Error(message3, { cause });
1313
1369
  };
1314
1370
 
1315
1371
  // src/services/git.ts
1316
1372
  var remoteWorktrees = /* @__PURE__ */ new Map();
1317
- var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd = ".") => {
1373
+ var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd2 = ".") => {
1318
1374
  let output = "";
1319
1375
  const args = [
1320
1376
  "diff",
@@ -1330,7 +1386,7 @@ var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd = ".") => {
1330
1386
  ...buildGitExcludePathspecs(ignore3)
1331
1387
  ];
1332
1388
  await $("git", args, {
1333
- cwd,
1389
+ cwd: cwd2,
1334
1390
  onStdout: (text2) => {
1335
1391
  output += text2;
1336
1392
  }
@@ -1384,8 +1440,8 @@ var cleanUpWorktrees = async () => {
1384
1440
  }
1385
1441
  remoteWorktrees.clear();
1386
1442
  };
1387
- var checkAuth = (message) => {
1388
- if (message.includes("Username for")) {
1443
+ var checkAuth = (message3) => {
1444
+ if (message3.includes("Username for")) {
1389
1445
  throw "Login to git first";
1390
1446
  }
1391
1447
  };
@@ -1404,8 +1460,8 @@ var clone = (repoUrl, dir, branch = defaultBranch, options = {}) => {
1404
1460
  ...shellOptions
1405
1461
  });
1406
1462
  };
1407
- var resetToCommit = async (commit2, cwd = ".") => {
1408
- await $("git", ["reset", "--hard", commit2], { cwd });
1463
+ var resetToCommit = async (commit2, cwd2 = ".") => {
1464
+ await $("git", ["reset", "--hard", commit2], { cwd: cwd2 });
1409
1465
  };
1410
1466
  var fetchWithRefRecovery = async (remote, args, shellOptions) => {
1411
1467
  try {
@@ -1444,12 +1500,12 @@ var updateRemote = async (name, source, shellOptions = {}) => {
1444
1500
  });
1445
1501
  updatedRemotes.add(remoteId);
1446
1502
  };
1447
- var readFileFromCommit = async (commit2, file, cwd = ".") => {
1503
+ var readFileFromCommit = async (commit2, file, cwd2 = ".") => {
1448
1504
  try {
1449
1505
  let content = "";
1450
1506
  const p = normalizePath(file);
1451
1507
  await $("git", ["show", `${commit2}:${p}`], {
1452
- cwd,
1508
+ cwd: cwd2,
1453
1509
  onStdout: (text2) => {
1454
1510
  content += text2;
1455
1511
  }
@@ -1459,12 +1515,12 @@ var readFileFromCommit = async (commit2, file, cwd = ".") => {
1459
1515
  return null;
1460
1516
  }
1461
1517
  };
1462
- var readFileFromIndex = async (file, stage = 0, cwd = ".") => {
1518
+ var readFileFromIndex = async (file, stage = 0, cwd2 = ".") => {
1463
1519
  try {
1464
1520
  let content = "";
1465
1521
  const p = normalizePath(file);
1466
1522
  await $("git", ["show", `:${stage}:${p}`], {
1467
- cwd,
1523
+ cwd: cwd2,
1468
1524
  onStdout: (text2) => {
1469
1525
  content += text2;
1470
1526
  }
@@ -1474,12 +1530,12 @@ var readFileFromIndex = async (file, stage = 0, cwd = ".") => {
1474
1530
  return null;
1475
1531
  }
1476
1532
  };
1477
- var readJsonFromCommit = async (commit2, file, cwd = ".") => {
1533
+ var readJsonFromCommit = async (commit2, file, cwd2 = ".") => {
1478
1534
  try {
1479
1535
  let content = "";
1480
1536
  const p = normalizePath(file);
1481
1537
  await $("git", ["show", `${commit2}:${p}`], {
1482
- cwd,
1538
+ cwd: cwd2,
1483
1539
  onStdout: (text2) => {
1484
1540
  content = text2;
1485
1541
  }
@@ -1489,12 +1545,12 @@ var readJsonFromCommit = async (commit2, file, cwd = ".") => {
1489
1545
  return {};
1490
1546
  }
1491
1547
  };
1492
- var readJsonFromIndex = async (file, cwd = ".") => {
1548
+ var readJsonFromIndex = async (file, cwd2 = ".") => {
1493
1549
  try {
1494
1550
  let content = "";
1495
1551
  const p = normalizePath(file);
1496
1552
  await $("git", ["show", `:0:${p}`], {
1497
- cwd,
1553
+ cwd: cwd2,
1498
1554
  onStdout: (text2) => {
1499
1555
  content = text2;
1500
1556
  }
@@ -1507,9 +1563,9 @@ var readJsonFromIndex = async (file, cwd = ".") => {
1507
1563
  var readJsonFromRemote = async (remote, file, branch = defaultBranch, commit2) => {
1508
1564
  return readJsonFromCommit(commit2 || `${remote}/${branch}`, file);
1509
1565
  };
1510
- var isCommitOlder = async (a, b, cwd = ".") => {
1566
+ var isCommitOlder = async (a, b, cwd2 = ".") => {
1511
1567
  try {
1512
- await $("git", ["merge-base", "--is-ancestor", a, b], { cwd });
1568
+ await $("git", ["merge-base", "--is-ancestor", a, b], { cwd: cwd2 });
1513
1569
  return true;
1514
1570
  } catch {
1515
1571
  return false;
@@ -1521,34 +1577,34 @@ var update = (shellOptions = {}) => {
1521
1577
  var getLatestCommitFromRemote = async (remote, branch) => {
1522
1578
  return getLatestCommit(`${remote}/${branch}`);
1523
1579
  };
1524
- var getLatestCommitFromPath = async (path38) => {
1525
- return getLatestCommit("HEAD", path38);
1580
+ var getLatestCommitFromPath = async (path41) => {
1581
+ return getLatestCommit("HEAD", path41);
1526
1582
  };
1527
- var getLatestCommit = async (rev, cwd = ".") => {
1528
- debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
1583
+ var getLatestCommit = async (rev, cwd2 = ".") => {
1584
+ debug(`Get latest commit for rev: ${rev} and cwd: ${cwd2}`);
1529
1585
  let commit2 = "";
1530
1586
  await $("git", ["rev-parse", rev], {
1531
- cwd,
1587
+ cwd: cwd2,
1532
1588
  onStdout: (text2) => {
1533
1589
  commit2 = text2;
1534
1590
  }
1535
1591
  });
1536
1592
  return commit2.replace(/\r?\n/g, "").trim();
1537
1593
  };
1538
- var getChangesLog = async (fromCommit, toCommit, cwd = ".") => {
1594
+ var getChangesLog = async (fromCommit, toCommit, cwd2 = ".") => {
1539
1595
  let changes = "";
1540
1596
  await $("git", ["log", `${fromCommit}..${toCommit}`, '--pretty=format:"%B"'], {
1541
- cwd,
1597
+ cwd: cwd2,
1542
1598
  onStdout: (text2) => {
1543
1599
  changes = text2;
1544
1600
  }
1545
1601
  });
1546
1602
  return changes;
1547
1603
  };
1548
- var listCommitsInRange = async (fromCommit, toCommit, cwd = ".") => {
1604
+ var listCommitsInRange = async (fromCommit, toCommit, cwd2 = ".") => {
1549
1605
  let out = "";
1550
1606
  await $("git", ["log", "--reverse", "--pretty=format:%H%x1f%B%x1e", `${fromCommit}..${toCommit}`], {
1551
- cwd,
1607
+ cwd: cwd2,
1552
1608
  onStdout: (text2) => {
1553
1609
  out += text2;
1554
1610
  }
@@ -1556,51 +1612,51 @@ var listCommitsInRange = async (fromCommit, toCommit, cwd = ".") => {
1556
1612
  return out.split("").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
1557
1613
  const sep = entry.indexOf("");
1558
1614
  const hash = (sep >= 0 ? entry.slice(0, sep) : entry).trim();
1559
- const message = sep >= 0 ? entry.slice(sep + 1).trim() : "";
1560
- const subject = message.split(/\r?\n/, 1)[0] ?? "";
1561
- return { hash, subject, message };
1615
+ const message3 = sep >= 0 ? entry.slice(sep + 1).trim() : "";
1616
+ const subject = message3.split(/\r?\n/, 1)[0] ?? "";
1617
+ return { hash, subject, message: message3 };
1562
1618
  });
1563
1619
  };
1564
- var unInit = (cwd) => {
1620
+ var unInit = (cwd2) => {
1565
1621
  debug("UnInit");
1566
- return import_fs_extra9.default.remove(import_node_path13.default.join(cwd, ".git"));
1622
+ return import_fs_extra9.default.remove(import_node_path13.default.join(cwd2, ".git"));
1567
1623
  };
1568
- var init = async (cwd) => {
1624
+ var init = async (cwd2) => {
1569
1625
  debug("Init");
1570
- await $("git", ["init"], { cwd });
1571
- await $("git", ["add", "."], { cwd });
1572
- await $("git", ["commit", "-m", "init"], { cwd });
1573
- await $("git", ["branch", "-m", defaultBranch], { cwd });
1626
+ await $("git", ["init"], { cwd: cwd2 });
1627
+ await $("git", ["add", "."], { cwd: cwd2 });
1628
+ await $("git", ["commit", "-m", "init"], { cwd: cwd2 });
1629
+ await $("git", ["branch", "-m", defaultBranch], { cwd: cwd2 });
1574
1630
  };
1575
- var add = async (toAdd, cwd = ".") => {
1631
+ var add = async (toAdd, cwd2 = ".") => {
1576
1632
  debug(`Git Add: ${toAdd}`);
1577
- await $("git", ["add", toAdd], { cwd });
1633
+ await $("git", ["add", toAdd], { cwd: cwd2 });
1578
1634
  };
1579
- var commit = async (msg, cwd = ".") => {
1635
+ var commit = async (msg, cwd2 = ".") => {
1580
1636
  debug(`Git commit: ${msg}`);
1581
- await $("git", ["commit", "--no-verify", "-m", msg], { cwd });
1637
+ await $("git", ["commit", "--no-verify", "-m", msg], { cwd: cwd2 });
1582
1638
  };
1583
- var rollback = async (cwd = ".") => {
1639
+ var rollback = async (cwd2 = ".") => {
1584
1640
  debug("Rollback");
1585
- await $("git", ["add", "."], { cwd });
1586
- await $("git", ["reset", "--hard"], { cwd });
1641
+ await $("git", ["add", "."], { cwd: cwd2 });
1642
+ await $("git", ["reset", "--hard"], { cwd: cwd2 });
1587
1643
  await cleanUpWorktrees();
1588
1644
  };
1589
- var hasUncommittedChanges = async (cwd = ".") => {
1645
+ var hasUncommittedChanges = async (cwd2 = ".") => {
1590
1646
  let status = "";
1591
1647
  await $("git", ["status", "--porcelain"], {
1592
- cwd,
1648
+ cwd: cwd2,
1593
1649
  onStdout: (text2) => {
1594
1650
  status += text2;
1595
1651
  }
1596
1652
  });
1597
1653
  return status.trim().length > 0;
1598
1654
  };
1599
- var hasStagedChanges = async (cwd = ".") => {
1655
+ var hasStagedChanges = async (cwd2 = ".") => {
1600
1656
  let lastError;
1601
1657
  for (let attempt = 0; attempt < 4; attempt++) {
1602
1658
  try {
1603
- await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd });
1659
+ await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd: cwd2 });
1604
1660
  return false;
1605
1661
  } catch (e) {
1606
1662
  if (e.code === 1) {
@@ -1615,9 +1671,9 @@ var hasStagedChanges = async (cwd = ".") => {
1615
1671
  }
1616
1672
  throw lastError;
1617
1673
  };
1618
- var checkout = async (branch, cwd = ".") => {
1674
+ var checkout = async (branch, cwd2 = ".") => {
1619
1675
  debug(`Git checkout: ${branch}`);
1620
- await $("git", ["checkout", branch], { cwd });
1676
+ await $("git", ["checkout", branch], { cwd: cwd2 });
1621
1677
  };
1622
1678
  var merge2 = async (remoteBranch, options = {}) => {
1623
1679
  debug(`Git merge: ${remoteBranch}`);
@@ -1627,10 +1683,10 @@ var merge2 = async (remoteBranch, options = {}) => {
1627
1683
  }
1628
1684
  await $("git", args);
1629
1685
  };
1630
- var hasConflicts = async (cwd = ".") => {
1686
+ var hasConflicts = async (cwd2 = ".") => {
1631
1687
  let unmerged = "";
1632
1688
  await $("git", ["ls-files", "--unmerged"], {
1633
- cwd,
1689
+ cwd: cwd2,
1634
1690
  onStdout: (text2) => {
1635
1691
  unmerged += text2;
1636
1692
  }
@@ -1671,57 +1727,57 @@ var listRemoteBranches = async (repoUrl) => {
1671
1727
  return ref.replace("refs/heads/", "");
1672
1728
  }).filter((branch) => branch.length > 0 && branch !== "main" && branch !== "master");
1673
1729
  };
1674
- var listBranches = async (cwd = ".") => {
1730
+ var listBranches = async (cwd2 = ".") => {
1675
1731
  let out = "";
1676
1732
  await $("git", ["branch", "--list"], {
1677
- cwd,
1733
+ cwd: cwd2,
1678
1734
  onStdout: (text2) => {
1679
1735
  out += text2;
1680
1736
  }
1681
1737
  });
1682
1738
  return out.split("\n").map((l) => l.replace(/^\*?\s+/, "").trim()).filter(Boolean).filter((b) => !b.startsWith("("));
1683
1739
  };
1684
- var createBranch = async (branch, from, cwd = ".") => {
1740
+ var createBranch = async (branch, from, cwd2 = ".") => {
1685
1741
  if (from) {
1686
- await $("git", ["checkout", "-B", branch, from], { cwd });
1742
+ await $("git", ["checkout", "-B", branch, from], { cwd: cwd2 });
1687
1743
  } else {
1688
- await $("git", ["checkout", "-b", branch], { cwd });
1744
+ await $("git", ["checkout", "-b", branch], { cwd: cwd2 });
1689
1745
  }
1690
1746
  };
1691
- var push = async (remote, branch, cwd = ".") => {
1692
- await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd });
1747
+ var push = async (remote, branch, cwd2 = ".") => {
1748
+ await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd: cwd2 });
1693
1749
  };
1694
- var checkoutFile = async (path38, ref, cwd = ".") => {
1750
+ var checkoutFile = async (path41, ref, cwd2 = ".") => {
1695
1751
  const args = ["checkout"];
1696
1752
  if (ref) args.push(ref);
1697
1753
  else args.push("HEAD");
1698
- args.push("--", path38);
1699
- await $("git", args, { cwd });
1754
+ args.push("--", path41);
1755
+ await $("git", args, { cwd: cwd2 });
1700
1756
  };
1701
- var pathExistsAsBlobInRev = async (rev, filePath, cwd = ".") => {
1757
+ var pathExistsAsBlobInRev = async (rev, filePath, cwd2 = ".") => {
1702
1758
  const p = normalizePath(filePath);
1703
1759
  try {
1704
- await $("git", ["cat-file", "-e", `${rev}:${p}`], { cwd });
1760
+ await $("git", ["cat-file", "-e", `${rev}:${p}`], { cwd: cwd2 });
1705
1761
  return true;
1706
1762
  } catch {
1707
1763
  return false;
1708
1764
  }
1709
1765
  };
1710
- var revertPathToHead = async (filePath, cwd = ".") => {
1766
+ var revertPathToHead = async (filePath, cwd2 = ".") => {
1711
1767
  const p = normalizePath(filePath);
1712
- if (await pathExistsAsBlobInRev("HEAD", p, cwd)) {
1713
- await checkoutFile(p, "HEAD", cwd);
1768
+ if (await pathExistsAsBlobInRev("HEAD", p, cwd2)) {
1769
+ await checkoutFile(p, "HEAD", cwd2);
1714
1770
  } else {
1715
- await $("git", ["rm", "-f", "--", p], { cwd });
1771
+ await $("git", ["rm", "-f", "--", p], { cwd: cwd2 });
1716
1772
  }
1717
1773
  };
1718
- var listCommits = async (limit, skip, cwd = ".") => {
1774
+ var listCommits = async (limit, skip, cwd2 = ".") => {
1719
1775
  let out = "";
1720
1776
  await $(
1721
1777
  "git",
1722
1778
  ["log", "--pretty=format:%H|%s", "-n", String(limit), "--skip", String(skip), "HEAD"],
1723
1779
  {
1724
- cwd,
1780
+ cwd: cwd2,
1725
1781
  onStdout: (text2) => {
1726
1782
  out += text2;
1727
1783
  }
@@ -1736,57 +1792,57 @@ var listCommits = async (limit, skip, cwd = ".") => {
1736
1792
  return { hash, subject: subjectRaw.trim() };
1737
1793
  });
1738
1794
  };
1739
- var listCommitsOldestFirst = async (cwd = ".") => {
1795
+ var listCommitsOldestFirst = async (cwd2 = ".") => {
1740
1796
  let out = "";
1741
1797
  await $("git", ["log", "--reverse", "--pretty=format:%H", "HEAD"], {
1742
- cwd,
1798
+ cwd: cwd2,
1743
1799
  onStdout: (text2) => {
1744
1800
  out += text2;
1745
1801
  }
1746
1802
  });
1747
1803
  return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1748
1804
  };
1749
- var fetchCommit = async (fromRepo, commit2, cwd = ".") => {
1805
+ var fetchCommit = async (fromRepo, commit2, cwd2 = ".") => {
1750
1806
  const ref = normalizeCommitRef(commit2);
1751
- await $("git", ["fetch", fromRepo, `+${ref}:FETCH_HEAD`], { cwd });
1807
+ await $("git", ["fetch", fromRepo, `+${ref}:FETCH_HEAD`], { cwd: cwd2 });
1752
1808
  };
1753
- var cherryPick = async (commitHash, subtree, noCommit, cwd = ".") => {
1809
+ var cherryPick = async (commitHash, subtree, noCommit, cwd2 = ".") => {
1754
1810
  const args = ["cherry-pick"];
1755
1811
  if (noCommit) args.push("--no-commit");
1756
1812
  if (subtree) args.push(`-Xsubtree=${subtree}`);
1757
1813
  args.push(normalizeCommitRef(commitHash));
1758
- await $("git", args, { cwd });
1814
+ await $("git", args, { cwd: cwd2 });
1759
1815
  };
1760
- var reset = async (path38, hard, cwd = ".") => {
1816
+ var reset = async (path41, hard, cwd2 = ".") => {
1761
1817
  const args = ["reset"];
1762
1818
  if (hard) args.push("--hard");
1763
- if (path38) args.push(path38);
1764
- await $("git", args, { cwd });
1819
+ if (path41) args.push(path41);
1820
+ await $("git", args, { cwd: cwd2 });
1765
1821
  };
1766
- var commitAll = async (message, cwd = ".") => {
1767
- await add(".", cwd);
1768
- await commit(message, cwd);
1822
+ var commitAll = async (message3, cwd2 = ".") => {
1823
+ await add(".", cwd2);
1824
+ await commit(message3, cwd2);
1769
1825
  };
1770
- var getUnmergedFiles = async (cwd = ".") => {
1826
+ var getUnmergedFiles = async (cwd2 = ".") => {
1771
1827
  let out = "";
1772
1828
  await $("git", ["status", "--porcelain"], {
1773
- cwd,
1829
+ cwd: cwd2,
1774
1830
  onStdout: (text2) => {
1775
1831
  out += text2;
1776
1832
  }
1777
1833
  });
1778
1834
  return out.split("\n").filter((l) => /^(U.|.U|AA|DD)/.test(l)).map((l) => l.slice(3).trim());
1779
1835
  };
1780
- var fetchRepo = async (cwd = ".") => {
1781
- await fetchWithRefRecovery("origin", ["fetch", "--progress", "origin"], { cwd });
1836
+ var fetchRepo = async (cwd2 = ".") => {
1837
+ await fetchWithRefRecovery("origin", ["fetch", "--progress", "origin"], { cwd: cwd2 });
1782
1838
  };
1783
- var getChangedFilesInCommit = async (commit2, cwd = ".") => {
1839
+ var getChangedFilesInCommit = async (commit2, cwd2 = ".") => {
1784
1840
  let out = "";
1785
1841
  await $(
1786
1842
  "git",
1787
1843
  ["diff-tree", "--no-renames", "--no-commit-id", "--name-only", "-r", "--root", normalizeCommitRef(commit2)],
1788
1844
  {
1789
- cwd,
1845
+ cwd: cwd2,
1790
1846
  onStdout: (text2) => {
1791
1847
  out += text2;
1792
1848
  }
@@ -1794,10 +1850,10 @@ var getChangedFilesInCommit = async (commit2, cwd = ".") => {
1794
1850
  );
1795
1851
  return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1796
1852
  };
1797
- var getChangedFilesFromHead = async (cwd = ".") => {
1853
+ var getChangedFilesFromHead = async (cwd2 = ".") => {
1798
1854
  let out = "";
1799
1855
  await $("git", ["diff", "--no-renames", "--name-status", "-z", "HEAD"], {
1800
- cwd,
1856
+ cwd: cwd2,
1801
1857
  onStdout: (text2) => {
1802
1858
  out += text2;
1803
1859
  }
@@ -1988,17 +2044,17 @@ async function migrate(name, { getPath = (f) => f, read, write }) {
1988
2044
  }
1989
2045
  return { output: currentRev, filesChanged };
1990
2046
  }
1991
- function migrateOnLocal(name, cwd = ".") {
2047
+ function migrateOnLocal(name, cwd2 = ".") {
1992
2048
  return migrate(name, {
1993
- getPath: (file) => import_node_path14.default.join(cwd, file),
2049
+ getPath: (file) => import_node_path14.default.join(cwd2, file),
1994
2050
  read: import_fs_extra10.default.readJson,
1995
2051
  write: import_fs_extra10.default.writeFile
1996
2052
  });
1997
2053
  }
1998
- function migrateOnRemote(name, commit2, cwd) {
2054
+ function migrateOnRemote(name, commit2, cwd2) {
1999
2055
  return migrate(name, {
2000
2056
  read: (file) => git.readJsonFromCommit(commit2, file),
2001
- getPath: cwd ? (file) => import_node_path14.default.join(cwd, file) : void 0
2057
+ getPath: cwd2 ? (file) => import_node_path14.default.join(cwd2, file) : void 0
2002
2058
  });
2003
2059
  }
2004
2060
 
@@ -2016,14 +2072,14 @@ async function migrateProjectBlocks(projectDir) {
2016
2072
  async function migrateAll(autoCommit, rootDir = ".") {
2017
2073
  let filesChanged = (await migrateOnLocal("app", rootDir)).filesChanged;
2018
2074
  filesChanged = await migrateProjectBlocks(rootDir) || filesChanged;
2019
- for (const app of listApps(rootDir)) {
2020
- filesChanged = (await migrateOnLocal(app.key, app.dir)).filesChanged || filesChanged;
2021
- filesChanged = await migrateProjectBlocks(app.dir) || filesChanged;
2075
+ for (const app2 of listApps(rootDir)) {
2076
+ filesChanged = (await migrateOnLocal(app2.key, app2.dir)).filesChanged || filesChanged;
2077
+ filesChanged = await migrateProjectBlocks(app2.dir) || filesChanged;
2022
2078
  }
2023
2079
  const urlsChanged = await updateSchemaUrls(rootDir);
2024
2080
  filesChanged = filesChanged || urlsChanged;
2025
2081
  if (autoCommit && filesChanged) {
2026
- for (const dir of [rootDir, ...listApps(rootDir).map((app) => app.dir)]) {
2082
+ for (const dir of [rootDir, ...listApps(rootDir).map((app2) => app2.dir)]) {
2027
2083
  if (await git.hasUncommittedChanges(dir)) {
2028
2084
  import_prompts2.log.warn(fmt.yellow(`Migrations done and will be commited`));
2029
2085
  await git.add(".", dir);
@@ -2050,10 +2106,10 @@ var import_klaw2 = __toESM(require("klaw"));
2050
2106
  var filterBlacklisted = (item) => {
2051
2107
  return !item.includes("node_modules") && !item.includes(".git");
2052
2108
  };
2053
- var deletePattern = async (cwd, patterns = []) => {
2109
+ var deletePattern = async (cwd2, patterns = []) => {
2054
2110
  const ig = (0, import_ignore2.default)().add(patterns);
2055
- for await (const file of (0, import_klaw2.default)(cwd, { filter: filterBlacklisted })) {
2056
- const relativePath = import_node_path16.default.relative(cwd, file.path);
2111
+ for await (const file of (0, import_klaw2.default)(cwd2, { filter: filterBlacklisted })) {
2112
+ const relativePath = import_node_path16.default.relative(cwd2, file.path);
2057
2113
  if (relativePath && ig.ignores(relativePath)) {
2058
2114
  if (!await import_fs_extra12.default.exists(file.path)) {
2059
2115
  continue;
@@ -2320,8 +2376,8 @@ function createAddScope(projectDir, blocks, options = {}) {
2320
2376
  }
2321
2377
  function toAddScope(scope) {
2322
2378
  if ("projectDir" in scope && "blocksRoot" in scope) return scope;
2323
- const cwd = import_node_path18.default.resolve(".");
2324
- return createAddScope(cwd, scope);
2379
+ const cwd2 = import_node_path18.default.resolve(".");
2380
+ return createAddScope(cwd2, scope);
2325
2381
  }
2326
2382
  function recordResult(results, result) {
2327
2383
  const index = results.findIndex(
@@ -2396,14 +2452,14 @@ async function snapshot(ownedPath, directory, entries = /* @__PURE__ */ new Map(
2396
2452
  }
2397
2453
  return entries;
2398
2454
  }
2399
- async function cleanup(before, after) {
2455
+ async function cleanup(before, after, projectDir) {
2400
2456
  const failures = [];
2401
2457
  const deletedMetadata = [...before].filter(
2402
2458
  ([filename, entry]) => entry.metadata && !after.has(filename)
2403
2459
  );
2404
2460
  for (const [filename, entry] of [...after, ...deletedMetadata].reverse()) {
2405
2461
  try {
2406
- assertNoSymlinkParents(filename, import_node_path18.default.resolve("."));
2462
+ assertNoSymlinkParents(filename, projectDir);
2407
2463
  if (!before.has(filename)) {
2408
2464
  if (entry.directory) {
2409
2465
  await import_fs_extra14.default.rmdir(filename);
@@ -2551,17 +2607,17 @@ async function addBlockWithResult(block, results, branch, destination, visiting,
2551
2607
  try {
2552
2608
  await runLifecycleHookWithTask(blockPath, hook, `Run block ${hook}`);
2553
2609
  } catch (cause) {
2554
- const message = `${block}: ${hook} hook failed: ${errorMessage2(cause)}`;
2555
- import_prompts2.log.error(message);
2610
+ const message3 = `${block}: ${hook} hook failed: ${errorMessage2(cause)}`;
2611
+ import_prompts2.log.error(message3);
2556
2612
  const shouldContinue = isNonInteractive() ? true : await confirm({
2557
2613
  message: `Continue adding ${block} despite the failed ${hook} hook?`,
2558
2614
  initialValue: true
2559
2615
  });
2560
2616
  if (!shouldContinue) {
2561
- throw new Error(message, { cause });
2617
+ throw new Error(message3, { cause });
2562
2618
  }
2563
- warnings.push(message);
2564
- import_prompts2.log.warn(`Adding ${block} with a warning: ${message}`);
2619
+ warnings.push(message3);
2620
+ import_prompts2.log.warn(`Adding ${block} with a warning: ${message3}`);
2565
2621
  }
2566
2622
  }
2567
2623
  after = await snapshot(
@@ -2596,7 +2652,8 @@ async function addBlockWithResult(block, results, branch, destination, visiting,
2596
2652
  after || await snapshot(
2597
2653
  import_node_path18.default.resolve(blockPath),
2598
2654
  import_node_path18.default.resolve(scope.projectDir)
2599
- )
2655
+ ),
2656
+ scope.projectDir
2600
2657
  );
2601
2658
  } catch (cleanupError) {
2602
2659
  reason += `; ${errorMessage2(cleanupError)}`;
@@ -2690,15 +2747,15 @@ async function addApp(appKey, appData, workspaceRoot, branch, options = {}) {
2690
2747
  try {
2691
2748
  await runLifecycleHookWithTask(appPath, hook, `Run app ${hook}`);
2692
2749
  } catch (cause) {
2693
- const message = `${appKey}: ${hook} hook failed: ${errorMessage2(cause)}`;
2694
- import_prompts2.log.error(message);
2750
+ const message3 = `${appKey}: ${hook} hook failed: ${errorMessage2(cause)}`;
2751
+ import_prompts2.log.error(message3);
2695
2752
  const shouldContinue = isNonInteractive() ? true : await confirm({
2696
2753
  message: `Continue adding ${appKey} despite the failed ${hook} hook?`,
2697
2754
  initialValue: true
2698
2755
  });
2699
- if (!shouldContinue) throw new Error(message, { cause });
2700
- warnings.push(message);
2701
- import_prompts2.log.warn(`Adding ${appKey} with a warning: ${message}`);
2756
+ if (!shouldContinue) throw new Error(message3, { cause });
2757
+ warnings.push(message3);
2758
+ import_prompts2.log.warn(`Adding ${appKey} with a warning: ${message3}`);
2702
2759
  }
2703
2760
  }
2704
2761
  if (backupPath) await import_fs_extra14.default.remove(backupPath);
@@ -2850,7 +2907,7 @@ and can be combined with either mode.`
2850
2907
  scope = createAddScope(context.projectDir, blocks);
2851
2908
  }
2852
2909
  const installed = getInstalledBlockNames(scope.blocksRoot);
2853
- const installedApps = new Set(listApps(context.workspaceRoot).map((app) => app.key));
2910
+ const installedApps = new Set(listApps(context.workspaceRoot).map((app2) => app2.key));
2854
2911
  const blocksToAdd = [];
2855
2912
  const appsToAdd = [];
2856
2913
  const requested = Array.isArray(selectedBlocks) ? selectedBlocks : [];
@@ -3038,13 +3095,13 @@ function buildBranchName(commitType, title) {
3038
3095
  // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
3039
3096
  var import_node_path19 = __toESM(require("path"));
3040
3097
  var import_fs_extra15 = __toESM(require("fs-extra"));
3041
- function getExcludedPrefixesForTarget(target, cwd) {
3098
+ function getExcludedPrefixesForTarget(target, cwd2) {
3042
3099
  if (target.type === ContributionTargetType.BLOCK) {
3043
3100
  return [];
3044
3101
  }
3045
3102
  const projectDir = !target.projectDir || target.projectDir === "." ? "" : target.projectDir;
3046
3103
  const excluded = [];
3047
- const blocksPath = import_node_path19.default.join(cwd, projectDir, blocksDir);
3104
+ const blocksPath = import_node_path19.default.join(cwd2, projectDir, blocksDir);
3048
3105
  if (import_fs_extra15.default.existsSync(blocksPath)) {
3049
3106
  const entries = import_fs_extra15.default.readdirSync(blocksPath, { withFileTypes: true });
3050
3107
  for (const entry of entries) {
@@ -3058,7 +3115,7 @@ function getExcludedPrefixesForTarget(target, cwd) {
3058
3115
  }
3059
3116
  }
3060
3117
  if (!projectDir) {
3061
- const appsPath = import_node_path19.default.join(cwd, appsDir);
3118
+ const appsPath = import_node_path19.default.join(cwd2, appsDir);
3062
3119
  if (import_fs_extra15.default.existsSync(appsPath)) {
3063
3120
  const entries = import_fs_extra15.default.readdirSync(appsPath, { withFileTypes: true });
3064
3121
  for (const entry of entries) {
@@ -3129,7 +3186,7 @@ var componentLabel = (component) => {
3129
3186
  }
3130
3187
  return `${component.type}/${component.name}`;
3131
3188
  };
3132
- var discoverContributionTargets = (cwd) => discoverBloxComponents(cwd, { scope: "project" }).map((component) => ({
3189
+ var discoverContributionTargets = (cwd2) => discoverBloxComponents(cwd2, { scope: "project" }).map((component) => ({
3133
3190
  ...component,
3134
3191
  label: componentLabel(component),
3135
3192
  hint: componentHint(component)
@@ -3162,9 +3219,9 @@ var parseTargetsList = (list, allTargets) => {
3162
3219
  );
3163
3220
  }
3164
3221
  if (parts.length === 4) {
3165
- const [, app, type, name] = parts;
3222
+ const [, app2, type, name] = parts;
3166
3223
  return allTargets.find(
3167
- (item) => item.type === type && item.name === name && item.app === app
3224
+ (item) => item.type === type && item.name === name && item.app === app2
3168
3225
  );
3169
3226
  }
3170
3227
  return void 0;
@@ -3491,19 +3548,19 @@ ${fmt.bold("Branch conflict check")} for ${fmt.cyan(branch)}`,
3491
3548
  });
3492
3549
  return { target, success: true, result };
3493
3550
  } catch (e) {
3494
- const message = e instanceof Error ? e.message : String(e);
3551
+ const message3 = e instanceof Error ? e.message : String(e);
3495
3552
  if (e instanceof MissingRegistrySourceError) {
3496
- this.logger.warn(`Skipping ${target.type}/${target.name}: ${message}`);
3497
- return { target, success: true, skipped: message };
3553
+ this.logger.warn(`Skipping ${target.type}/${target.name}: ${message3}`);
3554
+ return { target, success: true, skipped: message3 };
3498
3555
  }
3499
3556
  this.logger.error(
3500
3557
  `Contribution failed for ${target.type}/${target.name}. Skipping to next target.`,
3501
- message
3558
+ message3
3502
3559
  );
3503
3560
  return {
3504
3561
  target,
3505
3562
  success: false,
3506
- error: message,
3563
+ error: message3,
3507
3564
  ...e instanceof CliError ? { errorCode: e.code, details: e.details } : {}
3508
3565
  };
3509
3566
  }
@@ -3776,8 +3833,8 @@ var buildCommitMessage = ({
3776
3833
  }
3777
3834
  return parts.join("\n\n");
3778
3835
  };
3779
- var extractFooters = (message) => {
3780
- const paragraphs = message.split(/\r?\n\s*\r?\n/);
3836
+ var extractFooters = (message3) => {
3837
+ const paragraphs = message3.split(/\r?\n\s*\r?\n/);
3781
3838
  const footerParagraphs = [];
3782
3839
  for (let i = paragraphs.length - 1; i >= 1; i--) {
3783
3840
  const paragraph = paragraphs[i];
@@ -4021,13 +4078,16 @@ var drawBox = (styledTitle, bodyLines) => {
4021
4078
  `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`
4022
4079
  ];
4023
4080
  };
4024
- var boxedManualInstructions = (tmpRepoCwd) => drawBox(
4025
- fmt.bold(" Manual conflict resolution "),
4026
- buildManualInstructions(tmpRepoCwd).split("\n")
4027
- );
4028
- var showManualInstructionsBox = (tmpRepoCwd) => {
4029
- import_prompts2.log.message(["", ...boxedManualInstructions(tmpRepoCwd), ""].join("\n"));
4081
+ var boxedManualInstructions = (tmpRepoCwd, instructions = buildManualInstructions(tmpRepoCwd)) => drawBox(fmt.bold(" Manual conflict resolution "), instructions.split("\n"));
4082
+ var showManualInstructionsBox = (tmpRepoCwd, instructions) => {
4083
+ import_prompts2.log.message(["", ...boxedManualInstructions(tmpRepoCwd, instructions), ""].join("\n"));
4030
4084
  };
4085
+ var buildUpdateManualInstructions = (projectDir) => [
4086
+ "1. Open the project in your editor or a terminal:",
4087
+ ` ${fmt.green(`cd "${projectDir}"`)}`,
4088
+ "2. Resolve the conflict markers (<<<<<<<, =======, >>>>>>>) in the files above.",
4089
+ "3. Save the files, then come back here."
4090
+ ].join("\n");
4031
4091
  var showConflictSummary = (commit2, files, stillRemaining) => {
4032
4092
  const fileLabel = files.length === 1 ? "file" : "files";
4033
4093
  const title = stillRemaining ? fmt.yellow(fmt.bold(" Conflicts still detected ")) : fmt.red(fmt.bold(" Conflicts detected "));
@@ -4075,13 +4135,13 @@ var promptStagedMarkersAction = async (files) => {
4075
4135
  ]
4076
4136
  });
4077
4137
  };
4078
- var selectIdeForConflictResolution = async (ides, tmpRepoCwd) => {
4138
+ var selectIdeForConflictResolution = async (ides, tmpRepoCwd, opts = {}) => {
4079
4139
  const options = [
4080
4140
  ...ides.map((ide) => ({ value: ide.id, label: ide.name })),
4081
4141
  { value: MANUAL_IDE_VALUE, label: "Resolve manually without opening an IDE" }
4082
4142
  ];
4083
- const boxLines = boxedManualInstructions(tmpRepoCwd);
4084
- const message = "Select an IDE to open the temporary contribution project:";
4143
+ const boxLines = boxedManualInstructions(tmpRepoCwd, opts.instructions);
4144
+ const message3 = opts.message ?? "Select an IDE to open the temporary contribution project:";
4085
4145
  const optLabel = (option2, state) => {
4086
4146
  if (!option2) return "";
4087
4147
  switch (state) {
@@ -4099,7 +4159,7 @@ var selectIdeForConflictResolution = async (ides, tmpRepoCwd) => {
4099
4159
  options,
4100
4160
  render() {
4101
4161
  const title = `${fmt.gray("\u2502")}
4102
- ${stateSymbol(this.state)} ${message}
4162
+ ${stateSymbol(this.state)} ${message3}
4103
4163
  `;
4104
4164
  switch (this.state) {
4105
4165
  case "submit":
@@ -4842,18 +4902,18 @@ ${fmt.gray(
4842
4902
  pretty.split("\n").map((line) => ` ${line}`).join("\n")
4843
4903
  )}`;
4844
4904
  }
4845
- debug(message, data) {
4905
+ debug(message3, data) {
4846
4906
  if (!isDebugMode()) return;
4847
- import_prompts2.log.info(`${fmt.magenta("DEBUG")} ${message}${this.formatData(data)}`);
4907
+ import_prompts2.log.info(`${fmt.magenta("DEBUG")} ${message3}${this.formatData(data)}`);
4848
4908
  }
4849
- info(message, data) {
4850
- import_prompts2.log.info(`${fmt.cyan("INFO")} ${message}${this.formatData(data)}`);
4909
+ info(message3, data) {
4910
+ import_prompts2.log.info(`${fmt.cyan("INFO")} ${message3}${this.formatData(data)}`);
4851
4911
  }
4852
- warn(message, data) {
4853
- import_prompts2.log.warn(`${fmt.yellow("WARN")} ${message}${this.formatData(data)}`);
4912
+ warn(message3, data) {
4913
+ import_prompts2.log.warn(`${fmt.yellow("WARN")} ${message3}${this.formatData(data)}`);
4854
4914
  }
4855
- error(message, data) {
4856
- import_prompts2.log.error(`${fmt.red("ERROR")} ${fmt.bold(message)}${this.formatData(data)}`);
4915
+ error(message3, data) {
4916
+ import_prompts2.log.error(`${fmt.red("ERROR")} ${fmt.bold(message3)}${this.formatData(data)}`);
4857
4917
  }
4858
4918
  };
4859
4919
 
@@ -4938,10 +4998,10 @@ var PullRequestService = class {
4938
4998
  await git.push(opts.remote, opts.branch, opts.cwd);
4939
4999
  return;
4940
5000
  } catch (e) {
4941
- const message = e instanceof Error ? e.message : String(e);
4942
- opts.onAttemptFailed?.({ attempt, error: message });
5001
+ const message3 = e instanceof Error ? e.message : String(e);
5002
+ opts.onAttemptFailed?.({ attempt, error: message3 });
4943
5003
  if (attempt === maxAttempts) {
4944
- throw new Error(`git push failed after ${maxAttempts} attempts: ${message}`);
5004
+ throw new Error(`git push failed after ${maxAttempts} attempts: ${message3}`);
4945
5005
  }
4946
5006
  await sleep(500 * attempt);
4947
5007
  }
@@ -5197,7 +5257,7 @@ mode.`
5197
5257
  try {
5198
5258
  const context = resolveContext(".", args.app);
5199
5259
  projectDir = context.projectDir;
5200
- const cwd = process.cwd();
5260
+ const cwd2 = process.cwd();
5201
5261
  process.chdir(context.projectDir);
5202
5262
  try {
5203
5263
  if (!basic) {
@@ -5245,7 +5305,7 @@ mode.`
5245
5305
  printJsonResult({ name, base });
5246
5306
  }
5247
5307
  } finally {
5248
- process.chdir(cwd);
5308
+ process.chdir(cwd2);
5249
5309
  }
5250
5310
  } catch (e) {
5251
5311
  if (!isDebugMode() && !(e instanceof CliError)) {
@@ -7008,43 +7068,43 @@ be combined with either mode.`
7008
7068
  await replacePlaceholders(name, { app: { name } });
7009
7069
  updateCheckpoint(def.name, { commit: commit2, branch }, name);
7010
7070
  const root = import_node_path31.default.resolve(name);
7011
- for (const app of listApps(root)) {
7012
- if (!hasGitRepo(app.dir)) {
7013
- await git.init(app.dir);
7071
+ for (const app2 of listApps(root)) {
7072
+ if (!hasGitRepo(app2.dir)) {
7073
+ await git.init(app2.dir);
7014
7074
  }
7015
7075
  }
7016
7076
  const appResults = await materializeWorkspaceApps(root, await getAvailableApps(def));
7017
- for (const app of listApps(root)) {
7018
- ensureAppIgnored(root, app.key);
7077
+ for (const app2 of listApps(root)) {
7078
+ ensureAppIgnored(root, app2.key);
7019
7079
  }
7020
7080
  await git.init(name);
7021
7081
  task.stop(`App initialized in ${name}`);
7022
7082
  await runLifecycleHookWithTask(name || "", "init", "Run template init");
7023
7083
  const warnings = [];
7024
- for (const app of listApps(name)) {
7084
+ for (const app2 of listApps(name)) {
7025
7085
  try {
7026
7086
  await runLifecycleHookWithTask(
7027
- import_node_path31.default.join(name, "apps", app.key),
7087
+ import_node_path31.default.join(name, "apps", app2.key),
7028
7088
  "init",
7029
- `Run app init: ${app.key}`
7089
+ `Run app init: ${app2.key}`
7030
7090
  );
7031
7091
  } catch (cause) {
7032
- const message = `${app.key}: init hook failed: ${cause instanceof Error ? cause.message : String(cause)}`;
7033
- import_prompts2.log.error(message);
7092
+ const message3 = `${app2.key}: init hook failed: ${cause instanceof Error ? cause.message : String(cause)}`;
7093
+ import_prompts2.log.error(message3);
7034
7094
  const keepGoing = isNonInteractive() ? true : await confirm({
7035
- message: `Continue initializing ${app.key} despite the failed init hook?`,
7095
+ message: `Continue initializing ${app2.key} despite the failed init hook?`,
7036
7096
  initialValue: true
7037
7097
  });
7038
7098
  if (!keepGoing) throw cause;
7039
- warnings.push(message);
7099
+ warnings.push(message3);
7040
7100
  }
7041
7101
  }
7042
- const failedApps = appResults.filter((app) => app.status === "failed");
7102
+ const failedApps = appResults.filter((app2) => app2.status === "failed");
7043
7103
  if (failedApps.length) {
7044
7104
  process.exitCode = 1;
7045
7105
  import_prompts2.log.warn(
7046
7106
  fmt.yellow(
7047
- `${failedApps.length} app(s) failed to initialize \u2014 retry with: blox add ${failedApps.map((app) => `app/${app.key}`).join(" ")}`
7107
+ `${failedApps.length} app(s) failed to initialize \u2014 retry with: blox add ${failedApps.map((app2) => `app/${app2.key}`).join(" ")}`
7048
7108
  )
7049
7109
  );
7050
7110
  }
@@ -7085,7 +7145,7 @@ Non-interactive usage:
7085
7145
  import_prompts2.log.warn("Error happened, Will rollback changes");
7086
7146
  for (const dir of [
7087
7147
  workspaceRoot,
7088
- ...listApps(workspaceRoot).map((app) => app.dir)
7148
+ ...listApps(workspaceRoot).map((app2) => app2.dir)
7089
7149
  ]) {
7090
7150
  try {
7091
7151
  await git.rollback(dir);
@@ -7097,95 +7157,551 @@ Non-interactive usage:
7097
7157
  }
7098
7158
  });
7099
7159
 
7100
- // src/commands/remove/index.ts
7160
+ // src/mcp/server.ts
7161
+ var import_server2 = require("@modelcontextprotocol/server");
7162
+
7163
+ // src/mcp/context.ts
7164
+ var import_node_fs = __toESM(require("fs"));
7101
7165
  var import_node_path32 = __toESM(require("path"));
7102
- var import_fs_extra28 = __toESM(require("fs-extra"));
7103
- function listInstalledBlockRelPaths(blocksRoot, projectDir) {
7104
- if (!import_fs_extra28.default.existsSync(blocksRoot)) {
7105
- return [];
7166
+ function contextSummary(context) {
7167
+ return {
7168
+ workspaceRoot: context.workspaceRoot,
7169
+ projectDir: context.projectDir,
7170
+ app: context.app ?? null
7171
+ };
7172
+ }
7173
+ function isWithin(root, target) {
7174
+ const relative = import_node_path32.default.relative(root, target);
7175
+ return relative === "" || !relative.startsWith("..") && !import_node_path32.default.isAbsolute(relative);
7176
+ }
7177
+ function realDirectory(dir, label) {
7178
+ let stat;
7179
+ try {
7180
+ stat = import_node_fs.default.statSync(dir);
7181
+ } catch {
7182
+ throw new CliError(`${label} does not exist: ${dir}`, "NOT_FOUND", exitCodes.NOT_FOUND);
7106
7183
  }
7107
- const paths2 = [];
7108
- for (const entry of import_fs_extra28.default.readdirSync(blocksRoot, { withFileTypes: true })) {
7109
- if (!entry.isDirectory()) {
7110
- continue;
7111
- }
7112
- const abs = import_node_path32.default.join(blocksRoot, entry.name);
7113
- if (!isBlockDirectory(abs)) {
7114
- continue;
7184
+ if (!stat.isDirectory()) {
7185
+ throw new CliError(`${label} is not a directory: ${dir}`, "VALIDATION", exitCodes.USAGE);
7186
+ }
7187
+ try {
7188
+ import_node_fs.default.accessSync(dir, import_node_fs.default.constants.R_OK);
7189
+ return import_node_fs.default.realpathSync.native(dir);
7190
+ } catch {
7191
+ throw new CliError(
7192
+ `${label} is not accessible: ${dir}`,
7193
+ "NOT_ACCESSIBLE",
7194
+ exitCodes.GENERAL
7195
+ );
7196
+ }
7197
+ }
7198
+ function createBloxMcpContext(cwd2, base = process.cwd()) {
7199
+ const requested = import_node_path32.default.resolve(base, cwd2 ?? ".");
7200
+ const dir = realDirectory(requested, "MCP project directory");
7201
+ const projectDir = findProjectDir(dir);
7202
+ if (!projectDir) {
7203
+ throw new CliError(
7204
+ `No BLOX project found for ${dir}`,
7205
+ "NO_PROJECT",
7206
+ exitCodes.NOT_FOUND,
7207
+ "Start the server with `blox mcp --cwd <project>` pointing at a BLOX project (a directory with a .blox file), or run `blox mcp` inside a blox project."
7208
+ );
7209
+ }
7210
+ const context = resolveContext(projectDir);
7211
+ return Object.freeze({
7212
+ workspaceRoot: context.workspaceRoot,
7213
+ projectDir: context.projectDir,
7214
+ ...context.app ? { app: context.app } : {}
7215
+ });
7216
+ }
7217
+ function outsideProject(target, root, reason) {
7218
+ return new CliError(
7219
+ `cwd ${reason}: ${target}`,
7220
+ "OUTSIDE_PROJECT",
7221
+ exitCodes.USAGE,
7222
+ `This MCP server serves the BLOX project at ${root}. Omit cwd, or pass a path inside it (relative paths resolve against the project root).`
7223
+ );
7224
+ }
7225
+ function resolveToolCwd(mcpContext, input) {
7226
+ const root = mcpContext.workspaceRoot;
7227
+ if (input.cwd === void 0) return mcpContext.projectDir;
7228
+ const candidate = import_node_path32.default.resolve(root, input.cwd);
7229
+ if (!isWithin(root, candidate)) {
7230
+ throw outsideProject(candidate, root, "is outside the configured BLOX project");
7231
+ }
7232
+ let real;
7233
+ try {
7234
+ real = import_node_fs.default.realpathSync.native(candidate);
7235
+ } catch {
7236
+ throw new CliError(`cwd does not exist: ${candidate}`, "NOT_FOUND", exitCodes.NOT_FOUND);
7237
+ }
7238
+ if (!isWithin(root, real)) {
7239
+ throw outsideProject(
7240
+ candidate,
7241
+ root,
7242
+ "resolves (via symlink) outside the configured BLOX project"
7243
+ );
7244
+ }
7245
+ const found = findProjectDir(real);
7246
+ if (!found || resolveContext(found).workspaceRoot !== root) {
7247
+ throw outsideProject(candidate, root, "belongs to a different BLOX project");
7248
+ }
7249
+ return real;
7250
+ }
7251
+ function resolveMcpContext(input) {
7252
+ const cwd2 = import_node_path32.default.resolve(input.cwd);
7253
+ if (!findProjectDir(cwd2)) {
7254
+ throw new CliError(
7255
+ `No BLOX project found for ${cwd2}`,
7256
+ "NO_PROJECT",
7257
+ exitCodes.NOT_FOUND,
7258
+ "Pass `cwd` inside the configured BLOX project, or omit it."
7259
+ );
7260
+ }
7261
+ return { context: resolveContext(cwd2, input.app), cwd: cwd2 };
7262
+ }
7263
+
7264
+ // src/mcp/operations/utils.ts
7265
+ var import_node_path33 = __toESM(require("path"));
7266
+ var lifecycleHooks = ["init", "add", "update", "remove"];
7267
+ function toPosixPath(root, target) {
7268
+ return import_node_path33.default.relative(root, target).split(import_node_path33.default.sep).join("/");
7269
+ }
7270
+ function lifecycleHookNames(def) {
7271
+ if (!def) return [];
7272
+ return lifecycleHooks.filter((hook) => typeof def[hook] === "string" && !!def[hook]?.trim());
7273
+ }
7274
+ function summarizeTemplateDef(def) {
7275
+ if (!def?.name) return null;
7276
+ return {
7277
+ name: def.name,
7278
+ version: def.version ?? null,
7279
+ bases: (def.bases ?? []).map((base) => ({
7280
+ name: base.name,
7281
+ version: base.version ?? null
7282
+ })),
7283
+ lifecycleHooks: lifecycleHookNames(def),
7284
+ ..."dependencies" in def ? {
7285
+ dependencies: (def.dependencies ?? []).map((dep) => ({
7286
+ name: dep.name,
7287
+ version: dep.version ?? null
7288
+ })),
7289
+ templates: (def.templates ?? []).map((dep) => ({
7290
+ name: dep.name,
7291
+ version: dep.version ?? null
7292
+ }))
7293
+ } : {}
7294
+ };
7295
+ }
7296
+ function installedBlockSummaries(projectDir) {
7297
+ return getUsedBlockEntries(projectDir).map((entry) => {
7298
+ const def = entry.file.definition;
7299
+ const name = def?.name;
7300
+ if (!name) return null;
7301
+ const checkpoint = entry.file.checkpoints?.[name];
7302
+ return {
7303
+ name,
7304
+ path: toPosixPath(projectDir, entry.dir),
7305
+ version: checkpoint?.version ?? def?.version ?? null,
7306
+ checkpoint: checkpoint ?? null,
7307
+ dependencies: (def?.dependencies ?? []).map((dep) => dep.name),
7308
+ templates: (def?.templates ?? []).map((dep) => dep.name)
7309
+ };
7310
+ }).filter((block) => block !== null);
7311
+ }
7312
+ function resolveBlockRefs(args, toolName) {
7313
+ const names = [];
7314
+ for (const arg of args) {
7315
+ const ref = parseQualifiedRef(arg);
7316
+ if (ref.type && ref.type !== "block") {
7317
+ throw new CliError(
7318
+ `${toolName} only supports blocks; got "${arg}"`,
7319
+ "VALIDATION",
7320
+ exitCodes.USAGE,
7321
+ "Use an unqualified block name or block/<name>. Application tools are not available yet."
7322
+ );
7115
7323
  }
7116
- paths2.push(import_node_path32.default.relative(projectDir, abs));
7324
+ names.push(ref.name);
7117
7325
  }
7118
- return paths2;
7326
+ return [...new Set(names)];
7119
7327
  }
7120
- function dependentBlocksRoots2(context) {
7121
- return [import_node_path32.default.join(context.projectDir, blocksDir)];
7328
+ function resolveUpdateBlockRefs(input) {
7329
+ const scope = input.scope ?? "all";
7330
+ const blocks = input.blocks?.length ? resolveBlockRefs(input.blocks, "update_project") : void 0;
7331
+ if (blocks && scope !== "block") {
7332
+ throw new CliError(
7333
+ 'blocks is only valid when scope is "block"',
7334
+ "VALIDATION",
7335
+ exitCodes.USAGE,
7336
+ 'Omit blocks, or set scope to "block".'
7337
+ );
7338
+ }
7339
+ if (scope === "block" && !blocks?.length) {
7340
+ throw new CliError(
7341
+ 'blocks is required when scope is "block"',
7342
+ "VALIDATION",
7343
+ exitCodes.USAGE,
7344
+ "Pass at least one block name, or choose another update scope."
7345
+ );
7346
+ }
7347
+ return blocks;
7122
7348
  }
7123
- function getInstalledSelectOptions(context) {
7124
- const blocksRoot = import_node_path32.default.join(context.projectDir, blocksDir);
7125
- const options = listInstalledBlockRelPaths(blocksRoot, context.projectDir).map((rel) => {
7126
- const folder = import_node_path32.default.basename(rel);
7127
- const def = getBlockDef(import_node_path32.default.join(context.projectDir, rel));
7128
- const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
7129
- return { value: `block/${folder}`, label: `block/${label}`, hint: def?.name };
7349
+
7350
+ // src/mcp/operations/add.ts
7351
+ var message = (error2) => error2 instanceof Error ? error2.message : String(error2);
7352
+ async function addBlocksOperation(input) {
7353
+ const { context } = resolveMcpContext(input);
7354
+ if (await git.hasUncommittedChanges(context.projectDir)) {
7355
+ throw new CliError(
7356
+ "Make sure to commit any changes first",
7357
+ "DIRTY_WORKING_TREE",
7358
+ exitCodes.GENERAL
7359
+ );
7360
+ }
7361
+ await migrateAll(false, context.workspaceRoot);
7362
+ await syncRegistries(void 0, { force: input.refresh });
7363
+ const rootTemplateDef = getTemplateDef(context.workspaceRoot);
7364
+ const rootTemplateName = rootTemplateDef?.name || "";
7365
+ let blocks;
7366
+ if (context.app) {
7367
+ const appDef = getTemplateDef(context.projectDir);
7368
+ blocks = await getAvailableBlocks(appDef);
7369
+ } else {
7370
+ blocks = rootTemplateName ? await getAvailableBlocks(rootTemplateDef) : {};
7371
+ }
7372
+ const scope = createAddScope(context.projectDir, blocks, { app: context.app });
7373
+ const names = resolveBlockRefs(input.blocks, "add_blocks");
7374
+ const results = await addBlocks(names, scope, input.branch, input.destination, {
7375
+ replace: input.replace,
7376
+ rewriteDeps: input.rewriteDeps
7130
7377
  });
7131
- if (!context.app) {
7132
- for (const app of listApps(context.workspaceRoot)) {
7133
- options.push({ value: `app/${app.key}`, label: `app/${app.key}`, hint: app.def?.name });
7378
+ const addedOrWarning = results.some(
7379
+ (result) => result.status === "added" || result.status === "warning"
7380
+ );
7381
+ let templateAddHook = { status: "skipped" };
7382
+ if (addedOrWarning) {
7383
+ try {
7384
+ await runLifecycleHookWithTask(context.projectDir, "add", "Run template add");
7385
+ templateAddHook = { status: "ran" };
7386
+ } catch (error2) {
7387
+ templateAddHook = { status: "failed", error: message(error2) };
7134
7388
  }
7135
7389
  }
7136
- return options;
7390
+ let compatibility = { status: "skipped" };
7391
+ try {
7392
+ await checkVersionsCompatibility(context.projectDir);
7393
+ compatibility = { status: "passed" };
7394
+ } catch (error2) {
7395
+ compatibility = { status: "failed", error: message(error2) };
7396
+ }
7397
+ return {
7398
+ ok: !results.some((result) => result.status === "failed") && templateAddHook.status !== "failed" && compatibility.status !== "failed",
7399
+ context: contextSummary(context),
7400
+ results,
7401
+ templateAddHook,
7402
+ compatibility
7403
+ };
7137
7404
  }
7138
- function assertNoDependents(blockPathAbs, targetBlockName, roots) {
7139
- for (const root of roots) {
7140
- if (!import_fs_extra28.default.existsSync(root)) continue;
7141
- for (const entry of import_fs_extra28.default.readdirSync(root, { withFileTypes: true })) {
7142
- if (!entry.isDirectory()) continue;
7143
- const abs = import_node_path32.default.join(root, entry.name);
7144
- if (abs === blockPathAbs) continue;
7145
- const def = getBlockDef(abs);
7146
- for (const dep of def.dependencies || []) {
7147
- if (dep.name === targetBlockName) {
7148
- throw new Error(
7149
- `Cannot remove "${targetBlockName}": block "${def.name}" declares a dependency on it. Remove that dependency or the dependent block first.`
7150
- );
7405
+
7406
+ // src/mcp/operations/doctor.ts
7407
+ async function runDoctorOperation(input) {
7408
+ const { context } = resolveMcpContext({ cwd: input.cwd });
7409
+ const report = await runDoctor(doctorChecks, {
7410
+ projectRoot: context.workspaceRoot,
7411
+ fixMode: input.fix ?? false
7412
+ });
7413
+ const exitCode = getDoctorExitCode(report);
7414
+ return {
7415
+ ok: exitCode === 0,
7416
+ context: contextSummary(context),
7417
+ projectRoot: context.workspaceRoot,
7418
+ fixMode: input.fix ?? false,
7419
+ report,
7420
+ exitCode
7421
+ };
7422
+ }
7423
+
7424
+ // src/mcp/operations/plan.ts
7425
+ var import_semver2 = __toESM(require("semver"));
7426
+ function planComponent(base, checkpoint, versions, inRegistry) {
7427
+ const currentCommit = checkpoint?.commit ?? null;
7428
+ const empty = {
7429
+ ...base,
7430
+ currentCommit,
7431
+ currentVersion: null,
7432
+ targetVersion: null,
7433
+ targetCommit: null,
7434
+ breaking: false
7435
+ };
7436
+ if (!inRegistry) {
7437
+ return { ...empty, status: "missing", reason: "Not found in configured registries." };
7438
+ }
7439
+ if (!currentCommit) {
7440
+ return {
7441
+ ...empty,
7442
+ status: "unknown",
7443
+ reason: "No checkpoint recorded; update is skipped."
7444
+ };
7445
+ }
7446
+ const labels = Object.keys(versions ?? {});
7447
+ const currentVersion = labels.find((label) => versions[label]?.lastCommit === currentCommit) ?? null;
7448
+ const targetVersion = labels.filter((label) => import_semver2.default.valid(label)).sort(import_semver2.default.rcompare)[0] ?? null;
7449
+ const targetCommit = targetVersion ? versions[targetVersion]?.lastCommit ?? null : null;
7450
+ if (!targetVersion || !targetCommit) {
7451
+ return {
7452
+ ...empty,
7453
+ currentVersion,
7454
+ status: "unknown",
7455
+ reason: "No versioned releases in the registry; the update tracks the branch head."
7456
+ };
7457
+ }
7458
+ const planned = { ...empty, currentVersion, targetVersion, targetCommit };
7459
+ if (targetCommit === currentCommit) return { ...planned, status: "up-to-date" };
7460
+ if (!currentVersion) {
7461
+ return {
7462
+ ...planned,
7463
+ status: "unknown",
7464
+ reason: "Current commit is not a registry release; git history decides whether it is older."
7465
+ };
7466
+ }
7467
+ if (import_semver2.default.valid(currentVersion) && import_semver2.default.gte(currentVersion, targetVersion)) {
7468
+ return { ...planned, status: "up-to-date" };
7469
+ }
7470
+ return {
7471
+ ...planned,
7472
+ status: "update-available",
7473
+ breaking: !!import_semver2.default.valid(currentVersion) && import_semver2.default.major(targetVersion) > import_semver2.default.major(currentVersion)
7474
+ };
7475
+ }
7476
+ async function safeDirty(dir) {
7477
+ try {
7478
+ return await git.hasUncommittedChanges(dir);
7479
+ } catch {
7480
+ return null;
7481
+ }
7482
+ }
7483
+ async function planUpdateOperation(input) {
7484
+ const { context } = resolveMcpContext(input);
7485
+ const scope = input.scope ?? "all";
7486
+ const blocks = resolveUpdateBlockRefs(input);
7487
+ await syncRegistries(void 0, { force: input.refresh });
7488
+ const templates = await getAvailableTemplates();
7489
+ const rootTemplateName = getTemplateDef(context.workspaceRoot).name;
7490
+ const scopes = context.app ? [{ dir: context.projectDir, app: context.app }] : [
7491
+ { dir: context.workspaceRoot, app: void 0 },
7492
+ ...listApps(context.workspaceRoot).map((app2) => ({ dir: app2.dir, app: app2.key }))
7493
+ ];
7494
+ const versionsFor = (source) => source ? getAvailableVersions(source) : Promise.resolve(void 0);
7495
+ const components = [];
7496
+ const dirtyScopes = [];
7497
+ for (const scopeDir of scopes) {
7498
+ const label = scopeDir.app ?? "(root)";
7499
+ if (await safeDirty(scopeDir.dir)) dirtyScopes.push(label);
7500
+ const bloxFile = getBloxFile(scopeDir.dir);
7501
+ const templateDef = getTemplateDef(scopeDir.dir);
7502
+ const checkpoints = bloxFile.checkpoints ?? {};
7503
+ if (scope === "app" || scope === "all") {
7504
+ const source = templates[templateDef.name]?.source ?? (scopeDir.app ? templates[rootTemplateName]?.apps?.[scopeDir.app]?.source : void 0);
7505
+ components.push(
7506
+ planComponent(
7507
+ { scope: label, kind: "template", name: templateDef.name },
7508
+ checkpoints[templateDef.name],
7509
+ await versionsFor(source),
7510
+ !!source
7511
+ )
7512
+ );
7513
+ }
7514
+ if (scope === "bases" || scope === "all") {
7515
+ for (const base of templateDef.bases ?? []) {
7516
+ const source = templates[base.name]?.source;
7517
+ components.push(
7518
+ planComponent(
7519
+ { scope: label, kind: "base", name: base.name },
7520
+ checkpoints[base.name],
7521
+ await versionsFor(source),
7522
+ !!source
7523
+ )
7524
+ );
7525
+ }
7526
+ }
7527
+ if (scope === "block" || scope === "all") {
7528
+ const availableBlocks = await getAvailableBlocks(templateDef);
7529
+ const requested = scope === "block" ? new Set(blocks ?? []) : void 0;
7530
+ for (const entry of getUsedBlockEntries(scopeDir.dir)) {
7531
+ const def = entry.file.definition;
7532
+ if (!def?.name || requested && !requested.has(def.name)) continue;
7533
+ const source = availableBlocks[def.name]?.source;
7534
+ components.push({
7535
+ ...planComponent(
7536
+ { scope: label, kind: "block", name: def.name },
7537
+ entry.file.checkpoints?.[def.name],
7538
+ await versionsFor(source),
7539
+ !!source
7540
+ ),
7541
+ path: toPosixPath(context.workspaceRoot, entry.dir)
7542
+ });
7543
+ }
7544
+ if (requested) {
7545
+ const found = new Set(
7546
+ components.filter((component) => component.scope === label).map((component) => component.name)
7547
+ );
7548
+ for (const name of requested) {
7549
+ if (found.has(name)) continue;
7550
+ components.push({
7551
+ ...planComponent(
7552
+ { scope: label, kind: "block", name },
7553
+ void 0,
7554
+ void 0,
7555
+ false
7556
+ ),
7557
+ reason: "Block is not installed in this scope."
7558
+ });
7151
7559
  }
7152
7560
  }
7153
7561
  }
7154
7562
  }
7563
+ const count = (status) => components.filter((component) => component.status === status).length;
7564
+ const breaking = components.filter((component) => component.breaking).map((c) => c.name);
7565
+ const missingRequestedBlocks = scope === "block" ? components.filter(
7566
+ (component) => component.kind === "block" && component.status === "missing" && component.reason === "Block is not installed in this scope."
7567
+ ) : [];
7568
+ const blockers = [
7569
+ ...dirtyScopes.length ? [`Uncommitted changes in: ${dirtyScopes.join(", ")}. Commit before updating.`] : [],
7570
+ ...breaking.length && !input.allowBreaking ? [`Breaking updates (${breaking.join(", ")}) are skipped unless allowBreaking=true.`] : [],
7571
+ ...missingRequestedBlocks.map(
7572
+ (component) => `Block "${component.name}" is not installed in scope "${component.scope}"; scope=block requires it in every selected scope.`
7573
+ )
7574
+ ];
7575
+ return {
7576
+ ok: blockers.length === 0,
7577
+ dryRun: true,
7578
+ context: contextSummary(context),
7579
+ scope,
7580
+ components,
7581
+ summary: {
7582
+ updateAvailable: count("update-available"),
7583
+ upToDate: count("up-to-date"),
7584
+ unknown: count("unknown"),
7585
+ missing: count("missing"),
7586
+ breaking
7587
+ },
7588
+ blockers,
7589
+ note: 'Estimated from the registry versions index without fetching git history. Components marked "unknown" are resolved by the real update.'
7590
+ };
7591
+ }
7592
+
7593
+ // src/mcp/operations/project.ts
7594
+ async function safeDirty2(cwd2) {
7595
+ try {
7596
+ return await git.hasUncommittedChanges(cwd2);
7597
+ } catch {
7598
+ return null;
7599
+ }
7600
+ }
7601
+ async function getProjectContext(input) {
7602
+ const { context } = resolveMcpContext(input);
7603
+ const bloxFile = getBloxFile(context.projectDir);
7604
+ const projectDirty = await safeDirty2(context.projectDir);
7605
+ const workspaceDirty = context.workspaceRoot === context.projectDir ? projectDirty : await safeDirty2(context.workspaceRoot);
7606
+ return {
7607
+ ok: true,
7608
+ context: contextSummary(context),
7609
+ project: {
7610
+ schemaVersion: bloxFile.schemaVersion ?? null
7611
+ },
7612
+ template: summarizeTemplateDef(bloxFile.definition),
7613
+ apps: await Promise.all(
7614
+ listApps(context.workspaceRoot).map(async (app2) => ({
7615
+ key: app2.key,
7616
+ projectDir: app2.dir,
7617
+ template: summarizeTemplateDef(app2.def),
7618
+ dirty: await safeDirty2(app2.dir)
7619
+ }))
7620
+ ),
7621
+ installedBlocks: installedBlockSummaries(context.projectDir),
7622
+ git: {
7623
+ projectDirty,
7624
+ workspaceDirty
7625
+ }
7626
+ };
7627
+ }
7628
+
7629
+ // src/services/remove.ts
7630
+ var import_node_path34 = __toESM(require("path"));
7631
+ var import_fs_extra28 = __toESM(require("fs-extra"));
7632
+ var hasHook = (def) => typeof def?.remove === "string" && !!def.remove.trim();
7633
+ function relativeToProject(context, target) {
7634
+ return normalizePath(import_node_path34.default.relative(context.projectDir, target));
7155
7635
  }
7156
7636
  function assertUnderBlocksRoot(blockPathAbs, blocksRootAbs) {
7157
- const rel = import_node_path32.default.relative(blocksRootAbs, blockPathAbs);
7158
- if (!rel || rel.startsWith("..") || import_node_path32.default.isAbsolute(rel)) {
7637
+ const rel = import_node_path34.default.relative(blocksRootAbs, blockPathAbs);
7638
+ if (!rel || rel.startsWith("..") || import_node_path34.default.isAbsolute(rel)) {
7159
7639
  throw new Error("Block path escapes the blocks directory");
7160
7640
  }
7161
7641
  }
7162
- async function removeBlock(block, blocks, context, force = false) {
7642
+ function findDependents2(context, blockPathAbs, targetBlockName) {
7643
+ const root = import_node_path34.default.join(context.projectDir, blocksDir);
7644
+ if (!import_fs_extra28.default.existsSync(root)) return [];
7645
+ const dependents = [];
7646
+ for (const entry of import_fs_extra28.default.readdirSync(root, { withFileTypes: true })) {
7647
+ if (!entry.isDirectory()) continue;
7648
+ const abs = import_node_path34.default.join(root, entry.name);
7649
+ if (abs === blockPathAbs || !isBlockDirectory(abs)) continue;
7650
+ const def = getBlockDef(abs);
7651
+ if ((def?.dependencies || []).some((dep) => dep.name === targetBlockName)) {
7652
+ dependents.push(def.name);
7653
+ }
7654
+ }
7655
+ return dependents;
7656
+ }
7657
+ function planBlockRemoval(block, blocks, context) {
7163
7658
  const reg = blocks[block];
7164
7659
  const destination = reg ? reg.destination ?? block : block;
7165
- const blocksRoot = import_node_path32.default.join(context.projectDir, blocksDir);
7166
- const blockPathAbs = import_node_path32.default.resolve(blocksRoot, destination);
7660
+ const blocksRoot = import_node_path34.default.join(context.projectDir, blocksDir);
7661
+ const blockPathAbs = import_node_path34.default.resolve(blocksRoot, destination);
7167
7662
  assertUnderBlocksRoot(blockPathAbs, blocksRoot);
7168
7663
  if (!import_fs_extra28.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
7169
- throw new Error(`Block is not installed at ${import_node_path32.default.relative(process.cwd(), blockPathAbs)}`);
7664
+ throw new Error(
7665
+ `Block is not installed at ${relativeToProject(context, blockPathAbs)}`
7666
+ );
7170
7667
  }
7171
7668
  const targetDef = getBlockDef(blockPathAbs);
7172
7669
  if (!targetDef?.name) {
7173
7670
  throw new Error("Invalid block: missing name in .blox definition");
7174
7671
  }
7175
- if (!force) {
7176
- assertNoDependents(blockPathAbs, targetDef.name, dependentBlocksRoots2(context));
7672
+ return {
7673
+ block,
7674
+ name: targetDef.name,
7675
+ dir: blockPathAbs,
7676
+ path: relativeToProject(context, blockPathAbs),
7677
+ dependents: findDependents2(context, blockPathAbs, targetDef.name),
7678
+ hasRemoveHook: hasHook(targetDef)
7679
+ };
7680
+ }
7681
+ function templateHasRemoveHook(context) {
7682
+ return hasHook(getTemplateDef(context.projectDir));
7683
+ }
7684
+ async function removeBlock(block, blocks, context, force = false) {
7685
+ const plan = planBlockRemoval(block, blocks, context);
7686
+ if (!force && plan.dependents.length) {
7687
+ throw new Error(
7688
+ `Cannot remove "${plan.name}": block "${plan.dependents[0]}" declares a dependency on it. Remove that dependency or the dependent block first.`
7689
+ );
7177
7690
  }
7178
- await runLifecycleHookWithTask(blockPathAbs, "remove", "Run block remove");
7691
+ await runLifecycleHookWithTask(plan.dir, "remove", "Run block remove");
7692
+ const blocksRoot = import_node_path34.default.join(context.projectDir, blocksDir);
7179
7693
  await runTask("Remove block files", async () => {
7180
- assertUnderBlocksRoot(blockPathAbs, blocksRoot);
7181
- await import_fs_extra28.default.remove(blockPathAbs);
7694
+ assertUnderBlocksRoot(plan.dir, blocksRoot);
7695
+ await import_fs_extra28.default.remove(plan.dir);
7182
7696
  });
7183
7697
  return true;
7184
7698
  }
7185
7699
  async function removeApp(appKey, context, dirtyApps) {
7186
- const appPath = import_node_path32.default.join(context.workspaceRoot, appsDir, appKey);
7187
- if (!import_fs_extra28.default.existsSync(import_node_path32.default.join(appPath, ".blox"))) {
7188
- throw new Error(`Application is not installed at ${import_node_path32.default.relative(process.cwd(), appPath)}`);
7700
+ const appPath = import_node_path34.default.join(context.workspaceRoot, appsDir, appKey);
7701
+ if (!import_fs_extra28.default.existsSync(import_node_path34.default.join(appPath, ".blox"))) {
7702
+ throw new Error(
7703
+ `Application is not installed at ${normalizePath(import_node_path34.default.relative(context.workspaceRoot, appPath))}`
7704
+ );
7189
7705
  }
7190
7706
  if (dirtyApps.has(appKey)) {
7191
7707
  throw new CliError(
@@ -7202,291 +7718,300 @@ async function removeApp(appKey, context, dirtyApps) {
7202
7718
  removeAppIgnore(context.workspaceRoot, appKey);
7203
7719
  return true;
7204
7720
  }
7205
- var remove = addExecutionOptions(
7206
- command("remove").description("Remove block from app").alias("rm").argument(
7207
- "[blocks...]",
7208
- "Components to remove (registry key, installed folder name, app/<name>, or block/<name>)"
7209
- ).option("--app <name>", "Scope to an application under apps/").option("-f, --force", "Remove even if other blocks declare a dependency on this block").addHelpText(
7210
- "after",
7211
- `
7212
- Non-interactive usage:
7213
- blox remove block-a --non-interactive
7214
- blox remove app/web --non-interactive
7215
- blox remove auth --app web --non-interactive
7216
- blox remove block-a block-b --json # JSON result on stdout
7217
7721
 
7218
- In non-interactive mode (--non-interactive or a non-TTY stdin) component
7219
- arguments are required; nothing is prompted. Use app/<name> to remove an
7220
- application at workspace root, or --app <name> to remove blocks inside
7221
- that application. --json only controls the output format and can be
7222
- combined with either mode.`
7223
- )
7224
- ).action(async (selectedBlocks, args) => {
7225
- initExecutionMode(args);
7226
- const { force } = args;
7227
- let projectDir = ".";
7228
- try {
7229
- const context = resolveContext(".", args.app);
7230
- projectDir = context.projectDir;
7231
- if (await git.hasUncommittedChanges(context.projectDir)) {
7232
- if (isNonInteractive()) {
7233
- throw new CliError(
7234
- "Make sure to commit any changes first",
7235
- "DIRTY_WORKING_TREE",
7236
- exitCodes.GENERAL
7237
- );
7238
- }
7239
- import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
7240
- return;
7722
+ // src/mcp/operations/remove.ts
7723
+ var message2 = (error2) => error2 instanceof Error ? error2.message : String(error2);
7724
+ function planRemovals(names, blocks, context, force) {
7725
+ const removedEarlier = /* @__PURE__ */ new Set();
7726
+ const planned = [];
7727
+ const plans = [];
7728
+ for (const block of names) {
7729
+ let plan;
7730
+ try {
7731
+ plan = planBlockRemoval(block, blocks, context);
7732
+ } catch (error2) {
7733
+ planned.push({
7734
+ block,
7735
+ status: "not-installed",
7736
+ name: null,
7737
+ path: null,
7738
+ dependents: [],
7739
+ hasRemoveHook: false,
7740
+ reason: message2(error2)
7741
+ });
7742
+ continue;
7241
7743
  }
7242
- const dirtyApps = /* @__PURE__ */ new Set();
7243
- for (const app of listApps(context.workspaceRoot)) {
7244
- if (await git.hasUncommittedChanges(app.dir)) dirtyApps.add(app.key);
7744
+ const dependents = plan.dependents.filter((dep) => !removedEarlier.has(dep));
7745
+ const blocked = dependents.length > 0 && !force;
7746
+ planned.push({
7747
+ block,
7748
+ status: blocked ? "blocked" : "removable",
7749
+ name: plan.name,
7750
+ path: plan.path,
7751
+ dependents,
7752
+ hasRemoveHook: plan.hasRemoveHook,
7753
+ ...blocked ? {
7754
+ reason: `Required by ${dependents.join(", ")}. Remove those first (list them earlier in blocks), or pass force=true with the user's consent.`
7755
+ } : {}
7756
+ });
7757
+ if (!blocked) {
7758
+ plans.push(plan);
7759
+ removedEarlier.add(plan.name);
7245
7760
  }
7246
- await migrateAll(false, context.workspaceRoot);
7247
- await syncRegistries();
7248
- const templateDef = getTemplateDef(context.projectDir);
7249
- const blocks = await getAvailableBlocks(templateDef);
7250
- let componentsToRemove = Array.isArray(selectedBlocks) ? selectedBlocks : [];
7251
- if (!componentsToRemove.length) {
7252
- const options = getInstalledSelectOptions(context);
7253
- if (!options.length) {
7254
- throw new CliError(
7255
- context.app ? `No installed blocks found under ${args.app}/blocks/` : "No installed blocks or applications found",
7256
- "NOT_FOUND",
7257
- exitCodes.NOT_FOUND
7258
- );
7259
- }
7260
- if (isNonInteractive()) {
7261
- throw new MissingArgumentsError(["blocks"]);
7262
- }
7263
- componentsToRemove = await multiselect({
7264
- message: "Select components to remove",
7265
- options
7266
- });
7267
- }
7268
- if (!componentsToRemove.length) {
7269
- throw new CliError("No components selected", "VALIDATION", exitCodes.USAGE);
7270
- }
7271
- const installedApps = new Set(
7272
- context.app ? [] : listApps(context.workspaceRoot).map((app) => app.key)
7761
+ }
7762
+ return { planned, plans };
7763
+ }
7764
+ async function removeBlocksOperation(input) {
7765
+ const { context } = resolveMcpContext(input);
7766
+ const names = resolveBlockRefs(input.blocks, "remove_blocks");
7767
+ const force = input.force ?? false;
7768
+ const dirty = await git.hasUncommittedChanges(context.projectDir).catch(() => null);
7769
+ if (dirty !== false && !input.dryRun) {
7770
+ throw new CliError(
7771
+ dirty ? "Make sure to commit any changes first" : "Could not verify that the working tree is clean (is this a git repository?)",
7772
+ "DIRTY_WORKING_TREE",
7773
+ exitCodes.GENERAL,
7774
+ "remove_blocks only runs on a clean git working tree so every removal can be restored."
7273
7775
  );
7274
- if (force) {
7275
- import_prompts2.log.warn(
7276
- fmt.yellow(
7277
- "--force: skipping dependency check; dependent blocks may be left in a broken state."
7278
- )
7279
- );
7280
- }
7281
- const removed = [];
7282
- for (const arg of componentsToRemove) {
7283
- const ref = parseQualifiedRef(arg);
7284
- if (ref.type === "app") {
7285
- if (context.app) {
7286
- throw new CliError(
7287
- `Cannot remove an application inside application "${context.app}"`,
7288
- "VALIDATION",
7289
- exitCodes.USAGE
7290
- );
7291
- }
7292
- if (await removeApp(ref.name, context, dirtyApps)) {
7293
- removed.push(arg);
7294
- }
7295
- continue;
7296
- }
7297
- if (!ref.type && installedApps.has(ref.name)) {
7298
- const blocksRoot = import_node_path32.default.join(context.projectDir, blocksDir);
7299
- const isBlock = import_fs_extra28.default.existsSync(import_node_path32.default.join(blocksRoot, ref.name));
7300
- if (!isBlock) {
7301
- if (await removeApp(ref.name, context, dirtyApps)) {
7302
- removed.push(arg);
7303
- }
7304
- continue;
7305
- }
7306
- }
7307
- const blockRemoved = await removeBlock(ref.name, blocks, context, force);
7308
- if (blockRemoved) {
7309
- removed.push(arg);
7310
- }
7311
- }
7312
- if (removed.length) {
7313
- await runLifecycleHookWithTask(context.projectDir, "remove", "Run template remove");
7314
- }
7315
- if (!force) {
7316
- await checkVersionsCompatibility(context.projectDir);
7317
- }
7318
- if (isJsonMode()) {
7319
- printJsonResult({ removed });
7320
- }
7321
- } catch (e) {
7322
- if (!isDebugMode() && !(e instanceof CliError)) {
7323
- import_prompts2.log.warn("Error happened, Will rollback changes");
7324
- await git.rollback(projectDir);
7325
- }
7326
- handleCommandError(e);
7327
7776
  }
7328
- });
7329
-
7330
- // src/commands/skills/index.ts
7331
- var import_node_crypto2 = require("crypto");
7332
- var import_node_os4 = __toESM(require("os"));
7333
- var import_node_path34 = __toESM(require("path"));
7334
- var import_cross_spawn2 = __toESM(require("cross-spawn"));
7335
- var import_fs_extra30 = __toESM(require("fs-extra"));
7336
-
7337
- // src/commands/skills/constants.ts
7338
- var SKILLS_REPO_URL = "https://github.com/Naseej-its/blox.git";
7339
-
7340
- // src/commands/skills/utils/cliCompatibility.ts
7341
- var import_node_path33 = __toESM(require("path"));
7342
- var import_fs_extra29 = __toESM(require("fs-extra"));
7343
- var import_semver2 = __toESM(require("semver"));
7344
- var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
7345
- function getSkillscommandIndex(args, subcommand) {
7346
- for (let i = 0; i < args.length; i++) {
7347
- if (args[i] !== subcommand) {
7348
- continue;
7349
- }
7350
- if (args.slice(0, i).every((t) => t.startsWith("-"))) {
7351
- return i;
7777
+ if (!input.dryRun) await migrateAll(false, context.workspaceRoot);
7778
+ await syncRegistries(void 0, { force: input.refresh });
7779
+ const blocks = await getAvailableBlocks(getTemplateDef(context.projectDir));
7780
+ const { planned, plans } = planRemovals(names, blocks, context, force);
7781
+ const problems = planned.filter((item) => item.status !== "removable");
7782
+ if (input.dryRun) {
7783
+ return {
7784
+ ok: problems.length === 0 && dirty === false,
7785
+ dryRun: true,
7786
+ context: contextSummary(context),
7787
+ blocks: planned,
7788
+ templateRemoveHook: templateHasRemoveHook(context),
7789
+ blockers: [
7790
+ ...dirty === false ? [] : ["Uncommitted changes (or no git repository). Commit before removing."],
7791
+ ...problems.map((item) => `${item.block}: ${item.reason}`)
7792
+ ]
7793
+ };
7794
+ }
7795
+ if (problems.length) {
7796
+ throw new CliError(
7797
+ `Nothing was removed: ${problems.map((item) => `${item.block} (${item.status})`).join(", ")}`,
7798
+ "VALIDATION",
7799
+ exitCodes.USAGE,
7800
+ "Call remove_blocks with dryRun=true to see each problem.",
7801
+ { blocks: planned }
7802
+ );
7803
+ }
7804
+ const removed = [];
7805
+ try {
7806
+ for (const plan of plans) {
7807
+ await removeBlock(plan.block, blocks, context, force);
7808
+ removed.push(plan.name);
7352
7809
  }
7810
+ await runLifecycleHookWithTask(context.projectDir, "remove", "Run template remove");
7811
+ if (!force) await checkVersionsCompatibility(context.projectDir);
7812
+ } catch (error2) {
7813
+ await git.rollback(context.projectDir);
7814
+ throw new CliError(
7815
+ `Removal failed and was rolled back: ${message2(error2)}`,
7816
+ "REMOVE_FAILED",
7817
+ exitCodes.GENERAL,
7818
+ "The project was restored to its last commit. Fix the cause (often a lifecycle hook) and retry.",
7819
+ { attempted: plans.map((plan) => plan.name), removedBeforeFailure: removed }
7820
+ );
7353
7821
  }
7354
- return -1;
7822
+ return {
7823
+ ok: true,
7824
+ context: contextSummary(context),
7825
+ removed: plans.map((plan) => ({ block: plan.block, name: plan.name, path: plan.path })),
7826
+ force
7827
+ };
7355
7828
  }
7356
- function hasSkillscommand(args, subcommand) {
7357
- return getSkillscommandIndex(args, subcommand) !== -1;
7829
+
7830
+ // src/mcp/operations/registry.ts
7831
+ var import_semver3 = __toESM(require("semver"));
7832
+ async function resolveBlockCatalog(input) {
7833
+ const { context } = resolveMcpContext(input);
7834
+ await syncRegistries(void 0, { force: input.refresh });
7835
+ const templateDef = getTemplateDef(context.projectDir);
7836
+ const blocks = await getAvailableBlocks(templateDef);
7837
+ const installedEntries = getUsedBlockEntries(context.projectDir);
7838
+ return { context, blocks, installedEntries };
7358
7839
  }
7359
- function needsCliCompatibilityCheck(args) {
7360
- return SKILLS_CLI_COMPATIBILITY_COMMANDS.some((cmd) => hasSkillscommand(args, cmd));
7840
+ function entryNames(entry) {
7841
+ const def = entry.file.definition;
7842
+ return [def?.name, ...Object.keys(entry.file.checkpoints || {})].filter(
7843
+ (name) => !!name
7844
+ );
7361
7845
  }
7362
- function getAddCommandIndex(args) {
7363
- return getSkillscommandIndex(args, "add");
7846
+ function findInstalled(entries, name) {
7847
+ return entries.find((entry) => entryNames(entry).includes(name));
7364
7848
  }
7365
- async function loadSkillsData(cloneRoot) {
7366
- const skillsDir = import_node_path33.default.join(cloneRoot, "skills");
7367
- if (!await import_fs_extra29.default.pathExists(skillsDir)) {
7368
- return [];
7849
+ function installedInfo(context, entry, name) {
7850
+ if (!entry) {
7851
+ return { installed: false, path: null, version: null, checkpoint: null };
7369
7852
  }
7370
- const entries = await import_fs_extra29.default.readdir(skillsDir, { withFileTypes: true });
7371
- const manifests = await Promise.all(
7372
- entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
7373
- const filePath = import_node_path33.default.join(skillsDir, entry.name, "skill.json");
7374
- if (!await import_fs_extra29.default.pathExists(filePath)) {
7375
- return null;
7376
- }
7377
- const raw = await import_fs_extra29.default.readJson(filePath);
7378
- const range = raw.cliCompatibility?.trim();
7379
- if (!range) {
7380
- return null;
7381
- }
7382
- return {
7383
- name: raw.name || entry.name,
7384
- version: raw.version || "0.0.0",
7385
- cliCompatibility: range
7386
- };
7387
- })
7388
- );
7389
- return manifests.filter(Boolean);
7853
+ const def = entry.file.definition;
7854
+ const checkpoint = entry.file.checkpoints?.[name];
7855
+ return {
7856
+ installed: true,
7857
+ path: toPosixPath(context.projectDir, entry.dir),
7858
+ version: checkpoint?.version ?? def?.version ?? null,
7859
+ checkpoint: checkpoint ?? null
7860
+ };
7390
7861
  }
7391
- function getFirstIncompatibleSkill(skills2, cliVersion) {
7392
- const normalized = import_semver2.default.coerce(cliVersion)?.version ?? cliVersion;
7393
- return skills2.find((skill) => {
7394
- const range = skill.cliCompatibility;
7395
- return import_semver2.default.validRange(range) && !import_semver2.default.satisfies(normalized, range, {
7396
- includePrerelease: true
7397
- });
7398
- }) || null;
7862
+ async function listInstalledBlocks(input) {
7863
+ const { context } = resolveMcpContext(input);
7864
+ return {
7865
+ ok: true,
7866
+ context: contextSummary(context),
7867
+ blocks: installedBlockSummaries(context.projectDir)
7868
+ };
7399
7869
  }
7400
- function warnIncompatibleSkill(skill, cliVersion) {
7401
- const label = `${skill.name}@${skill.version}`;
7402
- console.log("");
7403
- console.log(
7404
- fmt.yellow(`\u26A0\uFE0F Skill "${label}" may be incompatible with your CLI (${cliVersion})`)
7405
- );
7406
- console.log("");
7407
- console.log(`${fmt.bold("Required:")} ${skill.cliCompatibility}`);
7408
- console.log(`${fmt.bold("Current :")} ${cliVersion}`);
7409
- console.log("");
7410
- console.log(fmt.bold("You can:"));
7411
- console.log(` ${fmt.cyan("\u2022")} Upgrade CLI \u2192 ${fmt.cyan("blox upgrade")}`);
7412
- console.log("");
7870
+ async function listAvailableBlocks(input) {
7871
+ const { context, blocks, installedEntries } = await resolveBlockCatalog(input);
7872
+ const query = input.query?.trim().toLowerCase();
7873
+ const tags = input.tags?.map((tag) => tag.toLowerCase()) ?? [];
7874
+ const available = Object.entries(blocks).map(([name, data]) => {
7875
+ const installedEntry = findInstalled(installedEntries, name);
7876
+ const installedDef = installedEntry?.file.definition;
7877
+ const checkpoint = installedEntry?.file.checkpoints?.[name];
7878
+ return {
7879
+ name,
7880
+ description: data.description ?? null,
7881
+ tags: data.tags ?? [],
7882
+ destination: data.destination ?? null,
7883
+ installed: !!installedEntry,
7884
+ installedVersion: checkpoint?.version ?? installedDef?.version ?? null,
7885
+ ...input.includeSource ? { source: data.source } : {}
7886
+ };
7887
+ }).filter((block) => {
7888
+ if (query) {
7889
+ const haystack = [block.name, block.description ?? "", ...block.tags].join(" ").toLowerCase();
7890
+ if (!haystack.includes(query)) return false;
7891
+ }
7892
+ if (tags.length) {
7893
+ return block.tags.some((tag) => tags.includes(tag.toLowerCase()));
7894
+ }
7895
+ return true;
7896
+ }).sort((a, b) => a.name.localeCompare(b.name));
7897
+ return {
7898
+ ok: true,
7899
+ context: contextSummary(context),
7900
+ blocks: available,
7901
+ count: available.length
7902
+ };
7413
7903
  }
7414
-
7415
- // src/commands/skills/index.ts
7416
- var skills = command("skills").description("Install, update, and manage BLOX CLI skills from internal repositories").helpOption(false).allowUnknownOption(true).action(async () => {
7417
- try {
7418
- const code = await runSkills();
7419
- process.exit(code);
7420
- } catch (e) {
7421
- error(e, false);
7422
- process.exit(1);
7423
- }
7424
- });
7425
- async function runSkills() {
7426
- const idx = process.argv.indexOf("skills");
7427
- const args = idx === -1 ? [] : process.argv.slice(idx + 1);
7428
- if (needsCliCompatibilityCheck(args)) {
7429
- const tempDir = import_node_path34.default.join(import_node_os4.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto2.randomUUID)()}`);
7430
- await import_fs_extra30.default.mkdir(tempDir);
7431
- try {
7432
- await git.clone(SKILLS_REPO_URL, tempDir);
7433
- const skills2 = await loadSkillsData(tempDir);
7434
- const cliVersion = getBloxCliVersion();
7435
- const uncompatibleSkill = getFirstIncompatibleSkill(skills2, cliVersion);
7436
- if (uncompatibleSkill) {
7437
- warnIncompatibleSkill(uncompatibleSkill, cliVersion);
7438
- const proceed = await confirm({
7439
- message: "Continue anyway? (No \u2014 exit and run blox upgrade first)",
7440
- initialValue: false
7441
- });
7442
- if (!proceed) {
7443
- return 1;
7444
- }
7445
- }
7446
- } finally {
7447
- try {
7448
- await import_fs_extra30.default.remove(tempDir);
7449
- } catch {
7450
- debug(`Failed to cleanup temp dir: ${tempDir}`);
7451
- }
7904
+ function compareVersionLabels(a, b) {
7905
+ const aSemver = import_semver3.default.valid(a);
7906
+ const bSemver = import_semver3.default.valid(b);
7907
+ if (aSemver && bSemver) return import_semver3.default.rcompare(a, b);
7908
+ if (aSemver) return -1;
7909
+ if (bSemver) return 1;
7910
+ return a.localeCompare(b);
7911
+ }
7912
+ function versionLabels(versions) {
7913
+ return Object.keys(versions ?? {}).sort(compareVersionLabels);
7914
+ }
7915
+ function selectVersionLabel(versions, requested, blockName) {
7916
+ const labels = versionLabels(versions);
7917
+ if (!labels.length) return void 0;
7918
+ const available = labels.join(", ");
7919
+ if (requested === void 0) {
7920
+ const label = labels.filter((version2) => import_semver3.default.valid(version2)).sort(import_semver3.default.rcompare)[0] ?? labels[labels.length - 1];
7921
+ return { label, def: versions[label] };
7922
+ }
7923
+ if (typeof requested === "string" && labels.includes(requested)) {
7924
+ return { label: requested, def: versions[requested] };
7925
+ }
7926
+ const requestedMajor = typeof requested === "number" ? requested : typeof requested === "string" && /^\d+$/.test(requested) ? Number(requested) : void 0;
7927
+ if (requestedMajor !== void 0) {
7928
+ const candidates = labels.filter(
7929
+ (version2) => import_semver3.default.valid(version2) && import_semver3.default.major(version2) === requestedMajor
7930
+ );
7931
+ const label = candidates.sort(import_semver3.default.rcompare)[0];
7932
+ if (!label) {
7933
+ throw new CliError(
7934
+ `Version ${requestedMajor} is not available for block ${blockName}`,
7935
+ "NOT_FOUND",
7936
+ exitCodes.NOT_FOUND,
7937
+ `Available versions: ${available}`
7938
+ );
7452
7939
  }
7940
+ return { label, def: versions[label] };
7453
7941
  }
7454
- const finalArgs = injectRepoUrlIfAdd(args, SKILLS_REPO_URL);
7455
- return runSkillsCommand(finalArgs, process.cwd());
7456
- }
7457
- function injectRepoUrlIfAdd(args, repoPath) {
7458
- const addIndex = getAddCommandIndex(args);
7459
- if (addIndex === -1) return args;
7460
- const next = args[addIndex + 1];
7461
- if (!next || next.startsWith("-")) {
7462
- return [...args.slice(0, addIndex + 1), repoPath, ...args.slice(addIndex + 1)];
7942
+ const requestedLabel = requested;
7943
+ if (!labels.includes(requestedLabel)) {
7944
+ throw new CliError(
7945
+ `Version "${requestedLabel}" is not available for block ${blockName}`,
7946
+ "NOT_FOUND",
7947
+ exitCodes.NOT_FOUND,
7948
+ `Available versions: ${available}`
7949
+ );
7463
7950
  }
7464
- const updated = [...args];
7465
- updated[addIndex + 1] = repoPath;
7466
- return updated;
7951
+ return { label: requestedLabel, def: versions[requestedLabel] };
7467
7952
  }
7468
- function runSkillsCommand(args, cwd) {
7469
- debug(`npx skills ${args.join(" ")}`);
7470
- return new Promise((resolve, reject) => {
7471
- const child = (0, import_cross_spawn2.default)("npx", ["skills", ...args], {
7472
- cwd,
7473
- stdio: "inherit"
7474
- });
7475
- child.on("error", reject);
7476
- child.on("close", (code) => resolve(code ?? 1));
7477
- });
7953
+ function summarizeVersionDef(def) {
7954
+ if (!def) return null;
7955
+ const blockDef = def;
7956
+ return {
7957
+ version: blockDef.version ?? null,
7958
+ dependencies: (blockDef.dependencies ?? []).map((dep) => ({
7959
+ name: dep.name,
7960
+ version: dep.version ?? null
7961
+ })),
7962
+ templates: (blockDef.templates ?? []).map((dep) => ({
7963
+ name: dep.name,
7964
+ version: dep.version ?? null
7965
+ })),
7966
+ bases: (blockDef.bases ?? []).map((dep) => ({
7967
+ name: dep.name,
7968
+ version: dep.version ?? null
7969
+ })),
7970
+ ignore: blockDef.ignore ?? [],
7971
+ lifecycleHooks: lifecycleHookNames(blockDef),
7972
+ lastCommit: blockDef.lastCommit ?? null
7973
+ };
7974
+ }
7975
+ async function getBlock(input) {
7976
+ const { context, blocks, installedEntries } = await resolveBlockCatalog(input);
7977
+ const registryBlock = blocks[input.name];
7978
+ if (!registryBlock) {
7979
+ const available = Object.keys(blocks).sort();
7980
+ throw new CliError(
7981
+ `Block not found: ${input.name}`,
7982
+ "NOT_FOUND",
7983
+ exitCodes.NOT_FOUND,
7984
+ available.length ? `Available blocks: ${available.slice(0, 50).join(", ")}` : "No blocks are available for this project scope."
7985
+ );
7986
+ }
7987
+ const versions = registryBlock.source ? await getAvailableVersions(registryBlock.source) : void 0;
7988
+ const selected = selectVersionLabel(versions, input.version, input.name);
7989
+ const installedEntry = findInstalled(installedEntries, input.name);
7990
+ return {
7991
+ ok: true,
7992
+ context: contextSummary(context),
7993
+ block: {
7994
+ name: input.name,
7995
+ registry: {
7996
+ description: registryBlock.description ?? null,
7997
+ tags: registryBlock.tags ?? [],
7998
+ destination: registryBlock.destination ?? null,
7999
+ ...input.includeSource ? { source: registryBlock.source } : {}
8000
+ },
8001
+ versions: versionLabels(versions),
8002
+ selectedVersion: selected?.label ?? null,
8003
+ definition: summarizeVersionDef(selected?.def),
8004
+ installed: installedInfo(context, installedEntry, input.name)
8005
+ }
8006
+ };
7478
8007
  }
7479
8008
 
7480
- // src/commands/update/index.ts
7481
- var import_prompts27 = require("@clack/prompts");
7482
-
7483
- // src/commands/update/utils.ts
7484
- var import_node_path37 = __toESM(require("path"));
7485
- var import_fs_extra32 = __toESM(require("fs-extra"));
8009
+ // src/services/updater/updateProject.ts
8010
+ var import_prompts25 = require("@clack/prompts");
7486
8011
 
7487
8012
  // src/services/updater/index.ts
7488
8013
  var import_node_path36 = __toESM(require("path"));
7489
- var import_fs_extra31 = __toESM(require("fs-extra"));
8014
+ var import_fs_extra29 = __toESM(require("fs-extra"));
7490
8015
  var import_klaw3 = __toESM(require("klaw"));
7491
8016
 
7492
8017
  // src/services/updater/utils/formaters.ts
@@ -7642,8 +8167,8 @@ async function updateFromRemote({
7642
8167
  const projectIgnore = bloxFile.project?.ignore || [];
7643
8168
  ignore3.push(...remoteIgnore, ...projectIgnore, bloxFilePath, `**/${bloxFilePath}`);
7644
8169
  const gitIgnorePath = import_node_path36.default.join(dir, ".gitignore");
7645
- if (await import_fs_extra31.default.pathExists(gitIgnorePath)) {
7646
- const gitIgnoreContent = await import_fs_extra31.default.readFile(gitIgnorePath, "utf8");
8170
+ if (await import_fs_extra29.default.pathExists(gitIgnorePath)) {
8171
+ const gitIgnoreContent = await import_fs_extra29.default.readFile(gitIgnorePath, "utf8");
7647
8172
  const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
7648
8173
  ignore3.push(...gitIgnorePatterns);
7649
8174
  debug(`Added ${gitIgnorePatterns.length} patterns from .gitignore`);
@@ -7655,7 +8180,7 @@ async function updateFromRemote({
7655
8180
  if (hard) {
7656
8181
  const getAllFiles = async (d) => {
7657
8182
  const files = [];
7658
- if (await import_fs_extra31.default.pathExists(d)) {
8183
+ if (await import_fs_extra29.default.pathExists(d)) {
7659
8184
  for await (const file of (0, import_klaw3.default)(d)) {
7660
8185
  if (file.path.includes("/.git/") || file.path.endsWith("/.git") || file.path.includes("\\.git\\") || file.path.endsWith("\\.git"))
7661
8186
  continue;
@@ -7684,20 +8209,20 @@ async function updateFromRemote({
7684
8209
  const localPath = import_node_path36.default.join(dir, file);
7685
8210
  const basePath = import_node_path36.default.join(baseDir, file);
7686
8211
  const remotePath = import_node_path36.default.join(remoteDir, file);
7687
- const existsLocal = await import_fs_extra31.default.pathExists(localPath);
7688
- const existsBase = await import_fs_extra31.default.pathExists(basePath);
7689
- const existsRemote = await import_fs_extra31.default.pathExists(remotePath);
8212
+ const existsLocal = await import_fs_extra29.default.pathExists(localPath);
8213
+ const existsBase = await import_fs_extra29.default.pathExists(basePath);
8214
+ const existsRemote = await import_fs_extra29.default.pathExists(remotePath);
7690
8215
  const ext = import_node_path36.default.extname(file);
7691
8216
  const isBinary = isBinaryFile(ext);
7692
8217
  if (existsRemote) {
7693
- await import_fs_extra31.default.ensureDir(import_node_path36.default.dirname(localPath));
8218
+ await import_fs_extra29.default.ensureDir(import_node_path36.default.dirname(localPath));
7694
8219
  }
7695
8220
  if (hard) {
7696
8221
  if (existsRemote) {
7697
- await import_fs_extra31.default.copy(remotePath, localPath, { overwrite: true });
8222
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
7698
8223
  debug(`Hard update: Overwrote ${file}`);
7699
8224
  } else if (existsLocal) {
7700
- await import_fs_extra31.default.remove(localPath);
8225
+ await import_fs_extra29.default.remove(localPath);
7701
8226
  debug(`Hard update: Removed ${file}`);
7702
8227
  }
7703
8228
  continue;
@@ -7706,29 +8231,29 @@ async function updateFromRemote({
7706
8231
  if (existsLocal) {
7707
8232
  if (isBinary) {
7708
8233
  debug(`Binary collision: ${file}, overwriting.`);
7709
- await import_fs_extra31.default.copy(remotePath, localPath, { overwrite: true });
8234
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
7710
8235
  logWarningSection(`Overwrote binary file collision: ${file}`);
7711
8236
  } else {
7712
8237
  const emptyBase = import_node_path36.default.join(baseDir, `${file}.empty`);
7713
- await import_fs_extra31.default.ensureFile(emptyBase);
8238
+ await import_fs_extra29.default.ensureFile(emptyBase);
7714
8239
  const result = await git.mergeFile(localPath, emptyBase, remotePath);
7715
8240
  if (!result) {
7716
8241
  hasConflicts2 = true;
7717
8242
  conflictFiles.push(file);
7718
8243
  }
7719
- await import_fs_extra31.default.remove(emptyBase);
8244
+ await import_fs_extra29.default.remove(emptyBase);
7720
8245
  }
7721
8246
  } else {
7722
- await import_fs_extra31.default.copy(remotePath, localPath);
8247
+ await import_fs_extra29.default.copy(remotePath, localPath);
7723
8248
  }
7724
8249
  continue;
7725
8250
  }
7726
8251
  if (existsBase && !existsRemote) {
7727
8252
  if (existsLocal) {
7728
- const localBuffer = await import_fs_extra31.default.readFile(localPath);
7729
- const baseBuffer = await import_fs_extra31.default.readFile(basePath);
8253
+ const localBuffer = await import_fs_extra29.default.readFile(localPath);
8254
+ const baseBuffer = await import_fs_extra29.default.readFile(basePath);
7730
8255
  if (localBuffer.equals(baseBuffer)) {
7731
- await import_fs_extra31.default.remove(localPath);
8256
+ await import_fs_extra29.default.remove(localPath);
7732
8257
  await pruneEmptyDirs(import_node_path36.default.dirname(localPath), dir);
7733
8258
  } else {
7734
8259
  logWarningSection(
@@ -7740,7 +8265,7 @@ async function updateFromRemote({
7740
8265
  }
7741
8266
  if (existsBase && existsRemote) {
7742
8267
  if (!existsLocal) {
7743
- await import_fs_extra31.default.copy(remotePath, localPath);
8268
+ await import_fs_extra29.default.copy(remotePath, localPath);
7744
8269
  logWarningSection(
7745
8270
  `File restored: ${file}`,
7746
8271
  `This file was deleted locally but updated in the remote block.
@@ -7749,7 +8274,7 @@ It has been recreated to apply upstream changes.`
7749
8274
  continue;
7750
8275
  }
7751
8276
  if (isBinary) {
7752
- await import_fs_extra31.default.copy(remotePath, localPath, { overwrite: true });
8277
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
7753
8278
  logWarningSection(`Updated binary file: ${file} (overwritten)`);
7754
8279
  } else {
7755
8280
  const result = await git.mergeFile(localPath, basePath, remotePath);
@@ -7779,47 +8304,44 @@ ${conflictFiles.map((f) => `- ${f}`).join("\n")}`,
7779
8304
  'Resolve conflicts by rerunning interactively, or use "--hard" to overwrite local changes.'
7780
8305
  );
7781
8306
  }
7782
- await select({
7783
- message: "Please resolve conflicts manually (look for <<<<<<< HEAD) and press enter to continue",
7784
- options: [{ value: true, label: "Resolved" }]
7785
- });
7786
- }
7787
- bloxFile.checkpoints[name] = { commit: toCommit };
7788
- if (bloxFile.definition.name === name) {
7789
- bloxFile.definition = remoteBloxFile.definition;
7790
- } else {
7791
- bloxFile.checkpoints[name].version = remoteBloxFile.definition.version;
7792
- }
7793
- saveBloxFile(bloxFile, dir);
7794
- return toCommit;
7795
- }
7796
-
7797
- // src/commands/update/utils.ts
7798
- function reportUpdateSummary(summary, mode) {
7799
- const failedScopes = (summary.scopes ?? []).filter((scope) => scope.error);
7800
- const failed = summary.failedBlocks.length > 0 || failedScopes.length > 0;
7801
- if (mode.json) {
7802
- if (failed) {
7803
- printJsonError({
7804
- code: summary.failedBlocks.length ? "BLOCK_UPDATE_FAILED" : "UPDATE_FAILED",
7805
- message: [
7806
- ...summary.failedBlocks.map(
7807
- (failure) => `${failure.block}: ${failure.error}`
7808
- ),
7809
- ...failedScopes.map((scope) => `${scope.scope}: ${scope.error}`)
7810
- ].join("; "),
7811
- details: { ...summary },
7812
- exitCode: exitCodes.GENERAL
8307
+ const projectDir = import_node_path36.default.resolve(dir);
8308
+ const instructions = buildUpdateManualInstructions(projectDir);
8309
+ const ides = await detectAvailableIdes();
8310
+ if (ides.length) {
8311
+ const ide = await selectIdeForConflictResolution(ides, projectDir, {
8312
+ message: `Select an editor to open the project and resolve the conflicts in "${name}":`,
8313
+ instructions
7813
8314
  });
8315
+ if (ide) {
8316
+ try {
8317
+ await openPathInIde(ide, projectDir);
8318
+ import_prompts2.log.info(`Opened the project in ${ide.name}.`);
8319
+ } catch (e) {
8320
+ logWarningSection(
8321
+ `Failed to open ${ide.name}: ${e instanceof Error ? e.message : String(e)}`
8322
+ );
8323
+ showManualInstructionsBox(projectDir, instructions);
8324
+ }
8325
+ }
7814
8326
  } else {
7815
- printJsonResult(summary);
8327
+ showManualInstructionsBox(projectDir, instructions);
7816
8328
  }
7817
- return;
8329
+ await select({
8330
+ message: "Resolve the conflicts (look for <<<<<<< HEAD), save the files, then press enter to continue",
8331
+ options: [{ value: true, label: "Resolved" }]
8332
+ });
7818
8333
  }
7819
- if (failed && mode.nonInteractive) {
7820
- process.exitCode = exitCodes.GENERAL;
8334
+ bloxFile.checkpoints[name] = { commit: toCommit };
8335
+ if (bloxFile.definition.name === name) {
8336
+ bloxFile.definition = remoteBloxFile.definition;
8337
+ } else {
8338
+ bloxFile.checkpoints[name].version = remoteBloxFile.definition.version;
7821
8339
  }
8340
+ saveBloxFile(bloxFile, dir);
8341
+ return toCommit;
7822
8342
  }
8343
+
8344
+ // src/services/updater/utils/updateSteps.ts
7823
8345
  var isRecoverableBlockUpdateError = (error2) => {
7824
8346
  if (!(error2 instanceof Error)) return false;
7825
8347
  if (!error2.message.startsWith('Command "git fetch ')) return false;
@@ -8053,49 +8575,17 @@ async function getCurrentCheckpoints(workspaceRoot = ".") {
8053
8575
  return checkpoints2;
8054
8576
  };
8055
8577
  let checkpoints = collect(workspaceRoot);
8056
- for (const app of listApps(workspaceRoot)) {
8057
- checkpoints = { ...checkpoints, ...collect(app.dir, `${app.key}/`) };
8578
+ for (const app2 of listApps(workspaceRoot)) {
8579
+ checkpoints = { ...checkpoints, ...collect(app2.dir, `${app2.key}/`) };
8058
8580
  }
8059
8581
  return checkpoints;
8060
8582
  }
8061
- async function printChangeLog(startCheckpoints, endCheckpoints, workspaceRoot = ".") {
8062
- const allChanges = [];
8063
- const repoDirFor = (name) => {
8064
- const appKey = name.split("/")[0] ?? "";
8065
- const appDir = import_node_path37.default.join(workspaceRoot, appsDir, appKey);
8066
- return name.includes("/") && import_fs_extra32.default.existsSync(import_node_path37.default.join(appDir, bloxFilePath)) ? appDir : workspaceRoot;
8067
- };
8068
- for (const name of Object.keys(startCheckpoints)) {
8069
- const fromCommit = startCheckpoints[name]?.commit;
8070
- const toCommit = endCheckpoints[name]?.commit;
8071
- if (!fromCommit || !toCommit) continue;
8072
- if (fromCommit === toCommit) continue;
8073
- const changes = await git.getChangesLog(
8074
- fromCommit,
8075
- toCommit,
8076
- repoDirFor(name)
8077
- );
8078
- if (changes.trim() !== "") {
8079
- allChanges.push(`${fmt.bold(fmt.bgYellowBright(name))}:
8080
-
8081
- ${changes}`);
8082
- }
8083
- }
8084
- if (allChanges.length) {
8085
- logWarningSection(
8086
- "ChangeLog, These is the changes from last update, make sure to review for breaking changes",
8087
- allChanges.join(`
8088
- ${fmt.gray("-".repeat(82))}
8089
8583
 
8090
- `).replace(/BREAKING CHANGE/gi, fmt.red("BREAKING CHANGE"))
8091
- );
8092
- } else {
8093
- import_prompts2.log.success("already up to date");
8094
- }
8584
+ // src/services/updater/updateProject.ts
8585
+ function getErrorMessage(error2) {
8586
+ return error2 instanceof Error ? error2.message : String(error2);
8095
8587
  }
8096
-
8097
- // src/commands/update/index.ts
8098
- async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8588
+ async function runUpdateScope(args, ignoresByName, rootTemplateName, appKey) {
8099
8589
  const templateDef = getTemplateDef();
8100
8590
  const templates = await getAvailableTemplates();
8101
8591
  const usedBlocks = getUsedBlocksDef();
@@ -8143,7 +8633,7 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8143
8633
  );
8144
8634
  for (const block of missingBlocks) {
8145
8635
  if (isNonInteractive()) {
8146
- import_prompts27.log.warn(
8636
+ import_prompts25.log.warn(
8147
8637
  `${block.name} does not exist in registries. Continuing with remaining parts.`
8148
8638
  );
8149
8639
  continue;
@@ -8151,14 +8641,8 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8151
8641
  const shouldUpdateRemaining = await select({
8152
8642
  message: `${block.name} does not exist in registries. Continue updating remaining parts?`,
8153
8643
  options: [
8154
- {
8155
- value: true,
8156
- label: "Continue"
8157
- },
8158
- {
8159
- value: false,
8160
- label: "Stop"
8161
- }
8644
+ { value: true, label: "Continue" },
8645
+ { value: false, label: "Stop" }
8162
8646
  ]
8163
8647
  });
8164
8648
  if (!shouldUpdateRemaining) {
@@ -8184,19 +8668,15 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8184
8668
  }))
8185
8669
  );
8186
8670
  if (failed.length) {
8187
- import_prompts27.log.warn(
8671
+ import_prompts25.log.warn(
8188
8672
  fmt.yellow(
8189
8673
  `${failedBlocks.length} block update${failedBlocks.length === 1 ? "" : "s"} failed.`
8190
8674
  )
8191
8675
  );
8192
8676
  for (const result of failed) {
8193
- import_prompts27.log.error(
8194
- fmt.red(`${result.block}: ${getErrorMessage(result.error)}`)
8195
- );
8677
+ import_prompts25.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
8196
8678
  }
8197
- import_prompts27.log.warn(
8198
- "Fix the errors above and rerun the update for the failed blocks."
8199
- );
8679
+ import_prompts25.log.warn("Fix the errors above and rerun the update for the failed blocks.");
8200
8680
  }
8201
8681
  for (const result of blockResults) {
8202
8682
  if (!result.updated) continue;
@@ -8240,13 +8720,11 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8240
8720
  block: result.block,
8241
8721
  error: getErrorMessage(result.error)
8242
8722
  });
8243
- import_prompts27.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
8723
+ import_prompts25.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
8244
8724
  }
8245
8725
  }
8246
8726
  if (blockResults.some((result) => result.error)) {
8247
- import_prompts27.log.warn(
8248
- "Fix the errors above and rerun the update for the failed blocks."
8249
- );
8727
+ import_prompts25.log.warn("Fix the errors above and rerun the update for the failed blocks.");
8250
8728
  }
8251
8729
  hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
8252
8730
  for (const result of blockResults) {
@@ -8256,7 +8734,7 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8256
8734
  }
8257
8735
  }
8258
8736
  if (!shouldContinue) {
8259
- import_prompts27.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
8737
+ import_prompts25.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
8260
8738
  }
8261
8739
  if (hasUpdate) {
8262
8740
  await runLifecycleHookWithTask(".", "update", "Run template update");
@@ -8264,163 +8742,1455 @@ async function runScopeUpdate(args, ignoresByName, rootTemplateName, appKey) {
8264
8742
  await checkVersionsCompatibility();
8265
8743
  return { updated: hasUpdate, stoppedEarly: !shouldContinue, failedBlocks };
8266
8744
  }
8267
- var update2 = addExecutionOptions(
8268
- command("update").description("Update app/block").alias("u").addOption(
8269
- option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
8270
- ).option("--app <name>", "Limit the update to one application under apps/").option(
8271
- "--ignore <list...>",
8272
- 'Files ignore list scoped by name i.e "repo:file"'
8273
- ).option(
8274
- "-b, --block <names...>",
8275
- "Blocks to update, valid only with scope block"
8276
- ).option("--hard", "Hard update (overwrite local changes)", false).option(
8277
- "--allow-breaking",
8278
- "authorize applying updates that contain breaking changes",
8279
- false
8280
- ).addHelpText(
8281
- "after",
8282
- `
8283
- Non-interactive usage:
8284
- blox update --non-interactive # update everything
8285
- blox update --non-interactive --allow-breaking # also apply breaking changes
8286
- blox update -s block -b my-block --json # single block, JSON output
8287
- blox update --app web # update only the web application
8288
-
8289
- In non-interactive mode (--non-interactive or a non-TTY stdin) nothing is
8290
- prompted. Updates containing breaking changes require --allow-breaking;
8291
- without it the command stops before applying them. --json only controls
8292
- the output format and can be combined with either mode.
8293
-
8294
- Without --app, an update run at the workspace root covers the root project
8295
- and every application under apps/ sequentially. Run inside an application
8296
- directory to limit the update to that application.`
8297
- )
8298
- ).action(async (args) => {
8299
- initExecutionMode(args);
8745
+ async function updateProject(context, options = {}) {
8746
+ const scope = options.scope ?? "all";
8747
+ if (scope === "block" && !options.blocks?.length) {
8748
+ throw new MissingArgumentsError(["blocks"]);
8749
+ }
8300
8750
  const ignoresByName = {};
8301
- for (const ignore3 of args.ignore || []) {
8302
- const [repo, pattern] = ignore3.split(":");
8303
- if (!repo || !pattern) {
8304
- handleCommandError(
8305
- new CliError("Invalid ignore pattern", "VALIDATION", exitCodes.USAGE)
8306
- );
8307
- continue;
8751
+ for (const ignore3 of options.ignore ?? []) {
8752
+ if (!ignore3.target || !ignore3.pattern) {
8753
+ throw new CliError("Invalid ignore entry", "VALIDATION", exitCodes.USAGE);
8308
8754
  }
8309
- if (!ignoresByName[repo]) {
8310
- ignoresByName[repo] = [];
8755
+ ignoresByName[ignore3.target] = [
8756
+ ...ignoresByName[ignore3.target] ?? [],
8757
+ ignore3.pattern
8758
+ ];
8759
+ }
8760
+ const scoped = context.app;
8761
+ const scopes = scoped ? [{ dir: context.projectDir, app: context.app }] : [
8762
+ { dir: context.workspaceRoot },
8763
+ ...listApps(context.workspaceRoot).map((app2) => ({
8764
+ dir: app2.dir,
8765
+ app: app2.key
8766
+ }))
8767
+ ];
8768
+ const dirtyScopes = [];
8769
+ for (const scopeDir of scopes) {
8770
+ if (await git.hasUncommittedChanges(scopeDir.dir)) {
8771
+ dirtyScopes.push(scopeDir.app ?? "workspace root");
8311
8772
  }
8312
- ignoresByName[repo].push(pattern);
8313
8773
  }
8774
+ if (dirtyScopes.length) {
8775
+ throw new CliError(
8776
+ `Make sure to commit any changes first: ${dirtyScopes.join(", ")}`,
8777
+ "DIRTY_WORKING_TREE",
8778
+ exitCodes.GENERAL
8779
+ );
8780
+ }
8781
+ const rootTemplateName = getTemplateDef(context.workspaceRoot).name;
8782
+ await migrateAll(true, context.workspaceRoot);
8783
+ await syncRegistries(void 0, { force: options.refreshRegistries });
8784
+ const startCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
8785
+ let hasUpdate = false;
8786
+ let stoppedEarly = false;
8787
+ const failedBlocks = [];
8788
+ const scopeResults = [];
8314
8789
  const touchedScopes = [];
8790
+ const cwd2 = process.cwd();
8315
8791
  try {
8316
- const context = resolveContext(".", args.app);
8317
- const scoped = args.app || context.app;
8318
- const scopes = scoped ? [{ dir: context.projectDir, app: context.app }] : [
8319
- { dir: context.workspaceRoot },
8320
- ...listApps(context.workspaceRoot).map((app) => ({
8321
- dir: app.dir,
8322
- app: app.key
8323
- }))
8324
- ];
8325
- const dirtyScopes = [];
8326
- for (const scope of scopes) {
8327
- if (await git.hasUncommittedChanges(scope.dir)) {
8328
- dirtyScopes.push(scope.app ?? "workspace root");
8329
- }
8330
- }
8331
- if (dirtyScopes.length) {
8332
- const message = `Make sure to commit any changes first: ${dirtyScopes.join(", ")}`;
8333
- if (isNonInteractive()) {
8334
- throw new CliError(message, "DIRTY_WORKING_TREE", exitCodes.GENERAL);
8335
- }
8336
- import_prompts27.log.warn(fmt.yellow(message));
8337
- return;
8338
- }
8339
- const rootTemplateName = getTemplateDef(context.workspaceRoot).name;
8340
- await migrateAll(true, context.workspaceRoot);
8341
- await syncRegistries();
8342
- const startCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
8343
- let hasUpdate = false;
8344
- let stoppedEarly = false;
8345
- const failedBlocks = [];
8346
- const scopeResults = [];
8347
- const cwd = process.cwd();
8348
- try {
8349
- for (const scope of scopes) {
8350
- process.chdir(scope.dir);
8351
- touchedScopes.push(scope.dir);
8792
+ for (const scopeDir of scopes) {
8793
+ process.chdir(scopeDir.dir);
8794
+ touchedScopes.push(scopeDir.dir);
8795
+ try {
8796
+ const result = await runUpdateScope(
8797
+ {
8798
+ scope,
8799
+ block: options.blocks,
8800
+ hard: options.hard,
8801
+ allowBreaking: options.allowBreaking
8802
+ },
8803
+ ignoresByName,
8804
+ rootTemplateName,
8805
+ scopeDir.app
8806
+ );
8807
+ hasUpdate = hasUpdate || result.updated;
8808
+ stoppedEarly = stoppedEarly || result.stoppedEarly;
8809
+ failedBlocks.push(...result.failedBlocks);
8810
+ scopeResults.push({ scope: scopeDir.app ?? "(root)", ...result });
8811
+ } catch (scopeError) {
8812
+ if (scopeError instanceof CliError) throw scopeError;
8813
+ const message3 = getErrorMessage(scopeError);
8352
8814
  try {
8353
- const result = await runScopeUpdate(
8354
- args,
8355
- ignoresByName,
8356
- rootTemplateName,
8357
- scope.app
8815
+ await git.rollback(scopeDir.dir);
8816
+ } catch (rollbackError) {
8817
+ import_prompts25.log.warn(
8818
+ fmt.yellow(`Rollback failed for ${scopeDir.dir}: ${rollbackError}`)
8358
8819
  );
8359
- hasUpdate = hasUpdate || result.updated;
8360
- stoppedEarly = stoppedEarly || result.stoppedEarly;
8361
- failedBlocks.push(...result.failedBlocks);
8362
- scopeResults.push({ scope: scope.app ?? "(root)", ...result });
8363
- } catch (scopeError) {
8364
- if (scopeError instanceof CliError) throw scopeError;
8365
- const message = scopeError instanceof Error ? scopeError.message : String(scopeError);
8366
- try {
8367
- await git.rollback(scope.dir);
8368
- } catch (rollbackError) {
8369
- import_prompts27.log.warn(
8370
- fmt.yellow(`Rollback failed for ${scope.dir}: ${rollbackError}`)
8371
- );
8372
- }
8373
- scopeResults.push({
8374
- scope: scope.app ?? "(root)",
8375
- updated: false,
8376
- stoppedEarly: false,
8377
- failedBlocks: [],
8378
- error: message
8379
- });
8380
- import_prompts27.log.error(fmt.red(`${scope.app ?? "workspace root"}: ${message}`));
8381
8820
  }
8821
+ scopeResults.push({
8822
+ scope: scopeDir.app ?? "(root)",
8823
+ updated: false,
8824
+ stoppedEarly: false,
8825
+ failedBlocks: [],
8826
+ error: message3
8827
+ });
8828
+ import_prompts25.log.error(fmt.red(`${scopeDir.app ?? "workspace root"}: ${message3}`));
8382
8829
  }
8383
- } finally {
8384
- process.chdir(cwd);
8385
- }
8386
- const endCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
8387
- await printChangeLog(startCheckpoints, endCheckpoints, context.workspaceRoot);
8388
- const failedScopes = scopeResults.filter((result) => result.error);
8389
- if (failedScopes.length) {
8390
- import_prompts27.log.warn(
8391
- fmt.yellow(
8392
- `${failedScopes.length} scope(s) failed to update: ${failedScopes.map((result) => result.scope).join(", ")}`
8393
- )
8394
- );
8395
8830
  }
8396
- reportUpdateSummary(
8397
- { updated: hasUpdate, stoppedEarly, failedBlocks, scopes: scopeResults },
8398
- { json: isJsonMode(), nonInteractive: isNonInteractive() }
8399
- );
8400
8831
  } catch (e) {
8401
8832
  if (!isDebugMode() && !(e instanceof CliError)) {
8402
- import_prompts27.log.warn("Error happened, Will rollback changes");
8403
8833
  for (const dir of new Set(touchedScopes)) {
8404
8834
  try {
8405
8835
  await git.rollback(dir);
8406
8836
  } catch {
8407
8837
  }
8408
8838
  }
8409
- if (!touchedScopes.length) {
8410
- await git.rollback();
8411
- }
8412
8839
  }
8413
- handleCommandError(e);
8840
+ throw e;
8414
8841
  } finally {
8842
+ process.chdir(cwd2);
8415
8843
  await git.cleanUpWorktrees();
8416
8844
  }
8417
- });
8418
- function getErrorMessage(error2) {
8419
- if (error2 instanceof Error) {
8420
- return error2.message;
8845
+ const endCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
8846
+ const changedComponents = Object.keys(endCheckpoints).filter(
8847
+ (name) => endCheckpoints[name]?.commit !== startCheckpoints[name]?.commit
8848
+ );
8849
+ for (const name of Object.keys(startCheckpoints)) {
8850
+ if (!(name in endCheckpoints)) changedComponents.push(name);
8851
+ }
8852
+ const failedScopes = scopeResults.filter((result) => result.error);
8853
+ const ok = failedBlocks.length === 0 && failedScopes.length === 0;
8854
+ return {
8855
+ ok,
8856
+ context,
8857
+ summary: { updated: hasUpdate, stoppedEarly, failedBlocks },
8858
+ scopes: scopeResults,
8859
+ changedComponents: [...new Set(changedComponents)]
8860
+ };
8861
+ }
8862
+
8863
+ // src/mcp/operations/update.ts
8864
+ async function updateProjectOperation(input) {
8865
+ const { context } = resolveMcpContext(input);
8866
+ const blocks = resolveUpdateBlockRefs(input);
8867
+ const result = await updateProject(context, {
8868
+ scope: input.scope,
8869
+ blocks,
8870
+ ignore: input.ignore,
8871
+ hard: input.hard,
8872
+ allowBreaking: input.allowBreaking,
8873
+ refreshRegistries: input.refresh
8874
+ });
8875
+ return {
8876
+ ok: result.ok,
8877
+ context: contextSummary(result.context),
8878
+ summary: result.summary,
8879
+ scopes: result.scopes,
8880
+ changedComponents: result.changedComponents
8881
+ };
8882
+ }
8883
+
8884
+ // src/mcp/operations/index.ts
8885
+ function createDefaultOperations() {
8886
+ return {
8887
+ getProjectContext,
8888
+ listInstalledBlocks,
8889
+ listAvailableBlocks,
8890
+ getBlock,
8891
+ addBlocks: addBlocksOperation,
8892
+ removeBlocks: removeBlocksOperation,
8893
+ updateProject: updateProjectOperation,
8894
+ planUpdate: planUpdateOperation,
8895
+ runDoctor: runDoctorOperation
8896
+ };
8897
+ }
8898
+
8899
+ // src/mcp/resources.ts
8900
+ var import_server = require("@modelcontextprotocol/server");
8901
+
8902
+ // src/mcp/errors.ts
8903
+ var CREDENTIAL_PATTERN = /(authorization|proxy-authorization|token|secret|password|api[_-]?key|credential)(\s*[:=]\s*)([^\s,;&]+)/gi;
8904
+ var URL_CREDENTIAL_PATTERN = /(https?:\/\/)([^/\s:@]+):([^/\s@]+)@/gi;
8905
+ function sanitizeMcpText(text2) {
8906
+ return text2.replace(URL_CREDENTIAL_PATTERN, "$1<redacted>@").replace(CREDENTIAL_PATTERN, "$1$2<redacted>");
8907
+ }
8908
+ function sanitizeValue(value) {
8909
+ if (typeof value === "string") return sanitizeMcpText(value);
8910
+ if (Array.isArray(value)) return value.map(sanitizeValue);
8911
+ if (value && typeof value === "object") {
8912
+ return Object.fromEntries(
8913
+ Object.entries(value).map(([key, entry]) => [
8914
+ key,
8915
+ sanitizeValue(entry)
8916
+ ])
8917
+ );
8421
8918
  }
8422
- return String(error2);
8919
+ return value;
8920
+ }
8921
+ function toToolResult(data) {
8922
+ return {
8923
+ content: [
8924
+ {
8925
+ type: "text",
8926
+ text: JSON.stringify(data, null, 2)
8927
+ }
8928
+ ],
8929
+ structuredContent: data
8930
+ };
8423
8931
  }
8932
+ function toToolError(error2) {
8933
+ const payload = error2 instanceof CliError ? {
8934
+ ok: false,
8935
+ error: {
8936
+ code: error2.code,
8937
+ message: sanitizeMcpText(error2.message),
8938
+ ...error2.suggestion ? { suggestion: sanitizeMcpText(error2.suggestion) } : {},
8939
+ ...error2.details ? { details: sanitizeValue(error2.details) } : {},
8940
+ exitCode: error2.exitCode
8941
+ }
8942
+ } : {
8943
+ ok: false,
8944
+ error: {
8945
+ code: error2 instanceof Error && error2.name === "AbortError" ? "CANCELLED" : "INTERNAL",
8946
+ message: sanitizeMcpText(
8947
+ error2 instanceof Error ? error2.message : String(error2)
8948
+ ),
8949
+ exitCode: exitCodes.GENERAL
8950
+ }
8951
+ };
8952
+ return {
8953
+ isError: true,
8954
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
8955
+ };
8956
+ }
8957
+
8958
+ // src/mcp/resources.ts
8959
+ var RESOURCE_MIME = "application/json";
8960
+ function resourceError(error2) {
8961
+ const payload = error2 instanceof CliError ? {
8962
+ ok: false,
8963
+ error: {
8964
+ code: error2.code,
8965
+ message: sanitizeMcpText(error2.message),
8966
+ ...error2.suggestion ? { suggestion: sanitizeMcpText(error2.suggestion) } : {},
8967
+ exitCode: error2.exitCode
8968
+ }
8969
+ } : {
8970
+ ok: false,
8971
+ error: {
8972
+ code: "INTERNAL",
8973
+ message: sanitizeMcpText(
8974
+ error2 instanceof Error ? error2.message : String(error2)
8975
+ ),
8976
+ exitCode: exitCodes.GENERAL
8977
+ }
8978
+ };
8979
+ return JSON.stringify(payload, null, 2);
8980
+ }
8981
+ async function readJsonResource(queue, uri, signal, cwd2, load) {
8982
+ try {
8983
+ const data = await queue.run(() => load(cwd2), signal);
8984
+ return {
8985
+ contents: [
8986
+ {
8987
+ uri: uri.href,
8988
+ mimeType: RESOURCE_MIME,
8989
+ text: JSON.stringify(data, null, 2)
8990
+ }
8991
+ ]
8992
+ };
8993
+ } catch (error2) {
8994
+ return {
8995
+ contents: [
8996
+ {
8997
+ uri: uri.href,
8998
+ mimeType: RESOURCE_MIME,
8999
+ text: resourceError(error2)
9000
+ }
9001
+ ]
9002
+ };
9003
+ }
9004
+ }
9005
+ function registerBloxResources(server, operations, mcpContext, queue) {
9006
+ const projectCwd = mcpContext.projectDir;
9007
+ const signal = (ctx) => ctx.mcpReq.signal;
9008
+ const read = (uri, ctx, load) => readJsonResource(queue, uri, signal(ctx), projectCwd, load);
9009
+ server.registerResource(
9010
+ "project",
9011
+ "blox://project",
9012
+ {
9013
+ title: "BLOX project context",
9014
+ description: "Context of the BLOX project this server is configured for (blox mcp --cwd).",
9015
+ mimeType: RESOURCE_MIME
9016
+ },
9017
+ (uri, ctx) => read(uri, ctx, (cwd2) => operations.getProjectContext({ cwd: cwd2 }))
9018
+ );
9019
+ server.registerResource(
9020
+ "installed-blocks",
9021
+ "blox://project/installed-blocks",
9022
+ {
9023
+ title: "Installed BLOX blocks",
9024
+ description: "Blocks installed in the resolved BLOX project scope.",
9025
+ mimeType: RESOURCE_MIME
9026
+ },
9027
+ (uri, ctx) => read(uri, ctx, (cwd2) => operations.listInstalledBlocks({ cwd: cwd2 }))
9028
+ );
9029
+ server.registerResource(
9030
+ "available-blocks",
9031
+ "blox://project/available-blocks",
9032
+ {
9033
+ title: "Available BLOX blocks",
9034
+ description: "Registry blocks available to the resolved BLOX project scope.",
9035
+ mimeType: RESOURCE_MIME
9036
+ },
9037
+ (uri, ctx) => read(
9038
+ uri,
9039
+ ctx,
9040
+ (cwd2) => operations.listAvailableBlocks({ cwd: cwd2, includeSource: false })
9041
+ )
9042
+ );
9043
+ const installedNames = async () => {
9044
+ try {
9045
+ const data = await queue.run(() => operations.listInstalledBlocks({ cwd: projectCwd }));
9046
+ const blocks = Array.isArray(data.blocks) ? data.blocks : [];
9047
+ return blocks.map((block) => block.name).filter((name) => typeof name === "string").sort();
9048
+ } catch {
9049
+ return [];
9050
+ }
9051
+ };
9052
+ server.registerResource(
9053
+ "block",
9054
+ new import_server.ResourceTemplate("blox://blocks/{name}", {
9055
+ // Listing only enumerates installed blocks: it is local and never
9056
+ // syncs registries. Any registry block name can still be read.
9057
+ list: async () => ({
9058
+ resources: (await installedNames()).map((name) => ({
9059
+ uri: `blox://blocks/${encodeURIComponent(name)}`,
9060
+ name,
9061
+ title: `BLOX block: ${name}`,
9062
+ mimeType: RESOURCE_MIME
9063
+ }))
9064
+ }),
9065
+ complete: {
9066
+ name: async (value) => (await installedNames()).filter((name) => name.startsWith(value))
9067
+ }
9068
+ }),
9069
+ {
9070
+ title: "BLOX block details",
9071
+ description: "Registry metadata, versions, latest definition, and installed state for one block (same data as get_block).",
9072
+ mimeType: RESOURCE_MIME
9073
+ },
9074
+ (uri, variables, ctx) => {
9075
+ const raw = variables.name;
9076
+ const name = decodeURIComponent(Array.isArray(raw) ? raw[0] ?? "" : raw ?? "");
9077
+ return read(uri, ctx, (cwd2) => operations.getBlock({ cwd: cwd2, name }));
9078
+ }
9079
+ );
9080
+ }
9081
+
9082
+ // src/mcp/serialization.ts
9083
+ function abortedError() {
9084
+ const error2 = new Error("The MCP request was cancelled");
9085
+ error2.name = "AbortError";
9086
+ return error2;
9087
+ }
9088
+ function createSerialQueue() {
9089
+ let tail = Promise.resolve();
9090
+ return {
9091
+ run(fn, signal) {
9092
+ const run = tail.then(async () => {
9093
+ if (signal?.aborted) throw abortedError();
9094
+ return fn();
9095
+ });
9096
+ tail = run.then(
9097
+ () => void 0,
9098
+ () => void 0
9099
+ );
9100
+ return run;
9101
+ }
9102
+ };
9103
+ }
9104
+
9105
+ // src/mcp/schemas.ts
9106
+ var import_zod2 = require("zod");
9107
+ var cwd = import_zod2.z.string().min(1).optional().describe(
9108
+ "Optional directory inside the BLOX project this server is configured for (blox mcp --cwd). Omit it to use that project. Relative paths resolve against the project root; paths outside it (including via symlinks) are rejected."
9109
+ );
9110
+ var app = import_zod2.z.string().min(1).optional().describe("Application key under apps/ to scope the operation to.");
9111
+ var refresh = import_zod2.z.boolean().optional().describe("Force a registry refresh instead of using the cached registry state.");
9112
+ var includeSource = import_zod2.z.boolean().optional().describe("Include registry source URLs/paths in the response. Defaults to false.");
9113
+ var projectContextInputSchema = import_zod2.z.strictObject({
9114
+ cwd,
9115
+ app
9116
+ });
9117
+ var listAvailableBlocksInputSchema = import_zod2.z.strictObject({
9118
+ cwd,
9119
+ app,
9120
+ query: import_zod2.z.string().optional().describe("Case-insensitive substring matched against block name, description, and tags."),
9121
+ tags: import_zod2.z.array(import_zod2.z.string().min(1)).optional().describe(
9122
+ "Tags used to filter available blocks. A block matches when it has any listed tag."
9123
+ ),
9124
+ refresh,
9125
+ includeSource
9126
+ });
9127
+ var getBlockInputSchema = import_zod2.z.strictObject({
9128
+ name: import_zod2.z.string().min(1).describe("Registry block name to inspect."),
9129
+ cwd,
9130
+ app,
9131
+ version: import_zod2.z.union([import_zod2.z.string().min(1), import_zod2.z.number().int().nonnegative()]).optional().describe(
9132
+ "Version label to select, or a numeric major version to select the newest matching semver label. Defaults to the latest valid semver label."
9133
+ ),
9134
+ refresh,
9135
+ includeSource
9136
+ });
9137
+ var listInstalledBlocksInputSchema = import_zod2.z.strictObject({
9138
+ cwd,
9139
+ app
9140
+ });
9141
+ var addBlocksInputSchema = import_zod2.z.strictObject({
9142
+ blocks: import_zod2.z.array(import_zod2.z.string().min(1)).min(1).describe("Block names to add. Accepts unqualified names or block/<name>."),
9143
+ cwd,
9144
+ app,
9145
+ branch: import_zod2.z.string().min(1).optional().describe("Optional branch to clone block sources from."),
9146
+ destination: import_zod2.z.string().min(1).optional().describe("Optional destination directory under blocks/."),
9147
+ replace: import_zod2.z.boolean().optional().describe("Replace an existing block destination without prompting. Defaults to false."),
9148
+ rewriteDeps: import_zod2.z.boolean().optional().describe(
9149
+ "Repoint dependent blocks at a replaced block without prompting. Defaults to false."
9150
+ ),
9151
+ refresh
9152
+ });
9153
+ var removeBlocksInputSchema = import_zod2.z.strictObject({
9154
+ blocks: import_zod2.z.array(import_zod2.z.string().min(1)).min(1).describe(
9155
+ "Installed blocks to remove, in order. Accepts registry names, installed folder names, or block/<name>. Applications are not accepted."
9156
+ ),
9157
+ cwd,
9158
+ app,
9159
+ force: import_zod2.z.boolean().optional().describe(
9160
+ "Remove even if other installed blocks declare a dependency on a block, which can leave them broken. Defaults to false; only set it after the user explicitly agrees."
9161
+ ),
9162
+ dryRun: import_zod2.z.boolean().optional().describe(
9163
+ "Return a read-only removal plan (paths, dependents, lifecycle hooks, blockers) without deleting anything. Defaults to false."
9164
+ ),
9165
+ refresh
9166
+ });
9167
+ var updateProjectInputSchema = import_zod2.z.strictObject({
9168
+ cwd,
9169
+ app,
9170
+ scope: import_zod2.z.enum(["app", "bases", "block", "all"]).optional().describe("Update scope. Defaults to all."),
9171
+ blocks: import_zod2.z.array(import_zod2.z.string().min(1)).optional().describe("Blocks to update. Required when scope is block."),
9172
+ ignore: import_zod2.z.array(
9173
+ import_zod2.z.strictObject({
9174
+ target: import_zod2.z.string().min(1).describe("Component name the ignore applies to."),
9175
+ pattern: import_zod2.z.string().min(1).describe("File pattern to ignore for that component.")
9176
+ })
9177
+ ).optional().describe("File ignore rules scoped by component name."),
9178
+ hard: import_zod2.z.boolean().optional().describe("Overwrite local changes while updating. Defaults to false."),
9179
+ allowBreaking: import_zod2.z.boolean().optional().describe("Authorize updates that contain breaking changes. Defaults to false."),
9180
+ dryRun: import_zod2.z.boolean().optional().describe(
9181
+ "Return a read-only update plan (current vs. target versions, breaking changes, blockers) without changing files, git state, or .blox. Defaults to false."
9182
+ ),
9183
+ refresh
9184
+ });
9185
+ var runDoctorInputSchema = import_zod2.z.strictObject({
9186
+ cwd,
9187
+ fix: import_zod2.z.boolean().optional().describe("Attempt automatic repairs for findings that support them. Defaults to false.")
9188
+ });
9189
+ var contextSummaryOutputSchema = import_zod2.z.object({
9190
+ workspaceRoot: import_zod2.z.string(),
9191
+ projectDir: import_zod2.z.string(),
9192
+ app: import_zod2.z.string().nullable()
9193
+ });
9194
+ var dependencyVersionOutputSchema = import_zod2.z.union([import_zod2.z.number(), import_zod2.z.tuple([import_zod2.z.number(), import_zod2.z.number()])]).nullable();
9195
+ var templateDependencyOutputSchema = import_zod2.z.object({
9196
+ name: import_zod2.z.string(),
9197
+ version: dependencyVersionOutputSchema
9198
+ });
9199
+ var templateCheckpointOutputSchema = import_zod2.z.object({
9200
+ commit: import_zod2.z.string(),
9201
+ version: import_zod2.z.number().optional(),
9202
+ branch: import_zod2.z.string().optional()
9203
+ });
9204
+ var templateSummaryOutputSchema = import_zod2.z.object({
9205
+ name: import_zod2.z.string(),
9206
+ version: import_zod2.z.number().nullable(),
9207
+ bases: import_zod2.z.array(templateDependencyOutputSchema),
9208
+ lifecycleHooks: import_zod2.z.array(import_zod2.z.string()),
9209
+ dependencies: import_zod2.z.array(templateDependencyOutputSchema).optional(),
9210
+ templates: import_zod2.z.array(templateDependencyOutputSchema).optional()
9211
+ });
9212
+ var installedBlockSummaryOutputSchema = import_zod2.z.object({
9213
+ name: import_zod2.z.string(),
9214
+ path: import_zod2.z.string(),
9215
+ version: import_zod2.z.number().nullable(),
9216
+ checkpoint: templateCheckpointOutputSchema.nullable(),
9217
+ dependencies: import_zod2.z.array(import_zod2.z.string()),
9218
+ templates: import_zod2.z.array(import_zod2.z.string())
9219
+ });
9220
+ var projectContextOutputSchema = import_zod2.z.object({
9221
+ ok: import_zod2.z.boolean(),
9222
+ context: contextSummaryOutputSchema,
9223
+ project: import_zod2.z.object({
9224
+ schemaVersion: import_zod2.z.number().nullable()
9225
+ }),
9226
+ template: templateSummaryOutputSchema.nullable(),
9227
+ apps: import_zod2.z.array(
9228
+ import_zod2.z.object({
9229
+ key: import_zod2.z.string(),
9230
+ projectDir: import_zod2.z.string(),
9231
+ template: templateSummaryOutputSchema.nullable(),
9232
+ dirty: import_zod2.z.boolean().nullable()
9233
+ })
9234
+ ),
9235
+ installedBlocks: import_zod2.z.array(installedBlockSummaryOutputSchema),
9236
+ git: import_zod2.z.object({
9237
+ projectDirty: import_zod2.z.boolean().nullable(),
9238
+ workspaceDirty: import_zod2.z.boolean().nullable()
9239
+ })
9240
+ });
9241
+ var listInstalledBlocksOutputSchema = import_zod2.z.object({
9242
+ ok: import_zod2.z.boolean(),
9243
+ context: contextSummaryOutputSchema,
9244
+ blocks: import_zod2.z.array(installedBlockSummaryOutputSchema)
9245
+ });
9246
+ var availableBlockSummaryOutputSchema = import_zod2.z.object({
9247
+ name: import_zod2.z.string(),
9248
+ description: import_zod2.z.string().nullable(),
9249
+ tags: import_zod2.z.array(import_zod2.z.string()),
9250
+ destination: import_zod2.z.string().nullable(),
9251
+ installed: import_zod2.z.boolean(),
9252
+ installedVersion: import_zod2.z.number().nullable(),
9253
+ source: import_zod2.z.string().optional()
9254
+ });
9255
+ var listAvailableBlocksOutputSchema = import_zod2.z.object({
9256
+ ok: import_zod2.z.boolean(),
9257
+ context: contextSummaryOutputSchema,
9258
+ blocks: import_zod2.z.array(availableBlockSummaryOutputSchema),
9259
+ count: import_zod2.z.number().int().nonnegative()
9260
+ });
9261
+ var blockVersionDefinitionOutputSchema = import_zod2.z.object({
9262
+ version: import_zod2.z.number().nullable(),
9263
+ dependencies: import_zod2.z.array(templateDependencyOutputSchema),
9264
+ templates: import_zod2.z.array(templateDependencyOutputSchema),
9265
+ bases: import_zod2.z.array(templateDependencyOutputSchema),
9266
+ ignore: import_zod2.z.array(import_zod2.z.string()),
9267
+ lifecycleHooks: import_zod2.z.array(import_zod2.z.string()),
9268
+ lastCommit: import_zod2.z.string().nullable()
9269
+ });
9270
+ var blockInstalledOutputSchema = import_zod2.z.object({
9271
+ installed: import_zod2.z.boolean(),
9272
+ path: import_zod2.z.string().nullable(),
9273
+ version: import_zod2.z.number().nullable(),
9274
+ checkpoint: templateCheckpointOutputSchema.nullable()
9275
+ });
9276
+ var blockDetailsOutputSchema = import_zod2.z.object({
9277
+ name: import_zod2.z.string(),
9278
+ registry: import_zod2.z.object({
9279
+ description: import_zod2.z.string().nullable(),
9280
+ tags: import_zod2.z.array(import_zod2.z.string()),
9281
+ destination: import_zod2.z.string().nullable(),
9282
+ source: import_zod2.z.string().optional()
9283
+ }),
9284
+ versions: import_zod2.z.array(import_zod2.z.string()),
9285
+ selectedVersion: import_zod2.z.string().nullable(),
9286
+ definition: blockVersionDefinitionOutputSchema.nullable(),
9287
+ installed: blockInstalledOutputSchema
9288
+ });
9289
+ var getBlockOutputSchema = import_zod2.z.object({
9290
+ ok: import_zod2.z.boolean(),
9291
+ context: contextSummaryOutputSchema,
9292
+ block: blockDetailsOutputSchema
9293
+ });
9294
+ var addBlockResultOutputSchema = import_zod2.z.object({
9295
+ block: import_zod2.z.string(),
9296
+ status: import_zod2.z.enum(["added", "warning", "skipped", "failed"]),
9297
+ warnings: import_zod2.z.array(import_zod2.z.string()).optional(),
9298
+ reason: import_zod2.z.string().optional()
9299
+ });
9300
+ var templateAddHookOutputSchema = import_zod2.z.object({
9301
+ status: import_zod2.z.enum(["ran", "skipped", "failed"]),
9302
+ error: import_zod2.z.string().optional()
9303
+ });
9304
+ var compatibilityCheckOutputSchema = import_zod2.z.object({
9305
+ status: import_zod2.z.enum(["passed", "failed", "skipped"]),
9306
+ error: import_zod2.z.string().optional()
9307
+ });
9308
+ var addBlocksOutputSchema = import_zod2.z.object({
9309
+ ok: import_zod2.z.boolean(),
9310
+ context: contextSummaryOutputSchema,
9311
+ results: import_zod2.z.array(addBlockResultOutputSchema),
9312
+ templateAddHook: templateAddHookOutputSchema,
9313
+ compatibility: compatibilityCheckOutputSchema
9314
+ });
9315
+ var plannedBlockRemovalOutputSchema = import_zod2.z.object({
9316
+ block: import_zod2.z.string(),
9317
+ status: import_zod2.z.enum(["removable", "blocked", "not-installed"]),
9318
+ name: import_zod2.z.string().nullable(),
9319
+ path: import_zod2.z.string().nullable(),
9320
+ dependents: import_zod2.z.array(import_zod2.z.string()),
9321
+ hasRemoveHook: import_zod2.z.boolean(),
9322
+ reason: import_zod2.z.string().optional()
9323
+ });
9324
+ var removedBlockOutputSchema = import_zod2.z.object({
9325
+ block: import_zod2.z.string(),
9326
+ name: import_zod2.z.string(),
9327
+ path: import_zod2.z.string()
9328
+ });
9329
+ var removeBlocksOutputSchema = import_zod2.z.union([
9330
+ import_zod2.z.object({
9331
+ ok: import_zod2.z.boolean(),
9332
+ context: contextSummaryOutputSchema,
9333
+ dryRun: import_zod2.z.literal(true),
9334
+ blocks: import_zod2.z.array(plannedBlockRemovalOutputSchema),
9335
+ templateRemoveHook: import_zod2.z.boolean(),
9336
+ blockers: import_zod2.z.array(import_zod2.z.string())
9337
+ }),
9338
+ import_zod2.z.object({
9339
+ ok: import_zod2.z.boolean(),
9340
+ context: contextSummaryOutputSchema,
9341
+ removed: import_zod2.z.array(removedBlockOutputSchema),
9342
+ force: import_zod2.z.boolean()
9343
+ })
9344
+ ]);
9345
+ var failedBlockOutputSchema = import_zod2.z.object({
9346
+ block: import_zod2.z.string(),
9347
+ error: import_zod2.z.string()
9348
+ });
9349
+ var updateScopeSummaryOutputSchema = import_zod2.z.object({
9350
+ scope: import_zod2.z.string(),
9351
+ updated: import_zod2.z.boolean(),
9352
+ stoppedEarly: import_zod2.z.boolean(),
9353
+ failedBlocks: import_zod2.z.array(failedBlockOutputSchema),
9354
+ error: import_zod2.z.string().optional()
9355
+ });
9356
+ var updateProjectOutputSchema = import_zod2.z.object({
9357
+ ok: import_zod2.z.boolean(),
9358
+ context: contextSummaryOutputSchema,
9359
+ summary: import_zod2.z.object({
9360
+ updated: import_zod2.z.boolean(),
9361
+ stoppedEarly: import_zod2.z.boolean(),
9362
+ failedBlocks: import_zod2.z.array(failedBlockOutputSchema)
9363
+ }),
9364
+ scopes: import_zod2.z.array(updateScopeSummaryOutputSchema),
9365
+ changedComponents: import_zod2.z.array(import_zod2.z.string())
9366
+ });
9367
+ var plannedStatusOutputSchema = import_zod2.z.enum(["up-to-date", "update-available", "unknown", "missing"]);
9368
+ var plannedComponentOutputSchema = import_zod2.z.object({
9369
+ scope: import_zod2.z.string(),
9370
+ kind: import_zod2.z.enum(["template", "base", "block"]),
9371
+ name: import_zod2.z.string(),
9372
+ status: plannedStatusOutputSchema,
9373
+ currentCommit: import_zod2.z.string().nullable(),
9374
+ currentVersion: import_zod2.z.string().nullable(),
9375
+ targetVersion: import_zod2.z.string().nullable(),
9376
+ targetCommit: import_zod2.z.string().nullable(),
9377
+ breaking: import_zod2.z.boolean(),
9378
+ path: import_zod2.z.string().optional(),
9379
+ reason: import_zod2.z.string().optional()
9380
+ });
9381
+ var planUpdateOutputSchema = import_zod2.z.object({
9382
+ ok: import_zod2.z.boolean(),
9383
+ dryRun: import_zod2.z.literal(true),
9384
+ context: contextSummaryOutputSchema,
9385
+ scope: import_zod2.z.enum(["app", "bases", "block", "all"]),
9386
+ components: import_zod2.z.array(plannedComponentOutputSchema),
9387
+ summary: import_zod2.z.object({
9388
+ updateAvailable: import_zod2.z.number().int().nonnegative(),
9389
+ upToDate: import_zod2.z.number().int().nonnegative(),
9390
+ unknown: import_zod2.z.number().int().nonnegative(),
9391
+ missing: import_zod2.z.number().int().nonnegative(),
9392
+ breaking: import_zod2.z.array(import_zod2.z.string())
9393
+ }),
9394
+ blockers: import_zod2.z.array(import_zod2.z.string()),
9395
+ note: import_zod2.z.string()
9396
+ });
9397
+ var updateProjectToolOutputSchema = import_zod2.z.union([
9398
+ updateProjectOutputSchema,
9399
+ planUpdateOutputSchema
9400
+ ]);
9401
+ var doctorDiagnosticOutputSchema = import_zod2.z.object({
9402
+ checkId: import_zod2.z.string(),
9403
+ checkName: import_zod2.z.string().optional(),
9404
+ id: import_zod2.z.string(),
9405
+ classification: import_zod2.z.enum(["invalid", "outdated", "informational"]),
9406
+ title: import_zod2.z.string(),
9407
+ message: import_zod2.z.string(),
9408
+ filePath: import_zod2.z.string().optional(),
9409
+ fixAvailable: import_zod2.z.boolean()
9410
+ });
9411
+ var doctorRepairOutputSchema = import_zod2.z.object({
9412
+ checkId: import_zod2.z.string(),
9413
+ diagnosticId: import_zod2.z.string(),
9414
+ result: import_zod2.z.object({
9415
+ status: import_zod2.z.enum(["fixed", "skipped", "failed"]),
9416
+ message: import_zod2.z.string()
9417
+ })
9418
+ });
9419
+ var doctorReportOutputSchema = import_zod2.z.object({
9420
+ diagnostics: import_zod2.z.array(doctorDiagnosticOutputSchema),
9421
+ repairs: import_zod2.z.array(doctorRepairOutputSchema),
9422
+ checkErrors: import_zod2.z.array(
9423
+ import_zod2.z.object({
9424
+ checkId: import_zod2.z.string(),
9425
+ message: import_zod2.z.string()
9426
+ })
9427
+ )
9428
+ });
9429
+ var runDoctorOutputSchema = import_zod2.z.object({
9430
+ ok: import_zod2.z.boolean(),
9431
+ context: contextSummaryOutputSchema,
9432
+ projectRoot: import_zod2.z.string(),
9433
+ fixMode: import_zod2.z.boolean(),
9434
+ report: doctorReportOutputSchema,
9435
+ exitCode: import_zod2.z.union([import_zod2.z.literal(0), import_zod2.z.literal(1), import_zod2.z.literal(2)])
9436
+ });
9437
+
9438
+ // src/mcp/tools.ts
9439
+ function registerBloxTools(server, operations, mcpContext, queue = createSerialQueue()) {
9440
+ const ctx = (c) => c.mcpReq.signal;
9441
+ async function executeTool(args, fn, signal) {
9442
+ try {
9443
+ const scoped = { ...args, cwd: resolveToolCwd(mcpContext, args) };
9444
+ const data = await queue.run(() => fn(scoped), signal);
9445
+ return toToolResult(data);
9446
+ } catch (error2) {
9447
+ return toToolError(error2);
9448
+ }
9449
+ }
9450
+ server.registerTool(
9451
+ "get_project_context",
9452
+ {
9453
+ title: "Get BLOX project context",
9454
+ description: "Resolve the current BLOX project/workspace/application scope and return local project state, installed blocks, apps, and git dirtiness.",
9455
+ inputSchema: projectContextInputSchema,
9456
+ outputSchema: projectContextOutputSchema,
9457
+ annotations: { readOnlyHint: true, openWorldHint: false }
9458
+ },
9459
+ (args, c) => executeTool(args, (a) => operations.getProjectContext(a), ctx(c))
9460
+ );
9461
+ server.registerTool(
9462
+ "list_installed_blocks",
9463
+ {
9464
+ title: "List installed BLOX blocks",
9465
+ description: "List blocks installed in the resolved BLOX project scope with paths, versions, checkpoints, and dependencies.",
9466
+ inputSchema: listInstalledBlocksInputSchema,
9467
+ outputSchema: listInstalledBlocksOutputSchema,
9468
+ annotations: { readOnlyHint: true, openWorldHint: false }
9469
+ },
9470
+ (args, c) => executeTool(args, (a) => operations.listInstalledBlocks(a), ctx(c))
9471
+ );
9472
+ server.registerTool(
9473
+ "list_available_blocks",
9474
+ {
9475
+ title: "List available BLOX blocks",
9476
+ description: "List blocks available from the configured registries for the resolved template scope, with installed status and optional filtering.",
9477
+ inputSchema: listAvailableBlocksInputSchema,
9478
+ outputSchema: listAvailableBlocksOutputSchema,
9479
+ annotations: { readOnlyHint: true, openWorldHint: true }
9480
+ },
9481
+ (args, c) => executeTool(args, (a) => operations.listAvailableBlocks(a), ctx(c))
9482
+ );
9483
+ server.registerTool(
9484
+ "get_block",
9485
+ {
9486
+ title: "Get BLOX block details",
9487
+ description: "Inspect one registry block: metadata, versions, selected version definition, requirements, lifecycle hook names, and installed state.",
9488
+ inputSchema: getBlockInputSchema,
9489
+ outputSchema: getBlockOutputSchema,
9490
+ annotations: { readOnlyHint: true, openWorldHint: true }
9491
+ },
9492
+ (args, c) => executeTool(args, (a) => operations.getBlock(a), ctx(c))
9493
+ );
9494
+ server.registerTool(
9495
+ "add_blocks",
9496
+ {
9497
+ title: "Add BLOX blocks",
9498
+ description: "Add one or more blocks to the resolved project scope. May clone sources, run lifecycle hooks, and modify .blox state. replace/rewriteDeps overwrite existing content when enabled.",
9499
+ inputSchema: addBlocksInputSchema,
9500
+ outputSchema: addBlocksOutputSchema,
9501
+ annotations: {
9502
+ readOnlyHint: false,
9503
+ destructiveHint: true,
9504
+ openWorldHint: true
9505
+ }
9506
+ },
9507
+ (args, c) => executeTool(args, (a) => operations.addBlocks(a), ctx(c))
9508
+ );
9509
+ server.registerTool(
9510
+ "remove_blocks",
9511
+ {
9512
+ title: "Remove BLOX blocks",
9513
+ description: "Remove installed blocks from the resolved project scope: runs each block's remove hook, deletes its blocks/ directory, then the template remove hook. Requires a clean git working tree; the whole batch is validated first and rolled back on failure. Blocks that other installed blocks depend on are refused unless force=true. Call with dryRun=true first and confirm with the user. Applications cannot be removed.",
9514
+ inputSchema: removeBlocksInputSchema,
9515
+ outputSchema: removeBlocksOutputSchema,
9516
+ annotations: {
9517
+ readOnlyHint: false,
9518
+ destructiveHint: true,
9519
+ idempotentHint: false,
9520
+ openWorldHint: false
9521
+ }
9522
+ },
9523
+ (args, c) => executeTool(args, (a) => operations.removeBlocks(a), ctx(c))
9524
+ );
9525
+ server.registerTool(
9526
+ "update_project",
9527
+ {
9528
+ title: "Update BLOX project",
9529
+ description: "Update the app/template, bases, and/or installed blocks using the BLOX update pipeline. Requires a clean working tree; breaking changes require allowBreaking. Set dryRun=true first to get a read-only plan of what would change.",
9530
+ inputSchema: updateProjectInputSchema,
9531
+ outputSchema: updateProjectToolOutputSchema,
9532
+ annotations: {
9533
+ readOnlyHint: false,
9534
+ destructiveHint: true,
9535
+ openWorldHint: true
9536
+ }
9537
+ },
9538
+ (args, c) => executeTool(
9539
+ args,
9540
+ (a) => a.dryRun ? operations.planUpdate(a) : operations.updateProject(a),
9541
+ ctx(c)
9542
+ )
9543
+ );
9544
+ server.registerTool(
9545
+ "run_doctor",
9546
+ {
9547
+ title: "Run BLOX doctor",
9548
+ description: "Diagnose the BLOX workspace with the existing doctor checks. Set fix=true to attempt automatic repairs for findings that support them.",
9549
+ inputSchema: runDoctorInputSchema,
9550
+ outputSchema: runDoctorOutputSchema,
9551
+ annotations: {
9552
+ readOnlyHint: false,
9553
+ destructiveHint: true,
9554
+ openWorldHint: false
9555
+ }
9556
+ },
9557
+ (args, c) => executeTool(args, (a) => operations.runDoctor(a), ctx(c))
9558
+ );
9559
+ }
9560
+
9561
+ // src/mcp/server.ts
9562
+ function bloxMcpInstructions(context) {
9563
+ const scope = context.app ? ` (application "${context.app}")` : "";
9564
+ return [
9565
+ "BLOX CLI MCP server: inspect and modify block-based BLOX projects.",
9566
+ "",
9567
+ `Project: this server is bound to the BLOX project at ${context.projectDir}${scope}. Every tool operates on it; you do not need to pass cwd. An optional cwd must stay inside ${context.workspaceRoot} (relative paths resolve against it). Pass \`app\` to target an application under apps/. To work on a different project, start another \`blox mcp --cwd <dir>\` server. Application management is not available through this server.`,
9568
+ "",
9569
+ "Recommended workflow:",
9570
+ "1. Call get_project_context first to learn the workspace, apps, installed blocks, and git dirtiness.",
9571
+ "2. Use list_available_blocks / get_block (or the blox://blocks/{name} resource) to explore blocks before adding them.",
9572
+ "3. add_blocks and update_project require a clean git working tree in the target scope; ask the user to commit first if git.projectDirty is true.",
9573
+ "4. Before update_project, call it with dryRun=true and show the plan to the user.",
9574
+ "5. Before remove_blocks, call it with dryRun=true, show which blocks and dependents are affected, and get confirmation from the user.",
9575
+ "",
9576
+ "Safety: remove_blocks deletes block directories; replace, rewriteDeps, hard, allowBreaking, remove_blocks force=true, and run_doctor fix=true can overwrite or break local work. Only set them after the user explicitly agrees. Mutating tools run one at a time and may take minutes (git clones, lifecycle hooks)."
9577
+ ].join("\n");
9578
+ }
9579
+ function createBloxMcpServer(options) {
9580
+ const { context } = options;
9581
+ const operations = options.operations ?? createDefaultOperations();
9582
+ const queue = createSerialQueue();
9583
+ const server = new import_server2.McpServer(
9584
+ {
9585
+ name: "blox",
9586
+ version: getBloxCliVersion()
9587
+ },
9588
+ {
9589
+ capabilities: {
9590
+ tools: {},
9591
+ resources: {},
9592
+ completions: {}
9593
+ },
9594
+ instructions: bloxMcpInstructions(context)
9595
+ }
9596
+ );
9597
+ registerBloxTools(server, operations, context, queue);
9598
+ registerBloxResources(server, operations, context, queue);
9599
+ return server;
9600
+ }
9601
+
9602
+ // src/mcp/stdio.ts
9603
+ var import_node_stream = require("stream");
9604
+ var import_stdio = require("@modelcontextprotocol/server/stdio");
9605
+ function isolateMcpStdout() {
9606
+ const originalWrite = process.stdout.write;
9607
+ const boundOriginalWrite = originalWrite.bind(process.stdout);
9608
+ const stderrWrite = process.stderr.write.bind(process.stderr);
9609
+ const protocolStdout = new import_node_stream.Writable({
9610
+ write(chunk, _encoding, callback) {
9611
+ boundOriginalWrite(chunk, () => callback());
9612
+ }
9613
+ });
9614
+ process.stdout.write = (chunk, ...rest) => stderrWrite(chunk, ...rest);
9615
+ return {
9616
+ protocolStdout,
9617
+ restore() {
9618
+ process.stdout.write = originalWrite;
9619
+ }
9620
+ };
9621
+ }
9622
+ function serveBloxMcp(options = {}) {
9623
+ const isolation = isolateMcpStdout();
9624
+ const context = createBloxMcpContext(options.cwd);
9625
+ const transport = new import_stdio.StdioServerTransport(process.stdin, isolation.protocolStdout);
9626
+ console.error(
9627
+ `[blox mcp] serving BLOX project ${context.projectDir}${context.app ? ` (app: ${context.app})` : ""}`
9628
+ );
9629
+ (0, import_stdio.serveStdio)(() => createBloxMcpServer({ context }), {
9630
+ transport,
9631
+ onerror: (error2) => {
9632
+ console.error(`[blox mcp] ${error2.message}`);
9633
+ }
9634
+ });
9635
+ return context;
9636
+ }
9637
+
9638
+ // src/commands/mcp/index.ts
9639
+ var mcp = command("mcp").description("Start the BLOX MCP server over stdio for one BLOX project").option(
9640
+ "--cwd <dir>",
9641
+ "BLOX project directory to serve (relative paths resolve against the current directory)"
9642
+ ).addHelpText(
9643
+ "after",
9644
+ `
9645
+ The MCP server is intended to be launched by an MCP-compatible client:
9646
+ blox mcp # serve the project containing the current directory
9647
+ blox mcp --cwd /projects/my-dashboard # serve an explicit project
9648
+
9649
+ One server serves one BLOX project, resolved and validated at startup. The
9650
+ server exits with an error when the directory does not exist, is not
9651
+ accessible, or is not inside a BLOX project. Start one server per project.
9652
+
9653
+ Stdout is reserved for MCP protocol messages; diagnostics go to stderr.
9654
+ The client owns the server lifecycle and should terminate it on shutdown.`
9655
+ ).action((options) => {
9656
+ setNonInteractive(true);
9657
+ setMinimalMode(true);
9658
+ try {
9659
+ serveBloxMcp({ cwd: options.cwd });
9660
+ } catch (e) {
9661
+ handleCommandError(e);
9662
+ }
9663
+ });
9664
+
9665
+ // src/commands/remove/index.ts
9666
+ var import_node_path37 = __toESM(require("path"));
9667
+ var import_fs_extra30 = __toESM(require("fs-extra"));
9668
+ function listInstalledBlockRelPaths(blocksRoot, projectDir) {
9669
+ if (!import_fs_extra30.default.existsSync(blocksRoot)) {
9670
+ return [];
9671
+ }
9672
+ const paths2 = [];
9673
+ for (const entry of import_fs_extra30.default.readdirSync(blocksRoot, { withFileTypes: true })) {
9674
+ if (!entry.isDirectory()) {
9675
+ continue;
9676
+ }
9677
+ const abs = import_node_path37.default.join(blocksRoot, entry.name);
9678
+ if (!isBlockDirectory(abs)) {
9679
+ continue;
9680
+ }
9681
+ paths2.push(import_node_path37.default.relative(projectDir, abs));
9682
+ }
9683
+ return paths2;
9684
+ }
9685
+ function getInstalledSelectOptions(context) {
9686
+ const blocksRoot = import_node_path37.default.join(context.projectDir, blocksDir);
9687
+ const options = listInstalledBlockRelPaths(blocksRoot, context.projectDir).map((rel) => {
9688
+ const folder = import_node_path37.default.basename(rel);
9689
+ const def = getBlockDef(import_node_path37.default.join(context.projectDir, rel));
9690
+ const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
9691
+ return { value: `block/${folder}`, label: `block/${label}`, hint: def?.name };
9692
+ });
9693
+ if (!context.app) {
9694
+ for (const app2 of listApps(context.workspaceRoot)) {
9695
+ options.push({ value: `app/${app2.key}`, label: `app/${app2.key}`, hint: app2.def?.name });
9696
+ }
9697
+ }
9698
+ return options;
9699
+ }
9700
+ var remove = addExecutionOptions(
9701
+ command("remove").description("Remove block from app").alias("rm").argument(
9702
+ "[blocks...]",
9703
+ "Components to remove (registry key, installed folder name, app/<name>, or block/<name>)"
9704
+ ).option("--app <name>", "Scope to an application under apps/").option("-f, --force", "Remove even if other blocks declare a dependency on this block").addHelpText(
9705
+ "after",
9706
+ `
9707
+ Non-interactive usage:
9708
+ blox remove block-a --non-interactive
9709
+ blox remove app/web --non-interactive
9710
+ blox remove auth --app web --non-interactive
9711
+ blox remove block-a block-b --json # JSON result on stdout
9712
+
9713
+ In non-interactive mode (--non-interactive or a non-TTY stdin) component
9714
+ arguments are required; nothing is prompted. Use app/<name> to remove an
9715
+ application at workspace root, or --app <name> to remove blocks inside
9716
+ that application. --json only controls the output format and can be
9717
+ combined with either mode.`
9718
+ )
9719
+ ).action(async (selectedBlocks, args) => {
9720
+ initExecutionMode(args);
9721
+ const { force } = args;
9722
+ let projectDir = ".";
9723
+ try {
9724
+ const context = resolveContext(".", args.app);
9725
+ projectDir = context.projectDir;
9726
+ if (await git.hasUncommittedChanges(context.projectDir)) {
9727
+ if (isNonInteractive()) {
9728
+ throw new CliError(
9729
+ "Make sure to commit any changes first",
9730
+ "DIRTY_WORKING_TREE",
9731
+ exitCodes.GENERAL
9732
+ );
9733
+ }
9734
+ import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
9735
+ return;
9736
+ }
9737
+ const dirtyApps = /* @__PURE__ */ new Set();
9738
+ for (const app2 of listApps(context.workspaceRoot)) {
9739
+ if (await git.hasUncommittedChanges(app2.dir)) dirtyApps.add(app2.key);
9740
+ }
9741
+ await migrateAll(false, context.workspaceRoot);
9742
+ await syncRegistries();
9743
+ const templateDef = getTemplateDef(context.projectDir);
9744
+ const blocks = await getAvailableBlocks(templateDef);
9745
+ let componentsToRemove = Array.isArray(selectedBlocks) ? selectedBlocks : [];
9746
+ if (!componentsToRemove.length) {
9747
+ const options = getInstalledSelectOptions(context);
9748
+ if (!options.length) {
9749
+ throw new CliError(
9750
+ context.app ? `No installed blocks found under ${args.app}/blocks/` : "No installed blocks or applications found",
9751
+ "NOT_FOUND",
9752
+ exitCodes.NOT_FOUND
9753
+ );
9754
+ }
9755
+ if (isNonInteractive()) {
9756
+ throw new MissingArgumentsError(["blocks"]);
9757
+ }
9758
+ componentsToRemove = await multiselect({
9759
+ message: "Select components to remove",
9760
+ options
9761
+ });
9762
+ }
9763
+ if (!componentsToRemove.length) {
9764
+ throw new CliError("No components selected", "VALIDATION", exitCodes.USAGE);
9765
+ }
9766
+ const installedApps = new Set(
9767
+ context.app ? [] : listApps(context.workspaceRoot).map((app2) => app2.key)
9768
+ );
9769
+ if (force) {
9770
+ import_prompts2.log.warn(
9771
+ fmt.yellow(
9772
+ "--force: skipping dependency check; dependent blocks may be left in a broken state."
9773
+ )
9774
+ );
9775
+ }
9776
+ const removed = [];
9777
+ for (const arg of componentsToRemove) {
9778
+ const ref = parseQualifiedRef(arg);
9779
+ if (ref.type === "app") {
9780
+ if (context.app) {
9781
+ throw new CliError(
9782
+ `Cannot remove an application inside application "${context.app}"`,
9783
+ "VALIDATION",
9784
+ exitCodes.USAGE
9785
+ );
9786
+ }
9787
+ if (await removeApp(ref.name, context, dirtyApps)) {
9788
+ removed.push(arg);
9789
+ }
9790
+ continue;
9791
+ }
9792
+ if (!ref.type && installedApps.has(ref.name)) {
9793
+ const blocksRoot = import_node_path37.default.join(context.projectDir, blocksDir);
9794
+ const isBlock = import_fs_extra30.default.existsSync(import_node_path37.default.join(blocksRoot, ref.name));
9795
+ if (!isBlock) {
9796
+ if (await removeApp(ref.name, context, dirtyApps)) {
9797
+ removed.push(arg);
9798
+ }
9799
+ continue;
9800
+ }
9801
+ }
9802
+ const blockRemoved = await removeBlock(ref.name, blocks, context, force);
9803
+ if (blockRemoved) {
9804
+ removed.push(arg);
9805
+ }
9806
+ }
9807
+ if (removed.length) {
9808
+ await runLifecycleHookWithTask(context.projectDir, "remove", "Run template remove");
9809
+ }
9810
+ if (!force) {
9811
+ await checkVersionsCompatibility(context.projectDir);
9812
+ }
9813
+ if (isJsonMode()) {
9814
+ printJsonResult({ removed });
9815
+ }
9816
+ } catch (e) {
9817
+ if (!isDebugMode() && !(e instanceof CliError)) {
9818
+ import_prompts2.log.warn("Error happened, Will rollback changes");
9819
+ await git.rollback(projectDir);
9820
+ }
9821
+ handleCommandError(e);
9822
+ }
9823
+ });
9824
+
9825
+ // src/commands/skills/index.ts
9826
+ var import_node_crypto2 = require("crypto");
9827
+ var import_node_os4 = __toESM(require("os"));
9828
+ var import_node_path39 = __toESM(require("path"));
9829
+ var import_cross_spawn2 = __toESM(require("cross-spawn"));
9830
+ var import_fs_extra32 = __toESM(require("fs-extra"));
9831
+
9832
+ // src/commands/skills/constants.ts
9833
+ var SKILLS_REPO_URL = "https://github.com/Naseej-its/blox.git";
9834
+
9835
+ // src/commands/skills/utils/cliCompatibility.ts
9836
+ var import_node_path38 = __toESM(require("path"));
9837
+ var import_fs_extra31 = __toESM(require("fs-extra"));
9838
+ var import_semver4 = __toESM(require("semver"));
9839
+ var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
9840
+ function getSkillscommandIndex(args, subcommand) {
9841
+ for (let i = 0; i < args.length; i++) {
9842
+ if (args[i] !== subcommand) {
9843
+ continue;
9844
+ }
9845
+ if (args.slice(0, i).every((t) => t.startsWith("-"))) {
9846
+ return i;
9847
+ }
9848
+ }
9849
+ return -1;
9850
+ }
9851
+ function hasSkillscommand(args, subcommand) {
9852
+ return getSkillscommandIndex(args, subcommand) !== -1;
9853
+ }
9854
+ function needsCliCompatibilityCheck(args) {
9855
+ return SKILLS_CLI_COMPATIBILITY_COMMANDS.some((cmd) => hasSkillscommand(args, cmd));
9856
+ }
9857
+ function getAddCommandIndex(args) {
9858
+ return getSkillscommandIndex(args, "add");
9859
+ }
9860
+ async function loadSkillsData(cloneRoot) {
9861
+ const skillsDir = import_node_path38.default.join(cloneRoot, "skills");
9862
+ if (!await import_fs_extra31.default.pathExists(skillsDir)) {
9863
+ return [];
9864
+ }
9865
+ const entries = await import_fs_extra31.default.readdir(skillsDir, { withFileTypes: true });
9866
+ const manifests = await Promise.all(
9867
+ entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
9868
+ const filePath = import_node_path38.default.join(skillsDir, entry.name, "skill.json");
9869
+ if (!await import_fs_extra31.default.pathExists(filePath)) {
9870
+ return null;
9871
+ }
9872
+ const raw = await import_fs_extra31.default.readJson(filePath);
9873
+ const range = raw.cliCompatibility?.trim();
9874
+ if (!range) {
9875
+ return null;
9876
+ }
9877
+ return {
9878
+ name: raw.name || entry.name,
9879
+ version: raw.version || "0.0.0",
9880
+ cliCompatibility: range
9881
+ };
9882
+ })
9883
+ );
9884
+ return manifests.filter(Boolean);
9885
+ }
9886
+ function getFirstIncompatibleSkill(skills2, cliVersion) {
9887
+ const normalized = import_semver4.default.coerce(cliVersion)?.version ?? cliVersion;
9888
+ return skills2.find((skill) => {
9889
+ const range = skill.cliCompatibility;
9890
+ return import_semver4.default.validRange(range) && !import_semver4.default.satisfies(normalized, range, {
9891
+ includePrerelease: true
9892
+ });
9893
+ }) || null;
9894
+ }
9895
+ function warnIncompatibleSkill(skill, cliVersion) {
9896
+ const label = `${skill.name}@${skill.version}`;
9897
+ console.log("");
9898
+ console.log(
9899
+ fmt.yellow(`\u26A0\uFE0F Skill "${label}" may be incompatible with your CLI (${cliVersion})`)
9900
+ );
9901
+ console.log("");
9902
+ console.log(`${fmt.bold("Required:")} ${skill.cliCompatibility}`);
9903
+ console.log(`${fmt.bold("Current :")} ${cliVersion}`);
9904
+ console.log("");
9905
+ console.log(fmt.bold("You can:"));
9906
+ console.log(` ${fmt.cyan("\u2022")} Upgrade CLI \u2192 ${fmt.cyan("blox upgrade")}`);
9907
+ console.log("");
9908
+ }
9909
+
9910
+ // src/commands/skills/index.ts
9911
+ var skills = command("skills").description("Install, update, and manage BLOX CLI skills from internal repositories").helpOption(false).allowUnknownOption(true).action(async () => {
9912
+ try {
9913
+ const code = await runSkills();
9914
+ process.exit(code);
9915
+ } catch (e) {
9916
+ error(e, false);
9917
+ process.exit(1);
9918
+ }
9919
+ });
9920
+ async function runSkills() {
9921
+ const idx = process.argv.indexOf("skills");
9922
+ const args = idx === -1 ? [] : process.argv.slice(idx + 1);
9923
+ if (needsCliCompatibilityCheck(args)) {
9924
+ const tempDir = import_node_path39.default.join(import_node_os4.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto2.randomUUID)()}`);
9925
+ await import_fs_extra32.default.mkdir(tempDir);
9926
+ try {
9927
+ await git.clone(SKILLS_REPO_URL, tempDir);
9928
+ const skills2 = await loadSkillsData(tempDir);
9929
+ const cliVersion = getBloxCliVersion();
9930
+ const uncompatibleSkill = getFirstIncompatibleSkill(skills2, cliVersion);
9931
+ if (uncompatibleSkill) {
9932
+ warnIncompatibleSkill(uncompatibleSkill, cliVersion);
9933
+ const proceed = await confirm({
9934
+ message: "Continue anyway? (No \u2014 exit and run blox upgrade first)",
9935
+ initialValue: false
9936
+ });
9937
+ if (!proceed) {
9938
+ return 1;
9939
+ }
9940
+ }
9941
+ } finally {
9942
+ try {
9943
+ await import_fs_extra32.default.remove(tempDir);
9944
+ } catch {
9945
+ debug(`Failed to cleanup temp dir: ${tempDir}`);
9946
+ }
9947
+ }
9948
+ }
9949
+ const finalArgs = injectRepoUrlIfAdd(args, SKILLS_REPO_URL);
9950
+ return runSkillsCommand(finalArgs, process.cwd());
9951
+ }
9952
+ function injectRepoUrlIfAdd(args, repoPath) {
9953
+ const addIndex = getAddCommandIndex(args);
9954
+ if (addIndex === -1) return args;
9955
+ const next = args[addIndex + 1];
9956
+ if (!next || next.startsWith("-")) {
9957
+ return [...args.slice(0, addIndex + 1), repoPath, ...args.slice(addIndex + 1)];
9958
+ }
9959
+ const updated = [...args];
9960
+ updated[addIndex + 1] = repoPath;
9961
+ return updated;
9962
+ }
9963
+ function runSkillsCommand(args, cwd2) {
9964
+ debug(`npx skills ${args.join(" ")}`);
9965
+ return new Promise((resolve, reject) => {
9966
+ const child = (0, import_cross_spawn2.default)("npx", ["skills", ...args], {
9967
+ cwd: cwd2,
9968
+ stdio: "inherit"
9969
+ });
9970
+ child.on("error", reject);
9971
+ child.on("close", (code) => resolve(code ?? 1));
9972
+ });
9973
+ }
9974
+
9975
+ // src/commands/update/index.ts
9976
+ var import_prompts29 = require("@clack/prompts");
9977
+
9978
+ // src/commands/update/utils.ts
9979
+ var import_node_path40 = __toESM(require("path"));
9980
+ var import_fs_extra33 = __toESM(require("fs-extra"));
9981
+ function reportUpdateSummary(summary, mode) {
9982
+ const failedScopes = (summary.scopes ?? []).filter((scope) => scope.error);
9983
+ const failed = summary.failedBlocks.length > 0 || failedScopes.length > 0;
9984
+ if (mode.json) {
9985
+ if (failed) {
9986
+ printJsonError({
9987
+ code: summary.failedBlocks.length ? "BLOCK_UPDATE_FAILED" : "UPDATE_FAILED",
9988
+ message: [
9989
+ ...summary.failedBlocks.map(
9990
+ (failure) => `${failure.block}: ${failure.error}`
9991
+ ),
9992
+ ...failedScopes.map((scope) => `${scope.scope}: ${scope.error}`)
9993
+ ].join("; "),
9994
+ details: { ...summary },
9995
+ exitCode: exitCodes.GENERAL
9996
+ });
9997
+ } else {
9998
+ printJsonResult(summary);
9999
+ }
10000
+ return;
10001
+ }
10002
+ if (failed && mode.nonInteractive) {
10003
+ process.exitCode = exitCodes.GENERAL;
10004
+ }
10005
+ }
10006
+ async function printChangeLog(startCheckpoints, endCheckpoints, workspaceRoot = ".") {
10007
+ const allChanges = [];
10008
+ const repoDirFor = (name) => {
10009
+ const appKey = name.split("/")[0] ?? "";
10010
+ const appDir = import_node_path40.default.join(workspaceRoot, appsDir, appKey);
10011
+ return name.includes("/") && import_fs_extra33.default.existsSync(import_node_path40.default.join(appDir, bloxFilePath)) ? appDir : workspaceRoot;
10012
+ };
10013
+ for (const name of Object.keys(startCheckpoints)) {
10014
+ const fromCommit = startCheckpoints[name]?.commit;
10015
+ const toCommit = endCheckpoints[name]?.commit;
10016
+ if (!fromCommit || !toCommit) continue;
10017
+ if (fromCommit === toCommit) continue;
10018
+ const changes = await git.getChangesLog(
10019
+ fromCommit,
10020
+ toCommit,
10021
+ repoDirFor(name)
10022
+ );
10023
+ if (changes.trim() !== "") {
10024
+ allChanges.push(`${fmt.bold(fmt.bgYellowBright(name))}:
10025
+
10026
+ ${changes}`);
10027
+ }
10028
+ }
10029
+ if (allChanges.length) {
10030
+ logWarningSection(
10031
+ "ChangeLog, These is the changes from last update, make sure to review for breaking changes",
10032
+ allChanges.join(`
10033
+ ${fmt.gray("-".repeat(82))}
10034
+
10035
+ `).replace(/BREAKING CHANGE/gi, fmt.red("BREAKING CHANGE"))
10036
+ );
10037
+ } else {
10038
+ import_prompts2.log.success("already up to date");
10039
+ }
10040
+ }
10041
+
10042
+ // src/commands/update/index.ts
10043
+ var update2 = addExecutionOptions(
10044
+ command("update").description("Update app/block").alias("u").addOption(
10045
+ option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
10046
+ ).option("--app <name>", "Limit the update to one application under apps/").option(
10047
+ "--ignore <list...>",
10048
+ 'Files ignore list scoped by name i.e "repo:file"'
10049
+ ).option(
10050
+ "-b, --block <names...>",
10051
+ "Blocks to update, valid only with scope block"
10052
+ ).option("--hard", "Hard update (overwrite local changes)", false).option(
10053
+ "--allow-breaking",
10054
+ "authorize applying updates that contain breaking changes",
10055
+ false
10056
+ ).addHelpText(
10057
+ "after",
10058
+ `
10059
+ Non-interactive usage:
10060
+ blox update --non-interactive # update everything
10061
+ blox update --non-interactive --allow-breaking # also apply breaking changes
10062
+ blox update -s block -b my-block --json # single block, JSON output
10063
+ blox update --app web # update only the web application
10064
+
10065
+ In non-interactive mode (--non-interactive or a non-TTY stdin) nothing is
10066
+ prompted. Updates containing breaking changes require --allow-breaking;
10067
+ without it the command stops before applying them. --json only controls
10068
+ the output format and can be combined with either mode.
10069
+
10070
+ Without --app, an update run at the workspace root covers the root project
10071
+ and every application under apps/ sequentially. Run inside an application
10072
+ directory to limit the update to that application.`
10073
+ )
10074
+ ).action(async (args) => {
10075
+ initExecutionMode(args);
10076
+ const ignoresByName = {};
10077
+ for (const ignore3 of args.ignore || []) {
10078
+ const [repo, pattern] = ignore3.split(":");
10079
+ if (!repo || !pattern) {
10080
+ handleCommandError(
10081
+ new CliError("Invalid ignore pattern", "VALIDATION", exitCodes.USAGE)
10082
+ );
10083
+ continue;
10084
+ }
10085
+ if (!ignoresByName[repo]) {
10086
+ ignoresByName[repo] = [];
10087
+ }
10088
+ ignoresByName[repo].push(pattern);
10089
+ }
10090
+ const touchedScopes = [];
10091
+ try {
10092
+ const context = resolveContext(".", args.app);
10093
+ const scoped = args.app || context.app;
10094
+ const scopes = scoped ? [{ dir: context.projectDir, app: context.app }] : [
10095
+ { dir: context.workspaceRoot },
10096
+ ...listApps(context.workspaceRoot).map((app2) => ({
10097
+ dir: app2.dir,
10098
+ app: app2.key
10099
+ }))
10100
+ ];
10101
+ const dirtyScopes = [];
10102
+ for (const scope of scopes) {
10103
+ if (await git.hasUncommittedChanges(scope.dir)) {
10104
+ dirtyScopes.push(scope.app ?? "workspace root");
10105
+ }
10106
+ }
10107
+ if (dirtyScopes.length) {
10108
+ const message3 = `Make sure to commit any changes first: ${dirtyScopes.join(", ")}`;
10109
+ if (isNonInteractive()) {
10110
+ throw new CliError(message3, "DIRTY_WORKING_TREE", exitCodes.GENERAL);
10111
+ }
10112
+ import_prompts29.log.warn(fmt.yellow(message3));
10113
+ return;
10114
+ }
10115
+ const rootTemplateName = getTemplateDef(context.workspaceRoot).name;
10116
+ await migrateAll(true, context.workspaceRoot);
10117
+ await syncRegistries();
10118
+ const startCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
10119
+ let hasUpdate = false;
10120
+ let stoppedEarly = false;
10121
+ const failedBlocks = [];
10122
+ const scopeResults = [];
10123
+ const cwd2 = process.cwd();
10124
+ try {
10125
+ for (const scope of scopes) {
10126
+ process.chdir(scope.dir);
10127
+ touchedScopes.push(scope.dir);
10128
+ try {
10129
+ const result = await runUpdateScope(
10130
+ args,
10131
+ ignoresByName,
10132
+ rootTemplateName,
10133
+ scope.app
10134
+ );
10135
+ hasUpdate = hasUpdate || result.updated;
10136
+ stoppedEarly = stoppedEarly || result.stoppedEarly;
10137
+ failedBlocks.push(...result.failedBlocks);
10138
+ scopeResults.push({ scope: scope.app ?? "(root)", ...result });
10139
+ } catch (scopeError) {
10140
+ if (scopeError instanceof CliError) throw scopeError;
10141
+ const message3 = scopeError instanceof Error ? scopeError.message : String(scopeError);
10142
+ try {
10143
+ await git.rollback(scope.dir);
10144
+ } catch (rollbackError) {
10145
+ import_prompts29.log.warn(
10146
+ fmt.yellow(`Rollback failed for ${scope.dir}: ${rollbackError}`)
10147
+ );
10148
+ }
10149
+ scopeResults.push({
10150
+ scope: scope.app ?? "(root)",
10151
+ updated: false,
10152
+ stoppedEarly: false,
10153
+ failedBlocks: [],
10154
+ error: message3
10155
+ });
10156
+ import_prompts29.log.error(fmt.red(`${scope.app ?? "workspace root"}: ${message3}`));
10157
+ }
10158
+ }
10159
+ } finally {
10160
+ process.chdir(cwd2);
10161
+ }
10162
+ const endCheckpoints = await getCurrentCheckpoints(context.workspaceRoot);
10163
+ await printChangeLog(startCheckpoints, endCheckpoints, context.workspaceRoot);
10164
+ const failedScopes = scopeResults.filter((result) => result.error);
10165
+ if (failedScopes.length) {
10166
+ import_prompts29.log.warn(
10167
+ fmt.yellow(
10168
+ `${failedScopes.length} scope(s) failed to update: ${failedScopes.map((result) => result.scope).join(", ")}`
10169
+ )
10170
+ );
10171
+ }
10172
+ reportUpdateSummary(
10173
+ { updated: hasUpdate, stoppedEarly, failedBlocks, scopes: scopeResults },
10174
+ { json: isJsonMode(), nonInteractive: isNonInteractive() }
10175
+ );
10176
+ } catch (e) {
10177
+ if (!isDebugMode() && !(e instanceof CliError)) {
10178
+ import_prompts29.log.warn("Error happened, Will rollback changes");
10179
+ for (const dir of new Set(touchedScopes)) {
10180
+ try {
10181
+ await git.rollback(dir);
10182
+ } catch {
10183
+ }
10184
+ }
10185
+ if (!touchedScopes.length) {
10186
+ await git.rollback();
10187
+ }
10188
+ }
10189
+ handleCommandError(e);
10190
+ } finally {
10191
+ await git.cleanUpWorktrees();
10192
+ }
10193
+ });
8424
10194
 
8425
10195
  // src/commands/upgrade/index.ts
8426
10196
  var upgrade = addExecutionOptions(
@@ -8456,7 +10226,8 @@ var commands = [
8456
10226
  detach,
8457
10227
  contribute,
8458
10228
  skills,
8459
- doctor
10229
+ doctor,
10230
+ mcp
8460
10231
  ];
8461
10232
 
8462
10233
  // bin/run.ts