@skathi-native/cli 0.1.0-beta.3 → 0.2.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 (68) hide show
  1. package/aot-inputs.ts +21 -2
  2. package/build.ts +241 -60
  3. package/check/bundle.ts +265 -0
  4. package/check/codes.ts +19 -0
  5. package/check/command.ts +5 -3
  6. package/check/graph.ts +3 -1
  7. package/check/index.ts +54 -2
  8. package/check/program.ts +26 -6
  9. package/cli/aot-build.ts +10 -7
  10. package/cli/build-app.ts +37 -8
  11. package/cli/config.ts +2 -2
  12. package/cli/create.ts +31 -8
  13. package/cli/dev.ts +109 -19
  14. package/cli/effects.ts +162 -0
  15. package/cli/elf.ts +3 -2
  16. package/cli/help.ts +56 -147
  17. package/cli/host-fetch.ts +33 -10
  18. package/cli/host.ts +43 -33
  19. package/cli/sk.ts +437 -234
  20. package/cli/skpk.ts +2 -0
  21. package/cli/stamp.ts +2 -2
  22. package/cli/term.ts +169 -38
  23. package/cli/workload-cache.ts +258 -0
  24. package/devtools/commands.ts +25 -0
  25. package/effects/compile.ts +1081 -0
  26. package/effects/redslangc.json +23 -0
  27. package/effects/redslangc.ts +220 -0
  28. package/effects/sk.slang +882 -0
  29. package/package.json +10 -4
  30. package/prod.ts +40 -7
  31. package/svelte.ts +76 -0
  32. package/templates/icon.png +0 -0
  33. package/templates/minimal/src/App.vue +2 -2
  34. package/templates/showcase/assets/textures/golden.png +0 -0
  35. package/templates/showcase/assets/textures/hammered.png +0 -0
  36. package/templates/showcase/assets/textures/noir.png +0 -0
  37. package/templates/showcase/assets/textures/reeded.png +0 -0
  38. package/templates/showcase/assets/textures/teal-orange.png +0 -0
  39. package/templates/showcase/shaders/dissolve.slang +40 -0
  40. package/templates/showcase/shaders/fireflies.slang +58 -0
  41. package/templates/showcase/shaders/glass.slang +31 -0
  42. package/templates/showcase/shaders/grade.slang +34 -0
  43. package/templates/showcase/shaders/halftone.slang +42 -0
  44. package/templates/showcase/shaders/lens.slang +51 -0
  45. package/templates/showcase/shaders/nebula.slang +57 -0
  46. package/templates/showcase/shaders/orbit.slang +52 -0
  47. package/templates/showcase/shaders/pond.slang +76 -0
  48. package/templates/showcase/shaders/ripples.slang +71 -0
  49. package/templates/showcase/shaders/shatter.slang +116 -0
  50. package/templates/showcase/shaders/sheen.slang +23 -0
  51. package/templates/showcase/shaders/snow.slang +57 -0
  52. package/templates/showcase/shaders/spotlight.slang +52 -0
  53. package/templates/showcase/src/App.vue +11 -16
  54. package/templates/showcase/src/components/FullWindow.vue +77 -0
  55. package/templates/showcase/src/components/Page.vue +2 -0
  56. package/templates/showcase/src/fullwindow.ts +36 -0
  57. package/templates/showcase/src/icons.ts +2 -0
  58. package/templates/showcase/src/pages/GraphicsPage.vue +122 -0
  59. package/templates/showcase/src/pages/MotionPage.vue +71 -1
  60. package/templates/showcase/src/pages/ShadersPage.vue +443 -0
  61. package/templates/showcase/src/pages/StylesPage.vue +9 -1
  62. package/templates/showcase/src/router.ts +32 -1
  63. package/templates/showcase/src/styles.css +2 -2
  64. package/templates/svelte/.vscode/settings.json +3 -0
  65. package/templates/svelte/assets/hello.txt +1 -0
  66. package/templates/svelte/src/App.svelte +142 -0
  67. package/templates/svelte/src/main.ts +4 -0
  68. package/vitecompat.ts +2 -0
package/cli/sk.ts CHANGED
@@ -1,268 +1,473 @@
1
1
  #!/usr/bin/env bun
2
2
  // sk — create, develop and package a Skathi app for Windows, macOS or Linux, without a
3
- // Rust toolchain.
3
+ // Rust toolchain. Every command and option is declared once here; help.ts lays the help out.
4
4
 
5
5
  import { spawn } from "node:child_process";
6
+ import { Command, CommanderError, Option, type CommandUnknownOpts } from "@commander-js/extra-typings";
6
7
  import { aotFlags } from "./aot-build";
7
8
  import { buildApp, summary } from "./build-app";
8
9
  import { ConfigError, parseVariant, PARTS_NOT_SELECTABLE, VARIANTS, type Variant } from "./config";
