@naseej/blox 1.8.0 → 1.9.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 (3) hide show
  1. package/dist/run.js +1245 -533
  2. package/package.json +11 -3
  3. package/readme.md +54 -12
package/dist/run.js CHANGED
@@ -201,10 +201,7 @@ var checkForCliUpdate = async (currentVersion, argv = []) => {
201
201
  };
202
202
 
203
203
  // package.json
204
- var version = "1.8.0";
205
-
206
- // src/commands/add/index.ts
207
- var import_fs_extra11 = __toESM(require("fs-extra"));
204
+ var version = "1.9.0";
208
205
 
209
206
  // src/migrations/index.ts
210
207
  var import_node_path11 = __toESM(require("path"));
@@ -551,6 +548,16 @@ function updateCheckpoint(name, checkpoint, cwd = ".") {
551
548
  info.checkpoints[name] = checkpoint;
552
549
  saveBloxFile(info, cwd);
553
550
  }
551
+ function getBlockPath(name) {
552
+ if (import_fs_extra5.default.existsSync(blocksDir)) {
553
+ for (const entry of import_fs_extra5.default.readdirSync(blocksDir, { withFileTypes: true })) {
554
+ if (!entry.isDirectory()) continue;
555
+ const dir = import_node_path7.default.join(blocksDir, entry.name);
556
+ if (getBloxFile(dir).definition?.name === name) return dir;
557
+ }
558
+ }
559
+ throw new Error(`Block is not installed: ${name}`);
560
+ }
554
561
  function getUsedBlocksDef() {
555
562
  return getUsedBlocks().map((b) => b.definition);
556
563
  }
@@ -738,7 +745,6 @@ var updatedRemotes = /* @__PURE__ */ new Set();
738
745
  var updateRemote = async (name, source, shellOptions = {}) => {
739
746
  const remoteId = `${name}:${source}`;
740
747
  if (updatedRemotes.has(remoteId)) return;
741
- updatedRemotes.add(remoteId);
742
748
  debug("updateRemote");
743
749
  debug({ name, source });
744
750
  try {
@@ -753,6 +759,7 @@ var updateRemote = async (name, source, shellOptions = {}) => {
753
759
  ...shellOptions
754
760
  });
755
761
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
762
+ updatedRemotes.add(remoteId);
756
763
  };
