@naseej/blox 0.2.0 → 1.1.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.
package/bin/run.ts CHANGED
@@ -3,9 +3,13 @@ import { cli } from '@/shared/command';
3
3
  import { version } from '../package.json';
4
4
  import { commands } from '../src';
5
5
 
6
- cli.name('blox').version(version);
7
- cli.option('-d, --debug', 'work in debug mode');
8
- cli.option('-m, --minimal', 'work in minimal mode');
6
+ async function main() {
7
+ cli.name('blox').version(version);
8
+ cli.option('-d, --debug', 'work in debug mode');
9
+ cli.option('-m, --minimal', 'work in minimal mode');
9
10
 
10
- commands.forEach((cmd) => cli.addCommand(cmd));
11
- cli.parse();
11
+ commands.forEach((cmd) => cli.addCommand(cmd));
12
+ cli.parse();
13
+ }
14
+
15
+ main();
package/dist/run.js CHANGED
@@ -31,15 +31,60 @@ var option = (flags, description) => {
31
31
  };
32
32
 
33
33
  // package.json
34
- var version = "0.2.0";
34
+ var version = "1.1.0";
35
35
 
36
36
  // src/commands/add/index.ts
37
- var import_fs_extra5 = __toESM(require("fs-extra"));
37
+ var import_fs_extra8 = __toESM(require("fs-extra"));
38
38
 
39
39
  // src/config/runtime.ts
40
40
  var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
41
41
  var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
42
42
 
43
+ // src/migrations/index.ts
44
+ var import_node_path4 = __toESM(require("path"));
45
+ var import_fs_extra3 = __toESM(require("fs-extra"));
46
+
47
+ // src/config/index.ts
48
+ var defaultConfig = {
49
+ registries: ["https://tfs.aas.com.sa/Medad/BLOX/_git/default-registry"]
50
+ };
51
+ var bloxFilePath = ".blox";
52
+ var blocksDir = "blocks";
53
+
54
+ // src/migrations/utils.ts
55
+ var import_node_path3 = __toESM(require("path"));
56
+ var import_fs_extra2 = __toESM(require("fs-extra"));
57
+
58
+ // src/migrations/list/v1.ts
59
+ var v1 = {
60
+ dependencies: {
61
+ packageJson: {
62
+ location: "package.json"
63
+ },
64
+ bloxFile: {
65
+ location: ".blox"
66
+ }
67
+ },
68
+ run: async ({ packageJson, bloxFile: oldBloxFile }) => {
69
+ const bloxFile = {
70
+ schemaVersion: 1,
71
+ definition: packageJson.blox,
72
+ checkpoints: {}
73
+ };
74
+ if (oldBloxFile.commit) {
75
+ bloxFile.checkpoints[bloxFile.definition.name] = { commit: oldBloxFile.commit };
76
+ }
77
+ Object.entries(oldBloxFile.bases || {}).forEach(([k, v]) => {
78
+ bloxFile.checkpoints[k] = v;
79
+ });
80
+ delete packageJson.blox;
81
+ return { bloxFile, packageJson };
82
+ }
83
+ };
84
+
85
+ // src/migrations/list/index.ts
86
+ var migrationsList = [v1];
87
+
43
88
  // src/services/git.ts
44
89
  var import_node_path2 = __toESM(require("path"));
45
90
  var import_fs_extra = __toESM(require("fs-extra"));
@@ -130,8 +175,8 @@ var clone = (repoUrl, options, shellOptions = {}) => {
130
175
  ...shellOptions
131
176
  });
132
177
  };
133
- var resetToCommit = async (commit, cwd = ".") => {
134
- await $("git", ["reset --hard", `${commit}`], { cwd });
178
+ var resetToCommit = async (commit2, cwd = ".") => {
179
+ await $("git", ["reset --hard", `${commit2}`], { cwd });
135
180
  };
136
181
  var updateRemote = async (name, source, shellOptions = {}) => {
137
182
  debug("updateRemote");
@@ -149,10 +194,10 @@ var updateRemote = async (name, source, shellOptions = {}) => {
149
194
  });
150
195
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
151
196
  };
