@skathi-native/cli 0.1.0-beta.2 → 0.1.0-beta.4

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 (50) hide show
  1. package/aot/host-globals.json +105 -0
  2. package/aot/native.ts +142 -0
  3. package/aot/pin.ts +67 -0
  4. package/aot/toolchain.lock.json +17 -0
  5. package/aot/transform.ts +69 -0
  6. package/check/codes.ts +19 -0
  7. package/check/command.ts +5 -3
  8. package/check/index.ts +44 -1
  9. package/cli/aot-build.ts +192 -0
  10. package/cli/build-app.ts +102 -31
  11. package/cli/config.ts +45 -102
  12. package/cli/create.ts +12 -54
  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 -148
  17. package/cli/host-fetch.ts +116 -54
  18. package/cli/host.ts +59 -39
  19. package/cli/sk.ts +440 -246
  20. package/cli/skpk.ts +6 -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/effects/compile.ts +952 -0
  25. package/effects/redslangc.json +23 -0
  26. package/effects/redslangc.ts +220 -0
  27. package/effects/sk.slang +558 -0
  28. package/package.json +6 -2
  29. package/templates/icon.png +0 -0
  30. package/templates/minimal/.vscode/settings.json +3 -0
  31. package/templates/minimal/src/App.vue +2 -2
  32. package/templates/showcase/.vscode/settings.json +3 -0
  33. package/templates/showcase/shaders/sheen.slang +23 -0
  34. package/templates/showcase/src/components/Titlebar.vue +7 -3
  35. package/templates/showcase/src/engine.ts +3 -26
  36. package/templates/showcase/src/pages/AudioPage.vue +6 -9
  37. package/templates/showcase/src/pages/FilesPage.vue +11 -15
  38. package/templates/showcase/src/pages/FormsPage.vue +2 -3
  39. package/templates/showcase/src/pages/GraphicsPage.vue +13 -15
  40. package/templates/showcase/src/pages/HomePage.vue +1 -2
  41. package/templates/showcase/src/pages/LocalePage.vue +2 -2
  42. package/templates/showcase/src/pages/MediaPage.vue +1 -1
  43. package/templates/showcase/src/pages/MotionPage.vue +1 -1
  44. package/templates/showcase/src/pages/NetworkPage.vue +6 -5
  45. package/templates/showcase/src/pages/PermissionsPage.vue +2 -2
  46. package/templates/showcase/src/pages/StoragePage.vue +23 -36
  47. package/templates/showcase/src/pages/StylesPage.vue +9 -1
  48. package/templates/showcase/src/pages/SystemPage.vue +3 -3
  49. package/templates/showcase/src/styles.css +2 -2
  50. package/templates/showcase/src/components/Missing.vue +0 -26
package/cli/sk.ts CHANGED
@@ -1,277 +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";
7
+ import { aotFlags } from "./aot-build";
6
8
  import { buildApp, summary } from "./build-app";
7
- import {
8
- ConfigError,
9
- OPTIONAL,
10
- parseParts,
11
- partsLeftOut,
12
- selectVariant,
13
- VARIANTS,
14
- variantFor,
15
- type Variant,
16
- } from "./config";
9
+ import { ConfigError, parseVariant, PARTS_NOT_SELECTABLE, VARIANTS, type Variant } from "./config";
10
+ import { createCommand } from "./create";
17
11
  import { dev } from "./dev";
12
+ import { helpFormat, section } from "./help";
18
13
  import { addHost, buildHost, CLI_VERSION, DEV_HOST, HostError, hostInfo, resolveHost } from "./host";
19
14
  import { fetchHost } from "./host-fetch";
20
- import { colorEnabled, colorFlag, lineProgress, logTo, paint, progressFor } from "./term";
21
- import { createCommand } from "./create";
22
15
  import { currentPlatform, parsePlatform } from "./platform";
