@makoojs/cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.CN.md +93 -345
  2. package/README.md +93 -345
  3. package/dist/bin.js +516 -1151
  4. package/dist/cli/commands/build.d.ts +2 -0
  5. package/dist/cli/commands/dev/DevTerminal.d.ts +51 -0
  6. package/dist/cli/commands/dev/dev.d.ts +2 -0
  7. package/dist/cli/commands/preview.d.ts +2 -0
  8. package/dist/cli/tasks/renderTasks.d.ts +2 -0
  9. package/dist/{shared → cli}/terminalColor.d.ts +2 -0
  10. package/dist/cli/version.d.ts +1 -0
  11. package/dist/config/defaults.d.ts +3 -24
  12. package/dist/config/errors.d.ts +14 -0
  13. package/dist/config/resolve.d.ts +6 -18
  14. package/dist/config/types.d.ts +8 -105
  15. package/dist/config/validation.d.ts +4 -7
  16. package/dist/index.cjs +121 -38
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +1036 -3240
  19. package/dist/session/DevSession.d.ts +13 -0
  20. package/dist/session/types.d.ts +22 -0
  21. package/dist/vite/makoo.d.ts +3 -0
  22. package/dist/vite/makooDev.d.ts +7 -0
  23. package/package.json +8 -13
  24. package/dist/command/_util.d.ts +0 -8
  25. package/dist/command/add.d.ts +0 -1
  26. package/dist/command/build.d.ts +0 -1
  27. package/dist/command/dev.d.ts +0 -1
  28. package/dist/command/inspect.d.ts +0 -35
  29. package/dist/config/config.d.ts +0 -3
  30. package/dist/error/MakooCliError.d.ts +0 -58
  31. package/dist/generator/generator.d.ts +0 -3
  32. package/dist/generator/render/import/importAdapter.d.ts +0 -3
  33. package/dist/generator/render/import/importComp.d.ts +0 -3
  34. package/dist/generator/render/import/importMakooRuntime.d.ts +0 -1
  35. package/dist/generator/render/import/importManifest.d.ts +0 -3
  36. package/dist/generator/render/import/importRuntimeSetup.d.ts +0 -1
  37. package/dist/generator/render/init/initMakooRuntime.d.ts +0 -4
  38. package/dist/generator/render/init/registerComp.d.ts +0 -3
  39. package/dist/generator/render/init/registerListener.d.ts +0 -4
  40. package/dist/generator/render/run/renderMakooStart.d.ts +0 -1
  41. package/dist/generator/render/util/match.d.ts +0 -1
  42. package/dist/generator/render/util/value.d.ts +0 -1
  43. package/dist/generator/types.d.ts +0 -27
  44. package/dist/manifest/index.cjs +0 -1
  45. package/dist/manifest/index.d.ts +0 -2
  46. package/dist/manifest/index.js +0 -7
  47. package/dist/scanner/collectDependenics.d.ts +0 -2
  48. package/dist/scanner/load/loadManifes.d.ts +0 -3
  49. package/dist/scanner/load/loadMeta.d.ts +0 -2
  50. package/dist/scanner/manifestBinding.d.ts +0 -14
  51. package/dist/scanner/scanner.d.ts +0 -3
  52. package/dist/scanner/types.d.ts +0 -50
  53. package/dist/scanner/util.d.ts +0 -2
  54. package/dist/scanner/validation.d.ts +0 -183
  55. package/dist/vitePlugin/hmrController.d.ts +0 -6
  56. package/dist/vitePlugin/makoo.d.ts +0 -3
  57. package/dist/vitePlugin/makooMonkey.d.ts +0 -3
  58. package/dist/vitePlugin/types.d.ts +0 -18
  59. package/dist/vitePlugin/virtualModule.d.ts +0 -2
  60. package/dist/vitePlugin/watchList.d.ts +0 -5
  61. /package/dist/{command → cli}/bin.d.ts +0 -0
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/command/bin.ts
4
- import { MakooError as MakooError2 } from "@makoojs/core";
3
+ // src/cli/bin.ts
4
+ import { MakooError } from "@makoojs/core";
5
5
 
6
6
  // ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