10
+ import { createCommand } from "./create";
9
11
  import { dev } from "./dev";
12
+ import { helpFormat, section } from "./help";
10
13
  import { addHost, buildHost, CLI_VERSION, DEV_HOST, HostError, hostInfo, resolveHost } from "./host";
11
14
  import { fetchHost } from "./host-fetch";
12
- import { colorEnabled, colorFlag, lineProgress, logTo, paint, progressFor } from "./term";
13
- import { createCommand } from "./create";
14
15
  import { currentPlatform, parsePlatform } from "./platform";
15
- import { commandHelp, topHelp } from "./help";
16
-
17
- type Flags = Record<string, string | boolean>;
18
- const BOOLEAN = new Set([
19
- "deny-warnings",
20
- "no-deps",
21
- "list",
22
- "console",
23
- "payload-only",
24
- "allow-host-mismatch",
25
- "aot-inputs",
26
- "aot",
27
- "no-aot",
28
- "help",
29
- "version",
30
- "json",
31
- "no-sign",
32
- "yes",
33
- "devtools",
34
- "no-devtools",
35
- "color",
36
- "no-color",
37
- ]);
38
- const REPEATABLE = new Set(["define"]);
39
-
40
- function parse(argv: string[]): {
41
- positional: string[];
42
- flags: Flags;
43
- repeated: Record<string, string[]>;
16
+ import { colorEnabled, lineProgress, logTo, paint, progressFor } from "./term";
17
+ import { PIN } from "../effects/redslangc";
18
+ import { cacheRoots, formatInventory, formatPrune, inventory, needed, prune } from "./workload-cache";
19
+
20
+ interface Run {
21
+ /** What follows `--`: the app's own arguments for `sk run`. */
44
22
  rest: string[];
45
- } {
46
- const positional: string[] = [];
47
- const flags: Flags = {};
48
- const repeated: Record<string, string[]> = {};
49
- let rest: string[] = [];
50
- for (let i = 0; i < argv.length; i++) {
51
- const a = argv[i]!;
52
- if (a === "--") {
53
- rest = argv.slice(i + 1);
54
- break;
55
- }
56
- if (a === "-h") flags.help = true;
57
- else if (a === "-y") flags.yes = true;
58
- else if (a === "-v") flags.version = true;
59
- else if (a.startsWith("--")) {
60
- // Split at the FIRST "=" only: `--define=K=V` keeps its own "=".
61
- const body = a.slice(2);
62
- const eq = body.indexOf("=");
63
- const name = eq < 0 ? body : body.slice(0, eq);
64
- const inline = eq < 0 ? undefined : body.slice(eq + 1);
65
- if (BOOLEAN.has(name)) flags[name] = true;
66
- else if (REPEATABLE.has(name)) (repeated[name] ??= []).push(inline ?? argv[++i] ?? "");
67
- else flags[name] = inline ?? argv[++i] ?? "";
68
- } else positional.push(a);
69
- }
70
- return { positional, flags, repeated, rest };
23
+ color: boolean | undefined;
24
+ code: number;
25
+ /** The command being parsed, for usage errors. */
26
+ at: string;
71
27
  }
72
28
 
73
- function refuseParts(flags: Flags): void {
74
- for (const gone of ["without", "features"]) {
75
- if (flags[gone] !== undefined) throw new ConfigError(`--${gone}: ${PARTS_NOT_SELECTABLE}`);
76
- }
29
+ const track = (run: Run) => (_: CommandUnknownOpts, sub: CommandUnknownOpts) => {
30
+ run.at = `${run.at} ${sub.name()}`;
31
+ };
32
+
33
+ /** `--color` / `--no-color` anywhere on the line, read before parsing so usage errors are coloured too. */
34
+ export const colorArg = (args: string[]): boolean | undefined =>
35
+ args.includes("--no-color") ? false : args.includes("--color") ? true : undefined;
36
+
37
+ const INSTALLABLE: readonly Variant[] = [...VARIANTS, DEV_HOST];
38
+
39
+ function installable(v: string): Variant {
40
+ const name = v.trim();
41
+ if (INSTALLABLE.includes(name)) return name;
42
+ throw new ConfigError(`${JSON.stringify(v)} is not a workload variant — ${INSTALLABLE.join(", ")}`);
77
43
  }
78
44
 
79
- function variantOf(flags: Flags): Variant | undefined {
80
- refuseParts(flags);
81
- return flags.variant === undefined ? undefined : parseVariant(flags.variant, "--variant");
45
+ function refuseParts(o: { without?: unknown; features?: unknown }): void {
46
+ if (o.without !== undefined) throw new ConfigError(`--without: ${PARTS_NOT_SELECTABLE}`);
47
+ if (o.features !== undefined) throw new ConfigError(`--features: ${PARTS_NOT_SELECTABLE}`);
82
48
  }
83
49
 
84
- async function main(argv: string[]): Promise<number> {
85
- const { positional, flags, repeated, rest } = parse(argv);
86
- const [command, ...args] = positional;
87
- if (command === "version" || (!command && flags.version === true)) {
88
- console.log(CLI_VERSION);
89
- return 0;
90
- }
91
- const color = colorEnabled(process.stdout, colorFlag(flags));
92
- const about = command === "help" ? args[0] : flags.help ? command : undefined;
93
- if (about !== undefined) {
94
- const text = commandHelp(about, color);
95
- if (text) {
96
- console.log(text);
97
- return 0;
98
- }
99
- }
100
- if (!command || flags.help || command === "help") {
101
- console.log(topHelp(color));
102
- return command || flags.help ? 0 : 1;
103
- }
50
+ const hidden = <Flags extends string>(flags: Flags) => new Option(flags).hideHelp();
104
51
 
105
- if (command === "build" || command === "publish" || command === "run") {
106
- const platform = flags.platform === undefined ? undefined : parsePlatform(flags.platform);
107
- if (command === "run" && platform && platform !== currentPlatform()) {
108
- throw new ConfigError(
109
- `sk run starts the app here; a ${platform} build cannot run on ${process.platform} — use sk build`,
110
- );
111
- }
112
- if (flags.sign !== undefined && (typeof flags.sign !== "string" || !flags.sign.trim())) {
113
- throw new ConfigError('--sign needs a codesign identity ("-" for ad hoc)');
114
- }
115
- if (flags.sign !== undefined && flags["no-sign"])
116
- throw new ConfigError("--sign and --no-sign contradict each other");
117
- const progress = progressFor(process.stderr, colorEnabled(process.stderr, colorFlag(flags)));
118
- const result = await buildApp({
119
- progress,
120
- target: args[0] ?? ".",
121
- configPath: typeof flags.config === "string" ? flags.config : undefined,
122
- out: typeof flags.out === "string" ? flags.out : undefined,
123
- host: typeof flags.host === "string" ? flags.host : undefined,
124
- variant: variantOf(flags),
125
- console: flags.console === true,
126
- payloadOnly: flags["payload-only"] === true,
127
- allowHostMismatch: flags["allow-host-mismatch"] === true,
128
- defines: repeated.define,
129
- aotInputs: flags["aot-inputs"] === true,
130
- ...aotFlags(flags),
131
- color: colorEnabled(process.stderr, colorFlag(flags)),
132
- platform,
133
- sign: flags["no-sign"] ? false : typeof flags.sign === "string" ? flags.sign.trim() : undefined,
134
- mode: command === "publish" ? "release" : "debug",
135
- }).finally(() => progress.end());
136
- if (flags.json) {
137
- const s = result.stamp;
138
- console.log(
139
- JSON.stringify({
140
- exe: result.exe,
141
- skpk: result.skpk,
142
- aotInputs: result.aotInputs,
143
- native: result.native,
144
- name: result.config.name,
145
- productName: result.config.productName,
146
- version: result.config.version,
147
- variant: result.variant,
148
- host: result.host && { exe: result.host.exe, source: result.host.source, profile: result.host.info.profile },
149
- assets: result.assets.length,
150
- bundleBytes: result.bundleBytes,
151
- payloadBytes: result.payloadBytes,
152
- ...(result.packs.length ? { packs: result.packs } : {}),
153
- stamp: s && {
154
- bytes: s.bytes,
155
- skew: s.skew,
156
- dataAligned: s.dataAligned,
157
- passes: s.passes,
158
- subsystem: s.subsystem,
159
- iconCount: s.iconCount,
160
- ms: s.ms,
161
- },
162
- ...(result.bundle && {
163
- platform: result.platform,
164
- app: result.bundle.app,
165
- bundle: {
166
- bundleId: result.bundle.bundleId,
167
- bytes: result.bundle.bytes,
168
- iconSizes: result.bundle.iconSizes,
169
- signed: result.bundle.signed,
170
- signNote: result.bundle.signNote,
171
- entitlements: result.bundle.entitlements,
172
- ms: result.bundle.ms,
52
+ const collect = (value: string, all: string[]) => [...all, value];
53
+
54
+ /** The options of `names` given on the line, for pairs that contradict each other. */
55
+ function given(cmd: CommandUnknownOpts, ...names: string[]): Set<string> {
56
+ const seen = new Set<string>();
57
+ for (const name of names) cmd.on(`option:${name}`, () => seen.add(name));
58
+ return seen;
59
+ }
60
+
61
+ /** Usage errors of `sk check` and `sk explain` exit 2, as their reports do. */
62
+ const exitWith =
63
+ (code: number) =>
64
+ (e: CommanderError): never => {
65
+ throw e.exitCode === 0 ? e : new CommanderError(code, e.code, e.message);
66
+ };
67
+
68
+ const BUILD_MODES = {
69
+ build: {
70
+ summary: "Debug build: devtools on, not minified",
71
+ about: "A debug build in <app>/dist/debug: devtools (F12) on, the bundle not minified.",
72
+ },
73
+ publish: {
74
+ summary: "Release build to ship",
75
+ about:
76
+ 'The release build in <app>/dist/release: minified, devtools only with "publishDevtools": true in sk.config.json.',
77
+ },
78
+ run: {
79
+ summary: "Build, then start the app",
80
+ about: "sk build, then start the app with its output in this terminal. Arguments after -- go to the app.",
81
+ },
82
+ } as const;
83
+
84
+ const CHECK_EXIT_CODES: [string, string][] = [
85
+ ["0", "Clean"],
86
+ ["1", "Errors (or warnings with --deny-warnings)"],
87
+ ["2", "Bad usage or config, or the check failed"],
88
+ ];
89
+
90
+ const RENAMED: Record<string, string> = { fetch: "install", path: "path", info: "info", add: "add", build: "build" };
91
+
92
+ function pruneCommand(parent: CommandUnknownOpts, run: Run) {
93
+ return new Command("prune")
94
+ .copyInheritedSettings(parent)
95
+ .summary("Remove cached workloads this sk does not use")
96
+ .description(
97
+ `Remove what sk ${CLI_VERSION} does not need: other versions' workloads and sk-aot, redslangc builds other than ${PIN.version}, incomplete downloads, ` +
98
+ "expanded native images (apps expand them again at start) and old toolchains.",
99
+ )
100
+ .option("--dry-run", "Show what would go, remove nothing")
101
+ .option("--keep <version>", "Keep this version's workloads too; repeatable", collect, [])
102
+ .option("--all", "Remove this version's workloads as well")
103
+ .action((o) => {
104
+ const roots = cacheRoots();
105
+ const options = { current: CLI_VERSION, keep: o.keep, all: o.all === true, dryRun: o.dryRun === true, roots };
106
+ const result = prune(inventory(roots), options);
107
+ console.log(formatPrune(result, options, colorEnabled(process.stdout, run.color)));
108
+ });
109
+ }
110
+
111
+ export function cli(run: Run): Command {
112
+ const outColor = colorEnabled(process.stdout, run.color);
113
+ const errColor = colorEnabled(process.stderr, run.color);
114
+ const p = paint(outColor);
115
+ const program = new Command("sk")
116
+ .description("Skathi apps for Windows, macOS and Linux")
117
+ .version(CLI_VERSION, "-v, --version", "Print the version")
118
+ .addHelpOption(hidden("-h, --help"))
119
+ .option("--no-color", "Plain output (--color forces colour)")
120
+ .addOption(hidden("--color"))
121
+ .configureHelp(helpFormat(outColor || errColor))
122
+ .configureOutput({
123
+ writeOut: (s) => process.stdout.write(s),
124
+ writeErr: (s) => process.stderr.write(s),
125
+ outputError: () => {},
126
+ getOutHasColors: () => outColor,
127
+ getErrHasColors: () => errColor,
128
+ })
129
+ .showSuggestionAfterError()
130
+ .exitOverride()
131
+ .hook("preSubcommand", track(run))
132
+ .addHelpText(
133
+ "after",
134
+ () => `\n${p.dim("Run sk <command> --help for its options. [app] is a directory (default: .).")}`,
135
+ );
136
+
137
+ program
138
+ .command("create")
139
+ .summary("Start a new app")
140
+ .description("Start a new app. In a terminal it asks for whatever the options leave open.")
141
+ .argument("[dir]")
142
+ .option("--name <name>", "The app's name (default: the directory's)")
143
+ .option("--template <name>", "showcase (every feature) or minimal")
144
+ .option("--os <list>", "What to package for: windows, macos, linux")
145
+ .option("--devtools", "Keep devtools (F12) in published builds")
146
+ .addOption(hidden("--no-devtools"))
147
+ .option("--pm <name>", "bun, npm, pnpm or yarn")
148
+ .option("-y, --yes", "Ask nothing, take the defaults")
149
+ .addOption(hidden("--without [parts]"))
150
+ .addOption(hidden("--features [parts]"))
151
+ .action(async (dir, o) => {
152
+ refuseParts(o);
153
+ run.code = await createCommand(dir, {
154
+ name: o.name,
155
+ template: o.template,
156
+ os: o.os,
157
+ devtools: o.devtools,
158
+ pm: o.pm,
159
+ yes: o.yes === true,
160
+ color: run.color,
161
+ });
162
+ });
163
+
164
+ program
165
+ .command("dev")
166
+ .summary("Run the app with hot reload")
167
+ .description(
168
+ "Run the app with hot reload: edits to .vue, .ts and .css apply without a restart; an edit to a shaders/*.slang effect recompiles it and restarts the app.",
169
+ )
170
+ .argument("[app]")
171
+ .option("--exe <workload>", "Run this dev workload instead of the cached one")
172
+ .option("--shader-compiler <exe>", "Compile effect shaders with this redslangc (or SK_REDSLANGC)")
173
+ .action(async (app, o) => {
174
+ run.code = await dev(app ?? ".", { exe: o.exe, shaderCompiler: o.shaderCompiler, color: run.color });
175
+ });
176
+
177
+ for (const [mode, text] of Object.entries(BUILD_MODES)) {
178
+ const cmd = program
179
+ .command(mode)
180
+ .summary(text.summary)
181
+ .description(text.about)
182
+ .argument("[app]")
183
+ .option("--platform <os>", "windows, macos or linux (default: this OS)")
184
+ .option("--out <dir>", "Output directory (default: <app>/dist/debug or dist/release)")
185
+ .option("--define <K=V>", "A Vite-style define; repeatable", collect, [])
186
+ .option("--config <path>", "An sk.config.json outside the app")
187
+ .option("--sign <identity>", "macOS: codesign identity (- for ad hoc)")
188
+ .option("--no-sign", "macOS: leave the bundle unsigned")
189
+ .option("--console", "Windows: keep the console window")
190
+ .option("--aot", "Windows x64: compile the app to a native image (--no-aot: don't)")
191
+ .addOption(hidden("--no-aot"))
192
+ .option("--json", "Print the result as JSON")
193
+ .optionsGroup("Advanced")
194
+ .option("--workload <exe>", "Stamp this workload instead of the cached one")
195
+ .option("--payload-only", "Write dist/.sk/app.skpk and stop")
196
+ .option("--aot-inputs", "Keep the typed sources for a later AOT compile")
197
+ .option("--aot-compiler <exe>", "Compile native images with this sk-aot.exe (or SK_AOT_COMPILER)")
198
+ .option("--shader-compiler <exe>", "Compile effect shaders with this redslangc (or SK_REDSLANGC)")
199
+ .addOption(hidden("--host <exe>"))
200
+ .addOption(hidden("--variant <name>"))
201
+ .addOption(hidden("--allow-workload-mismatch"))
202
+ .addOption(hidden("--allow-host-mismatch"))
203
+ .addOption(hidden("--without [parts]"))
204
+ .addOption(hidden("--features [parts]"));
205
+ const seen = given(cmd, "aot", "no-aot", "sign", "no-sign");
206
+ cmd.action(async (app, o) => {
207
+ refuseParts(o);
208
+ const platform = o.platform === undefined ? undefined : parsePlatform(o.platform);
209
+ if (mode === "run" && platform && platform !== currentPlatform()) {
210
+ throw new ConfigError(
211
+ `sk run starts the app here; a ${platform} build cannot run on ${process.platform} — use sk build`,
212
+ );
213
+ }
214
+ if (seen.has("sign") && seen.has("no-sign")) throw new ConfigError("--sign and --no-sign contradict each other");
215
+ const sign = typeof o.sign === "string" ? o.sign.trim() : o.sign === false ? false : undefined;
216
+ if (sign === "") throw new ConfigError('--sign needs a codesign identity ("-" for ad hoc)');
217
+ const aot = aotFlags({
218
+ aot: seen.has("aot"),
219
+ "no-aot": seen.has("no-aot"),
220
+ ...(o.aotCompiler !== undefined && { "aot-compiler": o.aotCompiler }),
221
+ });
222
+ const progress = progressFor(process.stderr, errColor);
223
+ const result = await buildApp({
224
+ progress,
225
+ target: app ?? ".",
226
+ configPath: o.config,
227
+ out: o.out,
228
+ host: o.workload ?? o.host,
229
+ variant: o.variant === undefined ? undefined : parseVariant(o.variant, "--variant"),
230
+ console: o.console === true,
231
+ payloadOnly: o.payloadOnly === true,
232
+ allowHostMismatch: o.allowWorkloadMismatch === true || o.allowHostMismatch === true,
233
+ defines: o.define,
234
+ aotInputs: o.aotInputs === true,
235
+ shaderCompiler: o.shaderCompiler,
236
+ ...aot,
237
+ color: errColor,
238
+ platform,
239
+ sign,
240
+ mode: mode === "publish" ? "release" : "debug",
241
+ }).finally(() => progress.end());
242
+ if (o.json) {
243
+ const s = result.stamp;
244
+ console.log(
245
+ JSON.stringify({
246
+ exe: result.exe,
247
+ skpk: result.skpk,
248
+ aotInputs: result.aotInputs,
249
+ effects: result.effects,
250
+ native: result.native,
251
+ name: result.config.name,
252
+ productName: result.config.productName,
253
+ version: result.config.version,
254
+ variant: result.variant,
255
+ host: result.host && {
256
+ exe: result.host.exe,
257
+ source: result.host.source,
258
+ profile: result.host.info.profile,
173
259
  },
260
+ assets: result.assets.length,
261
+ bundleBytes: result.bundleBytes,
262
+ payloadBytes: result.payloadBytes,
263
+ ...(result.packs.length ? { packs: result.packs } : {}),
264
+ stamp: s && {
265
+ bytes: s.bytes,
266
+ skew: s.skew,
267
+ dataAligned: s.dataAligned,
268
+ passes: s.passes,
269
+ subsystem: s.subsystem,
270
+ iconCount: s.iconCount,
271
+ ms: s.ms,
272
+ },
273
+ ...(result.bundle && {
274
+ platform: result.platform,
275
+ app: result.bundle.app,
276
+ bundle: {
277
+ bundleId: result.bundle.bundleId,
278
+ bytes: result.bundle.bytes,
279
+ iconSizes: result.bundle.iconSizes,
280
+ signed: result.bundle.signed,
281
+ signNote: result.bundle.signNote,
282
+ entitlements: result.bundle.entitlements,
283
+ ms: result.bundle.ms,
284
+ },
285
+ }),
286
+ warnings: result.warnings,
287
+ ms: result.ms,
174
288
  }),
175
- warnings: result.warnings,
176
- ms: result.ms,
177
- }),
178
- );
179
- } else {
180
- console.log(summary(result, colorEnabled(process.stdout, colorFlag(flags))));
181
- }
182
- if (command !== "run" || !result.exe) return 0;
183
- // `run`: inherited handles, so a GUI-subsystem exe's stderr still lands in this terminal.
184
- const child = spawn(result.exe, rest, { stdio: "inherit" });
185
- return await new Promise<number>((done) => child.on("exit", (c) => done(c ?? 0)));
289
+ );
290
+ } else {
291
+ console.log(summary(result, outColor));
292
+ }
293
+ if (mode !== "run" || !result.exe) return;
294
+ // Inherited handles, so a GUI-subsystem exe's stderr still lands in this terminal.
295
+ const child = spawn(result.exe, run.rest, { stdio: "inherit" });
296
+ run.code = await new Promise<number>((done) => child.on("exit", (c) => done(c ?? 0)));
297
+ });
186
298
  }
187
299
 
188
- if (command === "check") return await (await import("../check/command")).checkCommand(args[0], flags, CLI_VERSION);
189
- if (command === "explain")
190
- return (await import("../check/command")).explainCommand(args[0], flags.list === true, flags);
300
+ const colorFlags = { color: run.color === true, "no-color": run.color === false };
301
+ program
302
+ .command("check")
303
+ .summary("What breaks under AOT, and how well the code is typed")
304
+ .description(
305
+ "What in the bundle, app code and node_modules, breaks or slows down under AOT, and how well it is typed.",
306
+ )
307
+ .argument("[app]")
308
+ .option("--format <format>", "json: one JSON report on stdout (schema skathi.check)")
309
+ .option("--deny-warnings", "Fail on warnings too")
310
+ .option("--no-deps", "Only the app's own code")
311
+ .option("--config <path>", "An sk.config.json outside the app")
312
+ .addHelpText("after", () => section(p, "Exit codes", CHECK_EXIT_CODES).join("\n"))
313
+ .exitOverride(exitWith(2))
314
+ .action(async (app, o) => {
315
+ const { checkCommand } = await import("../check/command");
316
+ run.code = await checkCommand(
317
+ app,
318
+ { format: o.format, config: o.config, "deny-warnings": o.denyWarnings, "no-deps": !o.deps, ...colorFlags },
319
+ CLI_VERSION,
320
+ );
321
+ });
191
322
 
192
- if (command === "dev") {
193
- return await dev(args[0] ?? ".", { exe: typeof flags.exe === "string" ? flags.exe : undefined });
194
- }
323
+ program
324
+ .command("explain")
325
+ .summary("What a check code means and how to fix it")
326
+ .description("What a check code means, an example, and how to fix it.")
327
+ .argument("[code]")
328
+ .option("--list", "Every code")
329
+ .exitOverride(exitWith(2))
330
+ .action(async (code, o) => {
331
+ run.code = (await import("../check/command")).explainCommand(code, o.list === true, colorFlags);
332
+ });
195
333
 
196
- if (command === "host") {
197
- const [sub, arg] = args;
198
- if (sub === "info") {
199
- const exe = arg ?? resolveHost({ variant: variantOf(flags) ?? "standard", allowMismatch: true }).exe;
200
- // `hostInfo` refuses a stamped exe itself: asking one for host info would launch the app inside it.
201
- console.log(JSON.stringify(hostInfo(exe), null, 2));
202
- return 0;
203
- }
204
- if (sub === "path") {
205
- const h = resolveHost({
206
- variant: variantOf(flags) ?? "standard",
207
- host: typeof flags.host === "string" ? flags.host : undefined,
208
- platform: flags.platform === undefined ? undefined : parsePlatform(flags.platform),
209
- });
210
- console.log(flags.json ? JSON.stringify({ exe: h.exe, source: h.source, info: h.info }, null, 2) : h.exe);
211
- return 0;
212
- }
213
- if (sub === "add") {
214
- if (!arg) throw new HostError("sk host add <exe>");
215
- addHost(arg, (line) => console.log(line));
216
- return 0;
217
- }
218
- const color = colorEnabled(process.stderr, colorFlag(flags));
219
- if (sub === "fetch") {
220
- const named = flags.variant === "both" || flags.variant === DEV_HOST ? flags.variant : variantOf(flags);
221
- const variants = named === undefined ? [...VARIANTS, DEV_HOST] : named === "both" ? VARIANTS : [named];
222
- const progress = progressFor(process.stderr, color);
334
+ const workload = program
335
+ .command("workload")
336
+ .summary("Install, list and prune the engine workloads")
337
+ .description(
338
+ "A workload is the prebuilt engine executable an app is packed into. sk build and sk dev install " +
339
+ "this version's on demand.",
340
+ )
341
+ .hook("preSubcommand", track(run));
342
+
343
+ workload
344
+ .command("list")
345
+ .description("What is cached, its size, and what sk prune would remove")
346
+ .option("--json", "Print the inventory as JSON")
347
+ .action((o) => {
348
+ const roots = cacheRoots();
349
+ const entries = inventory(roots);
350
+ const keep = { current: CLI_VERSION };
351
+ if (o.json) {
352
+ const listed = entries.map((e) => ({ ...e, needed: needed(e, keep) }));
353
+ console.log(JSON.stringify({ root: roots.workloads, version: CLI_VERSION, entries: listed }, null, 2));
354
+ } else console.log(formatInventory(entries, roots, keep, outColor));
355
+ });
356
+
357
+ workload
358
+ .command("install")
359
+ .description(`Download this version's workloads (default: ${INSTALLABLE.join(", ")})`)
360
+ .argument("[variants...]")
361
+ .action(async (variants) => {
362
+ const progress = progressFor(process.stderr, errColor);
223
363
  try {
224
- for (const variant of variants) {
225
- progress.step(`${variant} host`);
226
- await fetchHost({ variant, log: (line) => progress.detail(line) });
364
+ for (const variant of variants.length ? variants.map(installable) : INSTALLABLE) {
365
+ progress.step(`${variant} workload`);
366
+ const { path } = await fetchHost({ variant, onBytes: (done, total) => progress.bytes(done, total) });
367
+ progress.detail(path);
227
368
  }
228
- } finally {
229
369
  progress.end();
370
+ } catch (e) {
371
+ progress.fail();
372
+ throw e;
230
373
  }
231
- return 0;
232
- }
233
- if (sub === "build") {
374
+ });
375
+
376
+ workload
377
+ .command("add")
378
+ .description("Verify a workload and add it to the cache")
379
+ .argument("<exe>")
380
+ .action((exe) => {
381
+ addHost(exe, (line) => console.log(line));
382
+ });
383
+
384
+ workload
385
+ .command("build")
386
+ .description(`In a Skathi checkout: build workloads with cargo (default: ${VARIANTS.join(" and ")})`)
387
+ .argument("[variants...]")
388
+ .action((variants) => {
234
389
  // cargo draws its own progress on the terminal: plain lines around it.
235
- const lines = lineProgress((line) => console.error(line), color);
236
- const v = flags.variant === "both" ? "both" : (variantOf(flags) ?? "both");
237
- for (const variant of v === "both" ? VARIANTS : [v]) {
238
- lines.step(`${variant} host`);
239
- const built = buildHost(variant, logTo(lines));
240
- lines.detail(built.path);
390
+ const lines = lineProgress((line) => console.error(line), errColor);
391
+ try {
392
+ for (const variant of variants.length ? variants.map((v) => parseVariant(v, "sk workload build")) : VARIANTS) {
393
+ lines.step(`${variant} workload`);
394
+ lines.detail(buildHost(variant, logTo(lines)).path);
395
+ }
396
+ lines.end();
397
+ } catch (e) {
398
+ lines.fail();
399
+ throw e;
241
400
  }
242
- lines.end();
243
- return 0;
244
- }
245
- throw new HostError("sk host info|path|fetch|add|build");
246
- }
401
+ });
247
402
 
248
- if (command === "create") {
249
- refuseParts(flags);
250
- const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string) : undefined);
251
- const yesNo = (k: string) => (flags[k] ? true : flags[`no-${k}`] ? false : undefined);
252
- return await createCommand(args[0], {
253
- name: str("name"),
254
- os: str("os"),
255
- devtools: yesNo("devtools"),
256
- template: str("template"),
257
- pm: str("pm"),
258
- yes: flags.yes === true,
403
+ workload
404
+ .command("path")
405
+ .description("Which workload sk build would use")
406
+ .option("--variant <name>", `${VARIANTS.join(" or ")} (default: standard)`)
407
+ .option("--workload <exe>", "Check this one instead of looking for it")
408
+ .option("--platform <os>", "windows, macos or linux (default: this OS)")
409
+ .option("--json", "Print it with what it says about itself")
410
+ .addOption(hidden("--host <exe>"))
411
+ .action((o) => {
412
+ const h = resolveHost({
413
+ variant: o.variant === undefined ? "standard" : parseVariant(o.variant, "--variant"),
414
+ host: o.workload ?? o.host,
415
+ platform: o.platform === undefined ? undefined : parsePlatform(o.platform),
416
+ });
417
+ console.log(o.json ? JSON.stringify({ exe: h.exe, source: h.source, info: h.info }, null, 2) : h.exe);
259
418
  });
260
- }
261
419
 
262
- console.error(
263
- `${paint(colorEnabled(process.stderr)).red("error")}: unknown command ${JSON.stringify(command)} (sk --help lists them)`,
264
- );
265
- return 1;
420
+ workload
421
+ .command("info")
422
+ .description("What a workload says about itself (default: the one sk build would use)")
423
+ .argument("[exe]")
424
+ .option("--variant <name>", `${VARIANTS.join(" or ")} (default: standard)`)
425
+ .action((exe, o) => {
426
+ const variant = o.variant === undefined ? "standard" : parseVariant(o.variant, "--variant");
427
+ // `hostInfo` refuses a stamped exe itself: asking one for its info would launch the app inside it.
428
+ console.log(JSON.stringify(hostInfo(exe ?? resolveHost({ variant, allowMismatch: true }).exe), null, 2));
429
+ });
430
+
431
+ workload.addCommand(pruneCommand(workload, run));
432
+ program.addCommand(pruneCommand(program, run));
433
+
434
+ program
435
+ .command("host", { hidden: true })
436
+ .argument("[command]")
437
+ .argument("[args...]")
438
+ .helpOption(false)
439
+ .allowUnknownOption()
440
+ .action((sub) => {
441
+ throw new HostError(`sk host is now sk workload: sk workload ${RENAMED[sub ?? ""] ?? "--help"}`);
442
+ });
443
+
444
+ program.command("version", { hidden: true }).action(() => console.log(CLI_VERSION));
445
+
446
+ return program;
447
+ }
448
+
449
+ function usageError(e: CommanderError, at: string, color: boolean): void {
450
+ const [first = "", ...more] = e.message.replace(/^error: /, "").split("\n");
451
+ const unknown = /^unknown command '(.*)'$/.exec(first);
452
+ const text = unknown
453
+ ? `unknown command ${JSON.stringify(unknown[1])} (${at} --help lists them)`
454
+ : `${first} (${at} --help lists the options)`;
455
+ console.error([`${paint(color).red("error")}: ${text}`, ...more].join("\n"));
456
+ }
457
+
458
+ export async function main(argv: string[]): Promise<number> {
459
+ const split = argv.indexOf("--");
460
+ const head = split < 0 ? argv : argv.slice(0, split);
461
+ const run: Run = { rest: split < 0 ? [] : argv.slice(split + 1), color: colorArg(head), code: 0, at: "sk" };
462
+ try {
463
+ await cli(run).parseAsync(head, { from: "user" });
464
+ } catch (e) {
465
+ if (!(e instanceof CommanderError)) throw e;
466
+ const shown = e.code === "commander.helpDisplayed" || e.code === "commander.help" || e.code === "commander.version";
467
+ if (!shown) usageError(e, run.at, colorEnabled(process.stderr, run.color));
468
+ return e.exitCode;
469
+ }
470
+ return run.code;
266
471
  }
267
472
 
268
473
  if (import.meta.main) {
@@ -270,12 +475,10 @@ if (import.meta.main) {
270
475
  (code) => process.exit(code),
271
476
  (e) => {
272
477
  const known = e instanceof ConfigError || e instanceof HostError;
273
- const red = paint(colorEnabled(process.stderr)).red;
478
+ const red = paint(colorEnabled(process.stderr, colorArg(process.argv.slice(2)))).red;
274
479
  if (known || (e instanceof Error && !process.env.SK_DEBUG)) console.error(`${red("error")}: ${e.message}`);
275
480
  else console.error(e);
276
481
  process.exit(1);
277
482
  },
278
483
  );
279
484
  }
280
-
281
- export { main };