23
- import { commandHelp, topHelp } from "./help";
24
-
25
- type Flags = Record<string, string | boolean>;
26
- const BOOLEAN = new Set([
27
- "deny-warnings",
28
- "no-deps",
29
- "list",
30
- "console",
31
- "payload-only",
32
- "allow-host-mismatch",
33
- "aot-inputs",
34
- "help",
35
- "version",
36
- "json",
37
- "no-sign",
38
- "yes",
39
- "devtools",
40
- "no-devtools",
41
- "color",
42
- "no-color",
43
- ]);
44
- const REPEATABLE = new Set(["define"]);
45
-
46
- function parse(argv: string[]): {
47
- positional: string[];
48
- flags: Flags;
49
- 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`. */
50
22
  rest: string[];
51
- } {
52
- const positional: string[] = [];
53
- const flags: Flags = {};
54
- const repeated: Record<string, string[]> = {};
55
- let rest: string[] = [];
56
- for (let i = 0; i < argv.length; i++) {
57
- const a = argv[i]!;
58
- if (a === "--") {
59
- rest = argv.slice(i + 1);
60
- break;
61
- }
62
- if (a === "-h") flags.help = true;
63
- else if (a === "-y") flags.yes = true;
64
- else if (a === "-v") flags.version = true;
65
- else if (a.startsWith("--")) {
66
- // Split at the FIRST "=" only: `--define=K=V` keeps its own "=".
67
- const body = a.slice(2);
68
- const eq = body.indexOf("=");
69
- const name = eq < 0 ? body : body.slice(0, eq);
70
- const inline = eq < 0 ? undefined : body.slice(eq + 1);
71
- if (BOOLEAN.has(name)) flags[name] = true;
72
- else if (REPEATABLE.has(name)) (repeated[name] ??= []).push(inline ?? argv[++i] ?? "");
73
- else flags[name] = inline ?? argv[++i] ?? "";
74
- } else positional.push(a);
75
- }
76
- return { positional, flags, repeated, rest };
23
+ color: boolean | undefined;
24
+ code: number;
25
+ /** The command being parsed, for usage errors. */
26
+ at: string;
27
+ }
28
+
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
- const list = (name: string) => {
81
- const v = flags[name];
82
- if (v === undefined) return undefined;
83
- if (typeof v !== "string" || !v.trim())
84
- throw new ConfigError(`--${name} needs a list of parts (${OPTIONAL.join(", ")})`);
85
- return parseParts(v, `--${name}`);
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}`);
48
+ }
49
+
50
+ const hidden = <Flags extends string>(flags: Flags) => new Option(flags).hideHelp();
51
+
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);
86
66
  };
87
- const host = flags.variant;
88
- if (host !== undefined && (typeof host !== "string" || !host.trim()))
89
- throw new ConfigError("--variant needs a variant name");
90
- const sel = { features: list("features"), without: list("without"), host: host as string | undefined };
91
- if (!sel.features && !sel.without && !sel.host) return undefined;
92
- // Normalised: `no-audio+no-devtools` and `no-devtools+no-audio` are one host.
93
- return variantFor(partsLeftOut(selectVariant(sel, "the command line")));
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
+ });
94
109
  }
95
110
 
96
- async function main(argv: string[]): Promise<number> {
97
- const { positional, flags, repeated, rest } = parse(argv);
98
- const [command, ...args] = positional;
99
- if (command === "version" || (!command && flags.version === true)) {
100
- console.log(CLI_VERSION);
101
- return 0;
102
- }
103
- const color = colorEnabled(process.stdout, colorFlag(flags));
104
- const about = command === "help" ? args[0] : flags.help ? command : undefined;
105
- if (about !== undefined) {
106
- const text = commandHelp(about, color);
107
- if (text) {
108
- console.log(text);
109
- return 0;
110
- }
111
- }
112
- if (!command || flags.help || command === "help") {
113
- console.log(topHelp(color));
114
- return command || flags.help ? 0 : 1;
115
- }
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
+ );
116
136
 