757
764
  var readJsonFromCommit = async (commit2, file, cwd = ".") => {
758
765
  try {
@@ -787,9 +794,9 @@ var readJsonFromIndex = async (file, cwd = ".") => {
787
794
  var readJsonFromRemote = async (remote, file, branch = defaultBranch, commit2) => {
788
795
  return readJsonFromCommit(commit2 || `${remote}/${branch}`, file);
789
796
  };
790
- var isCommitOlder = async (a, b) => {
797
+ var isCommitOlder = async (a, b, cwd = ".") => {
791
798
  try {
792
- await $("git", ["merge-base", "--is-ancestor", a, b]);
799
+ await $("git", ["merge-base", "--is-ancestor", a, b], { cwd });
793
800
  return true;
794
801
  } catch {
795
802
  return false;
@@ -1032,6 +1039,20 @@ var getUnmergedFiles = async (cwd = ".") => {
1032
1039
  var fetchRepo = async (cwd = ".") => {
1033
1040
  await $("git", ["fetch", "--progress", "origin"], { cwd });
1034
1041
  };
1042
+ var getChangedFilesInCommit = async (commit2, cwd = ".") => {
1043
+ let out = "";
1044
+ await $(
1045
+ "git",
1046
+ ["diff-tree", "--no-commit-id", "--name-only", "-r", "--root", normalizeCommitRef(commit2)],
1047
+ {
1048
+ cwd,
1049
+ onStdout: (text2) => {
1050
+ out += text2;
1051
+ }
1052
+ }
1053
+ );
1054
+ return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1055
+ };
1035
1056
  var getChangedFilesFromHead = async (cwd = ".") => {
1036
1057
  let out = "";
1037
1058
  await $("git", ["diff", "--name-status", "-z", "HEAD"], {
@@ -1098,7 +1119,8 @@ var git = {
1098
1119
  commitAll,
1099
1120
  getUnmergedFiles,
1100
1121
  fetchRepo,
1101
- getChangedFilesFromHead
1122
+ getChangedFilesFromHead,
1123
+ getChangedFilesInCommit
1102
1124
  };
1103
1125
 
1104
1126
  // src/shared/prompts/index.ts
@@ -1239,6 +1261,11 @@ async function migrateAll(autoCommit) {
1239
1261
  }
1240
1262
  }
1241
1263
 
1264
+ // src/services/add.ts
1265
+ var import_node_os2 = __toESM(require("os"));
1266
+ var import_node_path14 = __toESM(require("path"));
1267
+ var import_fs_extra11 = __toESM(require("fs-extra"));
1268
+
1242
1269
  // src/services/fs.ts
1243
1270
  var import_node_path12 = __toESM(require("path"));
1244
1271
  var import_fs_extra9 = __toESM(require("fs-extra"));
@@ -1261,6 +1288,97 @@ var deletePattern = async (cwd, patterns = []) => {
1261
1288
  }
1262
1289
  };
1263
1290
 
1291
+ // src/services/versions/checkCompatibility.ts
1292
+ function processDependencyVersion(dep) {
1293
+ if (!dep.version) dep.version = 0;
1294
+ return dep;
1295
+ }
1296
+ function processTemplate(def) {
1297
+ debug("processTemplate");
1298
+ if (!def.version) def.version = 0;
1299
+ Object.values(def.bases || {}).forEach(processDependencyVersion);
1300
+ return def;
1301
+ }
1302
+ function processBases(info) {
1303
+ debug("processBases");
1304
+ if (!info || !info.checkpoints) return {};
1305
+ Object.values(info.checkpoints).forEach((base) => {
1306
+ if (!base.version) base.version = 0;
1307
+ });
1308
+ return info.checkpoints;
1309
+ }
1310
+ function processBlocks(defs) {
1311
+ debug("processBlocks");
1312
+ defs.forEach((def) => {
1313
+ if (!def.version) def.version = 0;
1314
+ def.dependencies?.forEach(processDependencyVersion);
1315
+ def.templates?.forEach(processDependencyVersion);
1316
+ });
1317
+ return defs;
1318
+ }
1319
+ function ensureVersionOverlap(version2 = 0, range = 0, mismatchMessage) {
1320
+ if (typeof range === "number") {
1321
+ range = [range, range];
1322
+ }
1323
+ const match = version2 >= range[0] && version2 <= range[1];
1324
+ if (!match) {
1325
+ const requiredVersionText = range[0] === range[1] ? `${range[0]}` : `min: ${range[0]}, max: ${range[1]}`;
1326
+ throw new Error(
1327
+ normalizeLogMessage(`
1328
+ ${mismatchMessage}
1329
+ current version: ${version2}
1330
+ required version: ${requiredVersionText}
1331
+ `)
1332
+ );
1333
+ }
1334
+ }
1335
+ async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
1336
+ for (const templateBaseDep of template.bases || []) {
1337
+ const currentVersion = basesVersion[templateBaseDep.name]?.version;
1338
+ ensureVersionOverlap(
1339
+ currentVersion,
1340
+ templateBaseDep.version,
1341
+ `Template "${template.name}" version: ${template.version} is not compatible with base "${templateBaseDep.name}"`
1342
+ );
1343
+ }
1344
+ for (const block of usedBlocks) {
1345
+ for (const blockTemplateDep of block.templates || []) {
1346
+ const currentTemplate = basesVersion[blockTemplateDep.name];
1347
+ if (!currentTemplate) {
1348
+ throw new Error(
1349
+ `Block "${block.name}" version: ${block.version} depends on missing template "${blockTemplateDep.name}" `
1350
+ );
1351
+ }
1352
+ ensureVersionOverlap(
1353
+ currentTemplate?.version,
1354
+ blockTemplateDep.version,
1355
+ `Block "${block.name}" version: ${block.version} is not compatible with template "${blockTemplateDep.name}" `
1356
+ );
1357
+ }
1358
+ for (const blockDep of block.dependencies || []) {
1359
+ const blockDepDef = usedBlocks.find((b) => b.name === blockDep.name);
1360
+ if (!blockDepDef) {
1361
+ throw new Error(
1362
+ `Block "${block.name}" version: ${block.version} depends on missing block "${blockDep.name}" `
1363
+ );
1364
+ }
1365
+ ensureVersionOverlap(
1366
+ blockDepDef?.version,
1367
+ blockDep.version,
1368
+ `Block "${block.name}" version: ${block.version} is not compatible with block "${blockDep.name}" `
1369
+ );
1370
+ }
1371
+ }
1372
+ }
1373
+ async function checkVersionsCompatibility() {
1374
+ debug("checkVersionsCompatibility");
1375
+ const template = processTemplate(getTemplateDef());
1376
+ const usedBlocks = processBlocks(getUsedBlocksDef());
1377
+ const basesVersion = processBases(getBloxFile());
1378
+ basesVersion[template.name] = { version: template.version, commit: "" };
1379
+ await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
1380
+ }
1381
+
1264
1382
  // src/services/registry.ts
1265
1383
  var import_node_path13 = __toESM(require("path"));
1266
1384
  var import_fs_extra10 = __toESM(require("fs-extra"));
@@ -1387,97 +1505,6 @@ var getAvailableVersions = async (source) => {
1387
1505
  }
1388
1506
  };
1389
1507
 
1390
- // src/services/versions/checkCompatibility.ts
1391
- function processDependencyVersion(dep) {
1392
- if (!dep.version) dep.version = 0;
1393
- return dep;
1394
- }
1395
- function processTemplate(def) {
1396
- debug("processTemplate");
1397
- if (!def.version) def.version = 0;
1398
- Object.values(def.bases || {}).forEach(processDependencyVersion);
1399
- return def;
1400
- }
1401
- function processBases(info) {
1402
- debug("processBases");
1403
- if (!info || !info.checkpoints) return {};
1404
- Object.values(info.checkpoints).forEach((base) => {
1405
- if (!base.version) base.version = 0;
1406
- });
1407
- return info.checkpoints;
1408
- }
1409
- function processBlocks(defs) {
1410
- debug("processBlocks");
1411
- defs.forEach((def) => {
1412
- if (!def.version) def.version = 0;
1413
- def.dependencies?.forEach(processDependencyVersion);
1414
- def.templates?.forEach(processDependencyVersion);
1415
- });
1416
- return defs;
1417
- }
1418
- function ensureVersionOverlap(version2 = 0, range = 0, mismatchMessage) {
1419
- if (typeof range === "number") {
1420
- range = [range, range];
1421
- }
1422
- const match = version2 >= range[0] && version2 <= range[1];
1423
- if (!match) {
1424
- const requiredVersionText = range[0] === range[1] ? `${range[0]}` : `min: ${range[0]}, max: ${range[1]}`;
1425
- throw new Error(
1426
- normalizeLogMessage(`
1427
- ${mismatchMessage}
1428
- current version: ${version2}
1429
- required version: ${requiredVersionText}
1430
- `)
1431
- );
1432
- }
1433
- }
1434
- async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
1435
- for (const templateBaseDep of template.bases || []) {
1436
- const currentVersion = basesVersion[templateBaseDep.name]?.version;
1437
- ensureVersionOverlap(
1438
- currentVersion,
1439
- templateBaseDep.version,
1440
- `Template "${template.name}" version: ${template.version} is not compatible with base "${templateBaseDep.name}"`
1441
- );
1442
- }
1443
- for (const block of usedBlocks) {
1444
- for (const blockTemplateDep of block.templates || []) {
1445
- const currentTemplate = basesVersion[blockTemplateDep.name];
1446
- if (!currentTemplate) {
1447
- throw new Error(
1448
- `Block "${block.name}" version: ${block.version} depends on missing template "${blockTemplateDep.name}" `
1449
- );
1450
- }
1451
- ensureVersionOverlap(
1452
- currentTemplate?.version,
1453
- blockTemplateDep.version,
1454
- `Block "${block.name}" version: ${block.version} is not compatible with template "${blockTemplateDep.name}" `
1455
- );
1456
- }
1457
- for (const blockDep of block.dependencies || []) {
1458
- const blockDepDef = usedBlocks.find((b) => b.name === blockDep.name);
1459
- if (!blockDepDef) {
1460
- throw new Error(
1461
- `Block "${block.name}" version: ${block.version} depends on missing block "${blockDep.name}" `
1462
- );
1463
- }
1464
- ensureVersionOverlap(
1465
- blockDepDef?.version,
1466
- blockDep.version,
1467
- `Block "${block.name}" version: ${block.version} is not compatible with block "${blockDep.name}" `
1468
- );
1469
- }
1470
- }
1471
- }
1472
- async function checkVersionsCompatibility() {
1473
- debug("checkVersionsCompatibility");
1474
- const template = processTemplate(getTemplateDef());
1475
- const usedBlocks = processBlocks(getUsedBlocksDef());
1476
- const basesVersion = processBases(getBloxFile());
1477
- basesVersion[template.name] = { version: template.version, commit: "" };
1478
- await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
1479
- }
1480
-
1481
1508
  // src/services/versions/select.ts
1482
1509
  async function selectVersion(source, fromCommit) {
1483
1510
  const versionsData = await getAvailableVersions(source);
@@ -1510,22 +1537,155 @@ async function selectVersion(source, fromCommit) {
1510
1537
  return versionsData[version2]?.lastCommit;
1511
1538
  }
1512
1539
 
1513
- // src/commands/add/index.ts
1514
- var addBlock = async (block, blocks, branch, destination) => {
1515
- const blockRegistryData = blocks[block];
1516
- if (!destination) {
1517
- destination = blockRegistryData?.destination || block;
1540
+ // src/services/add.ts
1541
+ function recordResult(results, result) {
1542
+ const index = results.findIndex((previous) => previous.block === result.block);
1543
+ if (index === -1) {
1544
+ results.push(result);
1545
+ } else if (result.status !== "skipped") {
1546
+ results[index] = result;
1547
+ }
1548
+ }
1549
+ function getInstalledBlockNames() {
1550
+ return new Set(
1551
+ getUsedBlocks().flatMap(({ definition, checkpoints }) => [
1552
+ definition.name,
1553
+ ...Object.keys(checkpoints || {})
1554
+ ])
1555
+ );
1556
+ }
1557
+ function findDependents(oldNames, ownedDir) {
1558
+ if (!import_fs_extra11.default.existsSync(blocksDir)) return [];
1559
+ return import_fs_extra11.default.readdirSync(blocksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path14.default.join(blocksDir, entry.name)).filter((dir) => import_node_path14.default.resolve(dir) !== import_node_path14.default.resolve(ownedDir)).filter(
1560
+ (dir) => getBloxFile(dir).definition?.dependencies?.some(
1561
+ (d) => oldNames.has(d.name)
1562
+ )
1563
+ );
1564
+ }
1565
+ function renameDependency(dir, oldNames, newName) {
1566
+ const file = getBloxFile(dir);
1567
+ for (const dependency of file.definition.dependencies || []) {
1568
+ if (oldNames.has(dependency.name)) dependency.name = newName;
1569
+ }
1570
+ saveBloxFile(file, dir);
1571
+ }
1572
+ function errorMessage(cause) {
1573
+ return cause instanceof Error ? cause.message : String(cause);
1574
+ }
1575
+ function assertNoSymlinkParents(filename) {
1576
+ const root = import_node_path14.default.resolve(".");
1577
+ for (let parent = import_node_path14.default.dirname(import_node_path14.default.resolve(filename)); parent !== root; parent = import_node_path14.default.dirname(parent)) {
1578
+ if (parent === import_node_path14.default.dirname(parent)) throw new Error(`Path outside project: ${filename}`);
1579
+ if (import_fs_extra11.default.existsSync(parent) && import_fs_extra11.default.lstatSync(parent).isSymbolicLink()) {
1580
+ throw new Error(`Symbolic link in block destination: ${filename}`);
1581
+ }
1582
+ }
1583
+ }
1584
+ async function snapshot(ownedPath, directory = import_node_path14.default.resolve("."), entries = /* @__PURE__ */ new Map()) {
1585
+ for (const entry of await import_fs_extra11.default.readdir(directory, { withFileTypes: true })) {
1586
+ const filename = import_node_path14.default.join(directory, entry.name);
1587
+ const owned = filename === ownedPath || filename.startsWith(ownedPath + import_node_path14.default.sep);
1588
+ if (!owned && (entry.name === ".git" || entry.name === "node_modules")) continue;
1589
+ entries.set(filename, {
1590
+ directory: entry.isDirectory(),
1591
+ metadata: entry.isFile() && entry.name === ".blox" ? await import_fs_extra11.default.readFile(filename) : void 0
1592
+ });
1593
+ if (entry.isDirectory()) await snapshot(ownedPath, filename, entries);
1518
1594
  }
1519
- const blockPath = `blocks/${destination}`;
1520
- let newBlockAdded = false;
1521
- if (!import_fs_extra11.default.existsSync(blockPath)) {
1522
- newBlockAdded = true;
1595
+ return entries;
1596
+ }
1597
+ async function cleanup(before, after) {
1598
+ const failures = [];
1599
+ const deletedMetadata = [...before].filter(
1600
+ ([filename, entry]) => entry.metadata && !after.has(filename)
1601
+ );
1602
+ for (const [filename, entry] of [...after, ...deletedMetadata].reverse()) {
1603
+ try {
1604
+ assertNoSymlinkParents(filename);
1605
+ if (!before.has(filename)) {
1606
+ if (entry.directory) {
1607
+ await import_fs_extra11.default.rmdir(filename);
1608
+ } else {
1609
+ await import_fs_extra11.default.unlink(filename);
1610
+ }
1611
+ } else {
1612
+ const original = before.get(filename)?.metadata;
1613
+ if (original && !await import_fs_extra11.default.pathExists(filename)) {
1614
+ const existing = await import_fs_extra11.default.lstat(filename).catch((cause) => {
1615
+ if (cause.code !== "ENOENT") throw cause;
1616
+ return void 0;
1617
+ });
1618
+ if (existing) {
1619
+ throw new Error(`Cannot restore metadata through a symbolic link: ${filename}`);
1620
+ }
1621
+ await import_fs_extra11.default.outputFile(filename, original);
1622
+ } else if (original && entry.metadata && !original.equals(entry.metadata) && (await import_fs_extra11.default.lstat(filename)).isFile() && (await import_fs_extra11.default.readFile(filename)).equals(entry.metadata)) {
1623
+ await import_fs_extra11.default.writeFile(filename, original);
1624
+ }
1625
+ }
1626
+ } catch (cause) {
1627
+ const code = cause.code;
1628
+ if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") {
1629
+ failures.push(`${filename}: ${errorMessage(cause)}`);
1630
+ }
1631
+ }
1632
+ }
1633
+ if (failures.length) throw new Error(`Cleanup incomplete: ${failures.join("; ")}`);
1634
+ }
1635
+ async function addBlockWithResult(block, blocks, results, branch, destination, visiting = /* @__PURE__ */ new Set(), isDependency = false) {
1636
+ if (visiting.has(block)) return false;
1637
+ const warnings = [];
1638
+ let before;
1639
+ let after;
1640
+ let backupPath;
1641
+ let oldNames;
1642
+ debug(`blocks[block]: ${blocks[block]?.destination}`);
1643
+ const blockPath = `${blocksDir}/${destination || blocks[block]?.destination || block}`;
1644
+ debug(`Block path resolved to: ${blockPath}`);
1645
+ try {
1646
+ const installed = getInstalledBlockNames().has(block);
1647
+ if (!installed && !blocks[block]) {
1648
+ throw new Error(`Selected blocks not available in registries: ${block}`);
1649
+ }
1650
+ const occupied = await import_fs_extra11.default.pathExists(blockPath);
1651
+ if (installed && (isDependency || !occupied)) {
1652
+ recordResult(results, { block, status: "skipped", reason: "Already installed" });
1653
+ return false;
1654
+ }
1655
+ if (!blocks[block]) throw new Error(`Selected blocks not available in registries: ${block}`);
1656
+ const relative = import_node_path14.default.relative(import_node_path14.default.resolve(blocksDir), import_node_path14.default.resolve(blockPath));
1657
+ if (!relative || relative === ".." || relative.startsWith(`..${import_node_path14.default.sep}`) || import_node_path14.default.isAbsolute(relative)) {
1658
+ throw new Error(`Invalid block destination: ${blockPath}`);
1659
+ }
1660
+ assertNoSymlinkParents(blockPath);
1661
+ visiting.add(block);
1662
+ if (occupied) {
1663
+ const replace = await confirm({
1664
+ message: `Block destination already exists: ${blockPath}. Replace it?`,
1665
+ initialValue: false
1666
+ });
1667
+ if (!replace) {
1668
+ recordResult(results, { block, status: "skipped", reason: "Destination already exists" });
1669
+ return false;
1670
+ }
1671
+ const old = getBloxFile(blockPath);
1672
+ oldNames = new Set(
1673
+ [old.definition?.name, ...Object.keys(old.checkpoints || {})].filter(
1674
+ (name) => !!name && name !== block
1675
+ )
1676
+ );
1677
+ }
1678
+ before = await snapshot(import_node_path14.default.resolve(blockPath));
1679
+ if (occupied) {
1680
+ backupPath = await import_fs_extra11.default.mkdtemp(import_node_path14.default.join(import_node_os2.default.tmpdir(), "blox-replaced-"));
1681
+ await import_fs_extra11.default.move(blockPath, import_node_path14.default.join(backupPath, "block"));
1682
+ }
1523
1683
  await runTask(
1524
- { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
1684
+ { start: `Fetching block: ${block}`, end: `Fetched block: ${block}` },
1525
1685
  async () => {
1526
- const blockSource = blockRegistryData?.source || "";
1527
- await git.clone(blockSource, blockPath, branch);
1528
- let commit2 = await selectVersion(blockSource);
1686
+ const source = blocks[block]?.source || "";
1687
+ await git.clone(source, blockPath, branch);
1688
+ let commit2 = await selectVersion(source);
1529
1689
  if (commit2) {
1530
1690
  await git.resetToCommit(commit2, blockPath);
1531
1691
  } else {
@@ -1534,65 +1694,191 @@ var addBlock = async (block, blocks, branch, destination) => {
1534
1694
  await git.unInit(blockPath);
1535
1695
  await replacePlaceholders(blockPath, {});
1536
1696
  await migrateAll();
1537
- const def = getBlockDef(blockPath);
1538
- await deletePattern(blockPath, def.ignore);
1697
+ const definition = getBlockDef(blockPath);
1698
+ if (!definition) throw new Error(`Missing block definition: ${blockPath}/.blox`);
1699
+ await deletePattern(blockPath, definition.ignore);
1539
1700
  updateCheckpoint(block, { commit: commit2, branch }, blockPath);
1540
1701
  }
1541
1702
  );
1542
- await runLifecycleHookWithTask(blockPath, "init", "Run block init");
1543
- await runLifecycleHookWithTask(blockPath, "add", "Run block add");
1544
- } else {
1545
- debug(`${block} already exists`);
1703
+ if (oldNames?.size) {
1704
+ const replaced = oldNames;
1705
+ const dependents = findDependents(replaced, blockPath);
1706
+ if (dependents.length) {
1707
+ const names = [...oldNames].join(", ");
1708
+ const rewrite = await confirm({
1709
+ message: `${dependents.length} block(s) depend on "${names}". Point them to "${block}"?`,
1710
+ initialValue: false
1711
+ });
1712
+ if (rewrite) {
1713
+ dependents.forEach((dir) => renameDependency(dir, replaced, block));
1714
+ } else {
1715
+ import_prompts2.log.warn(`Blocks still referencing replaced "${names}": ${dependents.join(", ")}`);
1716
+ }
1717
+ }
1718
+ }
1719
+ for (const hook of ["init", "add"]) {
1720
+ try {
1721
+ await runLifecycleHookWithTask(blockPath, hook, `Run block ${hook}`);
1722
+ } catch (cause) {
1723
+ const message = `${block}: ${hook} hook failed: ${errorMessage(cause)}`;
1724
+ import_prompts2.log.error(message);
1725
+ const shouldContinue = await confirm({
1726
+ message: `Continue adding ${block} despite the failed ${hook} hook?`,
1727
+ initialValue: true
1728
+ });
1729
+ if (!shouldContinue) {
1730
+ throw new Error(message, { cause });
1731
+ }
1732
+ warnings.push(message);
1733
+ import_prompts2.log.warn(`Adding ${block} with a warning: ${message}`);
1734
+ }
1735
+ }
1736
+ after = await snapshot(import_node_path14.default.resolve(blockPath));
1737
+ for (const dependency of getBlockDef(blockPath).dependencies || []) {
1738
+ await addBlockWithResult(dependency.name, blocks, results, void 0, void 0, visiting, true);
1739
+ }
1740
+ if (backupPath) await import_fs_extra11.default.remove(backupPath);
1741
+ recordResult(results, { block, status: warnings.length ? "warning" : "added", warnings });
1742
+ return true;
1743
+ } catch (cause) {
1744
+ let reason = errorMessage(cause);
1745
+ if (before) {
1746
+ try {
1747
+ await cleanup(before, after || await snapshot(import_node_path14.default.resolve(blockPath)));
1748
+ } catch (cleanupError) {
1749
+ reason += `; ${errorMessage(cleanupError)}`;
1750
+ }
1751
+ }
1752
+ if (backupPath) {
1753
+ try {
1754
+ await import_fs_extra11.default.remove(blockPath);
1755
+ await import_fs_extra11.default.move(import_node_path14.default.join(backupPath, "block"), blockPath);
1756
+ await import_fs_extra11.default.remove(backupPath);
1757
+ } catch (restoreError) {
1758
+ reason += `; failed to restore previous block (kept at ${backupPath}): ${errorMessage(restoreError)}`;
1759
+ }
1760
+ }
1761
+ recordResult(results, { block, status: "failed", reason });
1762
+ throw new Error(reason, { cause });
1763
+ } finally {
1764
+ visiting.delete(block);
1546
1765
  }
1547
- const blockDef = getBlockDef(blockPath);
1548
- for (const dep of blockDef?.dependencies || []) {
1549
- const depNew = await addBlock(dep.name, blocks);
1550
- newBlockAdded = newBlockAdded || depNew;
1766
+ }
1767
+ async function addBlocks(selected, blocks, branch, destination) {
1768
+ const results = [];
1769
+ for (const block of new Set(selected)) {
1770
+ try {
1771
+ await addBlockWithResult(block, blocks, results, branch, destination);
1772
+ } catch {
1773
+ continue;
1774
+ }
1551
1775
  }
1552
- return newBlockAdded;
1553
- };
1554
- var add2 = command("add").description("Add block to app").alias("a").argument("[blocks...]", "Blocks to be added").option("--branch <name>", "branch name").option("--dest <name>", "destination dir").action(async (selectedBlocks, { branch, dest }) => {
1555
- if (await git.hasUncommittedChanges()) {
1556
- import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
1557
- return;
1776
+ return results;
1777
+ }
1778
+
1779
+ // src/commands/add/utils.ts
1780
+ var import_node_util = require("util");
1781
+ function formatAddSummary(results, terminalWidth = 80) {
1782
+ const count = (status) => results.filter((result) => result.status === status).length;
1783
+ const styles = {
1784
+ added: { symbol: "\u2713", paint: fmt.green },
1785
+ warning: { symbol: "\u26A0", paint: fmt.yellow },
1786
+ failed: { symbol: "\u2717", paint: fmt.red },
1787
+ skipped: { symbol: "\u25CB", paint: fmt.dim }
1788
+ };
1789
+ const rows = [
1790
+ ["Results", fmt.bold],
1791
+ [`\u2713 ${count("added")} added successfully`, fmt.green],
1792
+ [`\u26A0 ${count("warning")} added with warnings`, fmt.yellow],
1793
+ [`\u2717 ${count("failed")} failed`, fmt.red],
1794
+ [`\u25CB ${count("skipped")} skipped`, fmt.dim],
1795
+ ["", fmt.white],
1796
+ ["Details", fmt.bold]
1797
+ ];
1798
+ for (const result of results) {
1799
+ const { symbol, paint } = styles[result.status];
1800
+ rows.push(["", fmt.white], [`${symbol} ${result.block}`, paint]);
1801
+ const details = result.status === "warning" ? result.warnings : [result.reason];
1802
+ for (const detail of details ?? []) {
1803
+ if (!detail) continue;
1804
+ const description = result.status === "skipped" ? `Skipped: ${detail === "Already installed" ? "already installed." : detail}` : detail.startsWith(`${result.block}: `) ? detail.slice(result.block.length + 2) : detail;
1805
+ for (const text2 of description.split(/\r?\n/)) {
1806
+ rows.push([` ${text2}`, fmt.white]);
1807
+ }
1808
+ }
1809
+ if (result.status === "warning") {
1810
+ rows.push([" The block was added, but a lifecycle hook failed.", fmt.white]);
1811
+ }
1558
1812
  }
1559
- await migrateAll();
1560
- await syncRegistries();
1813
+ const title = " BLOX ADD SUMMARY ";
1814
+ const innerWidth = Math.min(
1815
+ Math.max(1, terminalWidth - 6),
1816
+ Math.max(54, ...rows.map(([text2]) => (0, import_node_util.stripVTControlCharacters)(text2).length))
1817
+ );
1818
+ const line = (text2, paint) => `\u2502 ${paint(text2)}${" ".repeat(innerWidth - text2.length)} \u2502`;
1819
+ const lines = [];
1820
+ for (const [text2, paint] of rows) {
1821
+ const plain = (0, import_node_util.stripVTControlCharacters)(text2);
1822
+ const indent = " ".repeat(Math.min(plain.length - plain.trimStart().length, innerWidth - 1));
1823
+ const available = innerWidth - indent.length;
1824
+ let remaining = plain.trimStart();
1825
+ do {
1826
+ const space = remaining.lastIndexOf(" ", available);
1827
+ const end = remaining.length <= available ? remaining.length : space > 0 ? space : available;
1828
+ lines.push(line(indent + remaining.slice(0, end), paint));
1829
+ remaining = remaining.slice(end).trimStart();
1830
+ } while (remaining);
1831
+ }
1832
+ const heading = title.slice(0, innerWidth);
1833
+ return [
1834
+ "",
1835
+ `\u250C\u2500${fmt.bold(heading)}${"\u2500".repeat(innerWidth - heading.length + 3)}\u2510`,
1836
+ line("", fmt.white),
1837
+ ...lines,
1838
+ line("", fmt.white),
1839
+ `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`,
1840
+ ""
1841
+ ].join("\n");
1842
+ }
1843
+
1844
+ // src/commands/add/index.ts
1845
+ var add2 = command("add").description("Add block to app").alias("a").argument("[blocks...]", "Blocks to be added").option("--branch <name>", "branch name").option("--dest <name>", "destination dir").action(async (selectedBlocks, { branch, dest }) => {
1561
1846
  try {
1847
+ if (await git.hasUncommittedChanges()) {
1848
+ import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
1849
+ return;
1850
+ }
1851
+ await migrateAll();
1852
+ await syncRegistries();
1562
1853
  const templateDef = getTemplateDef();
1563
1854
  const blocks = await getAvailableBlocks(templateDef);
1855
+ const installed = getInstalledBlockNames();
1564
1856
  let blocksToAdd = Array.isArray(selectedBlocks) ? selectedBlocks : [];
1565
1857
  if (!blocksToAdd.length) {
1566
1858
  blocksToAdd = await multiselect({
1567
1859
  message: "Select blocks to add",
1568
1860
  options: Object.entries(blocks).map(([tmpl, { description }]) => ({
1569
1861
  value: tmpl,
1570
- label: tmpl,
1862
+ label: tmpl + (installed.has(tmpl) ? ` ${fmt.green("(Already installed)")}` : ""),
1571
1863
  hint: description
1572
1864
  }))
1573
1865
  });
1574
1866
  }
1575
1867
  if (!blocksToAdd.length) {
1576
1868
  error("No blocks selected");
1869
+ return;
1577
1870
  }
1578
- const invalidBlocks = blocksToAdd.filter((blockName) => !blocks[blockName]);
1579
- if (invalidBlocks.length) {
1580
- error(`Selected blocks not available in registries: ${invalidBlocks.join(", ")}`);
1581
- }
1582
- let added = false;
1583
- for (const blockName of blocksToAdd) {
1584
- const blockAdded = await addBlock(blockName, blocks, branch, dest);
1585
- added = added || blockAdded;
1586
- }
1587
- if (added) {
1588
- await runLifecycleHookWithTask(".", "add", "Run template add");
1871
+ const results = await addBlocks(blocksToAdd, blocks, branch, dest);
1872
+ if (results.some((result) => result.status === "failed")) process.exitCode = 1;
1873
+ try {
1874
+ if (results.some((result) => result.status === "added" || result.status === "warning")) {
1875
+ await runLifecycleHookWithTask(".", "add", "Run template add");
1876
+ }
1877
+ await checkVersionsCompatibility();
1878
+ } finally {
1879
+ process.stdout.write(formatAddSummary(results, process.stdout.columns || 80));
1589
1880
  }
1590
- await checkVersionsCompatibility();
1591
1881
  } catch (e) {
1592
- if (!isDebugMode()) {
1593
- import_prompts2.log.warn("Error happened, Will rollback changes");
1594
- await git.rollback();
1595
- }
1596
1882
  error(e);
1597
1883
  }
1598
1884
  });
@@ -1622,11 +1908,6 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
1622
1908
 
1623
1909
  // src/services/contribute/constants/index.ts
1624
1910
  var UI_PAGE_SIZE = 15;
1625
- var TARGET_SELECT_PAGE = {
1626
- PREV: "__prev__",
1627
- NEXT: "__next__",
1628
- SEARCH_AGAIN: "__search__"
1629
- };
1630
1911
  var COMMIT_TYPES = [
1631
1912
  { value: "fix", label: "fix: A bug fix (PATCH)" },
1632
1913
  { value: "feat", label: "feat: A new feature (MINOR)" },
@@ -1638,16 +1919,8 @@ var COMMIT_TYPES = [
1638
1919
  { value: "ci", label: "ci: CI configuration (GitLab/GitHub)" }
1639
1920
  ];
1640
1921
 
1641
- // src/services/contribute/types.ts
1642
- var ContributionTargetType = /* @__PURE__ */ ((ContributionTargetType2) => {
1643
- ContributionTargetType2["TEMPLATE"] = "template";
1644
- ContributionTargetType2["BASE"] = "base";
1645
- ContributionTargetType2["BLOCK"] = "block";
1646
- return ContributionTargetType2;
1647
- })(ContributionTargetType || {});
1648
-
1649
1922
  // src/services/contribute/utils/bloxCheckpoint.ts
1650
- var import_node_path14 = __toESM(require("path"));
1923
+ var import_node_path15 = __toESM(require("path"));
1651
1924
  function getCheckpointForTarget(cwd, target) {
1652
1925
  const bloxDir = getBloxDirForTarget(cwd, target);
1653
1926
  const blox = getBloxFile(bloxDir);
@@ -1657,18 +1930,147 @@ function getCheckpointForTarget(cwd, target) {
1657
1930
  }
1658
1931
  function getBloxDirForTarget(cwd, target) {
1659
1932
  if (target.type === "block" /* BLOCK */) {
1660
- return import_node_path14.default.join(cwd, blocksDir, target.name);
1933
+ return import_node_path15.default.join(cwd, blocksDir, target.dir);
1661
1934
  }
1662
1935
  return cwd;
1663
1936
  }
1664
1937
 
1938
+ // src/services/contribute/utils/slugifyTitle.ts
1939
+ function slugifyTitle(title) {
1940
+ const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1941
+ return (s || "contribution").slice(0, 80);
1942
+ }
1943
+
1944
+ // src/services/contribute/utils/buildBranchName.ts
1945
+ function buildBranchName(commitType, title) {
1946
+ return `${commitType}/${slugifyTitle(title)}`;
1947
+ }
1948
+
1949
+ // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1950
+ var import_node_path16 = __toESM(require("path"));
1951
+ var import_fs_extra12 = __toESM(require("fs-extra"));
1952
+ function getExcludedPrefixesForTarget(target, cwd) {
1953
+ if (target.type === "block" /* BLOCK */) {
1954
+ return [];
1955
+ }
1956
+ const excluded = [];
1957
+ const blocksPath = import_node_path16.default.join(cwd, blocksDir);
1958
+ if (import_fs_extra12.default.existsSync(blocksPath)) {
1959
+ const entries = import_fs_extra12.default.readdirSync(blocksPath, { withFileTypes: true });
1960
+ for (const entry of entries) {
1961
+ if (!entry.isDirectory()) continue;
1962
+ const blockBloxFile = import_node_path16.default.join(blocksPath, entry.name, bloxFilePath);
1963
+ if (import_fs_extra12.default.existsSync(blockBloxFile)) {
1964
+ excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1965
+ }
1966
+ }
1967
+ }
1968
+ return excluded;
1969
+ }
1970
+
1971
+ // src/services/contribute/utils/getPathPrefixToStrip.ts
1972
+ function getPathPrefixToStrip(target) {
1973
+ if (target.type === "block" /* BLOCK */) {
1974
+ return normalizePath(`${blocksDir}/${target.dir}/`);
1975
+ }
1976
+ return "";
1977
+ }
1978
+
1979
+ // src/services/contribute/utils/shouldExcludeFile.ts
1980
+ function shouldExcludeFile(file, excludedPrefixes) {
1981
+ const f = normalizePath(file);
1982
+ return excludedPrefixes.some((p) => f.startsWith(p));
1983
+ }
1984
+
1985
+ // src/services/contribute/utils/computeTargetChangeHints.ts
1986
+ function targetHintKey(target) {
1987
+ return `${target.type}:${target.name}`;
1988
+ }
1989
+ async function computeTargetChangeHints(opts) {
1990
+ const changedFilesPerCommit = await Promise.all(
1991
+ opts.commits.map((commit2) => git.getChangedFilesInCommit(commit2, opts.cwd))
1992
+ );
1993
+ const changedFiles = [...new Set(changedFilesPerCommit.flat())].map((f) => normalizePath(f));
1994
+ const hints = /* @__PURE__ */ new Map();
1995
+ for (const target of opts.targets) {
1996
+ const subtreePath = getPathPrefixToStrip(target);
1997
+ const exclusion = getExcludedPrefixesForTarget(target, opts.cwd);
1998
+ const hasChanges = changedFiles.some((file) => {
1999
+ if (subtreePath && !file.startsWith(subtreePath)) return false;
2000
+ if (shouldExcludeFile(file, exclusion)) return false;
2001
+ return true;
2002
+ });
2003
+ hints.set(targetHintKey(target), hasChanges);
2004
+ }
2005
+ return hints;
2006
+ }
2007
+
2008
+ // src/services/contribute/utils/discoverContributionTargets.ts
2009
+ var import_node_path17 = __toESM(require("path"));
2010
+ var import_fs_extra13 = __toESM(require("fs-extra"));
2011
+ var readBloxFileIfExists = (cwd) => {
2012
+ const p = import_node_path17.default.join(cwd, bloxFilePath);
2013
+ if (!import_fs_extra13.default.existsSync(p)) return;
2014
+ try {
2015
+ return import_fs_extra13.default.readJSONSync(p);
2016
+ } catch {
2017
+ return;
2018
+ }
2019
+ };
2020
+ var discoverContributionTargets = (cwd) => {
2021
+ const targets = [];
2022
+ const rootBlox = readBloxFileIfExists(cwd);
2023
+ const appTemplateName = rootBlox?.definition?.name;
2024
+ const appTemplateDef = rootBlox?.definition;
2025
+ if (rootBlox?.definition?.name) {
2026
+ targets.push({
2027
+ type: "template" /* TEMPLATE */,
2028
+ name: rootBlox.definition.name,
2029
+ templateName: rootBlox.definition.name,
2030
+ templateDef: appTemplateDef,
2031
+ label: `template/${rootBlox.definition.name}`
2032
+ });
2033
+ for (const base of rootBlox.definition.bases || []) {
2034
+ targets.push({
2035
+ type: "base" /* BASE */,
2036
+ name: base.name,
2037
+ templateDef: appTemplateDef,
2038
+ label: `base/${base.name}`,
2039
+ hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
2040
+ });
2041
+ }
2042
+ }
2043
+ const blocksPath = import_node_path17.default.join(cwd, blocksDir);
2044
+ if (import_fs_extra13.default.existsSync(blocksPath)) {
2045
+ const entries = import_fs_extra13.default.readdirSync(blocksPath, { withFileTypes: true });
2046
+ for (const entry of entries) {
2047
+ if (!entry.isDirectory()) continue;
2048
+ const blockDir = entry.name;
2049
+ const blockBlox = readBloxFileIfExists(import_node_path17.default.join(blocksPath, blockDir));
2050
+ if (!blockBlox?.definition?.name) continue;
2051
+ targets.push({
2052
+ type: "block" /* BLOCK */,
2053
+ name: blockBlox.definition.name,
2054
+ dir: blockDir,
2055
+ templateName: appTemplateName,
2056
+ templateDef: appTemplateDef,
2057
+ label: `block/${blockBlox.definition.name}`,
2058
+ hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
2059
+ });
2060
+ }
2061
+ }
2062
+ return targets;
2063
+ };
2064
+
1665
2065
  // src/services/contribute/utils/getRepoUrl.ts
2066
+ var MissingRegistrySourceError = class extends Error {
2067
+ };
1666
2068
  var getTargetRepoUrl = async (target) => {
1667
2069
  if (target.type === "template" /* TEMPLATE */ || target.type === "base" /* BASE */) {
1668
2070
  const templates = await getAvailableTemplates();
1669
2071
  const t = templates[target.name];
1670
2072
  if (!t?.source) {
1671
- throw new Error(`No registry source found for template/base: ${target.name}`);
2073
+ throw new MissingRegistrySourceError(`No registry source found for template/base: ${target.name}`);
1672
2074
  }
1673
2075
  return t.source;
1674
2076
  }
@@ -1682,15 +2084,58 @@ var getTargetRepoUrl = async (target) => {
1682
2084
  const blocks = await getAvailableBlocks(templateDef);
1683
2085
  const blockSource = blocks?.[target.name]?.source;
1684
2086
  if (!blockSource) {
1685
- throw new Error(`No registry source found for block: ${target.name}`);
2087
+ throw new MissingRegistrySourceError(`No registry source found for block: ${target.name}`);
1686
2088
  }
1687
2089
  return blockSource;
1688
2090
  };
1689
2091
 
1690
- // src/services/contribute/utils/slugifyTitle.ts
1691
- function slugifyTitle(title) {
1692
- const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1693
- return (s || "contribution").slice(0, 80);
2092
+ // src/services/contribute/utils/getUpdateCommand.ts
2093
+ function getUpdateCommand(target) {
2094
+ switch (target.type) {
2095
+ case "block" /* BLOCK */:
2096
+ return `blox update -s block -b ${target.name}`;
2097
+ case "base" /* BASE */:
2098
+ return "blox update -s bases";
2099
+ default:
2100
+ return "blox update";
2101
+ }
2102
+ }
2103
+
2104
+ // src/services/contribute/utils/promptContributionMeta.ts
2105
+ async function promptContributionMeta(flags) {
2106
+ let title = flags.title?.trim();
2107
+ let description = flags.description?.trim();
2108
+ if (!title) {
2109
+ title = await text({
2110
+ message: "Contribution title (conventional commit style recommended)",
2111
+ validate: (v) => v.trim() ? void 0 : "Title is required"
2112
+ });
2113
+ }
2114
+ if (description === void 0) {
2115
+ description = await text({ message: "Description (optional)", defaultValue: "" });
2116
+ }
2117
+ return { title, description };
2118
+ }
2119
+
2120
+ // src/services/contribute/utils/remoteBranchExists.ts
2121
+ async function remoteBranchExists(repoUrl, branch) {
2122
+ try {
2123
+ await git.lsRemote(repoUrl, branch);
2124
+ return true;
2125
+ } catch {
2126
+ return false;
2127
+ }
2128
+ }
2129
+
2130
+ // src/services/contribute/utils/resolveRemoteHead.ts
2131
+ async function resolveRemoteHead(repoUrl, remoteBranch) {
2132
+ try {
2133
+ return await git.lsRemote(repoUrl, remoteBranch);
2134
+ } catch (e) {
2135
+ throw new Error(
2136
+ `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
2137
+ );
2138
+ }
1694
2139
  }
1695
2140
 
1696
2141
  // src/services/contribute/ContributionWorkflow.ts
@@ -1707,25 +2152,219 @@ var ContributionWorkflow = class {
1707
2152
  }
1708
2153
  async runFromFlags(flags) {
1709
2154
  await this.assertAppRepoClean();
1710
- const target = await this.targetSelector.selectTargetInteractive();
1711
- const mode = flags.existing ? "existing" : "new";
1712
- const { title, description } = await this.promptContributionMeta(flags);
1713
2155
  const commits = await this.resolveCommitsFromFlags(flags);
1714
- const branch = await this.resolveContributionBranch({ mode, target, title });
1715
- return this.run({
1716
- target,
1717
- mode,
1718
- title,
1719
- description,
1720
- branch,
1721
- commits
2156
+ const targets = await this.selectTargetsForCommits(commits, flags);
2157
+ await this.assertTargetsUpToDate(targets);
2158
+ const mode = flags.existing ? "existing" : "new";
2159
+ const { title, description } = await promptContributionMeta(flags);
2160
+ const commitType = mode === "new" && title ? await this.promptCommitType() : void 0;
2161
+ const skipped = mode === "new" && title && commitType ? await this.assertNoRemoteBranchConflicts(targets, buildBranchName(commitType, title)) : /* @__PURE__ */ new Map();
2162
+ const results = [];
2163
+ for (const target of targets) {
2164
+ const reason = skipped.get(target);
2165
+ if (reason) {
2166
+ results.push({ target, success: true, skipped: reason });
2167
+ continue;
2168
+ }
2169
+ results.push(
2170
+ await this.contributeToTarget(target, commits, {
2171
+ mode,
2172
+ title,
2173
+ description,
2174
+ commitType
2175
+ })
2176
+ );
2177
+ }
2178
+ this.logSummary(results);
2179
+ await this.reportAndOpenPullRequests(results);
2180
+ return results;
2181
+ }
2182
+ async selectTargetsForCommits(commits, flags) {
2183
+ const allTargets = discoverContributionTargets(this.ctx.cwd);
2184
+ if (flags.type && flags.name) {
2185
+ const target = allTargets.find((item) => item.type === flags.type && item.name === flags.name);
2186
+ if (target) return [target];
2187
+ this.logger.warn(
2188
+ `Contribution target ${flags.type}/${flags.name} not found. Select from the available targets.`
2189
+ );
2190
+ } else if (flags.type || flags.name) {
2191
+ this.logger.warn("Both --type and --name are needed to select a target. Select from the available targets.");
2192
+ }
2193
+ const changeHints = await computeTargetChangeHints({
2194
+ cwd: this.ctx.cwd,
2195
+ commits,
2196
+ targets: allTargets
2197
+ });
2198
+ return this.targetSelector.selectMultipleTargetsInteractive({ changeHints });
2199
+ }
2200
+ async assertTargetsUpToDate(targets) {
2201
+ if (this.ctx.force) {
2202
+ return;
2203
+ }
2204
+ const outdated = [];
2205
+ await runTask(
2206
+ {
2207
+ start: "Checking whether selected targets are up to date",
2208
+ end: "Checked whether selected targets are up to date"
2209
+ },
2210
+ async () => {
2211
+ for (const target of targets) {
2212
+ if (target.type === "template" /* TEMPLATE */) continue;
2213
+ try {
2214
+ const repoUrl = await getTargetRepoUrl(target);
2215
+ const checkpoint = getCheckpointForTarget(this.ctx.cwd, target);
2216
+ if (!checkpoint.commit) continue;
2217
+ const remoteHead = await resolveRemoteHead(
2218
+ repoUrl,
2219
+ checkpoint.branch || defaultBranch
2220
+ );
2221
+ if (checkpoint.commit !== remoteHead) outdated.push(target);
2222
+ } catch (cause) {
2223
+ if (!(cause instanceof MissingRegistrySourceError)) throw cause;
2224
+ }
2225
+ }
2226
+ }
2227
+ );
2228
+ if (!outdated.length) {
2229
+ return;
2230
+ }
2231
+ const blocks = outdated.filter((t) => t.type === "block" /* BLOCK */);
2232
+ const others = outdated.filter((t) => t.type !== "block" /* BLOCK */);
2233
+ const lines = others.map(
2234
+ (t) => `The selected target "${t.name}" is outdated. Please run "${getUpdateCommand(t)}", then retry "blox contribute".`
2235
+ );
2236
+ if (blocks.length) {
2237
+ const plural = blocks.length > 1;
2238
+ lines.unshift(
2239
+ `The selected ${plural ? "targets" : "target"} ${blocks.map((t) => `"${t.name}"`).join(", ")} ${plural ? "are" : "is"} outdated. Please run "blox update -s block -b ${blocks.map((t) => t.name).join(" ")}", then retry "blox contribute".`
2240
+ );
2241
+ }
2242
+ throw new Error(lines.join("\n"));
2243
+ }
2244
+ async assertNoRemoteBranchConflicts(targets, branch) {
2245
+ const conflicts = [];
2246
+ const clear = [];
2247
+ const skipped = /* @__PURE__ */ new Map();
2248
+ await runTask(
2249
+ {
2250
+ start: `Checking remote branches for conflicts with ${branch}`,
2251
+ end: `Checked remote branches for conflicts with ${branch}`
2252
+ },
2253
+ async () => {
2254
+ for (const target of targets) {
2255
+ try {
2256
+ const repoUrl = await getTargetRepoUrl(target);
2257
+ const exists = await remoteBranchExists(repoUrl, branch);
2258
+ (exists ? conflicts : clear).push(target);
2259
+ } catch (cause) {
2260
+ if (!(cause instanceof MissingRegistrySourceError)) throw cause;
2261
+ skipped.set(target, cause.message);
2262
+ this.logger.warn(`Skipping ${target.type}/${target.name}: ${cause.message}`);
2263
+ }
2264
+ }
2265
+ }
2266
+ );
2267
+ if (!conflicts.length) {
2268
+ return skipped;
2269
+ }
2270
+ import_prompts2.log.message(
2271
+ [
2272
+ `
2273
+ ${fmt.bold("Branch conflict check")} for ${fmt.cyan(branch)}`,
2274
+ ...conflicts.map(
2275
+ (t) => ` ${fmt.red("\u2717")} ${t.type}/${t.name} - branch already exists on remote. Use --existing to contribute to it.`
2276
+ ),
2277
+ ...clear.map(
2278
+ (t) => ` ${fmt.green("\u2713")} ${t.type}/${t.name} - no conflict, ready to contribute.`
2279
+ ),
2280
+ ""
2281
+ ].join("\n")
2282
+ );
2283
+ throw new Error(
2284
+ `Branch "${branch}" already exists on remote for ${conflicts.length} target(s). Re-run with --existing to contribute to them, or choose a different title.`
2285
+ );
2286
+ }
2287
+ async resolveBranchForTarget(target, mode, title, commitType) {
2288
+ if (mode === "new" && title && commitType) {
2289
+ return buildBranchName(commitType, title);
2290
+ }
2291
+ if (mode === "existing") {
2292
+ return this.resolveExistingBranch(target);
2293
+ }
2294
+ return void 0;
2295
+ }
2296
+ async contributeToTarget(target, commits, opts) {
2297
+ this.logger.info(`Starting contribution for ${target.type}/${target.name}`);
2298
+ try {
2299
+ const branch = await this.resolveBranchForTarget(
2300
+ target,
2301
+ opts.mode,
2302
+ opts.title,
2303
+ opts.commitType
2304
+ );
2305
+ const result = await this.run({
2306
+ target,
2307
+ mode: opts.mode,
2308
+ title: opts.title,
2309
+ description: opts.description,
2310
+ branch,
2311
+ commits
2312
+ });
2313
+ return { target, success: true, result };
2314
+ } catch (e) {
2315
+ const message = e instanceof Error ? e.message : String(e);
2316
+ if (e instanceof MissingRegistrySourceError) {
2317
+ this.logger.warn(`Skipping ${target.type}/${target.name}: ${message}`);
2318
+ return { target, success: true, skipped: message };
2319
+ }
2320
+ this.logger.error(
2321
+ `Contribution failed for ${target.type}/${target.name}. Skipping to next target.`,
2322
+ message
2323
+ );
2324
+ return { target, success: false, error: message };
2325
+ }
2326
+ }
2327
+ logSummary(results) {
2328
+ const succeeded = results.filter((r) => r.success && !r.skipped);
2329
+ const failed = results.filter((r) => !r.success);
2330
+ const lines = results.map((r) => {
2331
+ if (r.skipped) {
2332
+ return ` ${fmt.yellow("\u279C ")} ${r.target.type}/${r.target.name} - skipped (${r.skipped})`;
2333
+ }
2334
+ if (!r.success) {
2335
+ return ` ${fmt.red("\u2717 ")} ${r.target.type}/${r.target.name} - ${r.error}`;
2336
+ }
2337
+ if (r.result?.skipped) {
2338
+ return ` ${fmt.yellow("\u279C ")} ${r.target.type}/${r.target.name} - skipped (no changes applied)`;
2339
+ }
2340
+ return ` ${fmt.green("\u2713 ")} ${r.target.type}/${r.target.name}`;
1722
2341
  });
2342
+ import_prompts2.log.message(
2343
+ `
2344
+ ${fmt.bold("Contribution summary")} (${succeeded.length}/${results.length} succeeded)
2345
+ ` + lines.join("\n") + "\n"
2346
+ );
2347
+ if (failed.length) {
2348
+ this.logger.warn(`${failed.length} target(s) failed. See details above.`);
2349
+ }
2350
+ }
2351
+ async reportAndOpenPullRequests(results) {
2352
+ const prUrls = results.filter((r) => r.success && r.result?.prUrl).map((r) => r.result.prUrl);
2353
+ if (!prUrls.length) {
2354
+ return;
2355
+ }
2356
+ import_prompts2.log.message(
2357
+ `
2358
+ ${fmt.bold("Pull Request URLs")}
2359
+ ` + prUrls.map((url) => ` ${fmt.cyan(url)}`).join("\n") + "\n"
2360
+ );
2361
+ await this.pullRequest.openPullRequestUrls(prUrls);
1723
2362
  }
1724
2363
  async run(input) {
1725
2364
  const repoUrl = await getTargetRepoUrl(input.target);
1726
2365
  const checkpoint = getCheckpointForTarget(this.ctx.cwd, input.target);
1727
2366
  const remoteBranch = checkpoint.branch || defaultBranch;
1728
- const remoteHead = await this.resolveRemoteHeadOrThrow(repoUrl, remoteBranch);
2367
+ const remoteHead = await resolveRemoteHead(repoUrl, remoteBranch);
1729
2368
  this.ensureCheckpointValid(input, checkpoint, remoteHead);
1730
2369
  this.logger.debug("preflight.resolved", {
1731
2370
  repoUrl,
@@ -1750,7 +2389,9 @@ var ContributionWorkflow = class {
1750
2389
  branch,
1751
2390
  title: input.title
1752
2391
  });
1753
- const { title, description } = this.deriveTitleAndDescription(input);
2392
+ const title = input.title || "contribution title";
2393
+ const description = input.description || "";
2394
+ const beforeHead = await git.getLatestCommitFromPath(tmpCwd);
1754
2395
  await this.commitApplier.applyCommits({
1755
2396
  appRepoCwd: this.ctx.cwd,
1756
2397
  tmpRepoCwd: tmpCwd,
@@ -1759,6 +2400,13 @@ var ContributionWorkflow = class {
1759
2400
  title,
1760
2401
  description
1761
2402
  });
2403
+ const afterHead = await git.getLatestCommitFromPath(tmpCwd);
2404
+ if (beforeHead === afterHead) {
2405
+ this.logger.warn(
2406
+ `Skipped opening a PR for ${input.target.type}/${input.target.name}: no changes were left for this target after filtering.`
2407
+ );
2408
+ return { branch, commits: input.commits, skipped: true };
2409
+ }
1762
2410
  await this.pullRequest.pushBranch({
1763
2411
  cwd: tmpCwd,
1764
2412
  remote: "origin",
@@ -1777,16 +2425,18 @@ var ContributionWorkflow = class {
1777
2425
  title,
1778
2426
  description
1779
2427
  });
1780
- const pr = await this.pullRequest.openPullRequestPage({
2428
+ const prUrl = this.pullRequest.resolvePullRequestUrl({
1781
2429
  repoUrl,
1782
2430
  sourceBranch: branch,
1783
2431
  targetBranch: remoteBranch
1784
2432
  });
1785
- this.logCompletion(pr.prUrl);
2433
+ import_prompts2.log.success(
2434
+ fmt.green(`Contribution flow completed for ${input.target.type}/${input.target.name}.`)
2435
+ );
1786
2436
  return {
1787
2437
  branch,
1788
2438
  commits: input.commits,
1789
- prUrl: pr.prUrl
2439
+ prUrl
1790
2440
  };
1791
2441
  }
1792
2442
  async assertAppRepoClean() {
@@ -1796,20 +2446,6 @@ var ContributionWorkflow = class {
1796
2446
  );
1797
2447
  }
1798
2448
  }
1799
- async promptContributionMeta(flags) {
1800
- let title = flags.title?.trim();
1801
- let description = flags.description?.trim();
1802
- if (!title) {
1803
- title = await text({
1804
- message: "Contribution title (conventional commit style recommended)",
1805
- validate: (v) => v.trim() ? void 0 : "Title is required"
1806
- });
1807
- }
1808
- if (description === void 0) {
1809
- description = await text({ message: "Description (optional)", defaultValue: "" });
1810
- }
1811
- return { title, description };
1812
- }
1813
2449
  async resolveCommitsFromFlags(flags) {
1814
2450
  if (flags.commits) {
1815
2451
  const commits = flags.commits.split(",").map((c) => c.trim()).filter(Boolean);
@@ -1822,46 +2458,32 @@ var ContributionWorkflow = class {
1822
2458
  cwd: this.ctx.cwd
1823
2459
  });
1824
2460
  }
1825
- async resolveContributionBranch(opts) {
1826
- const { mode, target, title } = opts;
1827
- if (mode === "new" && title) {
1828
- const commitType = await select({
1829
- message: "Select the commit type for this contribution:",
1830
- options: COMMIT_TYPES
1831
- });
1832
- return `${commitType}/${slugifyTitle(title)}`;
1833
- }
1834
- if (mode === "existing") {
1835
- import_prompts2.log.info("Fetching remote branches for the existing contribution...");
1836
- const repoUrl = await getTargetRepoUrl(target);
1837
- const remoteBranches = await git.listRemoteBranches(repoUrl);
1838
- if (remoteBranches.length === 0) {
1839
- throw new Error("No remote branches found to contribute to.");
1840
- }
1841
- const selectedBranch = await select({
1842
- message: "Select the existing contribution branch:",
1843
- options: [
1844
- ...remoteBranches.map((b) => ({ label: b, value: b })),
1845
- { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
1846
- ]
1847
- });
1848
- if (selectedBranch === MANUAL_BRANCH_OPTION) {
1849
- return await text({
1850
- message: "Enter branch name:"
1851
- });
1852
- }
1853
- return selectedBranch;
1854
- }
1855
- return void 0;
2461
+ async promptCommitType() {
2462
+ return select({
2463
+ message: "Select the commit type for this contribution:",
2464
+ options: COMMIT_TYPES
2465
+ });
1856
2466
  }
1857
- async resolveRemoteHeadOrThrow(repoUrl, remoteBranch) {
1858
- try {
1859
- return await git.lsRemote(repoUrl, remoteBranch);
1860
- } catch (e) {
1861
- throw new Error(
1862
- `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
1863
- );
2467
+ async resolveExistingBranch(target) {
2468
+ import_prompts2.log.info("Fetching remote branches for the existing contribution...");
2469
+ const repoUrl = await getTargetRepoUrl(target);
2470
+ const remoteBranches = await git.listRemoteBranches(repoUrl);
2471
+ if (remoteBranches.length === 0) {
2472
+ throw new Error("No remote branches found to contribute to.");
2473
+ }
2474
+ const selectedBranch = await select({
2475
+ message: "Select the existing contribution branch:",
2476
+ options: [
2477
+ ...remoteBranches.map((b) => ({ label: b, value: b })),
2478
+ { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
2479
+ ]
2480
+ });
2481
+ if (selectedBranch === MANUAL_BRANCH_OPTION) {
2482
+ return await text({
2483
+ message: "Enter branch name:"
2484
+ });
1864
2485
  }
2486
+ return selectedBranch;
1865
2487
  }
1866
2488
  ensureCheckpointValid(input, checkpoint, remoteHead) {
1867
2489
  if (input.target.type === "template" /* TEMPLATE */ && !checkpoint.commit) {
@@ -1878,7 +2500,7 @@ var ContributionWorkflow = class {
1878
2500
  return;
1879
2501
  }
1880
2502
  if (checkpoint.commit !== remoteHead && !this.ctx.force) {
1881
- const hint = input.target.type === "block" /* BLOCK */ ? `Block (${input.target.name}) is outdated. Please run \`blox update -s block -b ${input.target.name}\`.` : `Local checkpoint does not match remote HEAD for ${input.target.type}/${input.target.name}. Run \`blox update\` first.`;
2503
+ const hint = input.target.type === "block" /* BLOCK */ ? `Block (${input.target.name}) is outdated. Please run \`${getUpdateCommand(input.target)}\`.` : `Local checkpoint does not match remote HEAD for ${input.target.type}/${input.target.name}. Run \`${getUpdateCommand(input.target)}\` first.`;
1882
2504
  throw new Error(
1883
2505
  `${hint}
1884
2506
  Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
@@ -1912,58 +2534,16 @@ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
1912
2534
  }
1913
2535
  await git.checkout(branch, tmpCwd);
1914
2536
  }
1915
- deriveTitleAndDescription(input) {
1916
- const title = input.title || "contribution title";
1917
- const description = input.description || "";
1918
- return { title, description };
1919
- }
1920
- logCompletion(prUrl) {
1921
- import_prompts2.log.success(
1922
- fmt.green("Contribution flow completed.") + (prUrl ? `
1923
- Pull Request (new):
1924
- ${prUrl}` : "\nPush completed.")
1925
- );
1926
- }
1927
2537
  };
1928
2538
 
1929
2539
  // src/services/contribute/services/CommitApplierService.ts
1930
- var import_node_path16 = __toESM(require("path"));
1931
- var import_fs_extra13 = __toESM(require("fs-extra"));
2540
+ var import_node_path18 = __toESM(require("path"));
2541
+ var import_fs_extra14 = __toESM(require("fs-extra"));
1932
2542
 
1933
2543
  // src/services/contribute/config/index.ts
1934
2544
  var tempRepoName = "tmp";
1935
2545
  var bloxConfigControlledKeys = ["checkpoints", "project"];
1936
2546
 
1937
- // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1938
- var import_node_path15 = __toESM(require("path"));
1939
- var import_fs_extra12 = __toESM(require("fs-extra"));
1940
- function getExcludedPrefixesForTarget(target, cwd) {
1941
- if (target.type === "block" /* BLOCK */) {
1942
- return [];
1943
- }
1944
- const excluded = [];
1945
- const blocksPath = import_node_path15.default.join(cwd, blocksDir);
1946
- if (import_fs_extra12.default.existsSync(blocksPath)) {
1947
- const entries = import_fs_extra12.default.readdirSync(blocksPath, { withFileTypes: true });
1948
- for (const entry of entries) {
1949
- if (!entry.isDirectory()) continue;
1950
- const blockBloxFile = import_node_path15.default.join(blocksPath, entry.name, bloxFilePath);
1951
- if (import_fs_extra12.default.existsSync(blockBloxFile)) {
1952
- excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1953
- }
1954
- }
1955
- }
1956
- return excluded;
1957
- }
1958
-
1959
- // src/services/contribute/utils/getPathPrefixToStrip.ts
1960
- function getPathPrefixToStrip(target) {
1961
- if (target.type === "block" /* BLOCK */) {
1962
- return normalizePath(`${blocksDir}/${target.name}/`);
1963
- }
1964
- return "";
1965
- }
1966
-
1967
2547
  // src/services/contribute/utils/orderCommitsOldestToNewest.ts
1968
2548
  var orderCommitsOldestToNewest = (commits, history) => {
1969
2549
  const historyIndex = new Map(history.map((commit2, index) => [commit2, index]));
@@ -1981,12 +2561,6 @@ var orderCommitsOldestToNewest = (commits, history) => {
1981
2561
  });
1982
2562
  };
1983
2563
 
1984
- // src/services/contribute/utils/shouldExcludeFile.ts
1985
- function shouldExcludeFile(file, excludedPrefixes) {
1986
- const f = normalizePath(file);
1987
- return excludedPrefixes.some((p) => f.startsWith(p));
1988
- }
1989
-
1990
2564
  // src/services/contribute/services/CommitApplierService.ts
1991
2565
  var CommitApplierService = class {
1992
2566
  constructor(logger) {
@@ -2002,6 +2576,11 @@ var CommitApplierService = class {
2002
2576
  this.logger.debug("Prepare for apply commits", {
2003
2577
  appRepo: opts.appRepoCwd,
2004
2578
  tmpRepo: opts.tmpRepoCwd,
2579
+ target: {
2580
+ type: opts.target.type,
2581
+ name: opts.target.name,
2582
+ dir: opts.target.dir
2583
+ },
2005
2584
  subtree: subtreePath || "(root)",
2006
2585
  exclusion,
2007
2586
  projectIgnore
@@ -2047,6 +2626,10 @@ var CommitApplierService = class {
2047
2626
  files: remainingConflicts
2048
2627
  });
2049
2628
  await this.waitUntilUserResolvesConflicts(opts.tmpRepoCwd, commit2);
2629
+ await this.filterGovernedKeysFromResolvedBloxFiles(
2630
+ remainingConflicts.filter(isBloxConfigFile),
2631
+ opts.tmpRepoCwd
2632
+ );
2050
2633
  }
2051
2634
  const committed = await this.commitStagedIfAny(opts, commit2);
2052
2635
  if (committed) {
@@ -2067,6 +2650,20 @@ Resolve manually in the temp repo:
2067
2650
  ${e instanceof Error ? e.message : String(e)}`);
2068
2651
  }
2069
2652
  }
2653
+ async filterGovernedKeysFromResolvedBloxFiles(files, tmpRepoCwd) {
2654
+ for (const file of files) {
2655
+ const stagedJson = await git.readJsonFromIndex(file, tmpRepoCwd);
2656
+ if (stagedJson === null) {
2657
+ throw new Error(`Unable to read resolved .blox file from git index: ${file}`);
2658
+ }
2659
+ const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
2660
+ await import_fs_extra14.default.outputFile(
2661
+ import_node_path18.default.join(tmpRepoCwd, file),
2662
+ JSON.stringify(withoutGovernedKeys, null, 2)
2663
+ );
2664
+ await git.add(file, tmpRepoCwd);
2665
+ }
2666
+ }
2070
2667
  async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, projectIgnoreMatcher, target) {
2071
2668
  const changedFromHeadFiles = await git.getChangedFilesFromHead(tmpRepoCwd);
2072
2669
  const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
@@ -2106,8 +2703,6 @@ ${e instanceof Error ? e.message : String(e)}`);
2106
2703
  return;
2107
2704
  }
2108
2705
  if (unmergedFiles.includes(file)) {
2109
- this.logger.debug("apply.commit.blox_merge_fallback", { file });
2110
- await git.revertPathToHead(file, tmpRepoCwd);
2111
2706
  return;
2112
2707
  }
2113
2708
  const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
@@ -2126,8 +2721,8 @@ ${e instanceof Error ? e.message : String(e)}`);
2126
2721
  }
2127
2722
  const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
2128
2723
  try {
2129
- const outPath = import_node_path16.default.join(tmpRepoCwd, file);
2130
- await import_fs_extra13.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
2724
+ const outPath = import_node_path18.default.join(tmpRepoCwd, file);
2725
+ await import_fs_extra14.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
2131
2726
  await git.add(file, tmpRepoCwd);
2132
2727
  } catch (e) {
2133
2728
  this.logger.warn("apply.commit.blox_merge_fallback", {
@@ -2261,79 +2856,128 @@ var CommitSelectorService = class {
2261
2856
  }
2262
2857
  };
2263
2858
 
2264
- // src/services/contribute/utils/discoverContributionTargets.ts
2265
- var import_node_path17 = __toESM(require("path"));
2266
- var import_fs_extra14 = __toESM(require("fs-extra"));
2267
- var readBloxFileIfExists = (cwd) => {
2268
- const p = import_node_path17.default.join(cwd, bloxFilePath);
2269
- if (!import_fs_extra14.default.existsSync(p)) return;
2270
- try {
2271
- return import_fs_extra14.default.readJSONSync(p);
2272
- } catch {
2273
- return;
2859
+ // src/shared/prompts/selectWithSearch.ts
2860
+ var import_core = require("@clack/core");
2861
+ var import_prompts15 = require("@clack/prompts");
2862
+ var SEARCH_REQUESTED = Symbol("search-requested");
2863
+ function isSelectedOption(option2, selectedValues) {
2864
+ return selectedValues.includes(option2.value);
2865
+ }
2866
+ function selectedOptionLabels(options, selectedValues) {
2867
+ return options.filter((option2) => isSelectedOption(option2, selectedValues)).map((option2) => option2.label);
2868
+ }
2869
+ function stateSymbol(state) {
2870
+ switch (state) {
2871
+ case "cancel":
2872
+ return fmt.red("\u25A0");
2873
+ case "error":
2874
+ return fmt.yellow("\u25B2");
2875
+ case "submit":
2876
+ return fmt.green("\u25C7");
2877
+ default:
2878
+ return fmt.cyan("\u25C6");
2274
2879
  }
2275
- };
2276
- var discoverContributionTargets = (cwd) => {
2277
- const targets = [];
2278
- const rootBlox = readBloxFileIfExists(cwd);
2279
- const appTemplateName = rootBlox?.definition?.name;
2280
- const appTemplateDef = rootBlox?.definition;
2281
- if (rootBlox?.definition?.name) {
2282
- targets.push({
2283
- type: "template" /* TEMPLATE */,
2284
- name: rootBlox.definition.name,
2285
- templateName: rootBlox.definition.name,
2286
- templateDef: appTemplateDef,
2287
- label: `template/${rootBlox.definition.name}`
2288
- });
2289
- for (const base of rootBlox.definition.bases || []) {
2290
- targets.push({
2291
- type: "base" /* BASE */,
2292
- name: base.name,
2293
- templateDef: appTemplateDef,
2294
- label: `base/${base.name}`,
2295
- hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
2296
- });
2297
- }
2880
+ }
2881
+ function exitIfRealCancel(result) {
2882
+ if ((0, import_prompts15.isCancel)(result)) {
2883
+ (0, import_prompts15.cancel)("Canceled");
2884
+ process.exit(0);
2298
2885
  }
2299
- const blocksPath = import_node_path17.default.join(cwd, blocksDir);
2300
- if (import_fs_extra14.default.existsSync(blocksPath)) {
2301
- const entries = import_fs_extra14.default.readdirSync(blocksPath, { withFileTypes: true });
2302
- for (const entry of entries) {
2303
- if (!entry.isDirectory()) continue;
2304
- const blockName = entry.name;
2305
- const blockBlox = readBloxFileIfExists(import_node_path17.default.join(blocksPath, blockName));
2306
- if (!blockBlox?.definition?.name) continue;
2307
- const def = blockBlox.definition;
2308
- const templateName = def.templates?.[0]?.name || appTemplateName;
2309
- targets.push({
2310
- type: "block" /* BLOCK */,
2311
- name: blockName,
2312
- templateName,
2313
- templateDef: appTemplateDef,
2314
- label: `block/${blockName}`,
2315
- hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
2316
- });
2886
+ }
2887
+ function watchForSearchKey(prompt) {
2888
+ let searchRequested = false;
2889
+ prompt.on("key", (char) => {
2890
+ if (char.toLowerCase() === "s") {
2891
+ searchRequested = true;
2892
+ prompt.state = "cancel";
2893
+ prompt.close();
2317
2894
  }
2895
+ });
2896
+ return () => searchRequested;
2897
+ }
2898
+ async function multiselectWithSearch(opts) {
2899
+ const required = opts.required ?? false;
2900
+ const optLabel = (option2, state) => {
2901
+ switch (state) {
2902
+ case "active":
2903
+ return `${fmt.cyan("\u25FB")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2904
+ case "selected":
2905
+ return `${fmt.green("\u25FC")} ${fmt.dim(option2.label)}`;
2906
+ case "active-selected":
2907
+ return `${fmt.green("\u25FC")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2908
+ default:
2909
+ return `${fmt.dim("\u25FB")} ${fmt.dim(option2.label)}`;
2910
+ }
2911
+ };
2912
+ const prompt = new import_core.MultiSelectPrompt({
2913
+ options: opts.options,
2914
+ initialValues: opts.initialValues,
2915
+ required,
2916
+ validate(selected) {
2917
+ if (required && (!selected || selected.length === 0)) {
2918
+ return `Please select at least one option.
2919
+ ${fmt.dim(
2920
+ `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2921
+ )}`;
2922
+ }
2923
+ return void 0;
2924
+ },
2925
+ render() {
2926
+ const title = `${fmt.gray("\u2502")}
2927
+ ${stateSymbol(this.state)} ${opts.message}
2928
+ `;
2929
+ const value = this.value ?? [];
2930
+ const styleOption = (option2, active) => {
2931
+ const selected = isSelectedOption(option2, value);
2932
+ if (active && selected) return optLabel(option2, "active-selected");
2933
+ if (selected) return optLabel(option2, "selected");
2934
+ return optLabel(option2, active ? "active" : "inactive");
2935
+ };
2936
+ switch (this.state) {
2937
+ case "submit":
2938
+ return `${title}${fmt.gray("\u2502")} ${selectedOptionLabels(this.options, value).map((label) => fmt.dim(label)).join(fmt.dim(", ")) || fmt.dim("none")}`;
2939
+ case "cancel": {
2940
+ const selectedLabels = selectedOptionLabels(this.options, value).map((label) => fmt.strikethrough(fmt.dim(label))).join(fmt.dim(", "));
2941
+ return `${title}${fmt.gray("\u2502")}${selectedLabels.trim() ? ` ${selectedLabels}
2942
+ ${fmt.gray("\u2502")}` : ""}`;
2943
+ }
2944
+ case "error": {
2945
+ const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2946
+ return `${title}${fmt.yellow("\u2502")} ${lines.join(`
2947
+ ${fmt.yellow("\u2502")} `)}
2948
+ ${fmt.yellow("\u2514")} ${fmt.yellow(this.error)}
2949
+ `;
2950
+ }
2951
+ default: {
2952
+ const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2953
+ return `${title}${fmt.cyan("\u2502")} ${lines.join(`
2954
+ ${fmt.cyan("\u2502")} `)}
2955
+ ${fmt.cyan("\u2514")} ${fmt.dim(
2956
+ `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2957
+ )}`;
2958
+ }
2959
+ }
2960
+ }
2961
+ });
2962
+ const searchRequested = watchForSearchKey(prompt);
2963
+ const result = await prompt.prompt();
2964
+ if (searchRequested()) {
2965
+ return SEARCH_REQUESTED;
2318
2966
  }
2319
- return targets;
2320
- };
2321
-
2322
- // src/services/contribute/utils/parseContributionTargetType.ts
2323
- var parseContributionTargetType = (segment) => {
2324
- if (segment === "template" /* TEMPLATE */ || segment === "base" /* BASE */ || segment === "block" /* BLOCK */) {
2325
- return segment;
2326
- }
2327
- return;
2328
- };
2967
+ exitIfRealCancel(result);
2968
+ return result;
2969
+ }
2329
2970
 
2330
2971
  // src/services/contribute/services/ContributionTargetSelector.ts
2972
+ var MULTI_NAV_PREV = "__prev__";
2973
+ var MULTI_NAV_NEXT = "__next__";
2974
+ var MULTI_NAV_FINISH = "__finish__";
2331
2975
  var ContributionTargetSelector = class {
2332
2976
  constructor(opts, logger) {
2333
2977
  this.opts = opts;
2334
2978
  this.logger = logger;
2335
2979
  }
2336
- async selectTargetInteractive() {
2980
+ async selectMultipleTargetsInteractive(opts) {
2337
2981
  const all = discoverContributionTargets(this.opts.cwd);
2338
2982
  if (!all.length) {
2339
2983
  throw new Error(
@@ -2341,56 +2985,104 @@ var ContributionTargetSelector = class {
2341
2985
  );
2342
2986
  }
2343
2987
  let query = "";
2344
- for (; ; ) {
2345
- query = await text({
2346
- message: `Search targets ${fmt.gray("(empty for all)")}`,
2347
- placeholder: "auth, template, base, ...",
2348
- defaultValue: query
2349
- });
2350
- const filtered = filterTargetsByQuery(all, query);
2351
- if (!filtered.length) {
2352
- this.logger.warn(`No matches for search: "${query}"`);
2353
- const again = await confirm({ message: "Search again?" });
2354
- if (again) {
2355
- query = " ";
2356
- continue;
2357
- }
2358
- throw new Error("Aborted: no target selected.");
2988
+ let filtered = all;
2989
+ const selectedKeys = /* @__PURE__ */ new Set();
2990
+ const selectedTargets = () => Array.from(selectedKeys).map((key) => {
2991
+ const found = all.find((target) => targetHintKey(target) === key);
2992
+ if (!found) {
2993
+ throw new Error(`Invalid selection: ${key}`);
2994
+ }
2995
+ if (found.type === "block" /* BLOCK */) {
2996
+ return {
2997
+ type: found.type,
2998
+ name: found.name,
2999
+ dir: found.dir,
3000
+ templateName: found.templateName,
3001
+ templateDef: found.templateDef
3002
+ };
2359
3003
  }
2360
- const pageSize = UI_PAGE_SIZE;
3004
+ return {
3005
+ type: found.type,
3006
+ name: found.name,
3007
+ templateName: found.templateName,
3008
+ templateDef: found.templateDef
3009
+ };
3010
+ });
3011
+ while (true) {
3012
+ const shouldPaginate = filtered.length > UI_PAGE_SIZE;
3013
+ const pageSize = shouldPaginate ? UI_PAGE_SIZE : filtered.length || 1;
2361
3014
  let page = 0;
2362
3015
  const maxPage = Math.max(0, Math.ceil(filtered.length / pageSize) - 1);
2363
3016
  while (true) {
2364
3017
  const start = page * pageSize;
2365
3018
  const slice = filtered.slice(start, start + pageSize);
2366
- const value = await select({
2367
- message: `Select contribution target ${fmt.gray(`(page ${page + 1}/${maxPage + 1})`)}`,
2368
- options: buildTargetPageSelectOptions(slice, page, maxPage)
3019
+ const initialValues = slice.map((t) => targetHintKey(t)).filter((key) => selectedKeys.has(key));
3020
+ const value = await multiselectWithSearch({
3021
+ message: shouldPaginate ? `Select contribution targets ${fmt.gray(`(page ${page + 1}/${maxPage + 1})`)} ${fmt.gray("(press s to search)")}` : `Select contribution targets ${fmt.gray("(press s to search)")}`,
3022
+ options: buildMultiTargetPageSelectOptions(slice, opts?.changeHints),
3023
+ initialValues,
3024
+ required: false
3025
+ });
3026
+ if (value === SEARCH_REQUESTED) {
3027
+ query = await text({
3028
+ message: `Search targets ${fmt.gray("(empty for all)")}`,
3029
+ placeholder: "auth, template, base, ...",
3030
+ defaultValue: query
3031
+ });
3032
+ filtered = filterTargetsByQuery(all, query);
3033
+ if (!filtered.length) {
3034
+ this.logger.warn(`No matches for search: "${query}"`);
3035
+ const again = await confirm({ message: "Search again?" });
3036
+ if (again) {
3037
+ query = " ";
3038
+ break;
3039
+ }
3040
+ filtered = all;
3041
+ }
3042
+ page = 0;
3043
+ break;
3044
+ }
3045
+ for (const t of slice) {
3046
+ const key = targetHintKey(t);
3047
+ if (value.includes(key)) {
3048
+ selectedKeys.add(key);
3049
+ } else {
3050
+ selectedKeys.delete(key);
3051
+ }
3052
+ }
3053
+ if (!shouldPaginate) {
3054
+ if (!selectedKeys.size) {
3055
+ this.logger.warn("You must select at least one target before continuing.");
3056
+ continue;
3057
+ }
3058
+ return selectedTargets();
3059
+ }
3060
+ const hasPrev = page > 0;
3061
+ const hasNext = page < maxPage;
3062
+ const navigation = await select({
3063
+ message: `${selectedKeys.size} target(s) selected. Choose an action:`,
3064
+ options: [
3065
+ ...hasPrev ? [{ label: "Previous page", value: MULTI_NAV_PREV }] : [],
3066
+ ...hasNext ? [{ label: "Next page", value: MULTI_NAV_NEXT }] : [],
3067
+ { label: "Done", value: MULTI_NAV_FINISH }
3068
+ ]
2369
3069
  });
2370
- if (value === TARGET_SELECT_PAGE.PREV) {
3070
+ if (navigation === MULTI_NAV_PREV) {
2371
3071
  page = Math.max(0, page - 1);
2372
3072
  continue;
2373
3073
  }
2374
- if (value === TARGET_SELECT_PAGE.NEXT) {
3074
+ if (navigation === MULTI_NAV_NEXT) {
2375
3075
  page = Math.min(maxPage, page + 1);
2376
3076
  continue;
2377
3077
  }
2378
- if (value === TARGET_SELECT_PAGE.SEARCH_AGAIN) {
2379
- query = " ";
2380
- break;
2381
- }
2382
- const [typeRaw, name, templateNameRaw] = value.split(":");
2383
- const type = typeRaw ? parseContributionTargetType(typeRaw) : void 0;
2384
- if (!type || !name) {
2385
- throw new Error(`Invalid selection: ${value}`);
3078
+ if (!selectedKeys.size) {
3079
+ this.logger.warn("You must select at least one target before continuing.");
3080
+ continue;
2386
3081
  }
2387
- const found = all.find((t) => t.type === type && t.name === name);
2388
- return {
2389
- type,
2390
- name,
2391
- templateName: templateNameRaw || void 0,
2392
- templateDef: found?.templateDef
2393
- };
3082
+ return selectedTargets();
3083
+ }
3084
+ if (!filtered.length) {
3085
+ filtered = all;
2394
3086
  }
2395
3087
  }
2396
3088
  }
@@ -2402,17 +3094,16 @@ function filterTargetsByQuery(all, query) {
2402
3094
  }
2403
3095
  return all.filter((t) => `${t.type}/${t.name}`.toLowerCase().includes(q));
2404
3096
  }
2405
- function buildTargetPageSelectOptions(slice, page, maxPage) {
2406
- return [
2407
- ...slice.map((t) => ({
2408
- value: `${t.type}:${t.name}:${t.templateName || ""}`,
2409
- label: t.label,
2410
- hint: t.hint
2411
- })),
2412
- ...page > 0 ? [{ value: TARGET_SELECT_PAGE.PREV, label: "\u25C0 prev page" }] : [],
2413
- ...page < maxPage ? [{ value: TARGET_SELECT_PAGE.NEXT, label: "next page \u25B6" }] : [],
2414
- { value: TARGET_SELECT_PAGE.SEARCH_AGAIN, label: "search again" }
2415
- ];
3097
+ function buildMultiTargetPageSelectOptions(slice, changeHints) {
3098
+ return slice.map((t) => {
3099
+ const hasChanges = changeHints?.get(targetHintKey(t));
3100
+ const changeHint = hasChanges === void 0 ? void 0 : hasChanges ? fmt.green("has changes in selected commits") : fmt.gray("no changes in selected commits");
3101
+ return {
3102
+ value: targetHintKey(t),
3103
+ label: hasChanges ? `${fmt.green("+")} ${t.label}` : t.label,
3104
+ hint: [t.hint, changeHint].filter(Boolean).join(" \xB7 ")
3105
+ };
3106
+ });
2416
3107
  }
2417
3108
 
2418
3109
  // src/services/contribute/services/LoggerService.ts
@@ -2533,57 +3224,80 @@ var PullRequestService = class {
2533
3224
  }
2534
3225
  }
2535
3226
  printPushSummary(opts) {
2536
- const line = "\u2501".repeat(60);
2537
- const header = fmt.bold(fmt.cyan("BRANCH PUSHED"));
3227
+ const description = opts.description.trim();
3228
+ const rows = [
3229
+ ["Target", opts.targetBranch, fmt.green],
3230
+ ["Source", opts.sourceBranch, fmt.yellow],
3231
+ ["Remote", opts.repoUrl, fmt.blue],
3232
+ ["Title", opts.title, (v) => v]
3233
+ ];
3234
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
3235
+ const plainLines = [
3236
+ ...rows.map(([label, value]) => `${label.padEnd(labelWidth)}: ${value}`),
3237
+ ...description ? ["Description:", ...description.split("\n")] : []
3238
+ ];
3239
+ const titleText = " BRANCH PUSHED ";
3240
+ const terminalWidth = process.stdout.columns || 80;
3241
+ const innerWidth = Math.min(
3242
+ Math.max(...plainLines.map((l) => l.length), titleText.length),
3243
+ terminalWidth - 6
3244
+ );
3245
+ const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
3246
+ const padVisible = (s) => s + " ".repeat(Math.max(innerWidth - stripAnsi(s).length, 0));
3247
+ const topBorder = `\u250C\u2500${fmt.bold(titleText)}${"\u2500".repeat(Math.max(innerWidth - titleText.length + 2, 0))}\u2500\u2510`;
3248
+ const bottomBorder = `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`;
3249
+ const emptyLine = `\u2502${" ".repeat(innerWidth + 4)}\u2502`;
3250
+ const line = (content) => `\u2502 ${padVisible(content)} \u2502`;
3251
+ const rowLines = rows.map(
3252
+ ([label, value, paint]) => line(`${fmt.bold(`${label}:`.padEnd(labelWidth + 1))} ${paint(value)}`)
3253
+ );
3254
+ const descriptionLines = description ? [line(fmt.gray("Description:")), ...description.split("\n").map((l) => line(l))] : [];
2538
3255
  import_prompts2.log.message(
2539
- `
2540
- ${fmt.cyan("\u25E2")}${line}${fmt.cyan("\u25E3")}
2541
- ${header}
2542
-
2543
- ${fmt.bold("Target:")} ${fmt.green(opts.targetBranch)}
2544
- ${fmt.bold("Source:")} ${fmt.yellow(opts.sourceBranch)}
2545
- ${fmt.bold("Remote:")} ${fmt.blue(opts.repoUrl)}
2546
- ${fmt.bold("Title:")} ${opts.title}
2547
- ` + (opts.description.trim() ? `
2548
- ${fmt.gray("Description:")}
2549
- ${opts.description.trim()}
2550
- ` : "") + `${fmt.cyan("\u25E5")}${line}${fmt.cyan("\u25E4")}
2551
- `
3256
+ [
3257
+ "",
3258
+ topBorder,
3259
+ emptyLine,
3260
+ ...rowLines,
3261
+ ...descriptionLines.length ? [emptyLine, ...descriptionLines] : [],
3262
+ emptyLine,
3263
+ bottomBorder,
3264
+ ""
3265
+ ].join("\n")
2552
3266
  );
2553
3267
  }
2554
- async openPullRequestPage(opts) {
3268
+ resolvePullRequestUrl(opts) {
2555
3269
  const parsed = extractAzureRepoInfoFromGit(opts.repoUrl);
2556
3270
  if (!parsed) {
2557
3271
  this.logger.info("pr.skipped", { reason: "remote_not_azure_devops_git" });
2558
- return { prUrl: void 0 };
3272
+ return void 0;
3273
+ }
3274
+ return buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
3275
+ }
3276
+ async openPullRequestUrls(urls) {
3277
+ if (!urls.length) {
3278
+ return;
2559
3279
  }
2560
3280
  const wantsPr = await confirm({
2561
- message: "Do you want to open a Pull Request?",
3281
+ message: urls.length > 1 ? "Do you want to open the Pull Requests?" : "Do you want to open the Pull Request?",
2562
3282
  initialValue: true
2563
3283
  });
2564
3284
  if (!wantsPr) {
2565
3285
  this.logger.info("pr.declined");
2566
- return { prUrl: void 0 };
3286
+ return;
2567
3287
  }
2568
- const createPageUrl = buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
2569
- try {
2570
- await openUrlInBrowser(createPageUrl);
2571
- } catch (e) {
2572
- this.logger.warn("Could not open browser", e);
3288
+ for (const url of urls) {
3289
+ try {
3290
+ await openUrlInBrowser(url);
3291
+ } catch (e) {
3292
+ this.logger.warn("Could not open browser", e);
3293
+ }
2573
3294
  }
2574
- import_prompts2.log.message(
2575
- `
2576
- ${fmt.green("Opening Pull Request creation in your browser.")}
2577
- ${fmt.cyan(createPageUrl)}
2578
- `
2579
- );
2580
- return { prUrl: createPageUrl };
2581
3295
  }
2582
3296
  };
2583
3297
 
2584
3298
  // src/services/contribute/services/TmpRepoService.ts
2585
- var import_node_os2 = require("os");
2586
- var import_node_path18 = __toESM(require("path"));
3299
+ var import_node_os3 = require("os");
3300
+ var import_node_path19 = __toESM(require("path"));
2587
3301
  var import_fs_extra15 = __toESM(require("fs-extra"));
2588
3302
  var TmpRepoService = class {
2589
3303
  constructor(logger) {
@@ -2603,7 +3317,7 @@ var TmpRepoService = class {
2603
3317
  const isBlock = target.type === "block" /* BLOCK */;
2604
3318
  const slugParts = isBlock && target.templateName ? [target.type, target.templateName, target.name] : [target.type, target.name];
2605
3319
  const slug = slugParts.join("-").replace(/[^a-zA-Z0-9._-]+/g, "-");
2606
- return import_node_path18.default.join((0, import_node_os2.homedir)(), bloxFilePath, tempRepoName, slug);
3320
+ return import_node_path19.default.join((0, import_node_os3.homedir)(), bloxFilePath, tempRepoName, slug);
2607
3321
  }
2608
3322
  async prepare(opts) {
2609
3323
  const taskSpinner = spinner();
@@ -2629,7 +3343,7 @@ var TmpRepoService = class {
2629
3343
  await import_fs_extra15.default.remove(dir);
2630
3344
  }
2631
3345
  }
2632
- await import_fs_extra15.default.ensureDir(import_node_path18.default.dirname(dir));
3346
+ await import_fs_extra15.default.ensureDir(import_node_path19.default.dirname(dir));
2633
3347
  await git.clone(opts.repoUrl, dir, opts.branch);
2634
3348
  taskSpinner.stop("Prepared tmp repo");
2635
3349
  return dir;
@@ -2643,26 +3357,19 @@ var TmpRepoService = class {
2643
3357
  // src/services/contribute/index.ts
2644
3358
  async function buildContributionWorkflow(opts) {
2645
3359
  const logger = new LoggerService();
2646
- const targetSelector = new ContributionTargetSelector({ cwd: opts.cwd }, logger);
2647
- const tmpRepo = new TmpRepoService(logger);
2648
- const commitSelector = new CommitSelectorService(logger);
2649
- const commitApplier = new CommitApplierService(logger);
2650
- const pullRequest = new PullRequestService(logger);
2651
3360
  return new ContributionWorkflow(
2652
3361
  { cwd: opts.cwd, force: opts.force },
2653
3362
  logger,
2654
- targetSelector,
2655
- tmpRepo,
2656
- commitSelector,
2657
- commitApplier,
2658
- pullRequest
3363
+ new ContributionTargetSelector({ cwd: opts.cwd }, logger),
3364
+ new TmpRepoService(logger),
3365
+ new CommitSelectorService(logger),
3366
+ new CommitApplierService(logger),
3367
+ new PullRequestService(logger)
2659
3368
  );
2660
3369
  }
2661
3370
 
2662
3371
  // src/commands/contribute/index.ts
2663
- var contribute = command("contribute").description("Contribute changes back to template/base/block repositories").alias("cb").option("--existing", "add changes to an existing contribution PR").option("--title <title>", "contribution title").option("--description <description>", "contribution description").option("--commits <commits>", "comma-separated commit hashes from app repo").option("--force", "bypass safety pre-flight checks").addOption(
2664
- option("--type <type>", "target type").choices(Object.values(ContributionTargetType))
2665
- ).option("--name <name>", "target name").action(async (flags) => {
3372
+ var contribute = command("contribute").description("Contribute changes back to template/base/block repositories").alias("cb").option("--existing", "add changes to an existing contribution PR").option("--title <title>", "contribution title").option("--description <description>", "contribution description").option("--commits <commits>", "comma-separated commit hashes from app repo").option("--type <type>", "target type (template, base, or block)").option("--name <name>", "target name (used with --type)").option("--force", "bypass safety pre-flight checks").action(async (flags) => {
2666
3373
  try {
2667
3374
  if (await git.hasUncommittedChanges()) {
2668
3375
  throw new Error(
@@ -2675,7 +3382,10 @@ var contribute = command("contribute").description("Contribute changes back to t
2675
3382
  cwd: process.cwd(),
2676
3383
  force: !!flags.force
2677
3384
  });
2678
- await workflow.runFromFlags(flags);
3385
+ const results = await workflow.runFromFlags(flags);
3386
+ if (results.some((r) => !r.success)) {
3387
+ process.exitCode = 1;
3388
+ }
2679
3389
  } catch (e) {
2680
3390
  error(e);
2681
3391
  }
@@ -2784,9 +3494,9 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
2784
3494
  });
2785
3495
 
2786
3496
  // src/commands/remove/index.ts
2787
- var import_node_path19 = __toESM(require("path"));
3497
+ var import_node_path20 = __toESM(require("path"));
2788
3498
  var import_fs_extra17 = __toESM(require("fs-extra"));
2789
- var blocksAbsolutePath = () => import_node_path19.default.resolve(process.cwd(), blocksDir);
3499
+ var blocksAbsolutePath = () => import_node_path20.default.resolve(process.cwd(), blocksDir);
2790
3500
  function listInstalledBlockRelPaths() {
2791
3501
  const root = blocksAbsolutePath();
2792
3502
  if (!import_fs_extra17.default.existsSync(root)) {
@@ -2797,17 +3507,17 @@ function listInstalledBlockRelPaths() {
2797
3507
  if (!entry.isDirectory()) {
2798
3508
  continue;
2799
3509
  }
2800
- const abs = import_node_path19.default.join(root, entry.name);
3510
+ const abs = import_node_path20.default.join(root, entry.name);
2801
3511
  if (!isBlockDirectory(abs)) {
2802
3512
  continue;
2803
3513
  }
2804
- paths2.push(import_node_path19.default.join(blocksDir, entry.name));
3514
+ paths2.push(import_node_path20.default.join(blocksDir, entry.name));
2805
3515
  }
2806
3516
  return paths2;
2807
3517
  }
2808
3518
  function getInstalledBlockSelectOptions() {
2809
3519
  return listInstalledBlockRelPaths().map((rel) => {
2810
- const folder = import_node_path19.default.basename(rel);
3520
+ const folder = import_node_path20.default.basename(rel);
2811
3521
  const def = getBlockDef(rel);
2812
3522
  const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
2813
3523
  return { value: folder, label, hint: def?.name };
@@ -2815,7 +3525,7 @@ function getInstalledBlockSelectOptions() {
2815
3525
  }
2816
3526
  function assertNoDependents(blockPathAbs, targetBlockName) {
2817
3527
  for (const rel of listInstalledBlockRelPaths()) {
2818
- const abs = import_node_path19.default.resolve(process.cwd(), rel);
3528
+ const abs = import_node_path20.default.resolve(process.cwd(), rel);
2819
3529
  if (abs === blockPathAbs) {
2820
3530
  continue;
2821
3531
  }
@@ -2831,19 +3541,19 @@ function assertNoDependents(blockPathAbs, targetBlockName) {
2831
3541
  }
2832
3542
  function assertUnderBlocksRoot(blockPathAbs) {
2833
3543
  const root = blocksAbsolutePath();
2834
- const rel = import_node_path19.default.relative(root, blockPathAbs);
2835
- if (!rel || rel.startsWith("..") || import_node_path19.default.isAbsolute(rel)) {
3544
+ const rel = import_node_path20.default.relative(root, blockPathAbs);
3545
+ if (!rel || rel.startsWith("..") || import_node_path20.default.isAbsolute(rel)) {
2836
3546
  throw new Error("Block path escapes the blocks directory");
2837
3547
  }
2838
3548
  }
2839
3549
  async function removeBlock(block, blocks, force = false) {
2840
3550
  const reg = blocks[block];
2841
3551
  const destination = reg ? reg.destination ?? block : block;
2842
- const blockPathRel = import_node_path19.default.join(blocksDir, destination);
2843
- const blockPathAbs = import_node_path19.default.resolve(process.cwd(), blockPathRel);
3552
+ const blockPathRel = import_node_path20.default.join(blocksDir, destination);
3553
+ const blockPathAbs = import_node_path20.default.resolve(process.cwd(), blockPathRel);
2844
3554
  assertUnderBlocksRoot(blockPathAbs);
2845
3555
  if (!import_fs_extra17.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
2846
- throw new Error(`Block is not installed at ${import_node_path19.default.relative(process.cwd(), blockPathAbs)}`);
3556
+ throw new Error(`Block is not installed at ${import_node_path20.default.relative(process.cwd(), blockPathAbs)}`);
2847
3557
  }
2848
3558
  const targetDef = getBlockDef(blockPathRel);
2849
3559
  if (!targetDef?.name) {
@@ -2912,8 +3622,8 @@ var remove = command("remove").description("Remove block from app").alias("rm").
2912
3622
 
2913
3623
  // src/commands/skills/index.ts
2914
3624
  var import_node_crypto = require("crypto");
2915
- var import_node_os3 = __toESM(require("os"));
2916
- var import_node_path21 = __toESM(require("path"));
3625
+ var import_node_os4 = __toESM(require("os"));
3626
+ var import_node_path22 = __toESM(require("path"));
2917
3627
  var import_cross_spawn2 = __toESM(require("cross-spawn"));
2918
3628
  var import_fs_extra19 = __toESM(require("fs-extra"));
2919
3629
 
@@ -2921,7 +3631,7 @@ var import_fs_extra19 = __toESM(require("fs-extra"));
2921
3631
  var SKILLS_REPO_URL = "https://github.com/Naseej-its/blox.git";
2922
3632
 
2923
3633
  // src/commands/skills/utils/cliCompatibility.ts
2924
- var import_node_path20 = __toESM(require("path"));
3634
+ var import_node_path21 = __toESM(require("path"));
2925
3635
  var import_fs_extra18 = __toESM(require("fs-extra"));
2926
3636
  var import_semver = __toESM(require("semver"));
2927
3637
  var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
@@ -2946,14 +3656,14 @@ function getAddCommandIndex(args) {
2946
3656
  return getSkillscommandIndex(args, "add");
2947
3657
  }
2948
3658
  async function loadSkillsData(cloneRoot) {
2949
- const skillsDir = import_node_path20.default.join(cloneRoot, "skills");
3659
+ const skillsDir = import_node_path21.default.join(cloneRoot, "skills");
2950
3660
  if (!await import_fs_extra18.default.pathExists(skillsDir)) {
2951
3661
  return [];
2952
3662
  }
2953
3663
  const entries = await import_fs_extra18.default.readdir(skillsDir, { withFileTypes: true });
2954
3664
  const manifests = await Promise.all(
2955
3665
  entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
2956
- const filePath = import_node_path20.default.join(skillsDir, entry.name, "skill.json");
3666
+ const filePath = import_node_path21.default.join(skillsDir, entry.name, "skill.json");
2957
3667
  if (!await import_fs_extra18.default.pathExists(filePath)) {
2958
3668
  return null;
2959
3669
  }
@@ -3009,7 +3719,7 @@ async function runSkills() {
3009
3719
  const idx = process.argv.indexOf("skills");
3010
3720
  const args = idx === -1 ? [] : process.argv.slice(idx + 1);
3011
3721
  if (needsCliCompatibilityCheck(args)) {
3012
- const tempDir = import_node_path21.default.join(import_node_os3.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto.randomUUID)()}`);
3722
+ const tempDir = import_node_path22.default.join(import_node_os4.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto.randomUUID)()}`);
3013
3723
  await import_fs_extra19.default.mkdir(tempDir);
3014
3724
  try {
3015
3725
  await git.clone(SKILLS_REPO_URL, tempDir);
@@ -3061,13 +3771,10 @@ function runSkillsCommand(args, cwd) {
3061
3771
  }
3062
3772
 
3063
3773
  // src/commands/update/index.ts
3064
- var import_prompts23 = require("@clack/prompts");
3065
-
3066
- // src/commands/update/utils.ts
3067
- var import_node_path23 = __toESM(require("path"));
3774
+ var import_prompts26 = require("@clack/prompts");
3068
3775
 
3069
3776
  // src/services/updater.ts
3070
- var import_node_path22 = __toESM(require("path"));
3777
+ var import_node_path23 = __toESM(require("path"));
3071
3778
  var import_fs_extra20 = __toESM(require("fs-extra"));
3072
3779
  var import_klaw3 = __toESM(require("klaw"));
3073
3780
  async function updateFromRemote({
@@ -3115,7 +3822,7 @@ async function updateFromRemote({
3115
3822
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
3116
3823
  const projectIgnore = bloxFile.project?.ignore || [];
3117
3824
  ignore3.push(...remoteIgnore, ...projectIgnore, bloxFilePath, `**/${bloxFilePath}`);
3118
- const gitIgnorePath = import_node_path22.default.join(dir, ".gitignore");
3825
+ const gitIgnorePath = import_node_path23.default.join(dir, ".gitignore");
3119
3826
  if (await import_fs_extra20.default.pathExists(gitIgnorePath)) {
3120
3827
  const gitIgnoreContent = await import_fs_extra20.default.readFile(gitIgnorePath, "utf8");
3121
3828
  const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
@@ -3136,7 +3843,7 @@ async function updateFromRemote({
3136
3843
  if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
3137
3844
  continue;
3138
3845
  if (file.stats.isFile()) {
3139
- files.push(import_node_path22.default.relative(d, file.path));
3846
+ files.push(import_node_path23.default.relative(d, file.path));
3140
3847
  }
3141
3848
  }
3142
3849
  }
@@ -3155,16 +3862,16 @@ async function updateFromRemote({
3155
3862
  for (const file of filesToProcess) {
3156
3863
  if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
3157
3864
  if (ignoredMatcher.ignores(toIgnorePath(file))) continue;
3158
- const localPath = import_node_path22.default.join(dir, file);
3159
- const basePath = import_node_path22.default.join(baseDir, file);
3160
- const remotePath = import_node_path22.default.join(remoteDir, file);
3865
+ const localPath = import_node_path23.default.join(dir, file);
3866
+ const basePath = import_node_path23.default.join(baseDir, file);
3867
+ const remotePath = import_node_path23.default.join(remoteDir, file);
3161
3868
  const existsLocal = await import_fs_extra20.default.pathExists(localPath);
3162
3869
  const existsBase = await import_fs_extra20.default.pathExists(basePath);
3163
3870
  const existsRemote = await import_fs_extra20.default.pathExists(remotePath);
3164
- const ext = import_node_path22.default.extname(file);
3871
+ const ext = import_node_path23.default.extname(file);
3165
3872
  const isBinary = isBinaryFile(ext);
3166
3873
  if (existsRemote) {
3167
- await import_fs_extra20.default.ensureDir(import_node_path22.default.dirname(localPath));
3874
+ await import_fs_extra20.default.ensureDir(import_node_path23.default.dirname(localPath));
3168
3875
  }
3169
3876
  if (hard) {
3170
3877
  if (existsRemote) {
@@ -3183,7 +3890,7 @@ async function updateFromRemote({
3183
3890
  await import_fs_extra20.default.copy(remotePath, localPath, { overwrite: true });
3184
3891
  logWarningSection(`Overwrote binary file collision: ${file}`);
3185
3892
  } else {
3186
- const emptyBase = import_node_path22.default.join(baseDir, `${file}.empty`);
3893
+ const emptyBase = import_node_path23.default.join(baseDir, `${file}.empty`);
3187
3894
  await import_fs_extra20.default.ensureFile(emptyBase);
3188
3895
  const result = await git.mergeFile(localPath, emptyBase, remotePath);
3189
3896
  if (!result) {
@@ -3254,6 +3961,13 @@ It has been recreated to apply upstream changes.`
3254
3961
  }
3255
3962
 
3256
3963
  // src/commands/update/utils.ts
3964
+ var isRecoverableBlockUpdateError = (error2) => {
3965
+ if (!(error2 instanceof Error)) return false;
3966
+ if (!error2.message.startsWith('Command "git fetch ')) return false;
3967
+ return /could not resolve host|failed to connect|connection (?:timed out|reset|refused)|network is unreachable|temporary failure in name resolution|operation timed out|remote end hung up unexpectedly|early EOF/i.test(
3968
+ error2.message
3969
+ );
3970
+ };
3257
3971
  async function confirmContinueWhenMissing(itemType, name) {
3258
3972
  return confirm({
3259
3973
  message: `${itemType}: ${name} does not exist in registries. Continue updating remaining parts?`,
@@ -3299,7 +4013,7 @@ async function updateApp({
3299
4013
  continue;
3300
4014
  }
3301
4015
  await git.updateRemote(block.name, blockRegistryData.source);
3302
- const blockPath = import_node_path23.default.join(blocksDir, block.name);
4016
+ const blockPath = getBlockPath(block.name);
3303
4017
  const currentBloxFile = getBloxFile(blockPath);
3304
4018
  const remoteBloxFile = (await migrateOnRemote(block.name, toAppCommit, blockPath)).output[".blox"];
3305
4019
  const blockFromCommit = currentBloxFile.checkpoints?.[block.name]?.commit;
@@ -3349,21 +4063,32 @@ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
3349
4063
  }
3350
4064
  async function updateBlock(block, blocks, ignore3, hard = false) {
3351
4065
  const blockRegistryData = blocks[block];
3352
- const blockPath = import_node_path23.default.join(blocksDir, block);
3353
4066
  let updated = false;
3354
4067
  try {
4068
+ const blockPath = getBlockPath(block);
3355
4069
  if (!blockRegistryData) {
3356
4070
  throw new Error(
3357
4071
  `${"block" /* BLOCK */}: ${block} does not exist in registries.`
3358
4072
  );
3359
4073
  }
3360
- const toCommit = await updateFromRemote({
3361
- name: block,
3362
- source: blockRegistryData.source,
3363
- dir: blockPath,
3364
- ignore: ignore3,
3365
- hard
3366
- });
4074
+ let toCommit;
4075
+ for (let attempt = 1; attempt <= 3; attempt++) {
4076
+ try {
4077
+ toCommit = await updateFromRemote({
4078
+ name: block,
4079
+ source: blockRegistryData.source,
4080
+ dir: blockPath,
4081
+ ignore: ignore3,
4082
+ hard
4083
+ });
4084
+ break;
4085
+ } catch (error2) {
4086
+ if (attempt === 3 || !isRecoverableBlockUpdateError(error2)) {
4087
+ throw error2;
4088
+ }
4089
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * 2 ** (attempt - 1)));
4090
+ }
4091
+ }
3367
4092
  if (toCommit) {
3368
4093
  updated = true;
3369
4094
  }
@@ -3411,7 +4136,7 @@ async function updateBlocks(blocks, availableBlocks, ignoresByName, hard = false
3411
4136
  return results;
3412
4137
  }
3413
4138
  async function runBlockUpdateHook(block) {
3414
- const blockPath = import_node_path23.default.join(blocksDir, block);
4139
+ const blockPath = getBlockPath(block);
3415
4140
  await runLifecycleHookWithTask(blockPath, "update", "Run block update");
3416
4141
  }
3417
4142
  async function getCurrentCheckpoints() {
@@ -3455,9 +4180,9 @@ ${fmt.gray("-".repeat(82))}
3455
4180
  // src/commands/update/index.ts
3456
4181
  var update2 = command("update").description("Update app/block").alias("u").addOption(
3457
4182
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
3458
- ).option("--ignore <list...>", 'Files ignore list scoped by name i.e "repo:file"').option("-b, --block <name>", "Block to update, valid only with scope block").option("--hard", "Hard update (overwrite local changes)", false).action(async (args) => {
4183
+ ).option("--ignore <list...>", 'Files ignore list scoped by name i.e "repo:file"').option("-b, --block <names...>", "Blocks to update, valid only with scope block").option("--hard", "Hard update (overwrite local changes)", false).action(async (args) => {
3459
4184
  if (await git.hasUncommittedChanges()) {
3460
- import_prompts23.log.warn(fmt.yellow("Make sure to commit any changes first"));
4185
+ import_prompts26.log.warn(fmt.yellow("Make sure to commit any changes first"));
3461
4186
  return;
3462
4187
  }
3463
4188
  await migrateAll(true);
@@ -3536,15 +4261,17 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3536
4261
  hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
3537
4262
  const failedBlocks = blockResults.filter((result) => result.error);
3538
4263
  if (failedBlocks.length) {
3539
- import_prompts23.log.warn(
4264
+ import_prompts26.log.warn(
3540
4265
  fmt.yellow(
3541
4266
  `${failedBlocks.length} block update${failedBlocks.length === 1 ? "" : "s"} failed.`
3542
4267
  )
3543
4268
  );
3544
4269
  for (const result of failedBlocks) {
3545
- import_prompts23.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4270
+ import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
3546
4271
  }
3547
- await waitForConflictResolution();
4272
+ import_prompts26.log.warn(
4273
+ "Fix the errors above and rerun the update for the failed blocks."
4274
+ );
3548
4275
  }
3549
4276
  for (const result of blockResults) {
3550
4277
  if (!result.updated) continue;
@@ -3553,41 +4280,45 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3553
4280
  }
3554
4281
  }
3555
4282
  if (shouldContinue && args.scope === "block") {
3556
- if (!args.block) {
3557
- args.block = await select({
4283
+ const requested = args.block?.length ? args.block : [
4284
+ await select({
3558
4285
  message: "Select block to be updated",
3559
4286
  options: usedBlocks.map((block) => ({
3560
4287
  value: block.name,
3561
4288
  label: block.name
3562
4289
  }))
3563
- });
3564
- }
3565
- const blockDef = usedBlocks.find((block) => block.name === args.block);
3566
- if (!blockDef) {
3567
- error("Selected block not used in app");
4290
+ })
4291
+ ];
4292
+ const unknown = requested.filter(
4293
+ (name) => !usedBlocks.some((block) => block.name === name)
4294
+ );
4295
+ if (unknown.length) {
4296
+ error(`Selected block not used in app: ${unknown.join(", ")}`);
3568
4297
  return;
3569
4298
  }
3570
- const [blockResult] = await updateBlocks(
3571
- [blockDef.name],
4299
+ const blockResults = await updateBlocks(
4300
+ requested,
3572
4301
  availableBlocks,
3573
4302
  ignoresByName,
3574
4303
  args.hard
3575
4304
  );
3576
- if (!blockResult) {
3577
- return;
4305
+ for (const result of blockResults) {
4306
+ if (result.error) {
4307
+ import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4308
+ }
3578
4309
  }
3579
- if (blockResult.error) {
3580
- import_prompts23.log.error(fmt.red(`${blockDef.name}: ${getErrorMessage(blockResult.error)}`));
3581
- await waitForConflictResolution();
4310
+ if (blockResults.some((result) => result.error)) {
4311
+ import_prompts26.log.warn("Fix the errors above and rerun the update for the failed blocks.");
3582
4312
  }
3583
- hasUpdate = hasUpdate || blockResult.updated;
3584
- shouldContinue = blockResult.shouldContinue;
3585
- if (blockResult.updated) {
3586
- await runBlockUpdateHook(blockDef.name);
4313
+ hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
4314
+ for (const result of blockResults) {
4315
+ if (result.updated) {
4316
+ await runBlockUpdateHook(result.block);
4317
+ }
3587
4318
  }
3588
4319
  }
3589
4320
  if (!shouldContinue) {
3590
- import_prompts23.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
4321
+ import_prompts26.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
3591
4322
  }
3592
4323
  if (hasUpdate) {
3593
4324
  await runLifecycleHookWithTask(".", "update", "Run template update");
@@ -3597,7 +4328,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3597
4328
  await printChangeLog(startCheckpoints, endCheckpoints);
3598
4329
  } catch (e) {
3599
4330
  if (!isDebugMode()) {
3600
- import_prompts23.log.warn("Error happened, Will rollback changes");
4331
+ import_prompts26.log.warn("Error happened, Will rollback changes");
3601
4332
  await git.rollback();
3602
4333
  }
3603
4334
  error(e);
@@ -3611,25 +4342,6 @@ function getErrorMessage(error2) {
3611
4342
  }
3612
4343
  return String(error2);
3613
4344
  }
3614
- async function waitForConflictResolution() {
3615
- import_prompts23.log.warn(
3616
- fmt.yellow(
3617
- [
3618
- "",
3619
- "Block update conflicts/errors detected.",
3620
- "Resolve the conflicts in the affected blocks, then press Enter to continue.",
3621
- ""
3622
- ].join("\n")
3623
- )
3624
- );
3625
- await new Promise((resolve) => {
3626
- process.stdin.resume();
3627
- process.stdin.once("data", () => {
3628
- process.stdin.pause();
3629
- resolve();
3630
- });
3631
- });
3632
- }
3633
4345
 
3634
4346
  // src/commands/upgrade/index.ts
3635
4347
  var upgrade = command("upgrade").description("Upgrade blox cli to latest version").action(async () => {