7
7
  function toArr(any) {
@@ -619,201 +619,21 @@ var CAC = class extends EventTarget {
619
619
  };
620
620
  var cac = (name = "") => new CAC(name);
621
621
 
622
- // src/command/add.ts
623
- import { existsSync as existsSync2 } from "fs";
624
- import { mkdir, writeFile as writeFile2 } from "fs/promises";
625
- import { join as join2 } from "path";
626
-
627
- // src/config/defaults.ts
628
- import process2 from "process";
629
- var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"];
630
- var ESM_IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|\bexport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g;
631
- var CJS_IMPORT_RE = /\brequire\s*\(['"]([^'"]+)['"]\)/g;
632
- var REACT_EXTENSIONS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
633
- var VUE_EXTENSIONS = /* @__PURE__ */ new Set([".vue"]);
634
- var DEFAULT_SOURCE_DIR = "injections";
635
- var DEFAULT_MANIFEST_FILE_NAME = "manifest";
636
- var DEFAULT_SOURCE_CONFIG = {
637
- dir: DEFAULT_SOURCE_DIR,
638
- // '*' matches any single path segment (bare directory name).
639
- // '**/*' would require a '/' and never match top-level folder names via picomatch.
640
- include: ["*"],
641
- exclude: [],
642
- manifest: DEFAULT_MANIFEST_FILE_NAME
643
- };
644
- var DEFAULT_INJECTION_DEFAULTS = {
645
- alive: false,
646
- scope: "local",
647
- timeout: 5e3,
648
- hooks: {}
649
- };
650
- var DEFAULT_MONKEY_SERVER_CONFIG = {
651
- open: process2.platform === "win32" || process2.platform === "darwin",
652
- prefix: "server:"
653
- };
654
-
655
- // src/error/MakooCliError.ts
656
- import { relative } from "path";
657
- import process3 from "process";
658
- import { ErrorCode, MakooError } from "@makoojs/core";
659
- var ModuleAlreadyExistsError = class extends MakooError {
660
- constructor(message, code = ErrorCode.CLI_MODULE_ALREADY_EXISTS, cause) {
661
- super(message, void 0, code, cause);
662
- this.name = "ModuleAlreadyExistsError";
663
- }
664
- };
665
- var LoadViteMakooConfigError = class extends MakooError {
666
- constructor(message, code, cause) {
667
- super(message, void 0, code, cause);
668
- this.name = "LoadViteMakooConfigError";
669
- }
670
- };
671
- var RuntimeSetupNotFoundError = class extends MakooError {
672
- constructor(file, code = ErrorCode.CLI_RUNTIME_SETUP_NOT_FOUND, cause) {
673
- super(
674
- `Runtime setup file not found at ${file}`,
675
- [{ path: "runtime.setup", message: file }],
676
- code,
677
- cause
678
- );
679
- this.name = "RuntimeSetupNotFoundError";
680
- }
681
- };
682
- var ManifestValidationError = class extends MakooError {
683
- constructor(file, zodIssues, code = ErrorCode.CLI_MANIFEST_VALIDATION_FAIL, cause) {
684
- const issues = zodIssues.map(toMakooIssue);
685
- const rel = relative(process3.cwd(), file);
686
- super(`Invalid manifest at ${rel}`, issues, code, cause);
687
- this.name = "ManifestValidationError";
688
- }
689
- };
690
- var UnknownFrameworkError = class extends MakooError {
691
- constructor(componentPath, code = ErrorCode.CLI_UNKNOWN_FRAMEWORK, cause) {
692
- super(
693
- `Cannot infer framework from "${componentPath}". Set "framework" explicitly ("Vue" or "React") in the module manifest.`,
694
- [{ path: "framework", message: `cannot infer from "${componentPath}"` }],
695
- code,
696
- cause
697
- );
698
- this.name = "UnknownFrameworkError";
699
- }
700
- };
701
- var ComponentNotFoundError = class extends MakooError {
702
- constructor(injectionName, code = ErrorCode.CLI_COMPONENT_NOT_FOUND, cause) {
703
- super(
704
- `Missing component path for injection "${injectionName}"`,
705
- [{ path: "component", message: "could not resolve component path" }],
706
- code,
707
- cause
708
- );
709
- this.name = "ComponentNotFoundError";
710
- }
711
- };
712
- var UnsupportedFrameworkGenerationError = class extends MakooError {
713
- constructor(ext, code = ErrorCode.CLI_UNSUPPORTED_FRAMEWORK, cause) {
714
- super(`Unsupported framework for template generation: ${ext}`, void 0, code, cause);
715
- this.name = "UnsupportedFrameworkError";
716
- }
717
- };
718
- var SourceDirNotFoundError = class extends MakooError {
719
- constructor(dir, code = ErrorCode.CLI_SOURCE_DIR_NOT_FOUND, cause) {
720
- super(`Source directory not found at ${dir}`, void 0, code, cause);
721
- this.name = "SourceDirNotFoundError";
722
- }
723
- };
724
- var ManifestNotFoundError = class extends MakooError {
725
- constructor(dir, code = ErrorCode.CLI_MANIFEST_NOT_FOUND, cause) {
726
- super(`No manifest found in source directory at ${dir}`, void 0, code, cause);
727
- this.name = "ManifestNotFoundError";
728
- }
729
- };
730
- var ManifestBindingNotFoundError = class extends MakooError {
731
- constructor(kind, id, code = ErrorCode.CLI_MANIFEST_BINDING_NOT_FOUND, cause) {
732
- const path5 = kind === "injectionDefaults" ? `${kind}.${id}` : `${kind}s.${id}`;
733
- const label = kind === "injectionDefaults" ? "injection defaults" : kind;
734
- super(
735
- `Missing manifest binding for ${label} "${id}"`,
736
- [{ path: path5, message: "could not resolve manifest source" }],
737
- code,
738
- cause
739
- );
740
- this.name = "ManifestBindingNotFoundError";
741
- }
742
- };
743
- var UnsupportedSelectorTargetError = class extends MakooError {
744
- constructor(file, path5, target, code = ErrorCode.CLI_SELECTOR_TARGET_UNSUPPORTED, cause) {
745
- const rel = relative(process3.cwd(), file);
746
- super(
747
- `Unsupported selector target "${target}" in manifest at ${rel}`,
748
- [{ path: path5, message: "must be a CSS selector; document and window are not supported" }],
749
- code,
750
- cause
751
- );
752
- this.name = "UnsupportedSelectorTargetError";
753
- }
754
- };
755
- var ManifestLoadError = class extends MakooError {
756
- constructor(path5, code = ErrorCode.CLI_MANIFEST_LOAD_FAIL, cause) {
757
- super(
758
- `Failed to load manifest at ${path5}`,
759
- [{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
760
- code,
761
- cause
762
- );
763
- this.name = "ManifestLoadError";
764
- }
765
- };
766
- var ModuleManifestLoadError = class extends MakooError {
767
- constructor(path5, code = ErrorCode.CLI_MODULE_MANIFEST_LOAD_FAIL, cause) {
768
- super(
769
- `Failed to load module manifest at ${path5}`,
770
- [{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
771
- code,
772
- cause
773
- );
774
- this.name = "ModuleManifestLoadError";
775
- }
776
- };
777
- var NoEnabledTasksError = class extends MakooError {
778
- constructor(code = ErrorCode.CLI_NO_ENABLED_TASKS, cause) {
779
- super(
780
- "No enabled tasks \u2014 all injections and listeners are disabled or filtered out",
781
- void 0,
782
- code,
783
- cause
784
- );
785
- this.name = "NoEnabledTasksError";
786
- }
787
- };
788
- function formatZodPath(path5) {
789
- if (path5.length === 0) return "(root)";
790
- return path5.filter((p) => typeof p !== "symbol").map((p) => typeof p === "number" ? `[${p}]` : p).join(".");
791
- }
792
- function formatZodMessage(issue) {
793
- if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) {
794
- return "is required";
795
- }
796
- return issue.message;
797
- }
798
- function toMakooIssue(issue) {
799
- return {
800
- path: formatZodPath(issue.path),
801
- message: formatZodMessage(issue)
802
- };
622
+ // src/cli/commands/build.ts
623
+ import { build } from "vite";
624
+ async function buildCommand(config) {
625
+ await build(config);
803
626
  }
804
627
 
805
- // src/command/_util.ts
806
- import { existsSync } from "fs";
807
- import { readdir, readFile, writeFile } from "fs/promises";
628
+ // src/cli/commands/dev/dev.ts
629
+ import { createServer } from "vite";
630
+
631
+ // src/cli/version.ts
632
+ import { readFile } from "fs/promises";
808
633
  import { dirname, join } from "path";
809
634
  import { fileURLToPath } from "url";
810
- import { ErrorCode as ErrorCode2 } from "@makoojs/core";
811
- import { createJiti } from "jiti";
812
- import { loadConfigFromFile } from "vite";
813
- async function loadCliVersion(cliVersionCache2) {
814
- if (cliVersionCache2) {
815
- return cliVersionCache2;
816
- }
635
+ async function loadCliVersion(cliVersionCache) {
636
+ if (cliVersionCache) return cliVersionCache;
817
637
  let currentDir = dirname(fileURLToPath(import.meta.url));
818
638
  while (true) {
819
639
  const packagePath = join(currentDir, "package.json");
@@ -821,1023 +641,568 @@ async function loadCliVersion(cliVersionCache2) {
821
641
  const content = await readFile(packagePath, "utf-8");
822
642
  const packageJson = JSON.parse(content);
823
643
  if (packageJson.name === "@makoojs/cli" && packageJson.version) {
824
- cliVersionCache2 = packageJson.version;
825
- return cliVersionCache2;
644
+ return packageJson.version;
826
645
  }
827
646
  } catch {
828
647
  }
829
648
  const parentDir = dirname(currentDir);
830
- if (parentDir === currentDir) {
831
- break;
832
- }
649
+ if (parentDir === currentDir) break;
833
650
  currentDir = parentDir;
834
651
  }
835
652
  return "0.0.0";
836
653
  }
837
- async function loadMakooConfig() {
838
- const root = process.cwd();
839
- const result = await loadConfigFromFile(
840
- { command: "build", mode: "production" },
841
- void 0,
842
- root
843
- );
844
- if (!result) {
845
- throw new LoadViteMakooConfigError(
846
- `No vite config file found in "${root}". Make sure a vite.config.ts (or .js/.mts) exists.`,
847
- ErrorCode2.CLI_VITE_CONFIG_NOT_FOUND
848
- );
849
- }
850
- const plugins = (result.config.plugins ?? []).flat().filter((p) => p != null && p !== false);
851
- const makooPlugin = plugins.find(
852
- (p) => p.name === "vite-plugin-makoo"
853
- );
854
- if (!makooPlugin) {
855
- throw new LoadViteMakooConfigError(
856
- `makoo plugin not found in vite config at "${result.path}". Make sure makoo() is included in your plugins array.`,
857
- ErrorCode2.CLI_PLUGIN_NOT_FOUND
858
- );
859
- }
860
- return makooPlugin.__makoo;
861
- }
862
- function getExtName(framework) {
863
- const lowerFramework = framework.toLowerCase();
864
- if (lowerFramework === "vue") {
865
- return ".vue";
866
- }
867
- if (lowerFramework === "react") {
868
- if (existsSync(join(process.cwd(), "tsconfig.json"))) {
869
- return ".tsx";
870
- }
871
- return ".jsx";
872
- }
873
- return null;
874
- }
875
- async function updateManifest(moduleName, updateData) {
876
- const sourcePath = join(process.cwd(), DEFAULT_SOURCE_DIR);
877
- const sourceFiles = await readdir(sourcePath);
878
- let manifestName = null;
879
- for (const file of sourceFiles) {
880
- if ("manifest" === file.split(".")[0]) {
881
- manifestName = file;
882
- break;
883
- }
884
- }
885
- const merged = { injections: { [moduleName]: updateData } };
886
- if (!manifestName) {
887
- const newManifestPath = join(sourcePath, "manifest.ts");
888
- await writeFile(
889
- newManifestPath,
890
- `import { defineInjections } from "@makoojs/cli/manifest";
891
- export default defineInjections(${JSON.stringify(merged, null, 2)})
892
- `,
893
- "utf-8"
894
- );
895
- return;
896
- }
897
- const manifestPath = join(sourcePath, manifestName);
898
- const manifestContent = await readFile(manifestPath, "utf-8");
899
- const jiti = createJiti(sourcePath, { moduleCache: false });
900
- const existing = await jiti.import(manifestPath, { default: true });
901
- const injections = existing.injections;
902
- let updatedInjections;
903
- if (Array.isArray(injections)) {
904
- updatedInjections = [...injections, { name: moduleName, ...updateData }];
905
- } else if (injections && typeof injections === "object") {
906
- updatedInjections = {
907
- ...injections,
908
- [moduleName]: updateData
909
- };
910
- } else {
911
- updatedInjections = { [moduleName]: updateData };
912
- }
913
- Object.assign(merged, { ...existing, injections: updatedInjections });
914
- const updated = manifestContent.replace(
915
- /defineInjections\s*\(\s*([\s\S]*?)\s*\)\s*;?\s*$/,
916
- `defineInjections(${JSON.stringify(merged, null, 2)})`
917
- );
918
- await writeFile(manifestPath, updated, "utf-8");
919
- }
920
- function moduleTemplate(framework) {
921
- switch (framework) {
922
- case "Vue":
923
- return vueTemplate();
924
- case "React":
925
- return reactTemplate();
926
- default:
927
- throw new UnsupportedFrameworkGenerationError(framework);
928
- }
929
- }
930
- function vueTemplate() {
931
- return `<template>
932
- <div>hello-Vue !!</div>
933
- </template>
934
- `;
935
- }
936
- function reactTemplate() {
937
- return `export default function App() {
938
- return <div>hello-React !!</div>;
939
- }
940
- `;
941
- }
942
654
 
943
- // src/command/add.ts
944
- async function addCommand(moduleName, framework) {
945
- const cwd = process.cwd();
946
- const sourceDir = join2(cwd, DEFAULT_SOURCE_DIR);
947
- const moduleDir = join2(sourceDir, moduleName);
948
- const extName = getExtName(framework);
949
- if (!extName) throw new UnsupportedFrameworkGenerationError(framework);
950
- const appPath = join2(moduleDir, `App${extName}`);
951
- if (existsSync2(moduleDir)) {
952
- throw new ModuleAlreadyExistsError(`Module "${moduleName}" already exists`);
953
- }
954
- await mkdir(moduleDir, { recursive: true });
955
- await writeFile2(appPath, moduleTemplate(framework));
956
- await updateManifest(moduleName, {
957
- injectAt: "body",
958
- component: `./${moduleName}/app${extName}`
959
- });
960
- }
655
+ // src/cli/commands/dev/DevTerminal.ts
656
+ import { emitKeypressEvents } from "readline";
657
+ import { createLogUpdate } from "log-update";
961
658
 
962
- // src/command/build.ts
963
- import { build } from "vite";
964
- async function buildCommand() {
965
- await build();
966
- }
659
+ // src/vite/makooDev.ts
660
+ var bindDevSession = /* @__PURE__ */ Symbol("makooDev.bindSession");
967
661
 
968
- // src/command/dev.ts
969
- import { createServer } from "vite";
662
+ // src/cli/tasks/renderTasks.ts
663
+ import Table from "cli-table3";
970
664
 
971
- // src/shared/terminalColor.ts
665
+ // src/cli/terminalColor.ts
972
666
  var ansi = {
973
667
  reset: "\x1B[0m",
974
668
  bold: "\x1B[1m",
975
669
  cyan: "\x1B[36m",
976
670
  deepPink: "\x1B[38;5;162m",
977
671
  green: "\x1B[32m",
672
+ red: "\x1B[31m",
673
+ yellow: "\x1B[33m",
978
674
  dim: "\x1B[2m"
979
675
  };
980
676
  var colorize = (value, ...codes) => `${codes.join("")}${value}${ansi.reset}`;
981
677
 
982
- // src/command/dev.ts
983
- var cliVersionCache = null;
984
- async function printDevBanner(server) {
985
- const cliVersion = await loadCliVersion(cliVersionCache);
986
- const title = `Makoo v${cliVersion}`;
987
- const urls = server.resolvedUrls;
988
- const localUrl = urls?.local[0];
989
- const networkUrl = urls?.network[0];
990
- console.log(`
991
- ${colorize(title, ansi.bold, ansi.cyan)}
992
- `);
993
- console.log(
994
- ` ${colorize("\u279C", ansi.green)} ${colorize("Local:", ansi.bold)} ${colorize(localUrl ?? "unavailable", ansi.cyan)}`
995
- );
996
- console.log(
997
- ` ${colorize("\u279C", ansi.green)} ${colorize("Network:", ansi.bold)} ${networkUrl ?? colorize("use --host to expose", ansi.dim)}`
998
- );
999
- }
1000
- async function devCommand() {
1001
- const server = await createServer();
1002
- await server.listen();
1003
- await printDevBanner(server);
1004
- server.bindCLIShortcuts({ print: true });
1005
- }
1006
-
1007
- // src/scanner/scanner.ts
1008
- import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
1009
- import path4 from "path";
1010
- import picomatch from "picomatch";
1011
-
1012
- // src/config/resolve.ts
1013
- import {
1014
- basename,
1015
- dirname as dirname2,
1016
- extname,
1017
- isAbsolute,
1018
- normalize,
1019
- resolve as resolvePath
1020
- } from "path";
1021
- import process4 from "process";
1022
-
1023
- // src/config/validation.ts
1024
- import { z } from "zod";
1025
- var AppConfigSchema = z.object({
1026
- name: z.string().min(1, "app.name is required"),
1027
- version: z.string().min(1, "app.version is required"),
1028
- description: z.string().optional()
1029
- });
1030
- var MonkeyConfigSchema = z.object({
1031
- server: z.object({}).passthrough().optional()
1032
- }).passthrough().superRefine((value, context) => {
1033
- if ("clientAlias" in value) {
1034
- context.addIssue({
1035
- code: z.ZodIssueCode.custom,
1036
- path: ["clientAlias"],
1037
- message: "monkey.clientAlias is not supported by makoo"
1038
- });
678
+ // src/cli/tasks/renderTasks.ts
679
+ function renderTaskStatus(status) {
680
+ switch (status) {
681
+ case "active":
682
+ return colorize("\u25CF active", ansi.green);
683
+ case "pending":
684
+ return colorize("\u25CF pending", ansi.yellow);
685
+ case "idle":
686
+ return colorize("\u25CF idle", ansi.dim);
1039
687
  }
1040
- if (value.server && typeof value.server === "object" && "mountGmApi" in value.server) {
1041
- context.addIssue({
1042
- code: z.ZodIssueCode.custom,
1043
- path: ["server", "mountGmApi"],
1044
- message: "monkey.server.mountGmApi is not supported by makoo"
1045
- });
1046
- }
1047
- });
1048
- var CliConfigSchema = z.object({
1049
- app: AppConfigSchema,
1050
- monkey: MonkeyConfigSchema.optional(),
1051
- source: z.object({}).passthrough().optional(),
1052
- runtime: z.object({}).passthrough().optional()
1053
- }).loose().superRefine((value, context) => {
1054
- if ("injector" in value) {
1055
- context.addIssue({
1056
- code: z.ZodIssueCode.custom,
1057
- path: ["injector"],
1058
- message: "injector is not supported in vite config; use manifest injectionDefaults instead"
688
+ }
689
+ function renderTasksTable(sanpshots) {
690
+ const tasks = sanpshots.flatMap((runtime) => runtime.tasks);
691
+ const lines = [colorize("Makoo Tasks", ansi.bold, ansi.deepPink), ""];
692
+ if (sanpshots.length === 0) {
693
+ lines.push(
694
+ colorize("\u25CF Runtime Session disconnected.", ansi.yellow),
695
+ "",
696
+ colorize("Waiting for reconnection.", ansi.dim)
697
+ );
698
+ return lines.join("\n");
699
+ }
700
+ if (tasks.length === 0) {
701
+ lines.push("No tasks registered.");
702
+ return lines.join("\n");
703
+ }
704
+ const showLabel = sanpshots.length > 1;
705
+ const showClient = new Set(sanpshots.map((runtime) => runtime.clientId)).size > 1;
706
+ for (const [index, runtime] of sanpshots.entries()) {
707
+ if (runtime.tasks.length === 0) continue;
708
+ if (showLabel) {
709
+ let label = `Makoo${runtime.runtimeId}`;
710
+ if (showClient) {
711
+ label = `Client ${runtime.clientId} \xB7 ${label}`;
712
+ }
713
+ lines.push(colorize(label, ansi.bold), "");
714
+ }
715
+ const table = new Table({
716
+ head: ["STATUS", "ID", "KIND", "TARGET"].map((heading) => colorize(heading, ansi.bold)),
717
+ style: { border: [], head: [] }
1059
718
  });
1060
- }
1061
- });
719
+ for (const task of runtime.tasks) {
720
+ table.push([
721
+ renderTaskStatus(task.status),
722
+ colorize(task.taskId, ansi.bold, ansi.cyan),
723
+ colorize(task.kind, ansi.deepPink),
724
+ colorize(`\u2192 ${task.injectAt}`, ansi.dim)
725
+ ]);
726
+ }
727
+ lines.push(table.toString());
728
+ if (index < sanpshots.length - 1) lines.push("");
729
+ }
730
+ const active = tasks.filter((task) => task.status === "active").length;
731
+ const pending = tasks.filter((task) => task.status === "pending").length;
732
+ const idle = tasks.filter((task) => task.status === "idle").length;
733
+ let total = `${tasks.length} tasks`;
734
+ if (tasks.length === 1) total = "1 task";
735
+ lines.push(
736
+ "",
737
+ `${total} \xB7 ${colorize(`${active} active`, ansi.green)} \xB7 ${colorize(`${pending} pending`, ansi.yellow)} \xB7 ${colorize(`${idle} idle`, ansi.dim)}`
738
+ );
739
+ return lines.join("\n");
740
+ }
1062
741
 
1063
- // src/config/resolve.ts
1064
- var toStringArray = (value, fallback) => {
1065
- if (Array.isArray(value)) {
1066
- return value;
1067
- }
1068
- if (typeof value === "undefined") {
1069
- return fallback;
1070
- }
1071
- return [value];
1072
- };
1073
- var resolveFileSystemPath = (root, value) => {
1074
- if (isAbsolute(value)) {
1075
- return normalize(value);
1076
- }
1077
- return normalize(resolvePath(root, value));
1078
- };
1079
- var resolveProjectRoot = (root) => {
1080
- return normalize(root ? resolvePath(root) : process4.cwd());
1081
- };
1082
- var inferFrameworkFromPath = (componentPath) => {
1083
- const extension = extname(componentPath).toLowerCase();
1084
- if (REACT_EXTENSIONS.has(extension)) {
1085
- return "React";
1086
- }
1087
- if (VUE_EXTENSIONS.has(extension)) {
1088
- return "Vue";
1089
- }
1090
- throw new UnknownFrameworkError(componentPath);
1091
- };
1092
- var resolveFramework = (framework, componentPath) => {
1093
- if (framework && framework !== "auto") {
1094
- return framework;
1095
- }
1096
- return inferFrameworkFromPath(componentPath);
1097
- };
1098
- var resolveMatchConfig = (match) => {
1099
- if (!match) {
1100
- return void 0;
1101
- }
1102
- if (Array.isArray(match)) {
1103
- return {
1104
- include: match
742
+ // src/cli/commands/dev/DevTerminal.ts
743
+ var ENTER_ALT_SCREEN = "\x1B[?1049h";
744
+ var LEAVE_ALT_SCREEN = "\x1B[?1049l";
745
+ var MAX_BUFFERED_LOGS = 1e3;
746
+ var DevTerminal = class {
747
+ constructor(server, cliVersion) {
748
+ this.server = server;
749
+ this.cliVersion = cliVersion;
750
+ this.session = server.config.plugins.find(
751
+ (plugin) => plugin.name === "makoo:dev"
752
+ )?.api?.session;
753
+ this.logger = server.config.logger;
754
+ this.originalInfo = this.logger.info;
755
+ this.originalWarn = this.logger.warn;
756
+ this.originalWarnOnce = this.logger.warnOnce;
757
+ this.originalError = this.logger.error;
758
+ this.originalClearScreen = this.logger.clearScreen;
759
+ this.logger.info = (message, options) => this.writeLog({ type: "info", message, options });
760
+ this.logger.warn = (message, options) => this.writeLog({ type: "warn", message, options });
761
+ this.logger.warnOnce = (message, options) => this.writeLog({ type: "warnOnce", message, options });
762
+ this.logger.error = (message, options) => this.writeLog({ type: "error", message, options });
763
+ this.logger.clearScreen = (type) => {
764
+ if (this.currentView === "logs") this.originalClearScreen.call(this.logger, type);
1105
765
  };
1106
766
  }
1107
- return {
1108
- include: match.include,
1109
- exclude: match.exclude
1110
- };
1111
- };
1112
- var deriveInjectionModuleId = (config, moduleDir, componentPath, fallbackName, index) => {
1113
- if (config.name) {
1114
- return config.name;
1115
- }
1116
- if (fallbackName) {
1117
- return fallbackName;
1118
- }
1119
- const moduleName = basename(moduleDir);
1120
- if (moduleName) {
1121
- return moduleName;
1122
- }
1123
- const componentName = basename(componentPath, extname(componentPath));
1124
- if (componentName) {
1125
- return componentName;
1126
- }
1127
- return `injection-${typeof index === "number" ? index + 1 : 1}`;
1128
- };
1129
- var deriveListenerId = (config, fallbackName, index) => {
1130
- if (config.name) {
1131
- return config.name;
1132
- }
1133
- if (fallbackName) {
1134
- return fallbackName;
1135
- }
1136
- return `listener-${typeof index === "number" ? index + 1 : 1}`;
1137
- };
1138
- var normalizeInjectionManifest = (injections) => {
1139
- const items = injections?.injections;
1140
- if (!items) {
1141
- return [];
1142
- }
1143
- if (Array.isArray(items)) {
1144
- return items;
1145
- }
1146
- return Object.entries(items).map(([name, config]) => ({
1147
- name,
1148
- ...config
1149
- }));
1150
- };
1151
- var normalizeListenerManifest = (manifest) => {
1152
- const items = manifest?.listeners;
1153
- if (!items) {
1154
- return [];
1155
- }
1156
- if (Array.isArray(items)) {
1157
- return items;
1158
- }
1159
- return Object.entries(items).map(([name, config]) => ({
1160
- name,
1161
- ...config
1162
- }));
1163
- };
1164
- var resolveSourceConfig = (config, root) => {
1165
- return {
1166
- dir: resolveFileSystemPath(root, DEFAULT_SOURCE_CONFIG.dir),
1167
- include: toStringArray(config?.include, DEFAULT_SOURCE_CONFIG.include),
1168
- exclude: toStringArray(config?.exclude, DEFAULT_SOURCE_CONFIG.exclude),
1169
- manifest: DEFAULT_MANIFEST_FILE_NAME
1170
- };
1171
- };
1172
- var resolveInjectionDefaults = (config) => {
1173
- return {
1174
- alive: config?.alive ?? DEFAULT_INJECTION_DEFAULTS.alive,
1175
- scope: config?.scope ?? DEFAULT_INJECTION_DEFAULTS.scope,
1176
- timeout: config?.timeout ?? DEFAULT_INJECTION_DEFAULTS.timeout,
1177
- hooks: config?.hooks
1178
- };
1179
- };
1180
- var resolveInjection = (config, options) => {
1181
- const root = resolveProjectRoot(options.root);
1182
- const source = options.source ?? resolveSourceConfig(void 0, root);
1183
- const injectionDefaults = options.injectionDefaults ?? resolveInjectionDefaults(void 0);
1184
- const componentBaseDir = options.moduleDir ? resolveFileSystemPath(root, options.moduleDir) : source.dir;
1185
- if (!options.componentPath) {
1186
- throw new ComponentNotFoundError(config.name ?? config.injectAt);
1187
- }
1188
- const componentPath = resolveFileSystemPath(root, options.componentPath);
1189
- const moduleDir = options.moduleDir ? componentBaseDir : componentPath ? dirname2(componentPath) : source.dir;
1190
- const {
1191
- component,
1192
- framework: _framework,
1193
- enabled: _enabled,
1194
- alive: _alive,
1195
- scope: _scope,
1196
- timeout: _timeout,
1197
- ...rest
1198
- } = config;
1199
- void component;
1200
- void _framework;
1201
- void _enabled;
1202
- void _alive;
1203
- void _scope;
1204
- void _timeout;
1205
- const moduleId = options.moduleId ?? deriveInjectionModuleId(
1206
- config,
1207
- moduleDir,
1208
- componentPath,
1209
- options.fallbackName,
1210
- options.index
1211
- );
1212
- const framework = resolveFramework(config.framework, componentPath);
1213
- const moduleManifestFile = options.moduleManifestFile ? resolveFileSystemPath(root, options.moduleManifestFile) : void 0;
1214
- return {
1215
- ...rest,
1216
- moduleId,
1217
- componentPath,
1218
- framework,
1219
- moduleDir,
1220
- moduleManifestFile,
1221
- enabled: config.enabled ?? true,
1222
- alive: config.alive ?? injectionDefaults.alive,
1223
- scope: config.scope ?? injectionDefaults.scope,
1224
- timeout: config.timeout ?? injectionDefaults.timeout,
1225
- match: resolveMatchConfig(config.match)
1226
- };
1227
- };
1228
- var resolveInjections = (injections, options) => {
1229
- const root = resolveProjectRoot(options.root);
1230
- const normalizedInjections = normalizeInjectionManifest(injections);
1231
- return normalizedInjections.map(
1232
- (injection, index) => resolveInjection(injection, {
1233
- root,
1234
- source: options.source,
1235
- injectionDefaults: options.injectionDefaults,
1236
- componentPath: resolvePath(options.source.dir, injection.component),
1237
- // `index` was a name of element
1238
- index
1239
- })
767
+ server;
768
+ cliVersion;
769
+ interactive = Boolean(
770
+ process.stdin.isTTY && process.stdout.isTTY && !process.env.CI
1240
771
  );
1241
- };
1242
- var resolveListener = (config, options) => {
1243
- const { name: _name, enabled: _enabled, match: _match, ...rest } = config;
1244
- void _name;
1245
- void _enabled;
1246
- void _match;
1247
- return {
1248
- ...rest,
1249
- listenerId: options.listenerId ?? deriveListenerId(config, options.fallbackName, options.index),
1250
- enabled: config.enabled ?? true,
1251
- match: resolveMatchConfig(config.match)
1252
- };
1253
- };
1254
- var resolveListeners = (manifest, options) => {
1255
- const normalizedListeners = normalizeListenerManifest(manifest);
1256
- return normalizedListeners.map(
1257
- (listener, index) => resolveListener(listener, {
1258
- root: options.root,
1259
- index
1260
- })
1261
- );
1262
- };
1263
-
1264
- // src/scanner/collectDependenics.ts
1265
- import { existsSync as existsSync3, readFileSync, statSync } from "fs";
1266
- import path from "path";
1267
- function isInsideRoot(file, root) {
1268
- const rel = path.relative(root, file);
1269
- return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
1270
- }
1271
- function isNodeModulesFile(file) {
1272
- return file.split(path.sep).includes("node_modules");
1273
- }
1274
- function isRelativeSpecifier(specifier) {
1275
- return specifier.startsWith("./") || specifier.startsWith("../");
1276
- }
1277
- function extractLocalSpecifiers(code) {
1278
- const specifiers = [];
1279
- for (const match of code.matchAll(ESM_IMPORT_RE)) {
1280
- const specifier = match[1] ?? match[2];
1281
- if (!specifier) continue;
1282
- if (!isRelativeSpecifier(specifier)) continue;
1283
- specifiers.push(specifier);
1284
- }
1285
- for (const match of code.matchAll(CJS_IMPORT_RE)) {
1286
- const specifier = match[1];
1287
- if (!specifier) continue;
1288
- if (!isRelativeSpecifier(specifier)) continue;
1289
- specifiers.push(specifier);
1290
- }
1291
- return specifiers;
1292
- }
1293
- function tryFile(filePath) {
1294
- if (!existsSync3(filePath)) return null;
1295
- if (!statSync(filePath).isFile()) return null;
1296
- return path.resolve(filePath);
1297
- }
1298
- function resolveLocalImport(fromDir, specifier) {
1299
- const base = path.resolve(fromDir, specifier);
1300
- const direct = tryFile(base);
1301
- if (direct) return direct;
1302
- for (const ext of SOURCE_EXTENSIONS) {
1303
- const withExt = tryFile(base + ext);
1304
- if (withExt) return withExt;
1305
- }
1306
- for (const ext of SOURCE_EXTENSIONS) {
1307
- const asIndex = tryFile(path.join(base, `index${ext}`));
1308
- if (asIndex) return asIndex;
1309
- }
1310
- return null;
1311
- }
1312
- function collectDependencies(entryFile, options) {
1313
- const root = path.resolve(options.root);
1314
- const visited = /* @__PURE__ */ new Set();
1315
- const result = /* @__PURE__ */ new Set();
1316
- const walk = (file) => {
1317
- const resolveFile = path.resolve(file);
1318
- if (visited.has(resolveFile)) return;
1319
- visited.add(resolveFile);
1320
- if (!isInsideRoot(resolveFile, root)) return;
1321
- if (isNodeModulesFile(resolveFile)) return;
1322
- if (!existsSync3(resolveFile)) return;
1323
- if (!statSync(resolveFile).isFile()) return;
1324
- if (options.includeEntry || resolveFile !== path.resolve(entryFile))
1325
- result.add(resolveFile);
1326
- const code = readFileSync(resolveFile, "utf8");
1327
- const dir = path.dirname(resolveFile);
1328
- for (const specifier of extractLocalSpecifiers(code)) {
1329
- const dep = resolveLocalImport(dir, specifier);
1330
- if (!dep) continue;
1331
- walk(dep);
772
+ session;
773
+ unsubscribe;
774
+ currentView = "logs";
775
+ previousView = "home";
776
+ selectedRuntime = 0;
777
+ runtimeCount = -1;
778
+ ready = false;
779
+ restarting = false;
780
+ actionRunning = false;
781
+ closed = false;
782
+ stopInput;
783
+ bufferedLogs = [];
784
+ omittedLogs = 0;
785
+ unreadErrors = 0;
786
+ screenOutput = createLogUpdate(process.stdout, { showCursor: true });
787
+ logger;
788
+ originalInfo;
789
+ originalWarn;
790
+ originalWarnOnce;
791
+ originalError;
792
+ originalClearScreen;
793
+ async start() {
794
+ process.once("exit", this.close);
795
+ if (this.session) {
796
+ this.server.config.inlineConfig.customLogger = this.logger;
797
+ this.server.config.inlineConfig[bindDevSession] = this.attachSession;
798
+ this.attachSession(this.session);
799
+ process.once("SIGINT", this.shutdown);
1332
800
  }
1333
- };
1334
- walk(entryFile);
1335
- return Array.from(result);
1336
- }
1337
-
1338
- // src/scanner/load/loadManifes.ts
1339
- import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
1340
- import path2 from "path";
1341
- import { createJiti as createJiti2 } from "jiti";
1342
-
1343
- // src/scanner/validation.ts
1344
- import { OBSERVE_EVENT_NAMES } from "@makoojs/core";
1345
- import { z as z2 } from "zod";
1346
- var ObserveEventNameSchema = z2.enum(OBSERVE_EVENT_NAMES);
1347
- var ObserveHookSchema = z2.custom((value) => typeof value === "function");
1348
- var HookSchema = z2.union([ObserveHookSchema, z2.array(ObserveHookSchema)]);
1349
- var LifecycleHookMapSchema = z2.record(z2.string(), HookSchema).refine((obj) => Object.keys(obj).every((k) => ObserveEventNameSchema.safeParse(k).success), {
1350
- message: "Invalid hook event name"
1351
- });
1352
- var InjectionDefaultsSchema = z2.object({
1353
- alive: z2.boolean().optional(),
1354
- scope: z2.enum(["local", "global"]).optional(),
1355
- timeout: z2.number().optional(),
1356
- hooks: LifecycleHookMapSchema.optional()
1357
- });
1358
- var InjectionMatchSchema = z2.union([
1359
- z2.array(z2.string()),
1360
- z2.object({
1361
- include: z2.array(z2.string()).optional(),
1362
- exclude: z2.array(z2.string()).optional()
1363
- })
1364
- ]);
1365
- var EventListenerSchema = z2.custom((value) => typeof value === "function");
1366
- var ActivitySignalSchema = z2.custom(
1367
- (value) => typeof value === "function"
1368
- );
1369
- var InjectionModuleListenerSchema = z2.object({
1370
- listenAt: z2.string(),
1371
- type: z2.string(),
1372
- callback: EventListenerSchema,
1373
- activitySignal: ActivitySignalSchema.optional()
1374
- });
1375
- var InjectionModuleSchema = z2.object({
1376
- name: z2.string().optional(),
1377
- injectAt: z2.string(),
1378
- component: z2.string(),
1379
- framework: z2.enum(["auto", "Vue", "React"]).optional(),
1380
- enabled: z2.boolean().optional(),
1381
- match: InjectionMatchSchema.optional(),
1382
- alive: z2.boolean().optional(),
1383
- scope: z2.enum(["local", "global"]).optional(),
1384
- timeout: z2.number().optional(),
1385
- hooks: LifecycleHookMapSchema.optional(),
1386
- on: InjectionModuleListenerSchema.optional()
1387
- });
1388
- var InjectionListenerSchema = InjectionModuleListenerSchema.extend({
1389
- name: z2.string().optional(),
1390
- enabled: z2.boolean().optional(),
1391
- match: InjectionMatchSchema.optional()
1392
- });
1393
- var InjectionManifestSchema = z2.object({
1394
- injectionDefaults: InjectionDefaultsSchema.optional(),
1395
- injections: z2.union([
1396
- z2.array(InjectionModuleSchema),
1397
- z2.record(z2.string(), InjectionModuleSchema.omit({ name: true }))
1398
- ]).optional(),
1399
- listeners: z2.union([
1400
- z2.array(InjectionListenerSchema),
1401
- z2.record(z2.string(), InjectionListenerSchema.omit({ name: true }))
1402
- ]).optional()
1403
- }).strict().refine((manifest) => manifest.injections || manifest.listeners, {
1404
- message: "Manifest must define injections or listeners"
1405
- });
1406
- function validateManifest(data, file) {
1407
- const result = InjectionManifestSchema.safeParse(data);
1408
- if (!result.success) {
1409
- throw new ManifestValidationError(file, result.error.issues);
1410
- }
1411
- assertManifestSelectorTargets(result.data, file);
1412
- return result.data;
1413
- }
1414
- function validateModuleMeta(data, file) {
1415
- const result = InjectionModuleSchema.safeParse(data);
1416
- if (!result.success) {
1417
- throw new ManifestValidationError(file, result.error.issues);
1418
- }
1419
- assertSelectorTarget(result.data.injectAt, file, "injectAt");
1420
- assertSelectorTarget(result.data.on?.listenAt, file, "on.listenAt");
1421
- return result.data;
1422
- }
1423
- function assertManifestSelectorTargets(manifest, file) {
1424
- if (Array.isArray(manifest.injections)) {
1425
- manifest.injections.forEach((injection, index) => {
1426
- assertSelectorTarget(injection.injectAt, file, `injections[${index}].injectAt`);
1427
- assertSelectorTarget(injection.on?.listenAt, file, `injections[${index}].on.listenAt`);
1428
- });
1429
- } else if (manifest.injections) {
1430
- Object.entries(manifest.injections).forEach(([id, injection]) => {
1431
- assertSelectorTarget(injection.injectAt, file, `injections.${id}.injectAt`);
1432
- assertSelectorTarget(injection.on?.listenAt, file, `injections.${id}.on.listenAt`);
1433
- });
1434
- }
1435
- if (Array.isArray(manifest.listeners)) {
1436
- manifest.listeners.forEach((listener, index) => {
1437
- assertSelectorTarget(listener.listenAt, file, `listeners[${index}].listenAt`);
1438
- });
1439
- } else if (manifest.listeners) {
1440
- Object.entries(manifest.listeners).forEach(([id, listener]) => {
1441
- assertSelectorTarget(listener.listenAt, file, `listeners.${id}.listenAt`);
1442
- });
1443
- }
1444
- }
1445
- function assertSelectorTarget(target, file, path5) {
1446
- if (target === "document" || target === "window") {
1447
- throw new UnsupportedSelectorTargetError(file, path5, target);
1448
- }
1449
- }
1450
-
1451
- // src/scanner/load/loadManifes.ts
1452
- async function loadManifest(source) {
1453
- if (!existsSync4(source.dir)) {
1454
- throw new SourceDirNotFoundError(source.dir);
1455
- }
1456
- const manifestName = source.manifest;
1457
- const jiti = createJiti2(source.dir, { moduleCache: false });
1458
- for (const entry of readdirSync(source.dir)) {
1459
- const fullPath = path2.join(source.dir, entry);
1460
- if (statSync2(fullPath).isFile() && path2.basename(entry, path2.extname(entry)) === manifestName) {
1461
- let raw;
1462
- try {
1463
- raw = await jiti.import(fullPath, { default: true });
1464
- } catch (err) {
1465
- throw new ManifestLoadError(
1466
- fullPath,
1467
- void 0,
1468
- err instanceof Error ? err : void 0
1469
- );
801
+ try {
802
+ await this.server.listen();
803
+ this.ready = true;
804
+ if (!this.session) {
805
+ this.logger.info(this.renderBanner());
806
+ this.server.bindCLIShortcuts({ print: true });
807
+ return;
1470
808
  }
1471
- return {
1472
- manifest: validateManifest(raw, fullPath),
1473
- manifestFile: fullPath,
1474
- dependencies: collectDependencies(fullPath, {
1475
- root: path2.resolve(source.dir, "..")
1476
- })
1477
- };
809
+ if (this.interactive) {
810
+ this.show("home");
811
+ this.bindShortcuts();
812
+ } else {
813
+ const runtimes = this.session.getTasks();
814
+ this.runtimeCount = runtimes.length;
815
+ this.logger.info(this.renderHome(runtimes));
816
+ }
817
+ } catch (error) {
818
+ this.close();
819
+ await this.server.close();
820
+ throw error;
1478
821
  }
1479
822
  }
1480
- return null;
1481
- }
1482
-
1483
- // src/scanner/load/loadMeta.ts
1484
- import fs from "fs";
1485
- import path3 from "path";
1486
- import { createJiti as createJiti3 } from "jiti";
1487
- async function loadMeta(root) {
1488
- const files = fs.readdirSync(root).filter((name) => {
1489
- const fullPath = path3.join(root, name);
1490
- return fs.statSync(fullPath).isFile();
1491
- });
1492
- if (files.length === 0) {
1493
- return null;
1494
- }
1495
- const jiti = createJiti3(root, { moduleCache: false });
1496
- for (const f of files) {
1497
- const fileName = path3.basename(f, path3.extname(f));
1498
- if (fileName === DEFAULT_MANIFEST_FILE_NAME) {
1499
- const fullPath = path3.join(root, f);
1500
- let raw;
1501
- try {
1502
- raw = await jiti.import(fullPath, { default: true });
1503
- } catch (err) {
1504
- throw new ModuleManifestLoadError(
1505
- fullPath,
1506
- void 0,
1507
- err instanceof Error ? err : void 0
1508
- );
823
+ attachSession = (session) => {
824
+ this.unsubscribe?.();
825
+ this.session = session;
826
+ this.selectedRuntime = 0;
827
+ this.unsubscribe = session.subscribe(this.refresh);
828
+ this.refresh();
829
+ };
830
+ // Session events, navigation and new logs all redraw through this entry point.
831
+ refresh = () => {
832
+ if (!this.ready || this.closed || !this.session) return;
833
+ const runtimes = this.session.getTasks();
834
+ this.selectedRuntime = runtimes.length === 0 ? 0 : this.selectedRuntime % runtimes.length;
835
+ if (!this.interactive) {
836
+ if (this.runtimeCount !== runtimes.length) {
837
+ this.runtimeCount = runtimes.length;
838
+ this.logger.info(` Runtime ${this.renderRuntimeStatus(runtimes.length)}`);
1509
839
  }
1510
- return {
1511
- moduleManifestFile: fullPath,
1512
- moduleConfig: validateModuleMeta(raw, fullPath),
1513
- dependencies: collectDependencies(fullPath, {
1514
- root: path3.resolve(root, "..", "..")
1515
- })
1516
- };
840
+ return;
841
+ }
842
+ switch (this.currentView) {
843
+ case "home":
844
+ this.draw(
845
+ this.renderHome(runtimes),
846
+ "Press a key to select an action. Press Ctrl+C to stop."
847
+ );
848
+ break;
849
+ case "tasks":
850
+ this.draw(
851
+ this.renderTasks(runtimes),
852
+ "Press t or Esc to return home. Press Ctrl+C to stop."
853
+ );
854
+ break;
855
+ case "help":
856
+ this.draw(this.renderHelp(), "Press h or Esc to return. Press Ctrl+C to stop.");
857
+ break;
858
+ case "logs":
859
+ break;
1517
860
  }
861
+ };
862
+ show(view) {
863
+ if (this.closed || !this.interactive) return;
864
+ const previous = this.currentView;
865
+ this.currentView = view;
866
+ if (previous === "logs" && view !== "logs") process.stdout.write(ENTER_ALT_SCREEN);
867
+ if (previous !== "logs" && view === "logs") {
868
+ this.screenOutput.clear();
869
+ process.stdout.write(LEAVE_ALT_SCREEN);
870
+ this.flushLogs();
871
+ this.originalInfo.call(
872
+ this.logger,
873
+ colorize("Press l or Esc to return home. Press Ctrl+C to stop.", ansi.dim)
874
+ );
875
+ }
876
+ this.refresh();
1518
877
  }
1519
- return null;
1520
- }
1521
-
1522
- // src/scanner/manifestBinding.ts
1523
- function buildManifestBindings(options) {
1524
- const manifestInjectionSources = /* @__PURE__ */ new Map();
1525
- const moduleInjectionSources = /* @__PURE__ */ new Map();
1526
- const listenerBindings = /* @__PURE__ */ new Map();
1527
- const injectionKeys = getCollectionKeys(options.manifest.injections);
1528
- const listenerKeys = getCollectionKeys(options.manifest.listeners);
1529
- const injectionConfigs = normalizeInjectionManifest(options.manifest);
1530
- const listenerConfigs = normalizeListenerManifest(options.manifest);
1531
- options.manifestInjections.forEach((injection, index) => {
1532
- manifestInjectionSources.set(injection.moduleId, {
1533
- config: injectionConfigs[index],
1534
- binding: {
1535
- manifestFile: options.manifestFile,
1536
- valuePath: ["injections", injectionKeys[index]]
1537
- }
1538
- });
1539
- });
1540
- options.moduleInjections.forEach((injection) => {
1541
- if (!injection.moduleManifestFile) return;
1542
- const config = options.moduleInjectionConfigs.get(injection.moduleId);
1543
- if (!config) {
1544
- throw new ManifestBindingNotFoundError("injection", injection.moduleId);
878
+ renderBanner() {
879
+ const urls = this.server.resolvedUrls;
880
+ return [
881
+ `
882
+ ${colorize("\u25C6", ansi.deepPink)} ${colorize(`Makoo v${this.cliVersion}`, ansi.bold, ansi.cyan)} ${colorize("dev", ansi.dim)}
883
+ `,
884
+ ` ${colorize("Local", ansi.dim)} ${colorize(urls?.local[0] ?? "unavailable", ansi.cyan)}`,
885
+ ` ${colorize("Network", ansi.dim)} ${urls?.network[0] ?? colorize("use --host to expose", ansi.dim)}`
886
+ ].join("\n");
887
+ }
888
+ renderRuntimeStatus(count) {
889
+ if (this.restarting) return "Restarting\u2026";
890
+ if (count === 0) return "Waiting for a browser runtime";
891
+ return `${count} browser runtime${count === 1 ? "" : "s"} connected`;
892
+ }
893
+ renderHome(runtimes) {
894
+ const waiting = this.restarting || runtimes.length === 0;
895
+ const total = this.bufferedLogs.length + this.omittedLogs;
896
+ const logs = `${total} new${this.unreadErrors ? ` \xB7 ${this.unreadErrors} error${this.unreadErrors === 1 ? "" : "s"}` : ""}`;
897
+ return [
898
+ this.renderBanner(),
899
+ ` ${colorize("Runtime", ansi.dim)} ${colorize(waiting ? "\u25CB" : "\u25CF", waiting ? ansi.yellow : ansi.green)} ${this.renderRuntimeStatus(runtimes.length)}`,
900
+ ` ${colorize("Logs", ansi.dim)} ${colorize(logs, this.unreadErrors ? ansi.red : ansi.dim)}`,
901
+ `
902
+ ${colorize("Actions", ansi.bold)}`,
903
+ ...this.hasInstallationPage() ? [` ${colorize("i", ansi.bold, ansi.cyan)} Open installation page`] : [],
904
+ ` ${colorize("t", ansi.bold, ansi.cyan)} View runtime tasks`,
905
+ ` ${colorize("l", ansi.bold, ansi.cyan)} View logs`,
906
+ ` ${colorize("r", ansi.bold, ansi.cyan)} Restart server`,
907
+ ` ${colorize("h", ansi.bold, ansi.cyan)} Show help`
908
+ ].join("\n");
909
+ }
910
+ renderTasks(runtimes) {
911
+ if (runtimes.length === 0) return "Makoo Tasks\n\nWaiting for a browser runtime";
912
+ const runtime = runtimes[this.selectedRuntime];
913
+ return [
914
+ `Runtime ${this.selectedRuntime + 1}/${runtimes.length} \xB7 Client ${runtime.clientId} \xB7 Makoo${runtime.runtimeId}`,
915
+ renderTasksTable([runtime]),
916
+ ...runtimes.length > 1 ? ["Press n to view the next runtime."] : []
917
+ ].join("\n\n");
918
+ }
919
+ renderHelp() {
920
+ return [
921
+ colorize("Shortcuts", ansi.bold),
922
+ "",
923
+ ...this.hasInstallationPage() ? [
924
+ ` ${colorize("i", ansi.bold, ansi.cyan)} open development script installation page`
925
+ ] : [],
926
+ ...[
927
+ ["t", "toggle Runtime tasks"],
928
+ ["n", "view next runtime tasks"],
929
+ ["l", "view logs / return home"],
930
+ ["r", "restart the server"],
931
+ ["u", "show server URLs"],
932
+ ["o", "open in browser"],
933
+ ["c", "clear console"],
934
+ ["q", "quit"],
935
+ ["h", "show help"]
936
+ ].map(
937
+ ([key, description]) => ` ${colorize(key, ansi.bold, ansi.cyan)} ${description}`
938
+ )
939
+ ].join("\n");
940
+ }
941
+ draw(content, hint) {
942
+ const lines = [content, ""];
943
+ const total = this.bufferedLogs.length + this.omittedLogs;
944
+ if (total > 0 && this.currentView !== "home") {
945
+ const status = `${total} new dev log${total === 1 ? "" : "s"}`;
946
+ const errors = this.unreadErrors > 0 ? ` \xB7 ${this.unreadErrors} error${this.unreadErrors === 1 ? "" : "s"}` : "";
947
+ lines.push(colorize(status + errors, this.unreadErrors ? ansi.red : ansi.dim));
1545
948
  }
1546
- moduleInjectionSources.set(injection.moduleId, {
1547
- config,
1548
- binding: {
1549
- manifestFile: injection.moduleManifestFile,
1550
- valuePath: []
1551
- }
1552
- });
1553
- });
1554
- options.manifestListeners.forEach((listener, index) => {
1555
- const baseBinding = {
1556
- manifestFile: options.manifestFile,
1557
- valuePath: ["listeners", listenerKeys[index]]
949
+ lines.push(colorize(hint, ansi.dim));
950
+ this.screenOutput(lines.join("\n"));
951
+ }
952
+ hasInstallationPage() {
953
+ return this.server.config.plugins.some((plugin) => plugin.name === "monkey:virtualHtml");
954
+ }
955
+ bindShortcuts() {
956
+ const wasRaw = process.stdin.isRaw;
957
+ const wasFlowing = process.stdin.readableFlowing;
958
+ emitKeypressEvents(process.stdin);
959
+ process.stdin.setRawMode(true);
960
+ process.stdin.on("keypress", this.onKey);
961
+ process.stdin.resume();
962
+ this.stopInput = () => {
963
+ process.stdin.off("keypress", this.onKey);
964
+ process.stdin.setRawMode(wasRaw);
965
+ if (!wasFlowing) process.stdin.pause();
1558
966
  };
1559
- const listenerConfig = listenerConfigs[index];
1560
- listenerBindings.set(listener.listenerId, {
1561
- callback: appendValuePath(baseBinding, ["callback"]),
1562
- activitySignal: listenerConfig.activitySignal ? appendValuePath(baseBinding, ["activitySignal"]) : void 0
1563
- });
1564
- });
1565
- return {
1566
- injectionDefaults: options.manifest.injectionDefaults?.hooks ? {
1567
- hooks: {
1568
- manifestFile: options.manifestFile,
1569
- valuePath: ["injectionDefaults", "hooks"]
967
+ }
968
+ onKey = async (_text, key) => {
969
+ if (key.ctrl && key.name === "c") {
970
+ await this.shutdown();
971
+ return;
972
+ }
973
+ if (this.actionRunning || key.ctrl) return;
974
+ if (key.name === "escape") {
975
+ this.show(this.currentView === "help" ? this.previousView : "home");
976
+ return;
977
+ }
978
+ if (key.meta || key.sequence?.length !== 1) return;
979
+ if (key.name === "h") {
980
+ if (this.currentView === "help") this.show(this.previousView);
981
+ else {
982
+ this.previousView = this.currentView;
983
+ this.show("help");
1570
984
  }
1571
- } : void 0,
1572
- injections: Object.fromEntries(
1573
- options.enabledInjections.map((injection) => {
1574
- const manifestSource = manifestInjectionSources.get(injection.moduleId);
1575
- const moduleSource = moduleInjectionSources.get(injection.moduleId);
1576
- if (!manifestSource && !moduleSource) {
1577
- throw new ManifestBindingNotFoundError("injection", injection.moduleId);
1578
- }
1579
- return [injection.moduleId, buildInjectionBindings(manifestSource, moduleSource)];
1580
- })
1581
- ),
1582
- listeners: selectBindings(
1583
- options.enabledListeners.map((listener) => listener.listenerId),
1584
- listenerBindings,
1585
- "listener"
1586
- )
1587
- };
1588
- }
1589
- function buildInjectionBindings(manifestSource, moduleSource) {
1590
- const hooksSource = selectFieldSource("hooks", manifestSource, moduleSource);
1591
- const onSource = selectFieldSource("on", manifestSource, moduleSource);
1592
- return {
1593
- hooks: hooksSource?.config.hooks ? appendValuePath(hooksSource.binding, ["hooks"]) : void 0,
1594
- on: onSource?.config.on ? {
1595
- callback: appendValuePath(onSource.binding, ["on", "callback"]),
1596
- activitySignal: onSource.config.on.activitySignal ? appendValuePath(onSource.binding, ["on", "activitySignal"]) : void 0
1597
- } : void 0
985
+ return;
986
+ }
987
+ if (!["i", "t", "n", "l", "r", "u", "o", "c", "q"].includes(key.name ?? "")) return;
988
+ if (key.name === "i" && !this.hasInstallationPage()) return;
989
+ if (this.currentView === "help") this.show(this.previousView);
990
+ this.actionRunning = true;
991
+ try {
992
+ switch (key.name) {
993
+ case "t":
994
+ this.show(this.currentView === "tasks" ? "home" : "tasks");
995
+ break;
996
+ case "n":
997
+ this.selectedRuntime += 1;
998
+ this.show("tasks");
999
+ break;
1000
+ case "l":
1001
+ this.show(this.currentView === "logs" ? "home" : "logs");
1002
+ break;
1003
+ case "r":
1004
+ await this.restart();
1005
+ break;
1006
+ case "u":
1007
+ this.show("home");
1008
+ break;
1009
+ case "o":
1010
+ this.server.openBrowser();
1011
+ break;
1012
+ case "i":
1013
+ this.openInstallationPage();
1014
+ break;
1015
+ case "c":
1016
+ this.show("logs");
1017
+ this.logger.clearScreen("error");
1018
+ break;
1019
+ case "q":
1020
+ await this.shutdown();
1021
+ break;
1022
+ }
1023
+ } catch (error) {
1024
+ this.logger.error(`[makoo] ${error instanceof Error ? error.message : String(error)}`);
1025
+ } finally {
1026
+ this.actionRunning = false;
1027
+ }
1598
1028
  };
1599
- }
1600
- function selectFieldSource(field, manifestSource, moduleSource) {
1601
- if (moduleSource && Object.hasOwn(moduleSource.config, field)) {
1602
- return moduleSource;
1029
+ openInstallationPage() {
1030
+ const open = this.server.config.server.open;
1031
+ try {
1032
+ this.server.config.server.open = this.server.config.base;
1033
+ this.server.openBrowser();
1034
+ } finally {
1035
+ this.server.config.server.open = open;
1036
+ }
1603
1037
  }
1604
- return manifestSource;
1605
- }
1606
- function appendValuePath(binding, valuePath) {
1607
- return {
1608
- manifestFile: binding.manifestFile,
1609
- valuePath: [...binding.valuePath, ...valuePath]
1610
- };
1611
- }
1612
- function getCollectionKeys(collection) {
1613
- if (!collection) return [];
1614
- return Array.isArray(collection) ? collection.map((_, index) => index) : Object.keys(collection);
1615
- }
1616
- function selectBindings(ids, bindings, kind) {
1617
- return Object.fromEntries(
1618
- ids.map((id) => {
1619
- const binding = bindings.get(id);
1620
- if (!binding) {
1621
- throw new ManifestBindingNotFoundError(kind, id);
1622
- }
1623
- return [id, binding];
1624
- })
1625
- );
1626
- }
1627
-
1628
- // src/scanner/util.ts
1629
- function mergeMeta(source, target) {
1630
- const targetMap = new Map(target.map((m) => [m.moduleId, m]));
1631
- const result = source.map((s) => targetMap.get(s.moduleId) ?? s);
1632
- for (const t of target) {
1633
- if (!source.some((s) => s.moduleId === t.moduleId)) {
1634
- result.push(t);
1038
+ async restart() {
1039
+ this.restarting = true;
1040
+ this.show("home");
1041
+ try {
1042
+ await this.server.restart();
1043
+ } finally {
1044
+ this.restarting = false;
1045
+ this.refresh();
1635
1046
  }
1636
1047
  }
1637
- return result;
1638
- }
1639
-
1640
- // src/scanner/scanner.ts
1641
- async function scanner(config) {
1642
- const loadedManifest = await loadManifest(config.source);
1643
- if (!loadedManifest) {
1644
- throw new ManifestNotFoundError(config.source.dir);
1645
- }
1646
- const manifestDependencies = new Set(loadedManifest.dependencies);
1647
- const moduleManifestDependencies = /* @__PURE__ */ new Set();
1648
- const runtimeSetupFiles = /* @__PURE__ */ new Set();
1649
- const runtimeDependencies = /* @__PURE__ */ new Set();
1650
- for (const setupFile of config.runtime.setup) {
1651
- if (!existsSync5(setupFile)) {
1652
- throw new RuntimeSetupNotFoundError(setupFile);
1048
+ shutdown = async () => {
1049
+ this.close();
1050
+ try {
1051
+ await this.server.close();
1052
+ } finally {
1053
+ process.exit(0);
1653
1054
  }
1654
- runtimeSetupFiles.add(setupFile);
1655
- for (const dependency of collectDependencies(setupFile, { root: config.root })) {
1656
- runtimeDependencies.add(dependency);
1055
+ };
1056
+ close = () => {
1057
+ if (this.closed) return;
1058
+ this.closed = true;
1059
+ this.unsubscribe?.();
1060
+ this.stopInput?.();
1061
+ process.off("exit", this.close);
1062
+ process.off("SIGINT", this.shutdown);
1063
+ if (this.currentView !== "logs") {
1064
+ this.screenOutput.clear();
1065
+ process.stdout.write(LEAVE_ALT_SCREEN);
1066
+ this.currentView = "logs";
1067
+ this.flushLogs();
1657
1068
  }
1658
- }
1659
- const injectionDefaults = resolveInjectionDefaults(loadedManifest.manifest.injectionDefaults);
1660
- const resolveManifest = resolveInjections(loadedManifest.manifest, {
1661
- root: config.root,
1662
- source: config.source,
1663
- injectionDefaults
1664
- });
1665
- const normalizedManifestInjections = normalizeInjectionManifest(loadedManifest.manifest);
1666
- const manifestInjectionConfigs = new Map(
1667
- resolveManifest.map((injection, index) => [
1668
- injection.moduleId,
1669
- normalizedManifestInjections[index]
1670
- ])
1671
- );
1672
- const folder = readdirSync2(config.source.dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
1673
- const isIncluded = picomatch(config.source.include);
1674
- const isExcluded = picomatch(config.source.exclude);
1675
- const filteredFolders = folder.filter((name) => isIncluded(name) && !isExcluded(name));
1676
- const injectionsMeta = [];
1677
- const moduleInjectionConfigs = /* @__PURE__ */ new Map();
1678
- for (const module of filteredFolders) {
1679
- const modulePath = path4.join(config.source.dir, module);
1680
- const meta = await loadMeta(modulePath);
1681
- if (!meta) {
1682
- continue;
1069
+ this.logger.info = this.originalInfo;
1070
+ this.logger.warn = this.originalWarn;
1071
+ this.logger.warnOnce = this.originalWarnOnce;
1072
+ this.logger.error = this.originalError;
1073
+ this.logger.clearScreen = this.originalClearScreen;
1074
+ };
1075
+ writeLog(log) {
1076
+ if (this.currentView === "logs") {
1077
+ this.printLog(log);
1078
+ return;
1683
1079
  }
1684
- for (const dependency of meta.dependencies) {
1685
- moduleManifestDependencies.add(dependency);
1080
+ if (log.type === "error") this.unreadErrors += 1;
1081
+ if (log.options) log.options = { ...log.options, clear: false };
1082
+ this.bufferedLogs.push(log);
1083
+ if (this.bufferedLogs.length > MAX_BUFFERED_LOGS) {
1084
+ this.bufferedLogs.shift();
1085
+ this.omittedLogs += 1;
1086
+ }
1087
+ this.refresh();
1088
+ }
1089
+ printLog(log) {
1090
+ switch (log.type) {
1091
+ case "info":
1092
+ this.originalInfo.call(this.logger, log.message, log.options);
1093
+ break;
1094
+ case "warn":
1095
+ this.originalWarn.call(this.logger, log.message, log.options);
1096
+ break;
1097
+ case "warnOnce":
1098
+ this.originalWarnOnce.call(this.logger, log.message, log.options);
1099
+ break;
1100
+ case "error":
1101
+ this.originalError.call(this.logger, log.message, log.options);
1102
+ break;
1686
1103
  }
1687
- const resolveOptions = {
1688
- root: config.root,
1689
- source: config.source,
1690
- injectionDefaults,
1691
- moduleDir: modulePath,
1692
- componentPath: path4.join(modulePath, meta.moduleConfig.component),
1693
- fallbackName: module,
1694
- moduleManifestFile: meta.moduleManifestFile
1695
- };
1696
- const moduleId = meta.moduleConfig.name || module;
1697
- const manifestConfig = manifestInjectionConfigs.get(moduleId);
1698
- const resolveMeta = resolveInjection(
1699
- manifestConfig ? { ...manifestConfig, ...meta.moduleConfig } : meta.moduleConfig,
1700
- resolveOptions
1701
- );
1702
- injectionsMeta.push(resolveMeta);
1703
- moduleInjectionConfigs.set(resolveMeta.moduleId, meta.moduleConfig);
1704
1104
  }
1705
- const injections = mergeMeta(resolveManifest, injectionsMeta).filter(
1706
- (injection) => injection.enabled
1707
- );
1708
- const resolvedListeners = resolveListeners(loadedManifest.manifest, {
1709
- root: config.root
1710
- });
1711
- const listeners = resolvedListeners.filter((listener) => listener.enabled);
1712
- if (injections.length === 0 && listeners.length === 0) {
1713
- throw new NoEnabledTasksError();
1714
- }
1715
- const manifestBindings = buildManifestBindings({
1716
- manifest: loadedManifest.manifest,
1717
- manifestFile: loadedManifest.manifestFile,
1718
- manifestInjections: resolveManifest,
1719
- moduleInjections: injectionsMeta,
1720
- moduleInjectionConfigs,
1721
- manifestListeners: resolvedListeners,
1722
- enabledInjections: injections,
1723
- enabledListeners: listeners
1724
- });
1725
- injections.sort((a, b) => a.moduleId.localeCompare(b.moduleId));
1726
- listeners.sort((a, b) => a.listenerId.localeCompare(b.listenerId));
1727
- const frameworks = [...new Set(injections.map((m) => m.framework))];
1728
- return {
1729
- config,
1730
- injectionDefaults,
1731
- manifestFile: loadedManifest.manifestFile,
1732
- manifestBindings,
1733
- manifestDependencies: [...manifestDependencies].sort(),
1734
- moduleManifestDependencies: [...moduleManifestDependencies].sort(),
1735
- runtimeSetupFiles: [...runtimeSetupFiles].sort(),
1736
- runtimeDependencies: [...runtimeDependencies].sort(),
1737
- injections,
1738
- listeners,
1739
- frameworks
1740
- };
1105
+ flushLogs() {
1106
+ if (this.omittedLogs > 0)
1107
+ this.originalWarn.call(
1108
+ this.logger,
1109
+ `[makoo] ${this.omittedLogs} earlier dev logs omitted.`
1110
+ );
1111
+ for (const log of this.bufferedLogs) this.printLog(log);
1112
+ this.bufferedLogs = [];
1113
+ this.omittedLogs = 0;
1114
+ this.unreadErrors = 0;
1115
+ }
1116
+ };
1117
+
1118
+ // src/cli/commands/dev/dev.ts
1119
+ async function devCommand(config) {
1120
+ const server = await createServer(config);
1121
+ const cliVersion = await loadCliVersion(null);
1122
+ const terminal = new DevTerminal(server, cliVersion);
1123
+ await terminal.start();
1741
1124
  }
1742
1125
 
1743
- // src/command/inspect.ts
1744
- function formatInspectInjection(injection, injectionDefaults) {
1745
- const { alive, scope, timeout, ...rest } = injection;
1746
- const resolvedInjectionDefaults = { alive, scope, timeout };
1747
- const injectionDefaultsOverrides = {
1748
- ...alive !== injectionDefaults.alive ? { alive } : {},
1749
- ...scope !== injectionDefaults.scope ? { scope } : {},
1750
- ...timeout !== injectionDefaults.timeout ? { timeout } : {}
1751
- };
1752
- if (Object.keys(injectionDefaultsOverrides).length === 0) {
1753
- return {
1754
- ...rest,
1755
- injectionDefaults: resolvedInjectionDefaults
1756
- };
1126
+ // src/cli/commands/preview.ts
1127
+ import { preview } from "vite";
1128
+ async function previewCommand(config) {
1129
+ const server = await preview(config);
1130
+ server.printUrls();
1131
+ server.bindCLIShortcuts({ print: true });
1132
+ }
1133
+
1134
+ // src/cli/bin.ts
1135
+ var cli = cac("makoo");
1136
+ function normalizeDuplicateOptions(options) {
1137
+ for (const [key, value] of Object.entries(options)) {
1138
+ if (Array.isArray(value)) options[key] = value[value.length - 1];
1757
1139
  }
1140
+ }
1141
+ function resolveCommonOptions(root, options) {
1758
1142
  return {
1759
- ...rest,
1760
- injectionDefaults: resolvedInjectionDefaults,
1761
- injectionDefaultsOverrides
1143
+ root,
1144
+ configFile: options.config,
1145
+ base: options.base === 0 ? "" : options.base === void 0 ? void 0 : String(options.base),
1146
+ mode: options.mode,
1147
+ logLevel: options.logLevel,
1148
+ clearScreen: options.clearScreen,
1149
+ configLoader: options.configLoader
1762
1150
  };
1763
1151
  }
1764
- function formatInspectResult(result) {
1765
- const { config, injectionDefaults, injections, listeners } = result;
1766
- const moduleManifestFiles = [
1767
- ...new Set(
1768
- injections.map((injection) => injection.moduleManifestFile).filter((file) => typeof file === "string")
1769
- )
1770
- ].sort();
1771
- return {
1772
- project: {
1773
- root: config.root,
1774
- app: config.app
1152
+ cli.option("-c, --config <file>", "Use specified Vite config file").option("-m, --mode <mode>", "Set environment mode").option("--base <path>", "Public base path").option("-l, --logLevel <level>", "Log level: info | warn | error | silent").option("--clearScreen", "Allow/disable clearing the terminal").option("--configLoader <loader>", "Config loader: bundle | runner | native");
1153
+ cli.command("build [root]", "Build the userscript").option("--target <target>", "Transpile target").option("--outDir <dir>", "Output directory").option("--assetsDir <dir>", "Directory for generated assets").option("--assetsInlineLimit <number>", "Asset inline threshold in bytes").option("--sourcemap [output]", "Source maps: true | false | inline | hidden").option("--minify [minifier]", "Enable/disable minification, or select a minifier").option("--manifest [name]", "Emit a build manifest").option("--emptyOutDir", "Allow/disable emptying the output directory").option("-w, --watch", "Rebuild when source files change").action(async (root, options) => {
1154
+ normalizeDuplicateOptions(options);
1155
+ let sourcemap = options.sourcemap;
1156
+ if (sourcemap === "true") sourcemap = true;
1157
+ if (sourcemap === "false") sourcemap = false;
1158
+ await buildCommand({
1159
+ ...resolveCommonOptions(root, options),
1160
+ build: {
1161
+ target: options.target,
1162
+ outDir: options.outDir,
1163
+ assetsDir: options.assetsDir,
1164
+ assetsInlineLimit: options.assetsInlineLimit,
1165
+ sourcemap,
1166
+ minify: options.minify,
1167
+ manifest: options.manifest,
1168
+ emptyOutDir: options.emptyOutDir,
1169
+ watch: options.watch ? {} : void 0
1170
+ }
1171
+ });
1172
+ });
1173
+ cli.command("dev [root]", "Start the dev server").option("--host [host]", "Listen on a hostname or all addresses").option("--port <port>", "Development server port").option("--open [path]", "Open the browser on startup").option("--cors", "Enable/disable CORS").option("--strictPort", "Exit if the requested port is in use").option("--force", "Ignore the dependency optimizer cache").action(async (root, options) => {
1174
+ normalizeDuplicateOptions(options);
1175
+ await devCommand({
1176
+ ...resolveCommonOptions(root, options),
1177
+ server: {
1178
+ host: typeof options.host === "number" ? String(options.host) : options.host,
1179
+ port: options.port,
1180
+ open: options.open,
1181
+ cors: options.cors,
1182
+ strictPort: options.strictPort
1775
1183
  },
1776
- source: {
1777
- config: config.source,
1778
- manifestFile: result.manifestFile,
1779
- moduleManifestFiles,
1780
- dependencies: {
1781
- manifest: result.manifestDependencies,
1782
- moduleManifests: result.moduleManifestDependencies
1184
+ forceOptimizeDeps: options.force
1185
+ });
1186
+ });
1187
+ cli.command("preview [root]", "Preview the built userscript").option("--host [host]", "Listen on a hostname or all addresses").option("--port <port>", "Preview server port").option("--open [path]", "Open the browser on startup").option("--strictPort", "Exit if the requested port is in use").option("--outDir <dir>", "Directory to preview").action(
1188
+ async (root, options) => {
1189
+ normalizeDuplicateOptions(options);
1190
+ await previewCommand({
1191
+ ...resolveCommonOptions(root, options),
1192
+ build: { outDir: options.outDir },
1193
+ preview: {
1194
+ host: typeof options.host === "number" ? String(options.host) : options.host,
1195
+ port: options.port,
1196
+ open: options.open,
1197
+ strictPort: options.strictPort
1783
1198
  }
1784
- },
1785
- runtime: {
1786
- setupFiles: result.runtimeSetupFiles,
1787
- dependencies: result.runtimeDependencies
1788
- },
1789
- monkey: config.monkey,
1790
- injectionDefaults,
1791
- injections: injections.map(
1792
- (injection) => formatInspectInjection(injection, injectionDefaults)
1793
- ),
1794
- listeners,
1795
- frameworks: result.frameworks
1796
- };
1797
- }
1798
- async function inspectCommand() {
1799
- const resolveViteMakooConfig = await loadMakooConfig();
1800
- const resolveManifest = await scanner(resolveViteMakooConfig);
1801
- const inspectResult = formatInspectResult(resolveManifest);
1802
- const sections = [
1803
- ["Project", inspectResult.project],
1804
- ["Source", inspectResult.source],
1805
- ["Runtime", inspectResult.runtime],
1806
- ["Monkey", inspectResult.monkey],
1807
- ["Injection Defaults", inspectResult.injectionDefaults],
1808
- ["Injections", inspectResult.injections],
1809
- ["Listeners", inspectResult.listeners],
1810
- ["Frameworks", inspectResult.frameworks]
1811
- ];
1812
- console.log(colorize("Makoo Inspect", ansi.bold, ansi.green));
1813
- for (const [label, value] of sections) {
1814
- console.log(`
1815
- ${colorize(label, ansi.cyan)}`);
1816
- console.dir(value, {
1817
- depth: null,
1818
- colors: true
1819
1199
  });
1820
1200
  }
1821
- }
1822
-
1823
- // src/command/bin.ts
1824
- var cli = cac("makoo");
1825
- cli.command("build", "Build the userscript").action(async () => {
1826
- await buildCommand();
1827
- });
1828
- cli.command("dev", "Start the dev server").action(async () => {
1829
- await devCommand();
1830
- });
1831
- cli.command("add <name>", "Add a new injection module").option("--framework <framework>", "Framework to use", { default: "React" }).action(async (name, options) => {
1832
- await addCommand(name, options.framework);
1833
- });
1834
- cli.command("inspect", "Inspect resolved makoo config").action(async () => {
1835
- await inspectCommand();
1836
- });
1201
+ );
1837
1202
  cli.help();
1838
- cli.version("1.3.1");
1203
+ cli.version(await loadCliVersion(null));
1839
1204
  process.on("unhandledRejection", (err) => {
1840
- if (err instanceof MakooError2) {
1205
+ if (err instanceof MakooError) {
1841
1206
  console.error(err);
1842
1207
  } else {
1843
1208
  console.error("[makoo]", err);