117
- if (command === "build" || command === "publish" || command === "run") {
118
- const platform = flags.platform === undefined ? undefined : parsePlatform(flags.platform);
119
- if (command === "run" && platform && platform !== currentPlatform()) {
120
- throw new ConfigError(
121
- `sk run starts the app here; a ${platform} build cannot run on ${process.platform} — use sk build`,
122
- );
123
- }
124
- if (flags.sign !== undefined && (typeof flags.sign !== "string" || !flags.sign.trim())) {
125
- throw new ConfigError('--sign needs a codesign identity ("-" for ad hoc)');
126
- }
127
- if (flags.sign !== undefined && flags["no-sign"])
128
- throw new ConfigError("--sign and --no-sign contradict each other");
129
- const progress = progressFor(process.stderr, colorEnabled(process.stderr, colorFlag(flags)));
130
- const result = await buildApp({
131
- progress,
132
- target: args[0] ?? ".",
133
- configPath: typeof flags.config === "string" ? flags.config : undefined,
134
- out: typeof flags.out === "string" ? flags.out : undefined,
135
- host: typeof flags.host === "string" ? flags.host : undefined,
136
- variant: variantOf(flags),
137
- console: flags.console === true,
138
- payloadOnly: flags["payload-only"] === true,
139
- allowHostMismatch: flags["allow-host-mismatch"] === true,
140
- defines: repeated.define,
141
- aotInputs: flags["aot-inputs"] === true,
142
- platform,
143
- sign: flags["no-sign"] ? false : typeof flags.sign === "string" ? flags.sign.trim() : undefined,
144
- mode: command === "publish" ? "release" : "debug",
145
- }).finally(() => progress.end());
146
- if (flags.json) {
147
- const s = result.stamp;
148
- console.log(
149
- JSON.stringify({
150
- exe: result.exe,
151
- skpk: result.skpk,
152
- aotInputs: result.aotInputs,
153
- name: result.config.name,
154
- productName: result.config.productName,
155
- version: result.config.version,
156
- variant: result.variant,
157
- host: result.host && { exe: result.host.exe, source: result.host.source, profile: result.host.info.profile },
158
- assets: result.assets.length,
159
- bundleBytes: result.bundleBytes,
160
- payloadBytes: result.payloadBytes,
161
- ...(result.packs.length ? { packs: result.packs } : {}),
162
- stamp: s && {
163
- bytes: s.bytes,
164
- skew: s.skew,
165
- dataAligned: s.dataAligned,
166
- passes: s.passes,
167
- subsystem: s.subsystem,
168
- iconCount: s.iconCount,
169
- ms: s.ms,
170
- },
171
- ...(result.bundle && {
172
- platform: result.platform,
173
- app: result.bundle.app,
174
- bundle: {
175
- bundleId: result.bundle.bundleId,
176
- bytes: result.bundle.bytes,
177
- iconSizes: result.bundle.iconSizes,
178
- signed: result.bundle.signed,
179
- signNote: result.bundle.signNote,
180
- entitlements: result.bundle.entitlements,
181
- ms: result.bundle.ms,
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,
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,
182
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,
183
288
  }),
184
- warnings: result.warnings,
185
- ms: result.ms,
186
- }),
187
- );
188
- } else {
189
- console.log(summary(result, colorEnabled(process.stdout, colorFlag(flags))));
190
- }
191
- if (command !== "run" || !result.exe) return 0;
192
- // `run`: inherited handles, so a GUI-subsystem exe's stderr still lands in this terminal.
193
- const child = spawn(result.exe, rest, { stdio: "inherit" });
194
- 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
+ });
195
298
  }
196
299
 
197
- if (command === "check") return await (await import("../check/command")).checkCommand(args[0], flags, CLI_VERSION);
198
- if (command === "explain")
199
- 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
+ });
200
322
 
