@naseej/blox 1.4.4 → 1.5.1

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 +1625 -159
  2. package/package.json +24 -22
  3. package/readme.md +24 -10
package/dist/run.js CHANGED
@@ -180,17 +180,17 @@ var checkForCliUpdate = async (currentVersion) => {
180
180
  };
181
181
 
182
182
  // package.json
183
- var version = "1.4.4";
183
+ var version = "1.5.1";
184
184
 
185
185
  // src/commands/add/index.ts
186
186
  var import_fs_extra9 = __toESM(require("fs-extra"));
187
187
 
188
188
  // src/migrations/index.ts
189
- var import_node_path6 = __toESM(require("path"));
189
+ var import_node_path8 = __toESM(require("path"));
190
190
  var import_fs_extra5 = __toESM(require("fs-extra"));
191
191
 
192
192
  // src/migrations/utils.ts
193
- var import_node_path5 = __toESM(require("path"));
193
+ var import_node_path7 = __toESM(require("path"));
194
194
  var import_fs_extra4 = __toESM(require("fs-extra"));
195
195
 
196
196
  // src/migrations/list/v1.ts
@@ -227,39 +227,43 @@ var v1 = {
227
227
  var migrationsList = [v1];
228
228
 
229
229
  // src/services/git.ts
230
- var import_node_path4 = __toESM(require("path"));
230
+ var import_node_os = __toESM(require("os"));
231
+ var import_node_path6 = __toESM(require("path"));
231
232
  var import_fs_extra3 = __toESM(require("fs-extra"));
232
233
 
233
- // src/services/path.ts
234
- var import_node_path3 = __toESM(require("path"));
235
- var normalizePath = (_path) => {
236
- return _path.split(import_node_path3.default.sep).join("/");
237
- };
238
-
239
234
  // src/services/shell.ts
240
- var import_node_child_process = require("child_process");
241
- var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
235
+ var import_cross_spawn = __toESM(require("cross-spawn"));
236
+ var $ = async (bin, options = [], { cwd, onStdout, shell = false } = {}) => {
242
237
  debug(`Command executed: "${bin} ${options.join(" ")}" with cwd = ${cwd}`);
243
238
  return new Promise(function(resolve, reject) {
244
- const child = (0, import_node_child_process.spawn)(bin, options, { cwd, shell: true, stdio: ["pipe", "pipe", "pipe"] });
245
- let error2 = "";
246
- child.stdout.on("data", (data) => {
239
+ const child = (0, import_cross_spawn.default)(bin, options, { cwd, shell, stdio: ["pipe", "pipe", "pipe"] });
240
+ let stdout = "";
241
+ let stderr = "";
242
+ child.stdout?.on("data", (data) => {
243
+ const str = data.toString();
244
+ stdout += str;
247
245
  try {
248
- debug(data.toString());
249
- onStdout && onStdout(data.toString());
246
+ onStdout && onStdout(str);
250
247
  } catch (e) {
251
248
  reject(e);
252
249
  }
253
250
  });
254
- child.stderr.on("data", (data) => {
255
- error2 += data.toString();
251
+ child.stderr?.on("data", (data) => {
252
+ stderr += data.toString();
256
253
  });
257
254
  child.on("close", function(code) {
258
- error2 && debug(error2);
259
255
  if (code) {
260
- reject(error2);
256
+ const combined = (stdout + "\n" + stderr).trim();
257
+ const msg = `Command "${bin} ${options.join(" ")}" failed (code ${code}).
258
+ ${combined}`;
259
+ const err = new Error(msg);
260
+ err.code = code;
261
+ err.stdout = stdout;
262
+ err.stderr = stderr;
263
+ err.combined = combined;
264
+ reject(err);
261
265
  } else {
262
- resolve(code);
266
+ resolve({ code, stdout, stderr });
263
267
  }
264
268
  });
265
269
  child.on("error", function(err) {
@@ -268,7 +272,206 @@ var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
268
272
  });
269
273
  };
270
274
 
275
+ // src/shared/utils/buildGitExcludePathspecs.ts
276
+ var buildGitExcludePathspecs = (patterns) => {
277
+ const out = [];
278
+ for (const raw of patterns) {
279
+ let p = raw.trim();
280
+ if (!p) continue;
281
+ if (p.startsWith("#")) continue;
282
+ if (p.startsWith("!")) continue;
283
+ p = normalizeIgnorePath(p);
284
+ if (!p) continue;
285
+ const hadTrailingSlash = p.endsWith("/");
286
+ if (hadTrailingSlash) {
287
+ p = p.replace(/\/+$/, "");
288
+ }
289
+ const isDir = hadTrailingSlash || !hasGlobMagic(p) && looksLikeDirectory(p);
290
+ if (isDir && !hasGlobMagic(p)) {
291
+ p = `${p}/**`;
292
+ }
293
+ out.push(`:(exclude,glob)${p}`);
294
+ }
295
+ return out;
296
+ };
297
+ var normalizeIgnorePath = (input) => {
298
+ let p = input.trim();
299
+ if (!p) return "";
300
+ p = p.replace(/\\/g, "/");
301
+ if (p.startsWith("./")) {
302
+ p = p.slice(2);
303
+ }
304
+ if (p.startsWith("/")) {
305
+ p = p.slice(1);
306
+ }
307
+ p = p.replace(/\/+/g, "/");
308
+ return p;
309
+ };
310
+ var hasGlobMagic = (pattern) => {
311
+ return /[*?\[]/.test(pattern);
312
+ };
313
+ var looksLikeDirectory = (pattern) => {
314
+ if (pattern.endsWith("/")) return true;
315
+ const lastSegment = pattern.split("/").pop();
316
+ if (!lastSegment) return false;
317
+ return !lastSegment.includes(".");
318
+ };
319
+
320
+ // src/shared/utils/gitignoreMatcher.ts
321
+ var import_node_path3 = __toESM(require("path"));
322
+ var import_ignore = __toESM(require("ignore"));
323
+ var createGitignoreMatcher = (patterns) => {
324
+ const cleaned = patterns.map((p) => p.trim()).filter((p) => p && !p.startsWith("#"));
325
+ return (0, import_ignore.default)().add(cleaned);
326
+ };
327
+ var toIgnorePath = (repoRelativePath) => {
328
+ let p = repoRelativePath.split(import_node_path3.default.sep).join("/");
329
+ if (p.startsWith("./")) p = p.slice(2);
330
+ return p;
331
+ };
332
+
333
+ // src/shared/utils/isBinaryFile.ts
334
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
335
+ ".png",
336
+ ".jpg",
337
+ ".jpeg",
338
+ ".gif",
339
+ ".svg",
340
+ ".ico",
341
+ ".ttf",
342
+ ".woff",
343
+ ".woff2",
344
+ ".otf",
345
+ ".mp4",
346
+ ".mp3",
347
+ ".zip",
348
+ ".plist",
349
+ ".DS_Store",
350
+ ".bin"
351
+ ]);
352
+ function isBinaryFile(ext) {
353
+ return BINARY_EXTENSIONS.has(ext);
354
+ }
355
+
356
+ // src/shared/utils/openUrlInBrowser.ts
357
+ var import_node_child_process = require("child_process");
358
+ function openUrlInBrowser(url) {
359
+ return new Promise((resolve, reject) => {
360
+ try {
361
+ let cmd;
362
+ let args;
363
+ if (process.platform === "win32") {
364
+ cmd = "cmd";
365
+ args = ["/c", "start", "", url];
366
+ } else if (process.platform === "darwin") {
367
+ cmd = "open";
368
+ args = [url];
369
+ } else {
370
+ cmd = "xdg-open";
371
+ args = [url];
372
+ }
373
+ const child = (0, import_node_child_process.execFile)(cmd, args, { windowsHide: true });
374
+ child.on("error", (err) => {
375
+ reject(err);
376
+ });
377
+ resolve();
378
+ } catch (err) {
379
+ reject(err);
380
+ }
381
+ });
382
+ }
383
+
384
+ // src/shared/utils/isBloxConfigFile.ts
385
+ var import_node_path4 = __toESM(require("path"));
386
+ function isBloxConfigFile(file) {
387
+ const normalized = file.split(import_node_path4.default.sep).join("/");
388
+ return normalized === bloxFilePath || normalized.endsWith(`/${bloxFilePath}`);
389
+ }
390
+
391
+ // src/shared/utils/omitKeys.ts
392
+ function omitKeys(value, keysToOmit) {
393
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
394
+ return value;
395
+ }
396
+ const result = { ...value };
397
+ for (const key of keysToOmit) {
398
+ delete result[key];
399
+ }
400
+ return result;
401
+ }
402
+
403
+ // src/shared/utils/normalizeCommitRef.ts
404
+ var normalizeCommitRef = (commit2) => commit2.trim().replace(/\r/g, "").replace(/^"+|"+$/g, "");
405
+
406
+ // src/services/path.ts
407
+ var import_node_path5 = __toESM(require("path"));
408
+ var normalizePath = (_path) => {
409
+ return _path.split(import_node_path5.default.sep).join("/");
410
+ };
411
+
271
412
  // src/services/git.ts
413
+ var remoteWorktrees = /* @__PURE__ */ new Map();
414
+ var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd = ".") => {
415
+ let output = "";
416
+ const args = [
417
+ "diff",
418
+ "--name-only",
419
+ "-z",
420
+ fromCommit,
421
+ toCommit,
422
+ "--",
423
+ ".",
424
+ ...buildGitExcludePathspecs(ignore3)
425
+ ];
426
+ await $("git", args, {
427
+ cwd,
428
+ onStdout: (text2) => {
429
+ output += text2;
430
+ }
431
+ });
432
+ return output.split("\0").filter(Boolean);
433
+ };
434
+ var getRemoteWorktree = async (remote, commit2) => {
435
+ const key = `${remote}:${commit2}`;
436
+ if (remoteWorktrees.has(key)) {
437
+ return remoteWorktrees.get(key);
438
+ }
439
+ const tmpDir = import_node_os.default.tmpdir();
440
+ const worktreeDir = import_node_path6.default.join(tmpDir, "blox-cli-worktrees", remote, commit2);
441
+ try {
442
+ await $("git", ["worktree", "prune"]);
443
+ } catch {
444
+ }
445
+ if (await import_fs_extra3.default.pathExists(worktreeDir)) {
446
+ try {
447
+ await $("git", ["worktree", "remove", "--force", worktreeDir]);
448
+ } catch {
449
+ await import_fs_extra3.default.remove(worktreeDir);
450
+ try {
451
+ await $("git", ["worktree", "prune"]);
452
+ } catch {
453
+ }
454
+ }
455
+ }
456
+ await $("git", ["worktree", "add", "--detach", "--force", worktreeDir, commit2]);
457
+ remoteWorktrees.set(key, worktreeDir);
458
+ return worktreeDir;
459
+ };
460
+ var cleanUpWorktrees = async () => {
461
+ debug("Cleaning up worktrees...");
462
+ for (const worktree of remoteWorktrees.values()) {
463
+ try {
464
+ await $("git", ["worktree", "remove", "--force", worktree]);
465
+ } catch (e) {
466
+ debug(`Failed to remove worktree ${worktree}: ${e}`);
467
+ }
468
+ }
469
+ try {
470
+ await $("git", ["worktree", "prune"]);
471
+ } catch {
472
+ }
473
+ remoteWorktrees.clear();
474
+ };
272
475
  var checkAuth = (message) => {
273
476
  if (message.includes("Username for")) {
274
477
  throw "Login to git first";
@@ -277,14 +480,20 @@ var checkAuth = (message) => {
277
480
  var defaultShellOptions = {
278
481
  onStdout: checkAuth
279
482
  };
280
- var clone = (repoUrl, options, branch = defaultBranch, shellOptions = {}) => {
281
- return $("git", ["clone", "--progress", repoUrl, "--branch", branch, options], {
483
+ var clone = (repoUrl, dir, branch = defaultBranch, options = {}) => {
484
+ const { depth, ...shellOptions } = options;
485
+ const args = ["clone", "--progress"];
486
+ if (depth != null && depth > 0) {
487
+ args.push("--depth", String(depth));
488
+ }
489
+ args.push(repoUrl, "--branch", branch, dir);
490
+ return $("git", args, {
282
491
  ...defaultShellOptions,
283
492
  ...shellOptions
284
493
  });
285
494
  };
286
495
  var resetToCommit = async (commit2, cwd = ".") => {
287
- await $("git", ["reset --hard", `${commit2}`], { cwd });
496
+ await $("git", ["reset", "--hard", commit2], { cwd });
288
497
  };
289
498
  var updatedRemotes = /* @__PURE__ */ new Set();
290
499
  var updateRemote = async (name, source, shellOptions = {}) => {
@@ -306,10 +515,12 @@ var updateRemote = async (name, source, shellOptions = {}) => {
306
515
  });
307
516
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
308
517
  };
309
- var readJsonFromCommit = async (commit2, file) => {
518
+ var readJsonFromCommit = async (commit2, file, cwd = ".") => {
310
519
  try {
311
520
  let content = "";
312
- await $("git", ["show", `${commit2}:${file}`], {
521
+ const p = normalizePath(file);
522
+ await $("git", ["show", `${commit2}:${p}`], {
523
+ cwd,
313
524
  onStdout: (text2) => {
314
525
  content = text2;
315
526
  }
@@ -319,12 +530,27 @@ var readJsonFromCommit = async (commit2, file) => {
319
530
  return {};
320
531
  }
321
532
  };
533
+ var readJsonFromIndex = async (file, cwd = ".") => {
534
+ try {
535
+ let content = "";
536
+ const p = normalizePath(file);
537
+ await $("git", ["show", `:0:${p}`], {
538
+ cwd,
539
+ onStdout: (text2) => {
540
+ content = text2;
541
+ }
542
+ });
543
+ return JSON.parse(content);
544
+ } catch {
545
+ return null;
546
+ }
547
+ };
322
548
  var readJsonFromRemote = async (remote, file, branch = defaultBranch, commit2) => {
323
549
  return readJsonFromCommit(commit2 || `${remote}/${branch}`, file);
324
550
  };
325
551
  var isCommitOlder = async (a, b) => {
326
552
  try {
327
- await $("git", ["merge-base --is-ancestor", a, b]);
553
+ await $("git", ["merge-base", "--is-ancestor", a, b]);
328
554
  return true;
329
555
  } catch {
330
556
  return false;
@@ -336,8 +562,8 @@ var update = (shellOptions = {}) => {
336
562
  var getLatestCommitFromRemote = async (remote, branch) => {
337
563
  return getLatestCommit(`${remote}/${branch}`);
338
564
  };
339
- var getLatestCommitFromPath = async (path12) => {
340
- return getLatestCommit("HEAD", path12);
565
+ var getLatestCommitFromPath = async (path19) => {
566
+ return getLatestCommit("HEAD", path19);
341
567
  };
342
568
  var getLatestCommit = async (rev, cwd = ".") => {
343
569
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
@@ -348,19 +574,7 @@ var getLatestCommit = async (rev, cwd = ".") => {
348
574
  commit2 = text2;
349
575
  }
350
576
  });
351
- return commit2.replace(/\n/g, "");
352
- };
353
- var createPatch = async (fromCommit, toCommit, outputPath, ignore2 = []) => {
354
- return $("git", [
355
- "diff",
356
- "--binary",
357
- fromCommit,
358
- toCommit,
359
- ">",
360
- outputPath,
361
- "--",
362
- ...ignore2.map((file) => `":(exclude)${file}"`)
363
- ]);
577
+ return commit2.replace(/\r?\n/g, "").trim();
364
578
  };
365
579
  var getChangesLog = async (fromCommit, toCommit) => {
366
580
  let changes = "";
@@ -371,18 +585,9 @@ var getChangesLog = async (fromCommit, toCommit) => {
371
585
  });
372
586
  return changes;
373
587
  };
374
- var applyPatch = (patch, cwd = ".") => {
375
- const args = ["apply", "-3", "--allow-empty"];
376
- if (cwd != ".") {
377
- args.push("--directory");
378
- args.push(normalizePath(cwd));
379
- }
380
- args.push(normalizePath(patch));
381
- return $("git", args);
382
- };
383
588
  var unInit = (cwd) => {
384
589
  debug("UnInit");
385
- return import_fs_extra3.default.remove(import_node_path4.default.join(cwd, ".git"));
590
+ return import_fs_extra3.default.remove(import_node_path6.default.join(cwd, ".git"));
386
591
  };
387
592
  var init = async (cwd) => {
388
593
  debug("Init");
@@ -391,18 +596,19 @@ var init = async (cwd) => {
391
596
  await $("git", ["commit", "-m", "init"], { cwd });
392
597
  await $("git", ["branch", "-m", defaultBranch], { cwd });
393
598
  };
394
- var add = async (toAdd) => {
599
+ var add = async (toAdd, cwd = ".") => {
395
600
  debug(`Git Add: ${toAdd}`);
396
- await $("git", ["add", toAdd]);
601
+ await $("git", ["add", toAdd], { cwd });
397
602
  };
398
- var commit = async (msg) => {
603
+ var commit = async (msg, cwd = ".") => {
399
604
  debug(`Git commit: ${msg}`);
400
- await $("git", ["commit", "-m", `"${msg}"`]);
605
+ await $("git", ["commit", "--no-verify", "-m", msg], { cwd });
401
606
  };
402
607
  var rollback = async () => {
403
608
  debug("Rollback");
404
609
  await $("git", ["add", "."]);
405
610
  await $("git", ["reset", "--hard"]);
611
+ await cleanUpWorktrees();
406
612
  };
407
613
  var hasUncommittedChanges = async (cwd = ".") => {
408
614
  let status = "";
@@ -414,6 +620,179 @@ var hasUncommittedChanges = async (cwd = ".") => {
414
620
  });
415
621
  return status.trim().length > 0;
416
622
  };
623
+ var hasStagedChanges = async (cwd = ".") => {
624
+ try {
625
+ await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd });
626
+ return false;
627
+ } catch {
628
+ return true;
629
+ }
630
+ };
631
+ var checkout = async (branch, cwd = ".") => {
632
+ debug(`Git checkout: ${branch}`);
633
+ await $("git", ["checkout", branch], { cwd });
634
+ };
635
+ var merge = async (remoteBranch, options = {}) => {
636
+ debug(`Git merge: ${remoteBranch}`);
637
+ const args = ["merge", remoteBranch, "--no-edit"];
638
+ if (options.allowUnrelatedHistories) {
639
+ args.push("--allow-unrelated-histories");
640
+ }
641
+ await $("git", args);
642
+ };
643
+ var hasConflicts = async (cwd = ".") => {
644
+ let unmerged = "";
645
+ await $("git", ["ls-files", "--unmerged"], {
646
+ cwd,
647
+ onStdout: (text2) => {
648
+ unmerged += text2;
649
+ }
650
+ });
651
+ return unmerged.trim().length > 0;
652
+ };
653
+ var mergeFile = async (current, base, other) => {
654
+ try {
655
+ await $("git", ["merge-file", current, base, other]);
656
+ return true;
657
+ } catch {
658
+ return false;
659
+ }
660
+ };
661
+ var lsRemote = async (repoUrl, branch) => {
662
+ let out = "";
663
+ await $("git", ["ls-remote", repoUrl, `refs/heads/${branch}`], {
664
+ onStdout: (text2) => {
665
+ out += text2;
666
+ }
667
+ });
668
+ const line = out.trim().split("\n")[0];
669
+ if (!line) throw new Error(`No remote ref refs/heads/${branch} for ${repoUrl}`);
670
+ const hash = line.split(/\s+/)[0];
671
+ if (!hash) throw new Error(`Could not parse ls-remote output: ${line}`);
672
+ return hash.trim();
673
+ };
674
+ var listRemoteBranches = async (repoUrl) => {
675
+ let out = "";
676
+ await $("git", ["ls-remote", "--heads", repoUrl], {
677
+ onStdout: (text2) => {
678
+ out += text2;
679
+ }
680
+ });
681
+ return out.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
682
+ const parts = line.split(/\s+/);
683
+ const ref = parts[1] || "";
684
+ return ref.replace("refs/heads/", "");
685
+ }).filter((branch) => branch.length > 0 && branch !== "main" && branch !== "master");
686
+ };
687
+ var listBranches = async (cwd = ".") => {
688
+ let out = "";
689
+ await $("git", ["branch", "--list"], {
690
+ cwd,
691
+ onStdout: (text2) => {
692
+ out += text2;
693
+ }
694
+ });
695
+ return out.split("\n").map((l) => l.replace(/^\*?\s+/, "").trim()).filter(Boolean).filter((b) => !b.startsWith("("));
696
+ };
697
+ var createBranch = async (branch, from, cwd = ".") => {
698
+ if (from) {
699
+ await $("git", ["checkout", "-B", branch, from], { cwd });
700
+ } else {
701
+ await $("git", ["checkout", "-b", branch], { cwd });
702
+ }
703
+ };
704
+ var push = async (remote, branch, cwd = ".") => {
705
+ await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd });
706
+ };
707
+ var checkoutFile = async (path19, ref, cwd = ".") => {
708
+ const args = ["checkout"];
709
+ if (ref) args.push(ref);
710
+ else args.push("HEAD");
711
+ args.push("--", path19);
712
+ await $("git", args, { cwd });
713
+ };
714
+ var pathExistsAsBlobInRev = async (rev, filePath, cwd = ".") => {
715
+ const p = normalizePath(filePath);
716
+ try {
717
+ await $("git", ["cat-file", "-e", `${rev}:${p}`], { cwd });
718
+ return true;
719
+ } catch {
720
+ return false;
721
+ }
722
+ };
723
+ var revertPathToHead = async (filePath, cwd = ".") => {
724
+ const p = normalizePath(filePath);
725
+ if (await pathExistsAsBlobInRev("HEAD", p, cwd)) {
726
+ await checkoutFile(p, "HEAD", cwd);
727
+ } else {
728
+ await $("git", ["rm", "-f", "--", p], { cwd });
729
+ }
730
+ };
731
+ var listCommits = async (limit, skip, cwd = ".") => {
732
+ let out = "";
733
+ await $(
734
+ "git",
735
+ ["log", "--pretty=format:%H|%s", "-n", String(limit), "--skip", String(skip), "HEAD"],
736
+ {
737
+ cwd,
738
+ onStdout: (text2) => {
739
+ out += text2;
740
+ }
741
+ }
742
+ );
743
+ const lines = out.split(/\r?\n/).filter(Boolean);
744
+ return lines.map((line) => {
745
+ const pipe = line.indexOf("|");
746
+ const hashRaw = pipe >= 0 ? line.slice(0, pipe) : line;
747
+ const subjectRaw = pipe >= 0 ? line.slice(pipe + 1) : "";
748
+ const hash = hashRaw.trim().replace(/^"+|"+$/g, "");
749
+ return { hash, subject: subjectRaw.trim() };
750
+ });
751
+ };
752
+ var fetchCommit = async (fromRepo, commit2, cwd = ".") => {
753
+ const ref = normalizeCommitRef(commit2);
754
+ await $("git", ["fetch", fromRepo, `+${ref}:FETCH_HEAD`], { cwd });
755
+ };
756
+ var cherryPick = async (commitHash, subtree, noCommit, cwd = ".") => {
757
+ const args = ["cherry-pick"];
758
+ if (noCommit) args.push("--no-commit");
759
+ if (subtree) args.push(`-Xsubtree=${subtree}`);
760
+ args.push(normalizeCommitRef(commitHash));
761
+ await $("git", args, { cwd });
762
+ };
763
+ var reset = async (path19, hard, cwd = ".") => {
764
+ const args = ["reset"];
765
+ if (hard) args.push("--hard");
766
+ if (path19) args.push(path19);
767
+ await $("git", args, { cwd });
768
+ };
769
+ var commitAll = async (message, cwd = ".") => {
770
+ await add(".", cwd);
771
+ await commit(message, cwd);
772
+ };
773
+ var getUnmergedFiles = async (cwd = ".") => {
774
+ let out = "";
775
+ await $("git", ["status", "--porcelain"], {
776
+ cwd,
777
+ onStdout: (text2) => {
778
+ out += text2;
779
+ }
780
+ });
781
+ return out.split("\n").filter((l) => /^(U.|.U|AA|DD)/.test(l)).map((l) => l.slice(3).trim());
782
+ };
783
+ var fetchRepo = async (cwd = ".") => {
784
+ await $("git", ["fetch", "--progress", "origin"], { cwd });
785
+ };
786
+ var getStagedFiles = async (cwd = ".") => {
787
+ let out = "";
788
+ await $("git", ["diff", "--cached", "--name-only"], {
789
+ cwd,
790
+ onStdout: (text2) => {
791
+ out += text2;
792
+ }
793
+ });
794
+ return out.split("\n").map((l) => l.trim()).filter(Boolean);
795
+ };
417
796
  var git = {
418
797
  clone,
419
798
  update,
@@ -421,18 +800,40 @@ var git = {
421
800
  init,
422
801
  getLatestCommitFromRemote,
423
802
  getLatestCommitFromPath,
424
- createPatch,
425
803
  getChangesLog,
426
- applyPatch,
427
804
  updateRemote,
428
805
  readJsonFromCommit,
806
+ readJsonFromIndex,
429
807
  readJsonFromRemote,
430
808
  isCommitOlder,
431
809
  rollback,
432
810
  add,
433
811
  resetToCommit,
434
812
  commit,
435
- hasUncommittedChanges
813
+ hasUncommittedChanges,
814
+ hasStagedChanges,
815
+ hasConflicts,
816
+ checkout,
817
+ merge,
818
+ getChangedFiles,
819
+ getRemoteWorktree,
820
+ cleanUpWorktrees,
821
+ mergeFile,
822
+ lsRemote,
823
+ listRemoteBranches,
824
+ listBranches,
825
+ createBranch,
826
+ push,
827
+ checkoutFile,
828
+ revertPathToHead,
829
+ listCommits,
830
+ fetchCommit,
831
+ cherryPick,
832
+ reset,
833
+ commitAll,
834
+ getUnmergedFiles,
835
+ fetchRepo,
836
+ getStagedFiles
436
837
  };
437
838
 
438
839
  // src/shared/prompts/index.ts
@@ -461,6 +862,16 @@ var text = async (opts) => {
461
862
  checkIfCanceled(value);
462
863
  return value;
463
864
  };
865
+ var confirm = async (opts) => {
866
+ const value = await (0, import_prompts3.confirm)(opts);
867
+ checkIfCanceled(value);
868
+ return value;
869
+ };
870
+ var multiselect = async (opts) => {
871
+ const value = await (0, import_prompts3.multiselect)(opts);
872
+ checkIfCanceled(value);
873
+ return value;
874
+ };
464
875
  var textList = async (opts) => {
465
876
  opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
466
877
  const value = await (0, import_prompts3.text)(opts);
@@ -534,7 +945,7 @@ async function migrate(name, { getPath = (f) => f, read, write }) {
534
945
  }
535
946
  function migrateOnLocal(name, cwd = ".") {
536
947
  return migrate(name, {
537
- getPath: (file) => import_node_path5.default.join(cwd, file),
948
+ getPath: (file) => import_node_path7.default.join(cwd, file),
538
949
  read: import_fs_extra4.default.readJson,
539
950
  write: import_fs_extra4.default.writeFile
540
951
  });
@@ -542,7 +953,7 @@ function migrateOnLocal(name, cwd = ".") {
542
953
  function migrateOnRemote(name, commit2, cwd) {
543
954
  return migrate(name, {
544
955
  read: (file) => git.readJsonFromCommit(commit2, file),
545
- getPath: cwd ? (file) => import_node_path5.default.join(cwd, file) : void 0
956
+ getPath: cwd ? (file) => import_node_path7.default.join(cwd, file) : void 0
546
957
  });
547
958
  }
548
959
 
@@ -551,7 +962,7 @@ async function migrateAll(autoCommit) {
551
962
  let filesChanged = (await migrateOnLocal("app")).filesChanged;
552
963
  const blocks = import_fs_extra5.default.existsSync(blocksDir) ? import_fs_extra5.default.readdirSync(blocksDir) : [];
553
964
  for (const block of blocks) {
554
- const res = await migrateOnLocal(block, import_node_path6.default.join(blocksDir, block));
965
+ const res = await migrateOnLocal(block, import_node_path8.default.join(blocksDir, block));
555
966
  filesChanged = filesChanged || res.filesChanged;
556
967
  }
557
968
  if (autoCommit && filesChanged && await git.hasUncommittedChanges()) {
@@ -562,17 +973,17 @@ async function migrateAll(autoCommit) {
562
973
  }
563
974
 
564
975
  // src/services/fs.ts
565
- var import_node_path7 = __toESM(require("path"));
976
+ var import_node_path9 = __toESM(require("path"));
566
977
  var import_fs_extra6 = __toESM(require("fs-extra"));
567
- var import_ignore = __toESM(require("ignore"));
978
+ var import_ignore2 = __toESM(require("ignore"));
568
979
  var import_klaw = __toESM(require("klaw"));
569
980
  var filterBlacklisted = (item) => {
570
981
  return !item.includes("node_modules") && !item.includes(".git");
571
982
  };
572
983
  var deletePattern = async (cwd, patterns = []) => {
573
- const ig = (0, import_ignore.default)().add(patterns);
984
+ const ig = (0, import_ignore2.default)().add(patterns);
574
985
  for await (const file of (0, import_klaw.default)(cwd, { filter: filterBlacklisted })) {
575
- const relativePath = import_node_path7.default.relative(cwd, file.path);
986
+ const relativePath = import_node_path9.default.relative(cwd, file.path);
576
987
  if (relativePath && ig.ignores(relativePath)) {
577
988
  if (!await import_fs_extra6.default.exists(file.path)) {
578
989
  continue;
@@ -584,7 +995,7 @@ var deletePattern = async (cwd, patterns = []) => {
584
995
  };
585
996
 
586
997
  // src/services/registry.ts
587
- var import_node_path8 = __toESM(require("path"));
998
+ var import_node_path10 = __toESM(require("path"));
588
999
  var import_fs_extra7 = __toESM(require("fs-extra"));
589
1000
  var import_merge = __toESM(require("lodash/merge"));
590
1001
 
@@ -620,7 +1031,7 @@ async function runTask(message, task) {
620
1031
  }
621
1032
 
622
1033
  // src/services/registry.ts
623
- var registriesDataPath = import_node_path8.default.join(appPaths.data, "registries");
1034
+ var registriesDataPath = import_node_path10.default.join(appPaths.data, "registries");
624
1035
  var upeToDate = false;
625
1036
  var syncRegistries = async (branch) => {
626
1037
  if (upeToDate) return;
@@ -633,10 +1044,13 @@ var syncRegistries = async (branch) => {
633
1044
  config.registries.map(async (registry) => {
634
1045
  debug(`update registry: ${registry}`);
635
1046
  const repoName = registry.split("/").pop() || "";
636
- const repoDir = import_node_path8.default.join(registriesDataPath, repoName);
1047
+ const repoDir = import_node_path10.default.join(registriesDataPath, repoName);
637
1048
  if (!import_fs_extra7.default.existsSync(repoDir)) {
638
- await git.clone(registry, "--depth 1", branch, { cwd: registriesDataPath });
639
- } else if (import_fs_extra7.default.existsSync(import_node_path8.default.join(repoDir, ".git"))) {
1049
+ await git.clone(registry, repoName, branch, {
1050
+ cwd: registriesDataPath,
1051
+ depth: 1
1052
+ });
1053
+ } else if (import_fs_extra7.default.existsSync(import_node_path10.default.join(repoDir, ".git"))) {
640
1054
  await git.update({ cwd: repoDir });
641
1055
  } else {
642
1056
  debug(`local registry`);
@@ -650,7 +1064,7 @@ var getAvailableTemplates = async () => {
650
1064
  const templates = {};
651
1065
  const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
652
1066
  for (const registry of registries) {
653
- const indexPath = import_node_path8.default.join(registriesDataPath, registry, "index.json");
1067
+ const indexPath = import_node_path10.default.join(registriesDataPath, registry, "index.json");
654
1068
  if (import_fs_extra7.default.existsSync(indexPath)) {
655
1069
  const data = import_fs_extra7.default.readJSONSync(indexPath);
656
1070
  Object.entries(data.templates || {}).forEach(([templateName, template]) => {
@@ -694,14 +1108,14 @@ var getAvailableBlocks = async (templateInfo) => {
694
1108
  var getAvailableVersions = async (source) => {
695
1109
  const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
696
1110
  for (const registry of registries) {
697
- const registryPath = import_node_path8.default.join(registriesDataPath, registry);
698
- const indexPath = import_node_path8.default.join(registryPath, "index.json");
1111
+ const registryPath = import_node_path10.default.join(registriesDataPath, registry);
1112
+ const indexPath = import_node_path10.default.join(registryPath, "index.json");
699
1113
  if (!import_fs_extra7.default.existsSync(indexPath)) continue;
700
1114
  const registryData = import_fs_extra7.default.readJSONSync(indexPath);
701
- const versionDirPath = import_node_path8.default.join(registryPath, "versions");
1115
+ const versionDirPath = import_node_path10.default.join(registryPath, "versions");
702
1116
  const versionsFilePaths = [
703
- import_node_path8.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
704
- import_node_path8.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
1117
+ import_node_path10.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
1118
+ import_node_path10.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
705
1119
  ];
706
1120
  for (const versionsFile of versionsFilePaths) {
707
1121
  if (import_fs_extra7.default.existsSync(versionsFile)) {
@@ -712,34 +1126,16 @@ var getAvailableVersions = async (source) => {
712
1126
  };
713
1127
 
714
1128
  // src/services/template.ts
715
- var import_node_path9 = __toESM(require("path"));
1129
+ var import_node_path11 = __toESM(require("path"));
716
1130
  var import_ejs = __toESM(require("ejs"));
717
1131
  var import_fs_extra8 = __toESM(require("fs-extra"));
718
1132
  var import_klaw2 = __toESM(require("klaw"));
719
- var NON_RENDERABLE_FILES = [
720
- ".png",
721
- ".jpg",
722
- ".jpeg",
723
- ".gif",
724
- ".svg",
725
- ".ico",
726
- ".ttf",
727
- ".woff",
728
- ".woff2",
729
- ".otf",
730
- ".mp4",
731
- ".mp3",
732
- ".zip",
733
- ".plist",
734
- ".DS_Store",
735
- ".bin"
736
- ];
737
1133
  async function replacePlaceholders(dir, context) {
738
1134
  debug("Replace placeholders");
739
1135
  for await (const file of (0, import_klaw2.default)(dir)) {
740
1136
  if (!file.stats.isFile()) continue;
741
- const ext = import_node_path9.default.extname(file.path).toLowerCase();
742
- if (NON_RENDERABLE_FILES.includes(ext)) {
1137
+ const ext = import_node_path11.default.extname(file.path).toLowerCase();
1138
+ if (isBinaryFile(ext)) {
743
1139
  continue;
744
1140
  }
745
1141
  const templateContent = import_fs_extra8.default.readFileSync(file.path, "utf8");
@@ -769,7 +1165,7 @@ function getBlockDef(cwd = ".") {
769
1165
  }
770
1166
  function getBloxFile(cwd = ".") {
771
1167
  try {
772
- const file = import_fs_extra8.default.readJSONSync(import_node_path9.default.join(cwd, bloxFilePath));
1168
+ const file = import_fs_extra8.default.readJSONSync(import_node_path11.default.join(cwd, bloxFilePath));
773
1169
  if (!file.checkpoints) {
774
1170
  file.checkpoints = {};
775
1171
  }
@@ -780,7 +1176,7 @@ function getBloxFile(cwd = ".") {
780
1176
  }
781
1177
  function saveBloxFile(info, cwd = ".") {
782
1178
  debug("Save info");
783
- import_fs_extra8.default.writeFileSync(import_node_path9.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
1179
+ import_fs_extra8.default.writeFileSync(import_node_path11.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
784
1180
  }
785
1181
  function updateCheckpoint(name, checkpoint, cwd = ".") {
786
1182
  const info = getBloxFile(cwd);
@@ -801,7 +1197,7 @@ function getUsedBlocks() {
801
1197
  if (!file.isDirectory()) {
802
1198
  return;
803
1199
  }
804
- const blockDef = getBloxFile(import_node_path9.default.join(blocksDir, file.name));
1200
+ const blockDef = getBloxFile(import_node_path11.default.join(blocksDir, file.name));
805
1201
  if (blockDef && blockDef.definition) {
806
1202
  blocks.push(blockDef);
807
1203
  }
@@ -939,7 +1335,7 @@ function runInitScript(cwd) {
939
1335
  debug(`Run init script in: ${cwd}`);
940
1336
  const info = getTemplateDef(cwd);
941
1337
  if (info.init) {
942
- return $(info.init, [], { cwd });
1338
+ return $(info.init, [], { cwd, shell: true });
943
1339
  }
944
1340
  }
945
1341
 
@@ -1036,6 +1432,957 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
1036
1432
  }
1037
1433
  });
1038
1434
 
1435
+ // src/services/contribute/constants/index.ts
1436
+ var UI_PAGE_SIZE = 15;
1437
+ var TARGET_SELECT_PAGE = {
1438
+ PREV: "__prev__",
1439
+ NEXT: "__next__",
1440
+ SEARCH_AGAIN: "__search__"
1441
+ };
1442
+ var COMMIT_TYPES = [
1443
+ { value: "fix", label: "fix: A bug fix (PATCH)" },
1444
+ { value: "feat", label: "feat: A new feature (MINOR)" },
1445
+ { value: "docs", label: "docs: Documentation only" },
1446
+ { value: "refactor", label: "refactor: Code change (no fix/feature)" },
1447
+ { value: "perf", label: "perf: Performance improvement" },
1448
+ { value: "test", label: "test: Adding/correcting tests" },
1449
+ { value: "build", label: "build: Build system / dependencies" },
1450
+ { value: "ci", label: "ci: CI configuration (GitLab/GitHub)" }
1451
+ ];
1452
+
1453
+ // src/services/contribute/types.ts
1454
+ var ContributionTargetType = /* @__PURE__ */ ((ContributionTargetType2) => {
1455
+ ContributionTargetType2["TEMPLATE"] = "template";
1456
+ ContributionTargetType2["BASE"] = "base";
1457
+ ContributionTargetType2["BLOCK"] = "block";
1458
+ return ContributionTargetType2;
1459
+ })(ContributionTargetType || {});
1460
+
1461
+ // src/services/contribute/utils/bloxCheckpoint.ts
1462
+ var import_node_path12 = __toESM(require("path"));
1463
+ function getCheckpointForTarget(cwd, target) {
1464
+ const bloxDir = getBloxDirForTarget(cwd, target);
1465
+ const blox = getBloxFile(bloxDir);
1466
+ const key = target.name;
1467
+ const cp = blox.checkpoints?.[key];
1468
+ return { commit: cp?.commit, branch: cp?.branch };
1469
+ }
1470
+ function getBloxDirForTarget(cwd, target) {
1471
+ if (target.type === "block" /* BLOCK */) {
1472
+ return import_node_path12.default.join(cwd, blocksDir, target.name);
1473
+ }
1474
+ return cwd;
1475
+ }
1476
+
1477
+ // src/services/contribute/utils/getRepoUrl.ts
1478
+ var getTargetRepoUrl = async (target) => {
1479
+ if (target.type === "template" /* TEMPLATE */ || target.type === "base" /* BASE */) {
1480
+ const templates = await getAvailableTemplates();
1481
+ const t = templates[target.name];
1482
+ if (!t?.source) {
1483
+ throw new Error(`No registry source found for template/base: ${target.name}`);
1484
+ }
1485
+ return t.source;
1486
+ }
1487
+ if (!target.templateName) {
1488
+ throw new Error(`Target missing templateName for block source resolution: ${target.name}`);
1489
+ }
1490
+ const templateDef = target.templateDef;
1491
+ if (!templateDef) {
1492
+ throw new Error(`Target missing templateDef for block source resolution: ${target.name}`);
1493
+ }
1494
+ const blocks = await getAvailableBlocks(templateDef);
1495
+ const blockSource = blocks?.[target.name]?.source;
1496
+ if (!blockSource) {
1497
+ throw new Error(`No registry source found for block: ${target.name}`);
1498
+ }
1499
+ return blockSource;
1500
+ };
1501
+
1502
+ // src/services/contribute/utils/slugifyTitle.ts
1503
+ function slugifyTitle(title) {
1504
+ const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1505
+ return (s || "contribution").slice(0, 80);
1506
+ }
1507
+
1508
+ // src/services/contribute/ContributionWorkflow.ts
1509
+ var MANUAL_BRANCH_OPTION = "__manual__";
1510
+ var ContributionWorkflow = class {
1511
+ constructor(ctx, logger, targetSelector, tmpRepo, commitSelector, commitApplier, pullRequest) {
1512
+ this.ctx = ctx;
1513
+ this.logger = logger;
1514
+ this.targetSelector = targetSelector;
1515
+ this.tmpRepo = tmpRepo;
1516
+ this.commitSelector = commitSelector;
1517
+ this.commitApplier = commitApplier;
1518
+ this.pullRequest = pullRequest;
1519
+ }
1520
+ async runFromFlags(flags) {
1521
+ await this.assertAppRepoClean();
1522
+ const target = await this.targetSelector.selectTargetInteractive();
1523
+ const mode = flags.existing ? "existing" : "new";
1524
+ const { title, description } = await this.promptNewContributionMeta(mode, flags);
1525
+ const commits = await this.resolveCommitsFromFlags(flags);
1526
+ const branch = await this.resolveContributionBranch({ mode, target, title });
1527
+ return this.run({
1528
+ target,
1529
+ mode,
1530
+ title,
1531
+ description,
1532
+ branch,
1533
+ commits
1534
+ });
1535
+ }
1536
+ async run(input) {
1537
+ const repoUrl = await getTargetRepoUrl(input.target);
1538
+ const checkpoint = getCheckpointForTarget(this.ctx.cwd, input.target);
1539
+ const remoteBranch = checkpoint.branch || defaultBranch;
1540
+ const remoteHead = await this.resolveRemoteHeadOrThrow(repoUrl, remoteBranch);
1541
+ this.ensureCheckpointValid(input, checkpoint, remoteHead);
1542
+ this.logger.debug("preflight.resolved", {
1543
+ repoUrl,
1544
+ remoteBranch,
1545
+ checkpoint: checkpoint.commit,
1546
+ remoteHead
1547
+ });
1548
+ this.assertCheckpointMatchesRemoteForNonTemplate(input, checkpoint, remoteHead);
1549
+ const tmpCwd = await this.tmpRepo.prepare({
1550
+ target: input.target,
1551
+ repoUrl,
1552
+ branch: remoteBranch
1553
+ });
1554
+ const branch = input.branch;
1555
+ if (!branch) {
1556
+ throw new Error("Internal error: branch not resolved.");
1557
+ }
1558
+ await this.checkoutBaseInTmp({
1559
+ tmpCwd,
1560
+ mode: input.mode,
1561
+ checkpointCommit: checkpoint.commit,
1562
+ branch,
1563
+ title: input.title
1564
+ });
1565
+ const { title, description } = this.deriveTitleAndDescription(input);
1566
+ await this.commitApplier.applyCommits({
1567
+ appRepoCwd: this.ctx.cwd,
1568
+ tmpRepoCwd: tmpCwd,
1569
+ commits: input.commits,
1570
+ target: input.target,
1571
+ title,
1572
+ description
1573
+ });
1574
+ await this.pullRequest.pushBranch({
1575
+ cwd: tmpCwd,
1576
+ remote: "origin",
1577
+ branch,
1578
+ onAttemptFailed: ({ attempt, error: error2 }) => this.logger.warn("push.failed", { attempt, error: error2 })
1579
+ });
1580
+ this.logger.info("branch.pushed", {
1581
+ branch,
1582
+ remote: repoUrl
1583
+ });
1584
+ this.pullRequest.printPushSummary({
1585
+ repoUrl,
1586
+ sourceBranch: branch,
1587
+ targetBranch: remoteBranch,
1588
+ title,
1589
+ description
1590
+ });
1591
+ const pr = await this.pullRequest.openPullRequestPage({
1592
+ repoUrl,
1593
+ sourceBranch: branch,
1594
+ targetBranch: remoteBranch
1595
+ });
1596
+ this.logCompletion(pr.prUrl);
1597
+ return {
1598
+ branch,
1599
+ commits: input.commits,
1600
+ prUrl: pr.prUrl
1601
+ };
1602
+ }
1603
+ async assertAppRepoClean() {
1604
+ if (await git.hasUncommittedChanges(this.ctx.cwd)) {
1605
+ throw new Error(
1606
+ "Make sure to commit or stash any changes in the app repo before contributing."
1607
+ );
1608
+ }
1609
+ }
1610
+ async promptNewContributionMeta(mode, flags) {
1611
+ let title = flags.title;
1612
+ let description = flags.description;
1613
+ if (mode === "new") {
1614
+ if (!title) {
1615
+ title = await text({
1616
+ message: "Contribution title (conventional commit style recommended)",
1617
+ validate: (v) => v.trim() ? void 0 : "Title is required"
1618
+ });
1619
+ }
1620
+ if (description === void 0) {
1621
+ description = await text({ message: "Description (optional)", defaultValue: "" });
1622
+ }
1623
+ }
1624
+ return { title, description };
1625
+ }
1626
+ async resolveCommitsFromFlags(flags) {
1627
+ if (flags.commits) {
1628
+ const commits = flags.commits.split(",").map((c) => c.trim()).filter(Boolean);
1629
+ if (!commits.length) {
1630
+ throw new Error("No commit hashes parsed from --commits.");
1631
+ }
1632
+ return commits;
1633
+ }
1634
+ return this.commitSelector.selectCommitsInteractive({
1635
+ cwd: this.ctx.cwd
1636
+ });
1637
+ }
1638
+ async resolveContributionBranch(opts) {
1639
+ const { mode, target, title } = opts;
1640
+ if (mode === "new" && title) {
1641
+ const commitType = await select({
1642
+ message: "Select the commit type for this contribution:",
1643
+ options: COMMIT_TYPES
1644
+ });
1645
+ return `${commitType}/${slugifyTitle(title)}`;
1646
+ }
1647
+ if (mode === "existing") {
1648
+ import_prompts2.log.info("Fetching remote branches for the existing contribution...");
1649
+ const repoUrl = await getTargetRepoUrl(target);
1650
+ const remoteBranches = await git.listRemoteBranches(repoUrl);
1651
+ if (remoteBranches.length === 0) {
1652
+ throw new Error("No remote branches found to contribute to.");
1653
+ }
1654
+ const selectedBranch = await select({
1655
+ message: "Select the existing contribution branch:",
1656
+ options: [
1657
+ ...remoteBranches.map((b) => ({ label: b, value: b })),
1658
+ { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
1659
+ ]
1660
+ });
1661
+ if (selectedBranch === MANUAL_BRANCH_OPTION) {
1662
+ return await text({
1663
+ message: "Enter branch name:"
1664
+ });
1665
+ }
1666
+ return selectedBranch;
1667
+ }
1668
+ return void 0;
1669
+ }
1670
+ async resolveRemoteHeadOrThrow(repoUrl, remoteBranch) {
1671
+ try {
1672
+ return await git.lsRemote(repoUrl, remoteBranch);
1673
+ } catch (e) {
1674
+ throw new Error(
1675
+ `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
1676
+ );
1677
+ }
1678
+ }
1679
+ ensureCheckpointValid(input, checkpoint, remoteHead) {
1680
+ if (input.target.type === "template" /* TEMPLATE */ && !checkpoint.commit) {
1681
+ checkpoint.commit = remoteHead;
1682
+ }
1683
+ if (!checkpoint.commit) {
1684
+ throw new Error(
1685
+ `Missing checkpoint commit for ${input.target.type}/${input.target.name} in .blox. Cannot contribute safely.`
1686
+ );
1687
+ }
1688
+ }
1689
+ assertCheckpointMatchesRemoteForNonTemplate(input, checkpoint, remoteHead) {
1690
+ if (input.target.type === "template" /* TEMPLATE */) {
1691
+ return;
1692
+ }
1693
+ if (checkpoint.commit !== remoteHead && !this.ctx.force) {
1694
+ 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.`;
1695
+ throw new Error(
1696
+ `${hint}
1697
+ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
1698
+ );
1699
+ }
1700
+ if (checkpoint.commit !== remoteHead && this.ctx.force) {
1701
+ this.logger.warn("preflight.overridden", {
1702
+ checkpoint: checkpoint.commit,
1703
+ remoteHead
1704
+ });
1705
+ }
1706
+ }
1707
+ async checkoutBaseInTmp(opts) {
1708
+ const { tmpCwd, mode, checkpointCommit, branch, title } = opts;
1709
+ if (mode === "new") {
1710
+ if (!title) {
1711
+ throw new Error("New contribution requires a title.");
1712
+ }
1713
+ await git.checkout(checkpointCommit, tmpCwd);
1714
+ this.logger.debug("branch.create", { branch, from: checkpointCommit });
1715
+ this.logger.info(`Create new branch ${branch} from ${checkpointCommit}`);
1716
+ await git.createBranch(branch, checkpointCommit, tmpCwd);
1717
+ return;
1718
+ }
1719
+ await git.checkout(branch, tmpCwd);
1720
+ }
1721
+ deriveTitleAndDescription(input) {
1722
+ const title = input.title || "contribution title";
1723
+ const description = input.description || "";
1724
+ return { title, description };
1725
+ }
1726
+ logCompletion(prUrl) {
1727
+ import_prompts2.log.success(
1728
+ fmt.green("Contribution flow completed.") + (prUrl ? `
1729
+ Pull Request (new):
1730
+ ${prUrl}` : "\nPush completed.")
1731
+ );
1732
+ }
1733
+ };
1734
+
1735
+ // src/services/contribute/services/CommitApplierService.ts
1736
+ var import_node_path14 = __toESM(require("path"));
1737
+ var import_fs_extra11 = __toESM(require("fs-extra"));
1738
+
1739
+ // src/services/contribute/config/index.ts
1740
+ var tempRepoName = "tmp";
1741
+ var bloxConfigControlledKeys = ["checkpoints"];
1742
+
1743
+ // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1744
+ var import_node_path13 = __toESM(require("path"));
1745
+ var import_fs_extra10 = __toESM(require("fs-extra"));
1746
+ function getExcludedPrefixesForTarget(target, cwd) {
1747
+ if (target.type === "block" /* BLOCK */) {
1748
+ return [];
1749
+ }
1750
+ const excluded = [];
1751
+ const blocksPath = import_node_path13.default.join(cwd, blocksDir);
1752
+ if (import_fs_extra10.default.existsSync(blocksPath)) {
1753
+ const entries = import_fs_extra10.default.readdirSync(blocksPath, { withFileTypes: true });
1754
+ for (const entry of entries) {
1755
+ if (!entry.isDirectory()) continue;
1756
+ const blockBloxFile = import_node_path13.default.join(blocksPath, entry.name, bloxFilePath);
1757
+ if (import_fs_extra10.default.existsSync(blockBloxFile)) {
1758
+ excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1759
+ }
1760
+ }
1761
+ }
1762
+ return excluded;
1763
+ }
1764
+
1765
+ // src/services/contribute/utils/getPathPrefixToStrip.ts
1766
+ function getPathPrefixToStrip(target) {
1767
+ if (target.type === "block" /* BLOCK */) {
1768
+ return normalizePath(`${blocksDir}/${target.name}/`);
1769
+ }
1770
+ return "";
1771
+ }
1772
+
1773
+ // src/services/contribute/utils/shouldExcludeFile.ts
1774
+ function shouldExcludeFile(file, excludedPrefixes) {
1775
+ const f = normalizePath(file);
1776
+ return excludedPrefixes.some((p) => f.startsWith(p));
1777
+ }
1778
+
1779
+ // src/services/contribute/services/CommitApplierService.ts
1780
+ var CommitApplierService = class {
1781
+ constructor(logger) {
1782
+ this.logger = logger;
1783
+ }
1784
+ async applyCommits(opts) {
1785
+ const subtreePath = getPathPrefixToStrip(opts.target).replace(/\/$/, "");
1786
+ const exclusion = getExcludedPrefixesForTarget(opts.target, opts.appRepoCwd);
1787
+ this.logger.debug("Prepare for apply commits", {
1788
+ appRepo: opts.appRepoCwd,
1789
+ tmpRepo: opts.tmpRepoCwd,
1790
+ subtree: subtreePath || "(root)",
1791
+ exclusion
1792
+ });
1793
+ this.logger.info("Prepare for apply commits");
1794
+ for (const commit2 of opts.commits) {
1795
+ await this.applySingleCommit(opts, subtreePath, exclusion, commit2);
1796
+ }
1797
+ }
1798
+ async applySingleCommit(opts, subtreePath, exclusion, commit2) {
1799
+ this.logger.debug("apply.commit.start", { commit: commit2.slice(0, 7) });
1800
+ this.logger.info(`Apply commit ${commit2.slice(0, 7)} start`);
1801
+ try {
1802
+ await git.fetchCommit(opts.appRepoCwd, commit2, opts.tmpRepoCwd);
1803
+ try {
1804
+ await git.cherryPick("FETCH_HEAD", subtreePath || void 0, true, opts.tmpRepoCwd);
1805
+ } catch (e) {
1806
+ this.logger.debug("apply.commit.conflicts_initial", {
1807
+ commit: commit2.slice(0, 7),
1808
+ message: e instanceof Error ? e.message : String(e)
1809
+ });
1810
+ }
1811
+ await this.revertExcludedStagedFiles(opts.tmpRepoCwd, commit2, exclusion, opts.target);
1812
+ const remainingConflicts = await git.getUnmergedFiles(opts.tmpRepoCwd);
1813
+ if (remainingConflicts.length) {
1814
+ this.logger.error("apply.commit.conflicts", {
1815
+ commit: commit2.slice(0, 7),
1816
+ files: remainingConflicts
1817
+ });
1818
+ await this.waitUntilUserResolvesConflicts(opts.tmpRepoCwd, commit2);
1819
+ }
1820
+ await this.commitStagedIfAny(opts, commit2);
1821
+ } catch (e) {
1822
+ const msg = `Failed to apply commit ${commit2.slice(0, 7)}.
1823
+ Resolve manually in the temp repo:
1824
+ cd ${opts.tmpRepoCwd}
1825
+ git status
1826
+ `;
1827
+ throw new Error(`${msg}
1828
+ ${e instanceof Error ? e.message : String(e)}`);
1829
+ }
1830
+ }
1831
+ async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, target) {
1832
+ const stagedFiles = await git.getStagedFiles(tmpRepoCwd);
1833
+ const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
1834
+ const allTouchedFiles = [.../* @__PURE__ */ new Set([...stagedFiles, ...unmergedFiles])];
1835
+ for (const file of allTouchedFiles) {
1836
+ const isBloxFile = isBloxConfigFile(file);
1837
+ const isExcludedByTarget = shouldExcludeFile(file, exclusion);
1838
+ if (isExcludedByTarget) {
1839
+ this.logger.warn("apply.commit.skip_file", { file });
1840
+ await git.revertPathToHead(file, tmpRepoCwd);
1841
+ continue;
1842
+ }
1843
+ if (isBloxFile) {
1844
+ await this.applyBloxConfigFileRevertPolicy(
1845
+ file,
1846
+ tmpRepoCwd,
1847
+ commit2,
1848
+ unmergedFiles,
1849
+ target
1850
+ );
1851
+ continue;
1852
+ }
1853
+ }
1854
+ }
1855
+ async applyBloxConfigFileRevertPolicy(file, tmpRepoCwd, commit2, unmergedFiles, target) {
1856
+ if (target.type === "base" /* BASE */) {
1857
+ this.logger.warn(
1858
+ "[.blox] revert policy: You cannot contribute the .blox file of a base from a template."
1859
+ );
1860
+ await git.revertPathToHead(file, tmpRepoCwd);
1861
+ return;
1862
+ }
1863
+ if (unmergedFiles.includes(file)) {
1864
+ this.logger.debug("apply.commit.blox_merge_fallback", { file });
1865
+ await git.revertPathToHead(file, tmpRepoCwd);
1866
+ return;
1867
+ }
1868
+ const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
1869
+ const headObj = headJson !== null && typeof headJson === "object" && !Array.isArray(headJson) ? headJson : null;
1870
+ const headDefinesAllGovernedKeys = bloxConfigControlledKeys.every(
1871
+ (key) => headObj !== null && Object.prototype.hasOwnProperty.call(headObj, key)
1872
+ );
1873
+ if (headDefinesAllGovernedKeys) {
1874
+ return;
1875
+ }
1876
+ const stagedJson = await git.readJsonFromIndex(file, tmpRepoCwd);
1877
+ if (stagedJson === null) {
1878
+ this.logger.debug("apply.commit.blox_merge_fallback", { file });
1879
+ await git.revertPathToHead(file, tmpRepoCwd);
1880
+ return;
1881
+ }
1882
+ const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
1883
+ try {
1884
+ const outPath = import_node_path14.default.join(tmpRepoCwd, file);
1885
+ await import_fs_extra11.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
1886
+ await git.add(file, tmpRepoCwd);
1887
+ } catch (e) {
1888
+ this.logger.warn("apply.commit.blox_merge_fallback", {
1889
+ commit: commit2.slice(0, 7),
1890
+ file,
1891
+ reason: "write-failed",
1892
+ message: e instanceof Error ? e.message : String(e)
1893
+ });
1894
+ await git.revertPathToHead(file, tmpRepoCwd);
1895
+ }
1896
+ }
1897
+ async waitUntilUserResolvesConflicts(tmpRepoCwd, commit2) {
1898
+ let remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
1899
+ while (remainingConflicts.length) {
1900
+ console.log(`
1901
+ ${fmt.red(fmt.bold("!! CONFLICTS DETECTED !!"))}`);
1902
+ console.log(
1903
+ fmt.yellow(`Commit ${commit2.slice(0, 7)} has conflicts in the following files:`)
1904
+ );
1905
+ remainingConflicts.forEach((f) => console.log(fmt.red(` - ${f}`)));
1906
+ console.log(`
1907
+ ${fmt.cyan("Instructions:")}`);
1908
+ console.log(fmt.white(" 1. Open a new terminal and go to:"));
1909
+ console.log(fmt.green(` cd "${tmpRepoCwd}"`));
1910
+ console.log(fmt.white(" 2. Resolve the conflicts manually."));
1911
+ console.log(fmt.white(" 3. Stage your changes with: ") + fmt.green("git add ."));
1912
+ console.log("\n");
1913
+ await text({
1914
+ message: "Press Enter once you have resolved and staged all changes to continue..."
1915
+ });
1916
+ remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
1917
+ if (remainingConflicts.length) {
1918
+ console.log(
1919
+ `
1920
+ ${fmt.red("Still detected conflicts in: " + remainingConflicts.join(", "))}`
1921
+ );
1922
+ console.log(fmt.yellow("Please make sure to 'git add' your resolved files."));
1923
+ }
1924
+ }
1925
+ }
1926
+ async commitStagedIfAny(opts, commit2) {
1927
+ if (await git.hasStagedChanges(opts.tmpRepoCwd)) {
1928
+ let commitMsg = `${opts.title}${opts.commits.length > 1 ? ` (cherry-pick: ${commit2.slice(0, 7)})` : ""}`;
1929
+ if (opts.description) {
1930
+ commitMsg += `
1931
+
1932
+ ${opts.description}`;
1933
+ }
1934
+ await git.commitAll(commitMsg, opts.tmpRepoCwd);
1935
+ this.logger.debug("apply.commit.success", { commit: commit2.slice(0, 7) });
1936
+ this.logger.info("Apply commit success");
1937
+ return;
1938
+ }
1939
+ this.logger.debug("apply.commit.skip_empty", {
1940
+ commit: commit2.slice(0, 7),
1941
+ message: "No changes left for this target after filtering."
1942
+ });
1943
+ this.logger.info(
1944
+ "Apply commit skip empty : No changes left for this target after filtering."
1945
+ );
1946
+ }
1947
+ };
1948
+
1949
+ // src/services/contribute/services/CommitSelectorService.ts
1950
+ var CommitSelectorService = class {
1951
+ constructor(logger) {
1952
+ this.logger = logger;
1953
+ }
1954
+ async selectCommitsInteractive(opts) {
1955
+ const selected = [];
1956
+ let page = 0;
1957
+ let hasMore = true;
1958
+ while (hasMore) {
1959
+ const commits = await git.listCommits(UI_PAGE_SIZE, page * UI_PAGE_SIZE, opts.cwd);
1960
+ if (!commits.length) {
1961
+ if (page === 0) {
1962
+ throw new Error("No commits found in app repository.");
1963
+ }
1964
+ break;
1965
+ }
1966
+ const value = await multiselect({
1967
+ message: `Select commits (Press <space> to select, <enter> to continue) ${fmt.gray(`(page ${page + 1})`)}`,
1968
+ options: commits.map((c) => ({
1969
+ value: c.hash,
1970
+ label: `${c.hash.slice(0, 7)} ${c.subject}`
1971
+ })),
1972
+ required: false
1973
+ });
1974
+ for (const h of value) {
1975
+ if (!selected.includes(h)) {
1976
+ selected.push(h);
1977
+ }
1978
+ }
1979
+ hasMore = commits.length === UI_PAGE_SIZE;
1980
+ if (!hasMore) {
1981
+ break;
1982
+ }
1983
+ const loadMore = await confirm({
1984
+ message: "Load next page of commits?",
1985
+ initialValue: false
1986
+ });
1987
+ if (!loadMore) {
1988
+ break;
1989
+ }
1990
+ page += 1;
1991
+ }
1992
+ if (!selected.length) {
1993
+ throw new Error("No commits selected.");
1994
+ }
1995
+ this.logger.debug("commits.selected", { count: selected.length });
1996
+ this.logger.info(`${selected.length} Commits selected`);
1997
+ return selected;
1998
+ }
1999
+ };
2000
+
2001
+ // src/services/contribute/utils/discoverContributionTargets.ts
2002
+ var import_node_path15 = __toESM(require("path"));
2003
+ var import_fs_extra12 = __toESM(require("fs-extra"));
2004
+ var readBloxFileIfExists = (cwd) => {
2005
+ const p = import_node_path15.default.join(cwd, bloxFilePath);
2006
+ if (!import_fs_extra12.default.existsSync(p)) return;
2007
+ try {
2008
+ return import_fs_extra12.default.readJSONSync(p);
2009
+ } catch {
2010
+ return;
2011
+ }
2012
+ };
2013
+ var discoverContributionTargets = (cwd) => {
2014
+ const targets = [];
2015
+ const rootBlox = readBloxFileIfExists(cwd);
2016
+ const appTemplateName = rootBlox?.definition?.name;
2017
+ const appTemplateDef = rootBlox?.definition;
2018
+ if (rootBlox?.definition?.name) {
2019
+ targets.push({
2020
+ type: "template" /* TEMPLATE */,
2021
+ name: rootBlox.definition.name,
2022
+ templateName: rootBlox.definition.name,
2023
+ templateDef: appTemplateDef,
2024
+ label: `template/${rootBlox.definition.name}`
2025
+ });
2026
+ for (const base of rootBlox.definition.bases || []) {
2027
+ targets.push({
2028
+ type: "base" /* BASE */,
2029
+ name: base.name,
2030
+ templateDef: appTemplateDef,
2031
+ label: `base/${base.name}`,
2032
+ hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
2033
+ });
2034
+ }
2035
+ }
2036
+ const blocksPath = import_node_path15.default.join(cwd, blocksDir);
2037
+ if (import_fs_extra12.default.existsSync(blocksPath)) {
2038
+ const entries = import_fs_extra12.default.readdirSync(blocksPath, { withFileTypes: true });
2039
+ for (const entry of entries) {
2040
+ if (!entry.isDirectory()) continue;
2041
+ const blockName = entry.name;
2042
+ const blockBlox = readBloxFileIfExists(import_node_path15.default.join(blocksPath, blockName));
2043
+ if (!blockBlox?.definition?.name) continue;
2044
+ const def = blockBlox.definition;
2045
+ const templateName = def.templates?.[0]?.name || appTemplateName;
2046
+ targets.push({
2047
+ type: "block" /* BLOCK */,
2048
+ name: blockName,
2049
+ templateName,
2050
+ templateDef: appTemplateDef,
2051
+ label: `block/${blockName}`,
2052
+ hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
2053
+ });
2054
+ }
2055
+ }
2056
+ return targets;
2057
+ };
2058
+
2059
+ // src/services/contribute/utils/parseContributionTargetType.ts
2060
+ var parseContributionTargetType = (segment) => {
2061
+ if (segment === "template" /* TEMPLATE */ || segment === "base" /* BASE */ || segment === "block" /* BLOCK */) {
2062
+ return segment;
2063
+ }
2064
+ return;
2065
+ };
2066
+
2067
+ // src/services/contribute/services/ContributionTargetSelector.ts
2068
+ var ContributionTargetSelector = class {
2069
+ constructor(opts, logger) {
2070
+ this.opts = opts;
2071
+ this.logger = logger;
2072
+ }
2073
+ async selectTargetInteractive() {
2074
+ const all = discoverContributionTargets(this.opts.cwd);
2075
+ if (!all.length) {
2076
+ throw new Error(
2077
+ "No contribution targets found (missing root `.blox` and/or `blocks/*/.blox`)."
2078
+ );
2079
+ }
2080
+ let query = "";
2081
+ for (; ; ) {
2082
+ query = await text({
2083
+ message: `Search targets ${fmt.gray("(empty for all)")}`,
2084
+ placeholder: "auth, template, base, ...",
2085
+ defaultValue: query
2086
+ });
2087
+ const filtered = filterTargetsByQuery(all, query);
2088
+ if (!filtered.length) {
2089
+ this.logger.warn(`No matches for search: "${query}"`);
2090
+ const again = await confirm({ message: "Search again?" });
2091
+ if (again) continue;
2092
+ throw new Error("Aborted: no target selected.");
2093
+ }
2094
+ const pageSize = UI_PAGE_SIZE;
2095
+ let page = 0;
2096
+ const maxPage = Math.max(0, Math.ceil(filtered.length / pageSize) - 1);
2097
+ while (true) {
2098
+ const start = page * pageSize;
2099
+ const slice = filtered.slice(start, start + pageSize);
2100
+ const value = await select({
2101
+ message: `Select contribution target ${fmt.gray(
2102
+ `(page ${page + 1}/${maxPage + 1})`
2103
+ )}`,
2104
+ options: buildTargetPageSelectOptions(slice, page, maxPage)
2105
+ });
2106
+ if (value === TARGET_SELECT_PAGE.PREV) {
2107
+ page = Math.max(0, page - 1);
2108
+ continue;
2109
+ }
2110
+ if (value === TARGET_SELECT_PAGE.NEXT) {
2111
+ page = Math.min(maxPage, page + 1);
2112
+ continue;
2113
+ }
2114
+ if (value === TARGET_SELECT_PAGE.SEARCH_AGAIN) {
2115
+ break;
2116
+ }
2117
+ const [typeRaw, name, templateNameRaw] = value.split(":");
2118
+ const type = typeRaw ? parseContributionTargetType(typeRaw) : void 0;
2119
+ if (!type || !name) {
2120
+ throw new Error(`Invalid selection: ${value}`);
2121
+ }
2122
+ const found = all.find((t) => t.type === type && t.name === name);
2123
+ return {
2124
+ type,
2125
+ name,
2126
+ templateName: templateNameRaw || void 0,
2127
+ templateDef: found?.templateDef
2128
+ };
2129
+ }
2130
+ }
2131
+ }
2132
+ };
2133
+ function filterTargetsByQuery(all, query) {
2134
+ const q = query.trim().toLowerCase();
2135
+ if (!q) {
2136
+ return all;
2137
+ }
2138
+ return all.filter((t) => `${t.type}/${t.name}`.toLowerCase().includes(q));
2139
+ }
2140
+ function buildTargetPageSelectOptions(slice, page, maxPage) {
2141
+ return [
2142
+ ...slice.map((t) => ({
2143
+ value: `${t.type}:${t.name}:${t.templateName || ""}`,
2144
+ label: t.label,
2145
+ hint: t.hint
2146
+ })),
2147
+ ...page > 0 ? [{ value: TARGET_SELECT_PAGE.PREV, label: "\u25C0 prev page" }] : [],
2148
+ ...page < maxPage ? [{ value: TARGET_SELECT_PAGE.NEXT, label: "next page \u25B6" }] : [],
2149
+ { value: TARGET_SELECT_PAGE.SEARCH_AGAIN, label: "search again" }
2150
+ ];
2151
+ }
2152
+
2153
+ // src/services/contribute/services/LoggerService.ts
2154
+ var LoggerService = class {
2155
+ constructor() {
2156
+ }
2157
+ formatData(data) {
2158
+ if (data === void 0) return "";
2159
+ const pretty = JSON.stringify(data, null, 2);
2160
+ return `
2161
+ ${fmt.gray(
2162
+ pretty.split("\n").map((line) => ` ${line}`).join("\n")
2163
+ )}`;
2164
+ }
2165
+ debug(message, data) {
2166
+ if (!isDebugMode()) return;
2167
+ import_prompts2.log.info(`${fmt.magenta("DEBUG")} ${message}${this.formatData(data)}`);
2168
+ }
2169
+ info(message, data) {
2170
+ import_prompts2.log.info(`${fmt.cyan("INFO")} ${message}${this.formatData(data)}`);
2171
+ }
2172
+ warn(message, data) {
2173
+ import_prompts2.log.warn(`${fmt.yellow("WARN")} ${message}${this.formatData(data)}`);
2174
+ }
2175
+ error(message, data) {
2176
+ import_prompts2.log.error(`${fmt.red("ERROR")} ${fmt.bold(message)}${this.formatData(data)}`);
2177
+ }
2178
+ };
2179
+
2180
+ // src/services/contribute/utils/buildPullRequestUrl.ts
2181
+ function buildPullRequestUrl(parsed, sourceBranch, targetBranch) {
2182
+ const repo = encodeURIComponent(parsed.repositoryId);
2183
+ const base = `${parsed.projectApiRootUrl}/_git/${repo}/pullrequestcreate`;
2184
+ const q = new URLSearchParams({
2185
+ sourceRef: sourceBranch,
2186
+ targetRef: targetBranch
2187
+ });
2188
+ return `${base}?${q.toString()}`;
2189
+ }
2190
+
2191
+ // src/services/contribute/utils/extractAzureRepoInfoFromGit.ts
2192
+ function extractAzureRepoInfoFromGit(rawUrl) {
2193
+ const trimmed = rawUrl.trim().replace(/\.git$/i, "");
2194
+ const ssh = trimmed.match(/^git@ssh\.dev\.azure\.com:v3\/([^/]+)\/([^/]+)\/(.+)$/i);
2195
+ if (ssh?.[1] && ssh[2] && ssh[3]) {
2196
+ const organization = decodeURIComponent(ssh[1]);
2197
+ const project = decodeURIComponent(ssh[2]);
2198
+ const repositoryId2 = decodeURIComponent(ssh[3]);
2199
+ const pathPrefix2 = `/${encodeURIComponent(organization)}/${encodeURIComponent(project)}`;
2200
+ return {
2201
+ projectApiRootUrl: joinProjectRoot("https://dev.azure.com", pathPrefix2),
2202
+ repositoryId: repositoryId2
2203
+ };
2204
+ }
2205
+ let parsed;
2206
+ try {
2207
+ parsed = new URL(trimmed);
2208
+ } catch {
2209
+ return null;
2210
+ }
2211
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2212
+ return null;
2213
+ }
2214
+ const pathname = (parsed.pathname || "/").replace(/\/+$/, "") || "/";
2215
+ const lower = pathname.toLowerCase();
2216
+ const marker = "/_git/";
2217
+ const gitAt = lower.indexOf(marker);
2218
+ if (gitAt === -1) {
2219
+ return null;
2220
+ }
2221
+ const pathPrefix = pathname.slice(0, gitAt);
2222
+ const repoPath = pathname.slice(gitAt + marker.length);
2223
+ if (!pathPrefix || pathPrefix === "/" || !repoPath) {
2224
+ return null;
2225
+ }
2226
+ const depth = pathPrefix.split("/").filter(Boolean).length;
2227
+ if (depth < 2) {
2228
+ return null;
2229
+ }
2230
+ const repositoryId = decodeURIComponent(repoPath.split("/").filter(Boolean).join("/"));
2231
+ if (!repositoryId) {
2232
+ return null;
2233
+ }
2234
+ return {
2235
+ projectApiRootUrl: joinProjectRoot(parsed.origin, pathPrefix),
2236
+ repositoryId
2237
+ };
2238
+ }
2239
+ function joinProjectRoot(origin, pathPrefix) {
2240
+ const prefix = pathPrefix.startsWith("/") ? pathPrefix : `/${pathPrefix}`;
2241
+ return `${origin.replace(/\/$/, "")}${prefix}`.replace(/\/$/, "");
2242
+ }
2243
+
2244
+ // src/services/contribute/utils/sleep.ts
2245
+ async function sleep(ms2) {
2246
+ await new Promise((r) => setTimeout(r, ms2));
2247
+ }
2248
+
2249
+ // src/services/contribute/services/PullRequestService.ts
2250
+ var PullRequestService = class {
2251
+ constructor(logger) {
2252
+ this.logger = logger;
2253
+ }
2254
+ async pushBranch(opts) {
2255
+ const maxAttempts = opts.maxAttempts ?? 3;
2256
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2257
+ try {
2258
+ await git.push(opts.remote, opts.branch, opts.cwd);
2259
+ return;
2260
+ } catch (e) {
2261
+ const message = e instanceof Error ? e.message : String(e);
2262
+ opts.onAttemptFailed?.({ attempt, error: message });
2263
+ if (attempt === maxAttempts) {
2264
+ throw new Error(`git push failed after ${maxAttempts} attempts: ${message}`);
2265
+ }
2266
+ await sleep(500 * attempt);
2267
+ }
2268
+ }
2269
+ }
2270
+ printPushSummary(opts) {
2271
+ const line = "\u2501".repeat(60);
2272
+ const header = fmt.bold(fmt.cyan("BRANCH PUSHED"));
2273
+ import_prompts2.log.message(
2274
+ `
2275
+ ${fmt.cyan("\u25E2")}${line}${fmt.cyan("\u25E3")}
2276
+ ${header}
2277
+
2278
+ ${fmt.bold("Target:")} ${fmt.green(opts.targetBranch)}
2279
+ ${fmt.bold("Source:")} ${fmt.yellow(opts.sourceBranch)}
2280
+ ${fmt.bold("Remote:")} ${fmt.blue(opts.repoUrl)}
2281
+ ${fmt.bold("Title:")} ${opts.title}
2282
+ ` + (opts.description.trim() ? `
2283
+ ${fmt.gray("Description:")}
2284
+ ${opts.description.trim()}
2285
+ ` : "") + `${fmt.cyan("\u25E5")}${line}${fmt.cyan("\u25E4")}
2286
+ `
2287
+ );
2288
+ }
2289
+ async openPullRequestPage(opts) {
2290
+ const parsed = extractAzureRepoInfoFromGit(opts.repoUrl);
2291
+ if (!parsed) {
2292
+ this.logger.info("pr.skipped", { reason: "remote_not_azure_devops_git" });
2293
+ return { prUrl: void 0 };
2294
+ }
2295
+ this.logger.info("pr.prompt.shown");
2296
+ const wantsPr = await confirm({
2297
+ message: "Do you want to open a Pull Request?",
2298
+ initialValue: true
2299
+ });
2300
+ if (!wantsPr) {
2301
+ this.logger.info("pr.declined");
2302
+ return { prUrl: void 0 };
2303
+ }
2304
+ const createPageUrl = buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
2305
+ try {
2306
+ await openUrlInBrowser(createPageUrl);
2307
+ } catch (e) {
2308
+ this.logger.warn("Could not open browser", e);
2309
+ }
2310
+ import_prompts2.log.message(
2311
+ `
2312
+ ${fmt.green("Opening Pull Request creation in your browser.")}
2313
+ ${fmt.cyan(createPageUrl)}
2314
+ `
2315
+ );
2316
+ return { prUrl: createPageUrl };
2317
+ }
2318
+ };
2319
+
2320
+ // src/services/contribute/services/TmpRepoService.ts
2321
+ var import_node_os2 = require("os");
2322
+ var import_node_path16 = __toESM(require("path"));
2323
+ var import_fs_extra13 = __toESM(require("fs-extra"));
2324
+ var TmpRepoService = class {
2325
+ constructor(logger) {
2326
+ this.logger = logger;
2327
+ }
2328
+ async getTmpDir(target) {
2329
+ const slug = `${target.type}-${target.name}`.replace(/[^a-zA-Z0-9._-]+/g, "-");
2330
+ return import_node_path16.default.join((0, import_node_os2.homedir)(), bloxFilePath, tempRepoName, slug);
2331
+ }
2332
+ async prepare(opts) {
2333
+ const dir = await this.getTmpDir(opts.target);
2334
+ this.logger.debug(`${tempRepoName}.prepare`, {
2335
+ dir,
2336
+ repoUrl: opts.repoUrl,
2337
+ branch: opts.branch
2338
+ });
2339
+ this.logger.info("Prepare for tmp repo");
2340
+ if (await import_fs_extra13.default.pathExists(dir)) {
2341
+ this.logger.debug(`${tempRepoName}.remove`, { dir });
2342
+ await import_fs_extra13.default.remove(dir);
2343
+ }
2344
+ await import_fs_extra13.default.ensureDir(import_node_path16.default.dirname(dir));
2345
+ await git.clone(opts.repoUrl, dir, opts.branch);
2346
+ return dir;
2347
+ }
2348
+ };
2349
+
2350
+ // src/services/contribute/index.ts
2351
+ async function buildContributionWorkflow(opts) {
2352
+ const logger = new LoggerService();
2353
+ const targetSelector = new ContributionTargetSelector({ cwd: opts.cwd }, logger);
2354
+ const tmpRepo = new TmpRepoService(logger);
2355
+ const commitSelector = new CommitSelectorService(logger);
2356
+ const commitApplier = new CommitApplierService(logger);
2357
+ const pullRequest = new PullRequestService(logger);
2358
+ return new ContributionWorkflow(
2359
+ { cwd: opts.cwd, force: opts.force },
2360
+ logger,
2361
+ targetSelector,
2362
+ tmpRepo,
2363
+ commitSelector,
2364
+ commitApplier,
2365
+ pullRequest
2366
+ );
2367
+ }
2368
+
2369
+ // src/commands/contribute/index.ts
2370
+ 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(
2371
+ option("--type <type>", "target type").choices(Object.values(ContributionTargetType))
2372
+ ).option("--name <name>", "target name").action(async (flags) => {
2373
+ try {
2374
+ await migrateAll(true);
2375
+ await syncRegistries();
2376
+ const workflow = await buildContributionWorkflow({
2377
+ cwd: process.cwd(),
2378
+ force: !!flags.force
2379
+ });
2380
+ await workflow.runFromFlags(flags);
2381
+ } catch (e) {
2382
+ error(e);
2383
+ }
2384
+ });
2385
+
1039
2386
  // src/commands/detach/index.ts
1040
2387
  var detach = command("detach").description("Migrate blox schema").option("--basic", "run detach only").action(async ({ basic }) => {
1041
2388
  try {
@@ -1077,7 +2424,7 @@ var detach = command("detach").description("Migrate blox schema").option("--basi
1077
2424
  });
1078
2425
 
1079
2426
  // src/commands/init/index.ts
1080
- var import_fs_extra10 = __toESM(require("fs-extra"));
2427
+ var import_fs_extra14 = __toESM(require("fs-extra"));
1081
2428
  var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").option("--branch <name>", "branch name").action(async ({ name, template, branch }) => {
1082
2429
  await syncRegistries();
1083
2430
  try {
@@ -1118,8 +2465,8 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
1118
2465
  task.stop(`App initialized in ${name}`);
1119
2466
  await runTask("Run init script", async () => runInitScript(name || ""));
1120
2467
  } catch (e) {
1121
- if (name && import_fs_extra10.default.existsSync(name)) {
1122
- await import_fs_extra10.default.remove(name);
2468
+ if (name && import_fs_extra14.default.existsSync(name)) {
2469
+ await import_fs_extra14.default.remove(name);
1123
2470
  }
1124
2471
  error(e);
1125
2472
  }
@@ -1139,15 +2486,22 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
1139
2486
  });
1140
2487
 
1141
2488
  // src/commands/update/index.ts
1142
- var import_prompts15 = require("@clack/prompts");
2489
+ var import_prompts21 = require("@clack/prompts");
1143
2490
 
1144
2491
  // src/commands/update/utils.ts
1145
- var import_node_path11 = __toESM(require("path"));
2492
+ var import_node_path18 = __toESM(require("path"));
1146
2493
 
1147
2494
  // src/services/updater.ts
1148
- var import_node_path10 = __toESM(require("path"));
1149
- var import_fs_extra11 = __toESM(require("fs-extra"));
1150
- async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir = "." }) {
2495
+ var import_node_path17 = __toESM(require("path"));
2496
+ var import_fs_extra15 = __toESM(require("fs-extra"));
2497
+ var import_klaw3 = __toESM(require("klaw"));
2498
+ async function updateFromRemote({
2499
+ name,
2500
+ source = "",
2501
+ ignore: ignore3 = [],
2502
+ dir = ".",
2503
+ hard = false
2504
+ }) {
1151
2505
  debug("Updating from remote");
1152
2506
  await git.updateRemote(name, source);
1153
2507
  const bloxFile = getBloxFile(dir);
@@ -1167,7 +2521,7 @@ async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir =
1167
2521
  debug("No new version");
1168
2522
  return;
1169
2523
  }
1170
- const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[".blox"];
2524
+ const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[bloxFilePath];
1171
2525
  for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.checkpoints || {})) {
1172
2526
  const baseFrom = bloxFile.checkpoints[baseName]?.commit;
1173
2527
  if (!baseFrom) {
@@ -1183,45 +2537,136 @@ async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir =
1183
2537
  );
1184
2538
  }
1185
2539
  }
1186
- const patchFilePath = import_node_path10.default.join(dir, "diff.patch");
1187
2540
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
1188
- ignore2.push(...remoteIgnore, ".blox", "**/.blox");
1189
- await git.createPatch(fromCommit, toCommit, patchFilePath, ignore2);
1190
- const deletePatchFile = async () => {
1191
- if (!isDebugMode()) {
1192
- await import_fs_extra11.default.unlink(patchFilePath);
2541
+ ignore3.push(...remoteIgnore, bloxFilePath, `**/${bloxFilePath}`);
2542
+ const gitIgnorePath = import_node_path17.default.join(dir, ".gitignore");
2543
+ if (await import_fs_extra15.default.pathExists(gitIgnorePath)) {
2544
+ const gitIgnoreContent = await import_fs_extra15.default.readFile(gitIgnorePath, "utf8");
2545
+ const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
2546
+ ignore3.push(...gitIgnorePatterns);
2547
+ debug(`Added ${gitIgnorePatterns.length} patterns from .gitignore`);
2548
+ }
2549
+ debug("Preparing update worktrees...");
2550
+ const baseDir = await git.getRemoteWorktree(name, fromCommit);
2551
+ const remoteDir = await git.getRemoteWorktree(name, toCommit);
2552
+ let filesToProcess = [];
2553
+ if (hard) {
2554
+ const getAllFiles = async (d) => {
2555
+ const files = [];
2556
+ if (await import_fs_extra15.default.pathExists(d)) {
2557
+ for await (const file of (0, import_klaw3.default)(d)) {
2558
+ if (file.path.includes("/.git/") || file.path.endsWith("/.git") || file.path.includes("\\.git\\") || file.path.endsWith("\\.git"))
2559
+ continue;
2560
+ if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
2561
+ continue;
2562
+ if (file.stats.isFile()) {
2563
+ files.push(import_node_path17.default.relative(d, file.path));
2564
+ }
2565
+ }
2566
+ }
2567
+ return files;
2568
+ };
2569
+ const remoteFiles = await getAllFiles(remoteDir);
2570
+ const localFiles = await getAllFiles(dir);
2571
+ const allFiles = /* @__PURE__ */ new Set([...remoteFiles, ...localFiles]);
2572
+ filesToProcess = Array.from(allFiles);
2573
+ } else {
2574
+ filesToProcess = await git.getChangedFiles(fromCommit, toCommit, ignore3);
2575
+ }
2576
+ const ignoredMatcher = createGitignoreMatcher(ignore3);
2577
+ let hasConflicts2 = false;
2578
+ const conflictFiles = [];
2579
+ for (const file of filesToProcess) {
2580
+ if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
2581
+ if (ignoredMatcher.ignores(toIgnorePath(file))) continue;
2582
+ const localPath = import_node_path17.default.join(dir, file);
2583
+ const basePath = import_node_path17.default.join(baseDir, file);
2584
+ const remotePath = import_node_path17.default.join(remoteDir, file);
2585
+ const existsLocal = await import_fs_extra15.default.pathExists(localPath);
2586
+ const existsBase = await import_fs_extra15.default.pathExists(basePath);
2587
+ const existsRemote = await import_fs_extra15.default.pathExists(remotePath);
2588
+ const ext = import_node_path17.default.extname(file);
2589
+ const isBinary = isBinaryFile(ext);
2590
+ if (existsRemote) {
2591
+ await import_fs_extra15.default.ensureDir(import_node_path17.default.dirname(localPath));
1193
2592
  }
1194
- debug("make sure to delete the patch file after you're done with it.");
1195
- };
1196
- let hasMergeConflicts = false;
1197
- try {
1198
- await git.applyPatch(patchFilePath, dir);
1199
- } catch (e) {
1200
- const errorMessage = `${e}`;
1201
- if (errorMessage.includes("error:")) {
1202
- await deletePatchFile();
1203
- console.log(errorMessage.replace("error:", fmt.red("error:")));
1204
- if (errorMessage.includes("does not exist in index")) {
2593
+ if (hard) {
2594
+ if (existsRemote) {
2595
+ await import_fs_extra15.default.copy(remotePath, localPath, { overwrite: true });
2596
+ debug(`Hard update: Overwrote ${file}`);
2597
+ } else if (existsLocal) {
2598
+ await import_fs_extra15.default.remove(localPath);
2599
+ debug(`Hard update: Removed ${file}`);
2600
+ }
2601
+ continue;
2602
+ }
2603
+ if (!existsBase && existsRemote) {
2604
+ if (existsLocal) {
2605
+ if (isBinary) {
2606
+ debug(`Binary collision: ${file}, overwriting.`);
2607
+ await import_fs_extra15.default.copy(remotePath, localPath, { overwrite: true });
2608
+ logWarningSection(`Overwrote binary file collision: ${file}`);
2609
+ } else {
2610
+ const emptyBase = import_node_path17.default.join(baseDir, `${file}.empty`);
2611
+ await import_fs_extra15.default.ensureFile(emptyBase);
2612
+ const result = await git.mergeFile(localPath, emptyBase, remotePath);
2613
+ if (!result) {
2614
+ hasConflicts2 = true;
2615
+ conflictFiles.push(file);
2616
+ }
2617
+ await import_fs_extra15.default.remove(emptyBase);
2618
+ }
2619
+ } else {
2620
+ await import_fs_extra15.default.copy(remotePath, localPath);
2621
+ }
2622
+ continue;
2623
+ }
2624
+ if (existsBase && !existsRemote) {
2625
+ if (existsLocal) {
2626
+ const localBuffer = await import_fs_extra15.default.readFile(localPath);
2627
+ const baseBuffer = await import_fs_extra15.default.readFile(basePath);
2628
+ if (localBuffer.equals(baseBuffer)) {
2629
+ await import_fs_extra15.default.remove(localPath);
2630
+ } else {
2631
+ logWarningSection(
2632
+ `File ${file} was deleted in remote but modified locally. Kept local version.`
2633
+ );
2634
+ }
2635
+ }
2636
+ continue;
2637
+ }
2638
+ if (existsBase && existsRemote) {
2639
+ if (!existsLocal) {
2640
+ await import_fs_extra15.default.copy(remotePath, localPath);
1205
2641
  logWarningSection(
1206
- "Some files has changes in remote but were deleted, \n if you want to skip them pass this arg to update command:",
1207
- fmt.cyan(
1208
- `--ignore ${[
1209
- ...errorMessage.matchAll(/error: (.*): does not exist in index/g)
1210
- ].map((m) => `"${name}:${m[1]}"`).join(",")}`
1211
- )
2642
+ `File restored: ${file}`,
2643
+ `This file was deleted locally but updated in the remote block.
2644
+ It has been recreated to apply upstream changes.`
1212
2645
  );
2646
+ continue;
2647
+ }
2648
+ if (isBinary) {
2649
+ await import_fs_extra15.default.copy(remotePath, localPath, { overwrite: true });
2650
+ logWarningSection(`Updated binary file: ${file} (overwritten)`);
2651
+ } else {
2652
+ const result = await git.mergeFile(localPath, basePath, remotePath);
2653
+ if (!result) {
2654
+ hasConflicts2 = true;
2655
+ conflictFiles.push(file);
2656
+ }
1213
2657
  }
1214
- throw new Error("Failed to apply changes.");
1215
2658
  }
1216
- hasMergeConflicts = errorMessage.includes("with conflicts");
1217
2659
  }
1218
- if (hasMergeConflicts) {
2660
+ if (hasConflicts2) {
2661
+ logWarningSection(
2662
+ "Conflicts detected in the following files:",
2663
+ conflictFiles.map((f) => fmt.red(f)).join("\n")
2664
+ );
1219
2665
  await select({
1220
- message: "Please resolve conflicts press enter",
1221
- options: [{ value: true, label: "continue" }]
2666
+ message: "Please resolve conflicts manually (look for <<<<<<< HEAD) and press enter to continue",
2667
+ options: [{ value: true, label: "Resolved" }]
1222
2668
  });
1223
2669
  }
1224
- await deletePatchFile();
1225
2670
  bloxFile.checkpoints[name] = { commit: toCommit };
1226
2671
  if (bloxFile.definition.name === name) {
1227
2672
  bloxFile.definition = remoteBloxFile.definition;
@@ -1238,7 +2683,8 @@ async function updateApp({
1238
2683
  templates,
1239
2684
  usedBlocks,
1240
2685
  availableBlocks,
1241
- ignore: ignore2
2686
+ ignore: ignore3,
2687
+ hard = false
1242
2688
  }) {
1243
2689
  await runTask({ start: "Update App", end: "Updated App" }, async () => {
1244
2690
  const template = templates[templateDef.name];
@@ -1249,7 +2695,8 @@ async function updateApp({
1249
2695
  const toAppCommit = await updateFromRemote({
1250
2696
  name: templateDef.name,
1251
2697
  source: template.source,
1252
- ignore: ignore2
2698
+ ignore: ignore3,
2699
+ hard
1253
2700
  });
1254
2701
  if (!toAppCommit) return;
1255
2702
  if (!templateDef.bases?.length) return;
@@ -1257,7 +2704,7 @@ async function updateApp({
1257
2704
  const blockRegistryData = availableBlocks[block.name];
1258
2705
  if (!blockRegistryData) return;
1259
2706
  await git.updateRemote(block.name, blockRegistryData.source);
1260
- const blockPath = import_node_path11.default.join(blocksDir, block.name);
2707
+ const blockPath = import_node_path18.default.join(blocksDir, block.name);
1261
2708
  const currentBloxFile = getBloxFile(blockPath);
1262
2709
  const remoteBloxFile = (await migrateOnRemote(block.name, toAppCommit, blockPath)).output[".blox"];
1263
2710
  const blockFromCommit = currentBloxFile.checkpoints?.[block.name]?.commit;
@@ -1273,7 +2720,7 @@ async function updateApp({
1273
2720
  }
1274
2721
  });
1275
2722
  }
1276
- async function updateAppBases(templateDef, templates, ignore2) {
2723
+ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
1277
2724
  for (const base of templateDef.bases || []) {
1278
2725
  await runTask(
1279
2726
  { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
@@ -1283,14 +2730,14 @@ async function updateAppBases(templateDef, templates, ignore2) {
1283
2730
  error("Selected template not available in registries");
1284
2731
  return;
1285
2732
  }
1286
- await updateFromRemote({ name: base.name, source: template.source, ignore: ignore2 });
2733
+ await updateFromRemote({ name: base.name, source: template.source, ignore: ignore3, hard });
1287
2734
  }
1288
2735
  );
1289
2736
  }
1290
2737
  }
1291
- async function updateBlock(block, blocks, ignore2) {
2738
+ async function updateBlock(block, blocks, ignore3, hard = false) {
1292
2739
  const blockRegistryData = blocks[block];
1293
- const blockPath = import_node_path11.default.join(blocksDir, block);
2740
+ const blockPath = import_node_path18.default.join(blocksDir, block);
1294
2741
  await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
1295
2742
  if (!blockRegistryData) {
1296
2743
  error(`Selected block: ${block} not available in registries`, false);
@@ -1300,7 +2747,8 @@ async function updateBlock(block, blocks, ignore2) {
1300
2747
  name: block,
1301
2748
  source: blockRegistryData.source,
1302
2749
  dir: blockPath,
1303
- ignore: ignore2
2750
+ ignore: ignore3,
2751
+ hard
1304
2752
  });
1305
2753
  });
1306
2754
  }
@@ -1342,9 +2790,9 @@ ${fmt.gray("-".repeat(82))}
1342
2790
  // src/commands/update/index.ts
1343
2791
  var update2 = command("update").description("Update app/block").alias("u").addOption(
1344
2792
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
1345
- ).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").action(async (args) => {
2793
+ ).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) => {
1346
2794
  if (await git.hasUncommittedChanges()) {
1347
- import_prompts15.log.warn(fmt.yellow("Make sure to commit any changes first"));
2795
+ import_prompts21.log.warn(fmt.yellow("Make sure to commit any changes first"));
1348
2796
  return;
1349
2797
  }
1350
2798
  await migrateAll(true);
@@ -1355,8 +2803,8 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1355
2803
  const templates = await getAvailableTemplates();
1356
2804
  const usedBlocks = getUsedBlocksDef();
1357
2805
  const ignoresByName = {};
1358
- for (const ignore2 of args.ignore || []) {
1359
- const [repo, pattern] = ignore2.split(":");
2806
+ for (const ignore3 of args.ignore || []) {
2807
+ const [repo, pattern] = ignore3.split(":");
1360
2808
  if (!repo || !pattern) {
1361
2809
  error("Invalid ignore pattern");
1362
2810
  return;
@@ -1373,15 +2821,26 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1373
2821
  templates,
1374
2822
  usedBlocks,
1375
2823
  availableBlocks,
1376
- ignore: ignoresByName[templateDef.name]
2824
+ ignore: ignoresByName[templateDef.name],
2825
+ hard: args.hard
1377
2826
  });
1378
2827
  }
1379
2828
  if (["bases", "all"].includes(args.scope)) {
1380
- await updateAppBases(templateDef, templates, ignoresByName[templateDef.name]);
2829
+ await updateAppBases(
2830
+ templateDef,
2831
+ templates,
2832
+ ignoresByName[templateDef.name],
2833
+ args.hard
2834
+ );
1381
2835
  }
1382
2836
  if (args.scope === "all") {
1383
2837
  for (const block of usedBlocks) {
1384
- await updateBlock(block.name, availableBlocks, ignoresByName[block.name]);
2838
+ await updateBlock(
2839
+ block.name,
2840
+ availableBlocks,
2841
+ ignoresByName[block.name],
2842
+ args.hard
2843
+ );
1385
2844
  }
1386
2845
  }
1387
2846
  if (args.scope === "block") {
@@ -1399,17 +2858,24 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1399
2858
  error("Selected block not used in app");
1400
2859
  return;
1401
2860
  }
1402
- await updateBlock(blockDef.name, availableBlocks, ignoresByName[blockDef.name]);
2861
+ await updateBlock(
2862
+ blockDef.name,
2863
+ availableBlocks,
2864
+ ignoresByName[blockDef.name],
2865
+ args.hard
2866
+ );
1403
2867
  }
1404
2868
  await checkVersionsCompatibility();
1405
2869
  const endCheckpoints = await getCurrentCheckpoints();
1406
2870
  await printChangeLog(startCheckpoints, endCheckpoints);
1407
2871
  } catch (e) {
1408
2872
  if (!isDebugMode()) {
1409
- import_prompts15.log.warn("Error happened, Will rollback changes");
2873
+ import_prompts21.log.warn("Error happened, Will rollback changes");
1410
2874
  await git.rollback();
1411
2875
  }
1412
2876
  error(e);
2877
+ } finally {
2878
+ await git.cleanUpWorktrees();
1413
2879
  }
1414
2880
  });
1415
2881
 
@@ -1424,7 +2890,7 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
1424
2890
  });
1425
2891
 
1426
2892
  // src/commands/index.ts
1427
- var commands = [init2, add2, update2, conf, upgrade, migrateSchema, detach];
2893
+ var commands = [init2, add2, update2, conf, upgrade, migrateSchema, detach, contribute];
1428
2894
 
1429
2895
  // bin/run.ts
1430
2896
  async function main() {