152
- var readJsonFromCommit = async (commit, file) => {
197
+ var readJsonFromCommit = async (commit2, file) => {
153
198
  try {
154
199
  let content = "";
155
- await $("git", ["show", `${commit}:${file}`], {
200
+ await $("git", ["show", `${commit2}:${file}`], {
156
201
  onStdout: (text2) => {
157
202
  content = text2;
158
203
  }
@@ -162,8 +207,8 @@ var readJsonFromCommit = async (commit, file) => {
162
207
  return {};
163
208
  }
164
209
  };
165
- var readJsonFromRemote = async (remote, file, commit) => {
166
- return readJsonFromCommit(commit || `${remote}/main`, file);
210
+ var readJsonFromRemote = async (remote, file, commit2) => {
211
+ return readJsonFromCommit(commit2 || `${remote}/main`, file);
167
212
  };
168
213
  var isCommitOlder = async (a, b) => {
169
214
  try {
@@ -179,21 +224,21 @@ var update = (shellOptions = {}) => {
179
224
  var getLatestCommitFromRemote = async (remote) => {
180
225
  return getLatestCommit(`${remote}/main`);
181
226
  };
182
- var getLatestCommitFromPath = async (path8) => {
183
- return getLatestCommit("HEAD", path8);
227
+ var getLatestCommitFromPath = async (path11) => {
228
+ return getLatestCommit("HEAD", path11);
184
229
  };
185
230
  var getLatestCommit = async (rev, cwd = ".") => {
186
231
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
187
- let commit = "";
232
+ let commit2 = "";
188
233
  await $("git", ["rev-parse", rev], {
189
234
  cwd,
190
235
  onStdout: (text2) => {
191
- commit = text2;
236
+ commit2 = text2;
192
237
  }
193
238
  });
194
- return commit.replace(/\n/g, "");
239
+ return commit2.replace(/\n/g, "");
195
240
  };
196
- var createPatch = async (fromCommit, toCommit, outputPath, ignore = []) => {
241
+ var createPatch = async (fromCommit, toCommit, outputPath, ignore2 = []) => {
197
242
  return $("git", [
198
243
  "diff",
199
244
  fromCommit,
@@ -201,7 +246,7 @@ var createPatch = async (fromCommit, toCommit, outputPath, ignore = []) => {
201
246
  ">",
202
247
  outputPath,
203
248
  "--",
204
- ...ignore.map((file) => `':!${file}'`)
249
+ ...ignore2.map((file) => `':!${file}'`)
205
250
  ]);
206
251
  };
207
252
  var getChangesLog = async (fromCommit, toCommit) => {
@@ -214,7 +259,7 @@ var getChangesLog = async (fromCommit, toCommit) => {
214
259
  return changes;
215
260
  };
216
261
  var applyPatch = (patch, cwd = ".") => {
217
- const args = ["apply", "-3"];
262
+ const args = ["apply", "-3", "--allow-empty"];
218
263
  if (cwd != ".") {
219
264
  args.push("--directory");
220
265
  args.push(normalizePath(cwd));
@@ -237,11 +282,25 @@ var add = async (toAdd) => {
237
282
  debug(`Git Add: ${toAdd}`);
238
283
  await $("git", ["add", toAdd]);
239
284
  };
285
+ var commit = async (msg) => {
286
+ debug(`Git commit: ${msg}`);
287
+ await $("git", ["commit", "-m", `"${msg}"`]);
288
+ };
240
289
  var rollback = async () => {
241
290
  debug("Rollback");
242
291
  await $("git", ["add", "."]);
243
292
  await $("git", ["reset", "--hard"]);
244
293
  };
294
+ var hasUncommittedChanges = async (cwd = ".") => {
295
+ let status = "";
296
+ await $("git", ["status", "--porcelain"], {
297
+ cwd,
298
+ onStdout: (text2) => {
299
+ status += text2;
300
+ }
301
+ });
302
+ return status.trim().length > 0;
303
+ };
245
304
  var git = {
246
305
  clone,
247
306
  update,
@@ -253,23 +312,167 @@ var git = {
253
312
  getChangesLog,
254
313
  applyPatch,
255
314
  updateRemote,
315
+ readJsonFromCommit,
256
316
  readJsonFromRemote,
257
317
  isCommitOlder,
258
318
  rollback,
259
319
  add,
260
- resetToCommit
320
+ resetToCommit,
321
+ commit,
322
+ hasUncommittedChanges
261
323
  };
262
324
 
263
- // src/services/registry.ts
264
- var import_node_path4 = __toESM(require("path"));
265
- var import_fs_extra3 = __toESM(require("fs-extra"));
325
+ // src/shared/prompts/index.ts
326
+ var import_prompts3 = require("@clack/prompts");
327
+ var checkIfCanceled = (value) => {
328
+ if ((0, import_prompts3.isCancel)(value)) {
329
+ (0, import_prompts3.cancel)();
330
+ process.exit(0);
331
+ }
332
+ };
333
+ var error = (error2, exit = true) => {
334
+ import_prompts3.log.error(
335
+ fmt.red(
336
+ typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
337
+ )
338
+ );
339
+ exit && process.exit(-1);
340
+ };
341
+ var select = async (opts) => {
342
+ const value = await (0, import_prompts3.select)(opts);
343
+ checkIfCanceled(value);
344
+ return value;
345
+ };
346
+ var text = async (opts) => {
347
+ const value = await (0, import_prompts3.text)(opts);
348
+ checkIfCanceled(value);
349
+ return value;
350
+ };
351
+ var textList = async (opts) => {
352
+ opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
353
+ const value = await (0, import_prompts3.text)(opts);
354
+ checkIfCanceled(value);
355
+ opts.validate?.(value);
356
+ return value.split(",");
357
+ };
358
+
359
+ // src/migrations/utils.ts
360
+ function getApplicableMigrations(schemaVersion = 0) {
361
+ if (schemaVersion > migrationsList.length) {
362
+ error(
363
+ normalizeLogMessage(
364
+ `Used blox schema version: ${schemaVersion} is newer than cli version: ${migrationsList.length},
365
+ please update cli first or use older version`
366
+ )
367
+ );
368
+ return [];
369
+ }
370
+ return migrationsList.slice(schemaVersion);
371
+ }
372
+ async function migrate(name, { getPath = (f) => f, read, write }) {
373
+ let remoteBloxFile;
374
+ try {
375
+ remoteBloxFile = await read(getPath(".blox"));
376
+ } catch {
377
+ remoteBloxFile = {};
378
+ }
379
+ const migrations = getApplicableMigrations(remoteBloxFile.schemaVersion);
380
+ if (migrations.length) {
381
+ import_prompts2.log.warn(fmt.yellow(`Migrations found for ${name}, will migrate to latest schema`));
382
+ }
383
+ const currentRev = {
384
+ ".blox": remoteBloxFile
385
+ };
386
+ for (const migration of migrations) {
387
+ const deps = {};
388
+ for (const [name2, { location, defaultValue = {} }] of Object.entries(
389
+ migration.dependencies
390
+ )) {
391
+ try {
392
+ const filePath = getPath(location);
393
+ if (currentRev[filePath] !== void 0) {
394
+ deps[name2] = currentRev[filePath];
395
+ } else {
396
+ deps[name2] = await read(filePath);
397
+ }
398
+ } catch {
399
+ }
400
+ if (deps[name2] === void 0) {
401
+ deps[name2] = defaultValue;
402
+ }
403
+ }
404
+ const output = await migration.run(deps);
405
+ for (const [name2, value] of Object.entries(output || {})) {
406
+ const { location } = migration.dependencies[name2] || {};
407
+ location && (currentRev[location] = value);
408
+ }
409
+ }
410
+ if (write) {
411
+ for (const [location, value] of Object.entries(currentRev)) {
412
+ await write(getPath(location), JSON.stringify(value, null, 2));
413
+ }
414
+ }
415
+ return { output: currentRev, migrationsRan: migrations.length };
416
+ }
417
+ function migrateOnLocal(name, cwd = ".") {
418
+ return migrate(name, {
419
+ getPath: (file) => import_node_path3.default.join(cwd, file),
420
+ read: import_fs_extra2.default.readJson,
421
+ write: import_fs_extra2.default.writeFile
422
+ });
423
+ }
424
+ function migrateOnRemote(name, commit2) {
425
+ return migrate(name, {
426
+ read: (file) => git.readJsonFromCommit(commit2, file)
427
+ });
428
+ }
429
+
430
+ // src/migrations/index.ts
431
+ async function migrateAll(autoCommit) {
432
+ let migrationsRan = (await migrateOnLocal("app")).migrationsRan;
433
+ const blocks = import_fs_extra3.default.existsSync(blocksDir) ? import_fs_extra3.default.readdirSync(blocksDir) : [];
434
+ for (const block of blocks) {
435
+ migrationsRan += (await migrateOnLocal(block, import_node_path4.default.join(blocksDir, block))).migrationsRan;
436
+ }
437
+ if (autoCommit && migrationsRan) {
438
+ import_prompts2.log.warn(fmt.yellow(`Migrations done and will be commited`));
439
+ await git.add(".");
440
+ await git.commit("chore: migrate blox schema");
441
+ }
442
+ }
443
+
444
+ // src/services/fs.ts
445
+ var import_node_path5 = __toESM(require("path"));
446
+ var import_fs_extra4 = __toESM(require("fs-extra"));
447
+ var import_ignore = __toESM(require("ignore"));
266
448
  var import_klaw = __toESM(require("klaw"));
449
+ var filterBlacklisted = (item) => {
450
+ return !item.includes("node_modules") && !item.includes(".git");
451
+ };
452
+ var deletePattern = async (cwd, patterns = []) => {
453
+ const ig = (0, import_ignore.default)().add(patterns);
454
+ for await (const file of (0, import_klaw.default)(cwd, { filter: filterBlacklisted })) {
455
+ const relativePath = import_node_path5.default.relative(cwd, file.path);
456
+ if (relativePath && ig.ignores(relativePath)) {
457
+ if (!await import_fs_extra4.default.exists(file.path)) {
458
+ continue;
459
+ }
460
+ debug(`deleting: ${relativePath}`);
461
+ await import_fs_extra4.default.remove(file.path);
462
+ }
463
+ }
464
+ };
465
+
466
+ // src/services/registry.ts
467
+ var import_node_path7 = __toESM(require("path"));
468
+ var import_fs_extra6 = __toESM(require("fs-extra"));
469
+ var import_klaw2 = __toESM(require("klaw"));
267
470
  var import_merge = __toESM(require("lodash/merge"));
268
471
 
269
472
  // src/shared/spinner.ts
270
- var import_prompts3 = require("@clack/prompts");
473
+ var import_prompts5 = require("@clack/prompts");
271
474
  var spinner = () => {
272
- const s = (0, import_prompts3.spinner)();
475
+ const s = (0, import_prompts5.spinner)();
273
476
  const minimal = isMinimalMode() || isDebugMode();
274
477
  return {
275
478
  start: (msg) => {
@@ -298,49 +501,40 @@ async function runTask(message, task) {
298
501
  }
299
502
 
300
503
  // src/services/config.ts
301
- var import_node_path3 = __toESM(require("path"));
504
+ var import_node_path6 = __toESM(require("path"));
302
505
  var import_env_paths = __toESM(require("env-paths"));
303
- var import_fs_extra2 = __toESM(require("fs-extra"));
304
-
305
- // src/config/index.ts
306
- var defaultConfig = {
307
- registries: ["https://tfs.aas.com.sa/Medad/BLOX/_git/default-registry"]
308
- };
309
- var basedOnFile = ".blox";
310
- var blocksDir = "blocks";
311
-
312
- // src/services/config.ts
506
+ var import_fs_extra5 = __toESM(require("fs-extra"));
313
507
  var appPaths = (0, import_env_paths.default)("blox", { suffix: "" });
314
- var configFilePath = import_node_path3.default.join(appPaths.config, "config.json");
508
+ var configFilePath = import_node_path6.default.join(appPaths.config, "config.json");
315
509
  var getLocalConfig = () => {
316
510
  try {
317
- return import_fs_extra2.default.readJSONSync(configFilePath);
511
+ return import_fs_extra5.default.readJSONSync(configFilePath);
318
512
  } catch {
319
513
  return defaultConfig;
320
514
  }
321
515
  };
322
516
  var updateLocalConfig = (config) => {
323
517
  debug("Update local config");
324
- import_fs_extra2.default.ensureFileSync(configFilePath);
518
+ import_fs_extra5.default.ensureFileSync(configFilePath);
325
519
  const current = getLocalConfig();
326
- import_fs_extra2.default.writeJsonSync(configFilePath, { ...current, ...config });
520
+ import_fs_extra5.default.writeJsonSync(configFilePath, { ...current, ...config });
327
521
  };
328
522
 
329
523
  // src/services/registry.ts
330
- var registriesDataPath = import_node_path4.default.join(appPaths.data, "registries");
524
+ var registriesDataPath = import_node_path7.default.join(appPaths.data, "registries");
331
525
  var syncRegistries = async () => {
332
526
  debug("Sync registries");
333
- import_fs_extra3.default.ensureDirSync(registriesDataPath);
527
+ import_fs_extra6.default.ensureDirSync(registriesDataPath);
334
528
  const config = getLocalConfig();
335
529
  return await runTask("Update registries", async () => {
336
530
  await Promise.all(
337
531
  config.registries.map(async (registry) => {
338
532
  debug(`update registry: ${registry}`);
339
533
  const repoName = registry.split("/").pop() || "";
340
- const repoDir = import_node_path4.default.join(registriesDataPath, repoName);
341
- if (!import_fs_extra3.default.existsSync(repoDir)) {
534
+ const repoDir = import_node_path7.default.join(registriesDataPath, repoName);
535
+ if (!import_fs_extra6.default.existsSync(repoDir)) {
342
536
  await git.clone(registry, "--depth 1", { cwd: registriesDataPath });
343
- } else if (import_fs_extra3.default.existsSync(import_node_path4.default.join(repoDir, ".git"))) {
537
+ } else if (import_fs_extra6.default.existsSync(import_node_path7.default.join(repoDir, ".git"))) {
344
538
  await git.update({ cwd: repoDir });
345
539
  } else {
346
540
  debug(`local registry`);
@@ -352,18 +546,24 @@ var syncRegistries = async () => {
352
546
  var getAvailableTemplates = async () => {
353
547
  debug("Get available templates");
354
548
  const templates = {};
355
- for await (const file of (0, import_klaw.default)(registriesDataPath, {
549
+ for await (const file of (0, import_klaw2.default)(registriesDataPath, {
356
550
  filter: (item) => !item.includes(".git")
357
551
  })) {
358
552
  if (file.path.endsWith(".json")) {
359
- const data = import_fs_extra3.default.readJSONSync(file.path);
553
+ const data = import_fs_extra6.default.readJSONSync(file.path);
360
554
  Object.entries(data.templates || {}).forEach(([templateName, template]) => {
361
555
  if (!template.source) {
362
- template.source = `${data.baseUrl}/template-${templateName}`;
556
+ template.source = `/template-${templateName}`;
557
+ }
558
+ if (template.source.startsWith("/")) {
559
+ template.source = data.baseUrl + template.source;
363
560
  }
364
561
  Object.entries(template.blocks || {}).forEach(([blockName, block]) => {
365
562
  if (!block.source) {
366
- block.source = `${data.baseUrl}/block-${templateName}-${blockName}`;
563
+ block.source = `/block-${templateName}-${blockName}`;
564
+ }
565
+ if (block.source.startsWith("/")) {
566
+ block.source = data.baseUrl + block.source;
367
567
  }
368
568
  });
369
569
  if (templates[templateName]) {
@@ -390,69 +590,74 @@ var getAvailableBlocks = async (templateInfo) => {
390
590
  return blocks;
391
591
  };
392
592
  var getAvailableVersions = async (id) => {
393
- const registries = import_fs_extra3.default.readdirSync(registriesDataPath);
593
+ const registries = import_fs_extra6.default.readdirSync(registriesDataPath);
394
594
  for (const registry of registries) {
395
- const versionsFile = import_node_path4.default.join(registriesDataPath, registry, "versions", `${id}.json`);
396
- if (import_fs_extra3.default.existsSync(versionsFile)) {
397
- return import_fs_extra3.default.readJSONSync(versionsFile);
595
+ const versionsFile = import_node_path7.default.join(registriesDataPath, registry, "versions", `${id}.json`);
596
+ if (import_fs_extra6.default.existsSync(versionsFile)) {
597
+ return import_fs_extra6.default.readJSONSync(versionsFile);
398
598
  }
399
599
  }
400
600
  };
401
601
 
402
602
  // src/services/template.ts
403
- var import_node_path5 = __toESM(require("path"));
603
+ var import_node_path8 = __toESM(require("path"));
404
604
  var import_ejs = __toESM(require("ejs"));
405
- var import_fs_extra4 = __toESM(require("fs-extra"));
406
- var import_klaw2 = __toESM(require("klaw"));
605
+ var import_fs_extra7 = __toESM(require("fs-extra"));
606
+ var import_klaw3 = __toESM(require("klaw"));
407
607
  async function replacePlaceholders(dir, context) {
408
608
  debug("Replace placeholders");
409
- for await (const file of (0, import_klaw2.default)(dir)) {
609
+ for await (const file of (0, import_klaw3.default)(dir)) {
410
610
  if (file.stats.isFile()) {
411
- const template = import_fs_extra4.default.readFileSync(file.path, "utf-8");
611
+ const template = import_fs_extra7.default.readFileSync(file.path, "utf-8");
412
612
  const rendered = import_ejs.default.render(template, context);
413
- import_fs_extra4.default.writeFileSync(file.path, rendered, "utf-8");
613
+ import_fs_extra7.default.writeFileSync(file.path, rendered, "utf-8");
414
614
  }
415
615
  }
416
616
  }
417
- function getPackage(cwd) {
418
- return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, "package.json"));
419
- }
420
617
  function getTemplateDef(cwd = ".") {
421
618
  debug("Get template def");
422
- const def = getPackage(cwd).blox;
619
+ const def = getBloxFile(cwd).definition;
423
620
  debug(def);
424
621
  return def;
425
622
  }
426
623
  function getBlockDef(cwd = ".") {
427
624
  debug("Get block def");
428
- const def = getPackage(cwd).blox;
625
+ const def = getBloxFile(cwd).definition;
429
626
  def && debug(def);
430
627
  return def;
431
628
  }
432
- function getBasedOnInfo(cwd = ".") {
629
+ function getBloxFile(cwd = ".") {
433
630
  try {
434
- return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, basedOnFile));
631
+ const file = import_fs_extra7.default.readJSONSync(import_node_path8.default.join(cwd, bloxFilePath));
632
+ if (!file.checkpoints) {
633
+ file.checkpoints = {};
634
+ }
635
+ return file;
435
636
  } catch {
436
637
  return {};
437
638
  }
438
639
  }
439
- function saveBasedOnInfo(info, cwd = ".") {
640
+ function saveBloxFile(info, cwd = ".") {
440
641
  debug("Save info");
441
- import_fs_extra4.default.writeFileSync(import_node_path5.default.join(cwd, basedOnFile), JSON.stringify(info, null, 2));
642
+ import_fs_extra7.default.writeFileSync(import_node_path8.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
442
643
  }
443
- function updateBasedOnInfo(updates, cwd = ".") {
444
- const info = getBasedOnInfo(cwd);
445
- saveBasedOnInfo({ ...info, ...updates }, cwd);
644
+ function updateCheckpoint(name, checkpoint, cwd = ".") {
645
+ const info = getBloxFile(cwd);
646
+ if (!info.checkpoints) {
647
+ info.checkpoints = {};
648
+ }
649
+ info.checkpoints[name] = checkpoint;
650
+ saveBloxFile(info, cwd);
446
651
  }
447
652
  function getUsedBlocks() {
448
653
  debug("Get used blocks");
449
654
  const blocks = [];
450
- if (import_fs_extra4.default.existsSync(blocksDir)) {
451
- import_fs_extra4.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
655
+ if (import_fs_extra7.default.existsSync(blocksDir)) {
656
+ import_fs_extra7.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
452
657
  if (!file.isDirectory()) {
453
658
  return;
454
659
  }
455
- const blockDef = getBlockDef(import_node_path5.default.join(blocksDir, file.name));
660
+ const blockDef = getBlockDef(import_node_path8.default.join(blocksDir, file.name));
456
661
  if (blockDef) {
457
662
  blocks.push(blockDef);
458
663
  }
@@ -473,11 +678,11 @@ function processTemplate(def) {
473
678
  return def;
474
679
  }
475
680
  function processBases(info) {
476
- if (!info || !info.bases) return {};
477
- Object.values(info.bases).forEach((base) => {
681
+ if (!info || !info.checkpoints) return {};
682
+ Object.values(info.checkpoints).forEach((base) => {
478
683
  if (!base.version) base.version = 0;
479
684
  });
480
- return info.bases;
685
+ return info.checkpoints;
481
686
  }
482
687
  function processBlocks(defs) {
483
688
  defs.forEach((def) => {
@@ -544,45 +749,11 @@ async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
544
749
  async function checkVersionsCompatibility() {
545
750
  const template = processTemplate(getTemplateDef());
546
751
  const usedBlocks = processBlocks(getUsedBlocks());
547
- const basesVersion = processBases(getBasedOnInfo());
752
+ const basesVersion = processBases(getBloxFile());
548
753
  basesVersion[template.name] = { version: template.version, commit: "" };
549
754
  await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
550
755
  }
551
756
 
552
- // src/shared/prompts/index.ts
553
- var import_prompts4 = require("@clack/prompts");
554
- var checkIfCanceled = (value) => {
555
- if ((0, import_prompts4.isCancel)(value)) {
556
- (0, import_prompts4.cancel)();
557
- process.exit(0);
558
- }
559
- };
560
- var error = (error2, exit = true) => {
561
- import_prompts4.log.error(
562
- fmt.red(
563
- typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
564
- )
565
- );
566
- exit && process.exit(-1);
567
- };
568
- var select = async (opts) => {
569
- const value = await (0, import_prompts4.select)(opts);
570
- checkIfCanceled(value);
571
- return value;
572
- };
573
- var text = async (opts) => {
574
- const value = await (0, import_prompts4.text)(opts);
575
- checkIfCanceled(value);
576
- return value;
577
- };
578
- var textList = async (opts) => {
579
- opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
580
- const value = await (0, import_prompts4.text)(opts);
581
- checkIfCanceled(value);
582
- opts.validate?.(value);
583
- return value.split(",");
584
- };
585
-
586
757
  // src/services/versions/select.ts
587
758
  async function selectVersion(remote, fromCommit) {
588
759
  const versionsData = await getAvailableVersions(remote);
@@ -628,20 +799,23 @@ function runInitScript(cwd) {
628
799
  var addBlock = async (block, blocks) => {
629
800
  const blockPath = `blocks/${block}`;
630
801
  const blockRegistryData = blocks[block];
631
- if (!import_fs_extra5.default.existsSync(blockPath)) {
802
+ if (!import_fs_extra8.default.existsSync(blockPath)) {
632
803
  await runTask(
633
804
  { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
634
805
  async () => {
635
806
  await git.clone(blockRegistryData?.source || "", blockPath);
636
- let commit = await selectVersion(block);
637
- if (commit) {
638
- await git.resetToCommit(commit, blockPath);
807
+ let commit2 = await selectVersion(block);
808
+ if (commit2) {
809
+ await git.resetToCommit(commit2, blockPath);
639
810
  } else {
640
- commit = await git.getLatestCommitFromPath(blockPath);
811
+ commit2 = await git.getLatestCommitFromPath(blockPath);
641
812
  }
642
813
  await git.unInit(blockPath);
643
814
  await replacePlaceholders(blockPath, {});
644
- saveBasedOnInfo({ commit }, blockPath);
815
+ await migrateAll();
816
+ const def = getBlockDef(blockPath);
817
+ await deletePattern(blockPath, def.ignore);
818
+ updateCheckpoint(block, { commit: commit2 }, blockPath);
645
819
  }
646
820
  );
647
821
  await runTask("Run init script", async () => runInitScript(blockPath));
@@ -654,6 +828,7 @@ var addBlock = async (block, blocks) => {
654
828
  }
655
829
  };
656
830
  var add2 = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").action(async (block) => {
831
+ await migrateAll();
657
832
  await syncRegistries();
658
833
  try {
659
834
  const templateDef = getTemplateDef();
@@ -706,6 +881,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
706
881
  });
707
882
 
708
883
  // src/commands/init/index.ts
884
+ var import_fs_extra9 = __toESM(require("fs-extra"));
709
885
  var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").action(async ({ name, template }) => {
710
886
  await syncRegistries();
711
887
  try {
@@ -729,81 +905,92 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
729
905
  const task = spinner();
730
906
  task.start(`Fetch template`);
731
907
  await git.clone(templates[template]?.source || "", name);
732
- let commit = await selectVersion(template);
733
- if (commit) {
734
- await git.resetToCommit(commit, name);
908
+ let commit2 = await selectVersion(template);
909
+ if (commit2) {
910
+ await git.resetToCommit(commit2, name);
735
911
  } else {
736
- commit = await git.getLatestCommitFromPath(name);
912
+ commit2 = await git.getLatestCommitFromPath(name);
737
913
  }
738
914
  await git.unInit(name);
915
+ await migrateAll();
916
+ const def = getTemplateDef(name);
917
+ await deletePattern(name, def.ignore);
739
918
  await replacePlaceholders(name, { app: { name } });
740
- updateBasedOnInfo({ commit }, name);
919
+ updateCheckpoint(name, { commit: commit2 }, name);
741
920
  await git.init(name);
742
921
  task.stop(`App initialized in ${name}`);
743
922
  await runTask("Run init script", async () => runInitScript(name || ""));
744
923
  } catch (e) {
924
+ if (name && import_fs_extra9.default.existsSync(name)) {
925
+ await import_fs_extra9.default.remove(name);
926
+ }
927
+ error(e);
928
+ }
929
+ });
930
+
931
+ // src/commands/migrate/index.ts
932
+ var migrateSchema = command("migrate").description("Migrate blox schema").action(async () => {
933
+ try {
934
+ await migrateAll();
935
+ } catch (e) {
936
+ if (!isDebugMode()) {
937
+ import_prompts2.log.warn("Error happened, Will rollback changes");
938
+ await git.rollback();
939
+ }
745
940
  error(e);
746
941
  }
747
942
  });
748
943
 
749
944
  // src/commands/update/index.ts
750
- var import_prompts12 = require("@clack/prompts");
945
+ var import_prompts13 = require("@clack/prompts");
751
946
 
752
947
  // src/commands/update/utils.ts
753
- var import_node_path7 = __toESM(require("path"));
948
+ var import_node_path10 = __toESM(require("path"));
754
949
 
755
950
  // src/services/updater.ts
756
- var import_node_path6 = __toESM(require("path"));
757
- var import_fs_extra6 = __toESM(require("fs-extra"));
758
- var import_merge2 = __toESM(require("lodash/merge"));
759
- async function updateFromRemote(name, source = "", ignore = [], destPath = ".") {
951
+ var import_node_path9 = __toESM(require("path"));
952
+ var import_fs_extra10 = __toESM(require("fs-extra"));
953
+ async function updateFromRemote(name, source = "", ignore2 = [], destPath = ".") {
760
954
  debug("Updating from remote");
761
955
  await git.updateRemote(name, source);
762
- const basedOnInfo = getBasedOnInfo(destPath);
763
- const baseFromCommit = basedOnInfo.bases?.[name]?.commit;
764
- const fromCommit = baseFromCommit || basedOnInfo.commit;
765
- let toCommit = await selectVersion(name, fromCommit);
766
- if (!toCommit) {
767
- toCommit = await git.getLatestCommitFromRemote(name);
768
- }
956
+ const bloxFile = getBloxFile(destPath);
957
+ const fromCommit = bloxFile.checkpoints[name]?.commit;
769
958
  if (!fromCommit) {
770
959
  debug("Skip update, no fromCommit found");
771
960
  return;
772
961
  }
962
+ let toCommit = await selectVersion(name, fromCommit);
963
+ if (!toCommit) {
964
+ toCommit = await git.getLatestCommitFromRemote(name);
965
+ }
773
966
  debug({ fromCommit, toCommit });
774
967
  if (fromCommit == toCommit) {
775
968
  debug("No new version");
776
969
  return;
777
970
  }
778
- const remoteBloxFile = await git.readJsonFromRemote(toCommit, ".blox");
779
- for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.bases || {})) {
780
- const baseFrom = basedOnInfo.bases?.[baseName]?.commit;
781
- const updateBase = () => {
782
- if (!basedOnInfo.bases) {
783
- basedOnInfo.bases = {};
784
- }
785
- basedOnInfo.bases = (0, import_merge2.default)(basedOnInfo.bases, { [baseName]: baseInfo });
786
- };
971
+ const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[".blox"];
972
+ for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.checkpoints || {})) {
973
+ const baseFrom = bloxFile.checkpoints[baseName]?.commit;
787
974
  if (!baseFrom) {
788
- updateBase();
975
+ bloxFile.checkpoints[baseName] = baseInfo;
789
976
  continue;
790
977
  }
791
978
  const baseTo = baseInfo.commit;
792
979
  if (await git.isCommitOlder(baseFrom, baseTo)) {
793
- updateBase();
980
+ bloxFile.checkpoints[baseName] = baseInfo;
794
981
  } else {
795
982
  logWarningSection(
796
983
  `${baseName} is newer in project than template, make sure no breaking changes`
797
984
  );
798
985
  }
799
986
  }
800
- const patchFilePath = import_node_path6.default.join(destPath, "diff.patch");
801
- ignore.push("./.blox");
802
- await git.createPatch(fromCommit, toCommit, patchFilePath, ignore);
987
+ const patchFilePath = import_node_path9.default.join(destPath, "diff.patch");
988
+ ignore2.push("./.blox");
989
+ await git.createPatch(fromCommit, toCommit, patchFilePath, ignore2);
803
990
  const changes = await git.getChangesLog(fromCommit, toCommit);
804
991
  const deletePatchFile = async () => {
805
992
  if (!isDebugMode()) {
806
- await import_fs_extra6.default.unlink(patchFilePath);
993
+ await import_fs_extra10.default.unlink(patchFilePath);
807
994
  }
808
995
  debug("make sure to delete the patch file after you're done with it.");
809
996
  };
@@ -814,7 +1001,7 @@ async function updateFromRemote(name, source = "", ignore = [], destPath = ".")
814
1001
  if (errorMessage.includes("error:")) {
815
1002
  await deletePatchFile();
816
1003
  console.log(`${e}`.replace("error:", fmt.red("error:")));
817
- error("Failed to apply changes.");
1004
+ throw new Error("Failed to apply changes.");
818
1005
  }
819
1006
  }
820
1007
  if (changes.trim() !== "") {
@@ -824,17 +1011,13 @@ async function updateFromRemote(name, source = "", ignore = [], destPath = ".")
824
1011
  );
825
1012
  }
826
1013
  await deletePatchFile();
827
- if (baseFromCommit) {
828
- if (!basedOnInfo.bases) {
829
- basedOnInfo.bases = {};
830
- }
831
- const remotePackageJson = await git.readJsonFromRemote(name, "package.json");
832
- const version2 = remotePackageJson.blox?.version;
833
- basedOnInfo.bases[name] = { commit: toCommit, version: version2 };
1014
+ bloxFile.checkpoints[name] = { commit: toCommit };
1015
+ if (bloxFile.definition.name === name) {
1016
+ bloxFile.definition = remoteBloxFile.definition;
834
1017
  } else {
835
- basedOnInfo.commit = toCommit;
1018
+ bloxFile.checkpoints[name].version = remoteBloxFile.definition.version;
836
1019
  }
837
- saveBasedOnInfo(basedOnInfo, destPath);
1020
+ saveBloxFile(bloxFile, destPath);
838
1021
  }
839
1022
 
840
1023
  // src/commands/update/utils.ts
@@ -842,7 +1025,7 @@ async function updateApp(templateInfo, templates) {
842
1025
  await runTask({ start: "Update App", end: "Updated App" }, async () => {
843
1026
  const template = templates[templateInfo.name];
844
1027
  if (!template) {
845
- error("Selected template not available in registries");
1028
+ error(`Selected template: ${templateInfo.name} not available in registries`);
846
1029
  return;
847
1030
  }
848
1031
  await updateFromRemote(templateInfo.name, template.source, templateInfo.ignore);
@@ -864,14 +1047,15 @@ async function updateAppBases(templateInfo, templates) {
864
1047
  }
865
1048
  }
866
1049
  async function updateBlock(block, blocks) {
867
- const blockDef = blocks[block];
868
- const blockPath = import_node_path7.default.join(blocksDir, block);
1050
+ const blockRegistryData = blocks[block];
1051
+ const blockPath = import_node_path10.default.join(blocksDir, block);
1052
+ const blockDef = getBlockDef(blockPath);
869
1053
  await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
870
- if (!blockDef) {
871
- error("Selected block not available in registries", false);
1054
+ if (!blockRegistryData) {
1055
+ error(`Selected block: ${block} not available in registries`, false);
872
1056
  return;
873
1057
  }
874
- await updateFromRemote(block, blockDef.source, blockDef.ignore, blockPath);
1058
+ await updateFromRemote(block, blockRegistryData.source, blockDef.ignore, blockPath);
875
1059
  });
876
1060
  }
877
1061
 
@@ -879,6 +1063,11 @@ async function updateBlock(block, blocks) {
879
1063
  var update2 = command("update").description("Update app/block").alias("u").addOption(
880
1064
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
881
1065
  ).option("-b, --block <name>", "Block to update, valid only with scope block").action(async (args) => {
1066
+ if (await git.hasUncommittedChanges()) {
1067
+ import_prompts13.log.warn(fmt.yellow("Make sure to commit any changes first"));
1068
+ return;
1069
+ }
1070
+ await migrateAll(true);
882
1071
  await syncRegistries();
883
1072
  const templateDef = getTemplateDef();
884
1073
  const availableBlocks = await getAvailableBlocks(templateDef);
@@ -916,7 +1105,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
916
1105
  await checkVersionsCompatibility();
917
1106
  } catch (e) {
918
1107
  if (!isDebugMode()) {
919
- import_prompts12.log.warn("Error happened, Will rollback changes");
1108
+ import_prompts13.log.warn("Error happened, Will rollback changes");
920
1109
  await git.rollback();
921
1110
  }
922
1111
  error(e);
@@ -934,11 +1123,14 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
934
1123
  });
935
1124
 
936
1125
  // src/commands/index.ts
937
- var commands = [init2, add2, update2, conf, upgrade];
1126
+ var commands = [init2, add2, update2, conf, upgrade, migrateSchema];
938
1127
 
939
1128
  // bin/run.ts
940
- import_extra_typings2.program.name("blox").version(version);
941
- import_extra_typings2.program.option("-d, --debug", "work in debug mode");
942
- import_extra_typings2.program.option("-m, --minimal", "work in minimal mode");
943
- commands.forEach((cmd) => import_extra_typings2.program.addCommand(cmd));
944
- import_extra_typings2.program.parse();
1129
+ async function main() {
1130
+ import_extra_typings2.program.name("blox").version(version);
1131
+ import_extra_typings2.program.option("-d, --debug", "work in debug mode");
1132
+ import_extra_typings2.program.option("-m, --minimal", "work in minimal mode");
1133
+ commands.forEach((cmd) => import_extra_typings2.program.addCommand(cmd));
1134
+ import_extra_typings2.program.parse();
1135
+ }
1136
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naseej/blox",
3
- "version": "0.2.0",
3
+ "version": "1.1.0",
4
4
  "description": "blox cli",
5
5
  "bin": {
6
6
  "blox": "./bin/run"
@@ -72,6 +72,7 @@
72
72
  "commander": "12.1.0",
73
73
  "ms": "2.1.3",
74
74
  "dayjs": "1.11.13",
75
- "lodash": "^4.17.21"
75
+ "lodash": "^4.17.21",
76
+ "ignore": "^7.0.5"
76
77
  }
77
78
  }
package/readme.md CHANGED
@@ -50,6 +50,7 @@ Options:
50
50
  * [update](#update)
51
51
  * [conf](#conf)
52
52
  * [upgrade](#upgrade)
53
+ * [migrate](#migrate)
53
54
 
54
55
  #### init
55
56
 
@@ -126,6 +127,17 @@ blox upgrade
126
127
 
127
128
  Upgrade blox cli to latest version
128
129
  ```
130
+ #### migrate
131
+
132
+ ```sh
133
+ blox migrate --help
134
+ ```
135
+
136
+ ```
137
+ blox migrate
138
+
139
+ Migrate blox schema
140
+ ```
129
141
 
130
142
  ### Docs
131
143