201
- if (command === "dev") {
202
- return await dev(args[0] ?? ".", { exe: typeof flags.exe === "string" ? flags.exe : undefined });
203
- }
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
+ });
204
333
 
205
- if (command === "host") {
206
- const [sub, arg] = args;
207
- if (sub === "info") {
208
- const exe = arg ?? resolveHost({ variant: variantOf(flags) ?? "standard", allowMismatch: true }).exe;
209
- // `hostInfo` refuses a stamped exe itself: asking one for host info would launch the app inside it.
210
- console.log(JSON.stringify(hostInfo(exe), null, 2));
211
- return 0;
212
- }
213
- if (sub === "path") {
214
- const h = resolveHost({
215
- variant: variantOf(flags) ?? "standard",
216
- host: typeof flags.host === "string" ? flags.host : undefined,
217
- platform: flags.platform === undefined ? undefined : parsePlatform(flags.platform),
218
- });
219
- console.log(flags.json ? JSON.stringify({ exe: h.exe, source: h.source, info: h.info }, null, 2) : h.exe);
220
- return 0;
221
- }
222
- if (sub === "add") {
223
- if (!arg) throw new HostError("sk host add <exe>");
224
- addHost(arg, (line) => console.log(line));
225
- return 0;
226
- }
227
- const color = colorEnabled(process.stderr, colorFlag(flags));
228
- if (sub === "fetch") {
229
- const named = flags.variant === "both" || flags.variant === DEV_HOST ? flags.variant : variantOf(flags);
230
- const variants = named === undefined ? [...VARIANTS, DEV_HOST] : named === "both" ? VARIANTS : [named];
231
- 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);
232
363
  try {
233
- for (const variant of variants) {
234
- progress.step(`${variant} host`);
235
- 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);
236
368
  }
237
- } finally {
238
369
  progress.end();
370
+ } catch (e) {
371
+ progress.fail();
372
+ throw e;
239
373
  }
240
- return 0;
241
- }
242
- 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) => {
243
389
  // cargo draws its own progress on the terminal: plain lines around it.
244
- const lines = lineProgress((line) => console.error(line), color);
245
- const v = flags.variant === "both" ? "both" : (variantOf(flags) ?? "both");
246
- for (const variant of v === "both" ? VARIANTS : [v]) {
247
- lines.step(`${variant} host`);
248
- const built = buildHost(variant, logTo(lines));
249
- 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;
250
400
  }
251
- lines.end();
252
- return 0;
253
- }
254
- throw new HostError("sk host info|path|fetch|add|build");
255
- }
401
+ });
256
402
 
257
- if (command === "create") {
258
- const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string) : undefined);
259
- const yesNo = (k: string) => (flags[k] ? true : flags[`no-${k}`] ? false : undefined);
260
- return await createCommand(args[0], {
261
- name: str("name"),
262
- os: str("os"),
263
- without: str("without"),
264
- devtools: yesNo("devtools"),
265
- template: str("template"),
266
- pm: str("pm"),
267
- 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);
268
418
  });
269
- }
270
419
 
271
- console.error(
272
- `${paint(colorEnabled(process.stderr)).red("error")}: unknown command ${JSON.stringify(command)} (sk --help lists them)`,
273
- );
274
- 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;
275
471
  }
276
472
 
277
473
  if (import.meta.main) {
@@ -279,12 +475,10 @@ if (import.meta.main) {
279
475
  (code) => process.exit(code),
280
476
  (e) => {
281
477
  const known = e instanceof ConfigError || e instanceof HostError;
282
- const red = paint(colorEnabled(process.stderr)).red;
478
+ const red = paint(colorEnabled(process.stderr, colorArg(process.argv.slice(2)))).red;
283
479
  if (known || (e instanceof Error && !process.env.SK_DEBUG)) console.error(`${red("error")}: ${e.message}`);
284
480
  else console.error(e);
285
481
  process.exit(1);
286
482
  },
287
483
  );
288
484
  }
289
-
290
- export { main };