@appling/cli 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @appling/cli
2
2
 
3
- Command line tool to check, format and inspect Appling models (`.appling` files).
3
+ Command line tool to set up, check, format and inspect Appling models (`.appling` files) and open them in the read only inspector.
4
4
 
5
5
  Appling is a declarative language that describes a business or web application in five layers: domain, behavior, application, interfaces and experience. The language itself lives in [`@appling/lang`](https://www.npmjs.com/package/@appling/lang).
6
6
 
@@ -19,11 +19,13 @@ npx @appling/cli check models
19
19
  ## Usage
20
20
 
21
21
  ```sh
22
+ appling init [folder] [--name <name>] [--agents <agents>] [--stack <stack>]
23
+ appling inspect [folder]
22
24
  appling check [files or folders...]
23
25
  appling fmt [files or folders...]
24
26
  appling graph [files or folders...]
25
27
  appling release <version> [files or folders...]
26
- appling generate [--plan | --migrate] [files or folders...]
28
+ appling generate [--plan | --coverage [--json] | --migrate | --sync] [files or folders...]
27
29
  appling simulate reach <machine> <state> [files or folders...]
28
30
  appling simulate actors <action> [files or folders...]
29
31
  appling simulate risks <action> [files or folders...]
@@ -34,6 +36,22 @@ Folders are searched recursively for `.appling` files. Hidden folders and `node_
34
36
 
35
37
  All files are loaded as one workspace, so references between modules resolve across files.
36
38
 
39
+ ### init
40
+
41
+ Sets up a new project: writes `package.json` if missing, installs `@appling/cli`, `@appling/ai` and the stack's extension, writes a starter module, the generate target (an empty `appling.config.json` with `--stack none`) and the missing `.gitignore` lines (`node_modules/`, `.appling/view.json`, the stack's local files), and connects the chosen coding agents (`claude`, `codex`, `opencode`, `gemini`, `antigravity`) to the Appling MCP server, the `appling` skill and its rules, all referenced from `node_modules`. It asks for what the flags leave open; `--stack` takes `django`, `ash`, `go`, `rust` or `none`.
42
+
43
+ ```sh
44
+ npx @appling/cli init todo --name todo --agents claude,codex --stack django
45
+ ```
46
+
47
+ ### inspect
48
+
49
+ Opens the read only inspector of a folder (the current folder by default) in your browser: the model canvas and the floating inspector of the selected element, to debug and inspect the model. It starts the server of `@appling/inspect` on a free port of `127.0.0.1`, prints its address, opens it in the default browser and runs until Ctrl+C.
50
+
51
+ ```sh
52
+ npx appling inspect models
53
+ ```
54
+
37
55
  ### check
38
56
 
39
57
  Parses, links and validates every file and prints one line per problem:
@@ -43,6 +61,8 @@ models/sales.appling:13:23 error A machine must govern an entity field marked "s
43
61
  2 file(s), 1 error(s)
44
62
  ```
45
63
 
64
+ Once there are no errors, it runs every `scenario` in the simulator and reports each one whose `then` does not hold as an error at its name, such as `Scenario ClerkCancelsDraft fails: order.status == placed is false.`
65
+
46
66
  ### fmt
47
67
 
48
68
  Rewrites every file into its canonical form:
@@ -70,11 +90,11 @@ When the model has errors, they are printed to stderr instead and nothing is wri
70
90
 
71
91
  Writes a snapshot of the semantic graph to `.appling/releases/<version>.json` in the current folder. The version looks like `1.2.3`. A model with errors is not released, and an existing version is never overwritten.
72
92
 
73
- Once a release exists, tools that edit the model (the IDE, the AI) record renames, type changes and removals of released domain elements as migration steps, in one block per module named after the release, such as `migration since_v1_0_0`.
93
+ Once a release exists, tools that edit the model (the AI) record renames, type changes and removals of released domain elements as migration steps, in one block per module named after the release, such as `migration since_v1_0_0`.
74
94
 
75
95
  ### generate
76
96
 
77
- Generates a draft project for every target in `appling.config.json` through its code generation extension, and writes the task registry `.appling/tasks.json` into it. See [`@appling/codegen`](https://www.npmjs.com/package/@appling/codegen) for the configuration. With `--plan`, it prints the steps without running them.
97
+ Generates a draft project for every target in `appling.config.json` through its code generation extension, and writes the task registry `.appling/tasks.json` into it. See [`@appling/codegen`](https://www.npmjs.com/package/@appling/codegen) for the configuration. With `--plan`, it prints the steps without running them. With `--coverage`, it plans every target and prints only the coverage as Markdown: the share of generated, partial and todo elements per extension, the completion (`(generated + partial / 2) / elements`), the registry tasks and the same per element kind; `--coverage --json` prints it as JSON.
78
98
 
79
99
  Generation checks the tools the extension needs first and refuses to write into a folder that is not empty.
80
100
 
@@ -93,12 +113,12 @@ paid is reachable from draft:
93
113
 
94
114
  ### refs
95
115
 
96
- Prints the code references of the workspace in the current folder (`.appling/references.json`): where an element and its members are implemented, by file and line range. With `--check`, it lists every reference whose anchor line moved (`shifted`), whose file or anchor is gone (`broken`) or whose element the model no longer has (`orphaned`), and exits with 1 when there is one.
116
+ Prints the code references of the workspace in the current folder: the `@appling <qualified name> <fingerprint>` markers in the code of its git work tree and its generated targets, with the lines of the declaration each marks. With `--check`, it lists every reference whose element changed since the code was written or was renamed by a migration step (`stale`) or that the model no longer has (`orphaned`), and exits with 1 when there is one.
97
117
 
98
118
  ```
99
119
  $ appling refs --check
100
- ../shop/sales/models.py:16-33 sales.Order: shifted from 14-31
101
- 1 reference(s), 1 shifted, 0 broken, 0 orphaned
120
+ ../shop/sales/models.py:9-9 sales.Order.status: stale, the element changed since the code was written
121
+ 2 reference(s), 1 stale, 0 orphaned
102
122
  ```
103
123
 
104
124
  ## Exit codes
@@ -106,8 +126,8 @@ $ appling refs --check
106
126
  | Code | Meaning |
107
127
  |---|---|
108
128
  | 0 | No errors |
109
- | 1 | `check`, `graph`, `release`, `generate` or `refs` found errors, `refs --check` found a reference that is not current, `release` found an invalid or existing version, `generate` failed, or `fmt` skipped a file with syntax errors |
110
- | 2 | Unknown command, `release` without a version, or `refs` without a qualified name or `--check` |
129
+ | 1 | `init` was cancelled or the installation failed, `inspect` got a folder that does not exist or its server failed, `check`, `graph`, `release`, `generate` or `refs` found errors, `refs --check` found a reference that is not current, `release` found an invalid or existing version, `generate` failed, or `fmt` skipped a file with syntax errors |
130
+ | 2 | Unknown command, `init` with an invalid flag or without a terminal and not every flag given, `release` without a version, or `refs` without a qualified name or `--check` |
111
131
 
112
132
  ## License
113
133
 
package/out/ide.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Serves the IDE for a folder, opens it in the browser and runs until the server ends or Ctrl+C. */
2
+ export declare function ide([folder]: string[]): Promise<number>;
package/out/ide.js ADDED
@@ -0,0 +1,21 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import open from 'open';
4
+ import { startIdeProcess } from '@appling/ide/process';
5
+ /** Serves the IDE for a folder, opens it in the browser and runs until the server ends or Ctrl+C. */
6
+ export async function ide([folder = '.']) {
7
+ const root = resolve(folder);
8
+ if (!existsSync(root)) {
9
+ console.error(`${root} does not exist`);
10
+ return 1;
11
+ }
12
+ const server = await startIdeProcess(root).catch((error) => error);
13
+ if (server instanceof Error) {
14
+ console.error(server.message);
15
+ return 1;
16
+ }
17
+ console.log(`Appling IDE for ${root} at ${server.url}\nPress Ctrl+C to stop.`);
18
+ await open(server.url).catch(() => undefined);
19
+ process.once('SIGINT', () => server.close());
20
+ return new Promise(done => server.child.once('exit', code => done(code ? 1 : 0)));
21
+ }
package/out/init.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { STACKS, type Stack } from '@appling/codegen';
2
+ export declare const AGENTS: {
3
+ claude: {
4
+ label: string;
5
+ skills: string;
6
+ setup(dir: string): void;
7
+ };
8
+ codex: {
9
+ label: string;
10
+ skills: string;
11
+ setup(dir: string): void;
12
+ };
13
+ opencode: {
14
+ label: string;
15
+ skills: string;
16
+ setup(dir: string): void;
17
+ };
18
+ gemini: {
19
+ label: string;
20
+ skills: string;
21
+ setup(dir: string): void;
22
+ };
23
+ antigravity: {
24
+ label: string;
25
+ skills: string;
26
+ setup(dir: string): void;
27
+ };
28
+ };
29
+ export { STACKS, type Stack };
30
+ export type Agent = keyof typeof AGENTS;
31
+ export interface InitOptions {
32
+ name: string;
33
+ agents: Agent[];
34
+ stack?: Stack;
35
+ }
36
+ /** appling init [folder] [--name <name>] [--agents <a,b>] [--stack <stack|none>]: asks for what the flags leave open. */
37
+ export declare function init(args: string[]): Promise<number>;
38
+ /** Writes the model, the generate target and each agent's wiring. Safe to run again: existing settings are kept. */
39
+ export declare function scaffold(dir: string, { name, agents, stack }: InitOptions): void;
package/out/init.js ADDED
@@ -0,0 +1,185 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join, relative, resolve } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { cancel, intro, isCancel, multiselect, outro, select, text } from '@clack/prompts';
6
+ import { addTarget, CONFIG, ignore, STACKS } from '@appling/codegen';
7
+ import { findApplingFiles } from '@appling/model';
8
+ /** Referenced from node_modules, never copied, so updating @appling/ai updates what every agent reads. */
9
+ const RULES = 'node_modules/@appling/ai/rules/appling.md';
10
+ const SKILLS = 'node_modules/@appling/ai/skills';
11
+ const SERVER = { command: 'npx', args: ['appling-mcp', '.'] };
12
+ const READ_RULES = `This application is modeled in Appling. Read ${RULES} and follow it before any work.`;
13
+ export const AGENTS = {
14
+ claude: {
15
+ label: 'Claude Code', skills: '.claude/skills', setup(dir) {
16
+ updateJson(join(dir, '.mcp.json'), c => { c.mcpServers = { ...c.mcpServers, appling: SERVER }; });
17
+ updateJson(join(dir, '.claude/settings.json'), c => { c.enabledMcpjsonServers = union(c.enabledMcpjsonServers, 'appling'); });
18
+ appendOnce(join(dir, 'CLAUDE.md'), `@${RULES}`);
19
+ }
20
+ },
21
+ codex: {
22
+ label: 'Codex', skills: '.agents/skills', setup(dir) {
23
+ appendOnce(join(dir, '.codex/config.toml'), '[mcp_servers.appling]\ncommand = "npx"\nargs = ["appling-mcp", "."]');
24
+ appendOnce(join(dir, 'AGENTS.md'), READ_RULES);
25
+ }
26
+ },
27
+ opencode: {
28
+ label: 'OpenCode', skills: '.agents/skills', setup(dir) {
29
+ updateJson(join(dir, 'opencode.json'), c => {
30
+ c.$schema ??= 'https://opencode.ai/config.json';
31
+ c.mcp = { ...c.mcp, appling: { type: 'local', command: [SERVER.command, ...SERVER.args], enabled: true } };
32
+ c.instructions = union(c.instructions, RULES);
33
+ });
34
+ }
35
+ },
36
+ gemini: {
37
+ label: 'Gemini CLI', skills: '.agents/skills', setup(dir) {
38
+ updateJson(join(dir, '.gemini/settings.json'), c => { c.mcpServers = { ...c.mcpServers, appling: SERVER }; });
39
+ appendOnce(join(dir, 'GEMINI.md'), `@./${RULES}`);
40
+ }
41
+ },
42
+ antigravity: {
43
+ label: 'Antigravity CLI', skills: '.agents/skills', setup(dir) {
44
+ updateJson(join(dir, '.agents/mcp_config.json'), c => { c.mcpServers = { ...c.mcpServers, appling: SERVER }; });
45
+ appendOnce(join(dir, 'AGENTS.md'), READ_RULES);
46
+ }
47
+ }
48
+ };
49
+ export { STACKS };
50
+ const NAME = /^[a-z][a-z0-9_-]*$/;
51
+ const NAME_HINT = 'lower case letters, digits, "-" and "_", starting with a letter';
52
+ /** appling init [folder] [--name <name>] [--agents <a,b>] [--stack <stack|none>]: asks for what the flags leave open. */
53
+ export async function init(args) {
54
+ let flags;
55
+ try {
56
+ flags = parseArgs({ args, allowPositionals: true, options: { name: { type: 'string' }, agents: { type: 'string' }, stack: { type: 'string' } } });
57
+ }
58
+ catch (error) {
59
+ console.error(error.message);
60
+ return 2;
61
+ }
62
+ const dir = resolve(flags.positionals[0] ?? '.');
63
+ const given = {
64
+ name: flags.values.name,
65
+ agents: flags.values.agents?.split(',').map(a => a.trim()),
66
+ stack: flags.values.stack
67
+ };
68
+ const invalid = [
69
+ given.name !== undefined && !NAME.test(given.name) && `--name: use ${NAME_HINT}`,
70
+ given.agents?.some(a => !(a in AGENTS)) && `--agents: choose from ${Object.keys(AGENTS).join(', ')}`,
71
+ given.stack !== undefined && given.stack !== 'none' && !(given.stack in STACKS) && `--stack: choose from ${Object.keys(STACKS).join(', ')}, none`
72
+ ].filter(Boolean);
73
+ if (invalid.length) {
74
+ invalid.forEach(line => console.error(line));
75
+ return 2;
76
+ }
77
+ const complete = given.name !== undefined && given.agents !== undefined && given.stack !== undefined;
78
+ if (!complete && !process.stdin.isTTY) {
79
+ console.error('Not interactive: pass --name, --agents and --stack.');
80
+ return 2;
81
+ }
82
+ const options = complete
83
+ ? { name: given.name, agents: given.agents, stack: given.stack === 'none' ? undefined : given.stack }
84
+ : await ask(dir, given);
85
+ if (!options)
86
+ return 1;
87
+ mkdirSync(dir, { recursive: true });
88
+ if (!existsSync(join(dir, 'package.json')))
89
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: options.name, private: true }, null, 2) + '\n');
90
+ const packages = ['@appling/cli', '@appling/ai', ...(options.stack ? [STACKS[options.stack]] : [])];
91
+ const manager = packageManager(dir);
92
+ const install = spawnSync(manager, [...(manager === 'npm' ? ['install', '--save-dev'] : ['add', '-D']), ...packages], { cwd: dir, stdio: 'inherit', shell: process.platform === 'win32' });
93
+ if (install.status !== 0) {
94
+ console.error(`Installing ${packages.join(' ')} with ${manager} failed.`);
95
+ return 1;
96
+ }
97
+ scaffold(dir, options);
98
+ console.log(`Appling is set up for ${options.agents.map(a => AGENTS[a].label).join(', ')}. Start your agent in ${relative(process.cwd(), dir) || 'this folder'} and describe the application you want.`);
99
+ return 0;
100
+ }
101
+ /** Writes the model, the generate target and each agent's wiring. Safe to run again: existing settings are kept. */
102
+ export function scaffold(dir, { name, agents, stack }) {
103
+ const module = name.replace(/-/g, '_');
104
+ if (stack)
105
+ addTarget(dir, stack, module);
106
+ else if (!existsSync(join(dir, CONFIG)))
107
+ writeFileSync(join(dir, CONFIG), '{}\n');
108
+ ignore(dir, ['node_modules/', '.appling/view.json']);
109
+ if (!findApplingFiles(dir).length) {
110
+ mkdirSync(join(dir, 'models'), { recursive: true });
111
+ writeFileSync(join(dir, 'models', `${module}.appling`), `module ${module} {\n}\n`);
112
+ }
113
+ const skills = readdirSync(join(dir, SKILLS));
114
+ for (const agent of agents) {
115
+ AGENTS[agent].setup(dir);
116
+ for (const skill of skills)
117
+ link(join(dir, AGENTS[agent].skills, skill), join(dir, SKILLS, skill));
118
+ }
119
+ }
120
+ async function ask(dir, given) {
121
+ intro('appling init');
122
+ const name = given.name ?? await text({
123
+ message: 'Project name',
124
+ initialValue: NAME.test(basename(dir)) ? basename(dir) : '',
125
+ validate: value => NAME.test(value ?? '') ? undefined : `Use ${NAME_HINT}.`
126
+ });
127
+ if (isCancel(name))
128
+ return stop();
129
+ const agents = given.agents ?? await multiselect({
130
+ message: 'Coding agents to connect',
131
+ options: Object.entries(AGENTS).map(([value, agent]) => ({ value, label: agent.label })),
132
+ required: true
133
+ });
134
+ if (isCancel(agents))
135
+ return stop();
136
+ const stack = given.stack ?? await select({
137
+ message: 'Stack to generate the application with',
138
+ options: [...Object.keys(STACKS).map(value => ({ value, label: value[0].toUpperCase() + value.slice(1) })), { value: 'none', label: 'Decide later' }]
139
+ });
140
+ if (isCancel(stack))
141
+ return stop();
142
+ outro('Installing');
143
+ return { name, agents: agents, stack: stack === 'none' ? undefined : stack };
144
+ }
145
+ function stop() {
146
+ cancel('Cancelled.');
147
+ return undefined;
148
+ }
149
+ /** The project's lockfile decides, then the package manager that ran init (npx, pnpm dlx, yarn dlx, bunx), else npm. */
150
+ function packageManager(dir) {
151
+ const locks = [['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['package-lock.json', 'npm']];
152
+ const lock = locks.find(([file]) => existsSync(join(dir, file)));
153
+ if (lock)
154
+ return lock[1];
155
+ const runner = process.env.npm_config_user_agent?.split('/')[0];
156
+ return runner && ['pnpm', 'yarn', 'bun'].includes(runner) ? runner : 'npm';
157
+ }
158
+ function updateJson(path, change) {
159
+ const json = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
160
+ change(json);
161
+ mkdirSync(dirname(path), { recursive: true });
162
+ writeFileSync(path, JSON.stringify(json, null, 2) + '\n');
163
+ }
164
+ /** Appends the text unless the file already has its first line. */
165
+ function appendOnce(path, text) {
166
+ const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
167
+ if (current.includes(text.split('\n')[0]))
168
+ return;
169
+ mkdirSync(dirname(path), { recursive: true });
170
+ writeFileSync(path, current ? `${current.trimEnd()}\n\n${text}\n` : `${text}\n`);
171
+ }
172
+ function union(list, item) {
173
+ return [...new Set([...(list ?? []), item])];
174
+ }
175
+ /** A relative link, so the project can move; a junction on Windows, which needs no privileges. */
176
+ function link(path, target) {
177
+ try {
178
+ lstatSync(path);
179
+ return;
180
+ }
181
+ catch {
182
+ mkdirSync(dirname(path), { recursive: true });
183
+ symlinkSync(relative(dirname(path), target), path, 'junction');
184
+ }
185
+ }
@@ -0,0 +1,2 @@
1
+ /** Serves the read only inspector for a folder, opens it in the browser and runs until the server ends or Ctrl+C. */
2
+ export declare function inspect([folder]: string[]): Promise<number>;
package/out/inspect.js ADDED
@@ -0,0 +1,21 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import open from 'open';
4
+ import { startInspectProcess } from '@appling/inspect/process';
5
+ /** Serves the read only inspector for a folder, opens it in the browser and runs until the server ends or Ctrl+C. */
6
+ export async function inspect([folder = '.']) {
7
+ const root = resolve(folder);
8
+ if (!existsSync(root)) {
9
+ console.error(`${root} does not exist`);
10
+ return 1;
11
+ }
12
+ const server = await startInspectProcess(root).catch((error) => error);
13
+ if (server instanceof Error) {
14
+ console.error(server.message);
15
+ return 1;
16
+ }
17
+ console.log(`Appling Inspect for ${root} at ${server.url}\nPress Ctrl+C to stop.`);
18
+ await open(server.url).catch(() => undefined);
19
+ process.once('SIGINT', () => server.close());
20
+ return new Promise(done => server.child.once('exit', code => done(code ? 1 : 0)));
21
+ }
package/out/main.js CHANGED
@@ -5,24 +5,33 @@ import { basename, join, relative, resolve } from 'node:path';
5
5
  import { URI } from 'langium';
6
6
  import { NodeFileSystem } from 'langium/node';
7
7
  import { createApplingServices, print } from '@appling/lang';
8
- import { BASELINE, checkPrerequisites, describe, loadExtension, mergeGeneration, pendingChanges, plan, planMigrations, readApplied, readConfig, readRegistry, runMigrations, runPlan } from '@appling/codegen';
9
- import { buildGraph, dependencies, findApplingFiles, resolveReferences, Simulator, writeRelease } from '@appling/model';
8
+ import { BASELINE, checkPrerequisites, coverage, coverageMarkdown, coverageReport, coverageTable, describe, loadExtension, mergeGeneration, pendingChanges, plan, planMigrations, readApplied, readConfig, readRegistry, recordGeneration, runMigrations, runPlan, workspaceReferences } from '@appling/codegen';
9
+ import { buildGraph, checkScenarios, dependencies, findApplingFiles, Simulator, writeRelease } from '@appling/model';
10
+ import { inspect } from './inspect.js';
11
+ import { init } from './init.js';
10
12
  const USAGE = [
11
- 'Usage: appling <check|fmt|graph> [files or folders...]',
13
+ 'Usage: appling init [folder] [--name <name>] [--agents <claude,codex,opencode,gemini,antigravity>] [--stack <django|ash|go|rust|none>]',
14
+ ' appling inspect [folder]',
15
+ ' appling <check|fmt|graph> [files or folders...]',
12
16
  ' appling release <version> [files or folders...]',
13
- ' appling generate [--plan | --migrate | --sync] [files or folders...]',
17
+ ' appling generate [--plan | --coverage [--json] | --migrate | --sync] [files or folders...]',
14
18
  ' appling simulate <reach <machine> <state> | actors <action> | risks <action>> [files or folders...]',
15
19
  ' appling refs <qualified name | --check> [files or folders...]'
16
20
  ].join('\n');
17
21
  async function main([command, ...args]) {
22
+ if (command === 'init')
23
+ return init(args);
24
+ if (command === 'inspect')
25
+ return inspect(args);
18
26
  const question = command === 'simulate' ? args.slice(0, args[0] === 'reach' ? 3 : 2) : command === 'refs' ? args.slice(0, 1) : [];
19
27
  if (!['check', 'fmt', 'graph', 'release', 'generate', 'simulate', 'refs'].includes(command) || ((command === 'release' || command === 'refs') && !args[0])
20
28
  || (command === 'simulate' && (!['reach', 'actors', 'risks'].includes(question[0]) || question.some(a => !a)))) {
21
29
  console.error(USAGE);
22
30
  return 2;
23
31
  }
24
- const mode = command === 'generate' && ['--plan', '--migrate', '--sync'].includes(args[0]) ? args[0] : undefined;
25
- const [version, paths] = command === 'release' ? [args[0], args.slice(1)] : ['', args.slice(mode ? 1 : question.length)];
32
+ const mode = command === 'generate' && ['--plan', '--coverage', '--migrate', '--sync'].includes(args[0]) ? args[0] : undefined;
33
+ const json = mode === '--coverage' && args[1] === '--json';
34
+ const [version, paths] = command === 'release' ? [args[0], args.slice(1)] : ['', args.slice(mode ? (json ? 2 : 1) : question.length)];
26
35
  const files = (paths.length ? paths : ['.']).flatMap(p => findApplingFiles(resolve(p)));
27
36
  const { shared, Appling } = createApplingServices(NodeFileSystem);
28
37
  const documents = await Promise.all(files.map(f => shared.workspace.LangiumDocuments.getOrCreateDocument(URI.file(f))));
@@ -34,12 +43,19 @@ async function main([command, ...args]) {
34
43
  if (command === 'release')
35
44
  return release(documents, Appling, version);
36
45
  if (command === 'generate')
37
- return generate(documents, Appling, mode);
46
+ return generate(documents, Appling, mode, json);
38
47
  if (command === 'simulate')
39
48
  return simulate(documents, Appling, question);
40
49
  if (command === 'refs')
41
50
  return refs(documents, Appling, question[0]);
42
- const errors = report(documents, console.log);
51
+ let errors = report(documents, console.log);
52
+ // Scenarios run in the simulator once the model itself has no errors.
53
+ if (!errors) {
54
+ for (const problem of checkScenarios(documents.map(doc => doc.parseResult.value), Appling)) {
55
+ errors++;
56
+ console.log(`${relative('.', URI.parse(problem.uri).fsPath)}:${problem.range.start.line + 1}:${problem.range.start.character + 1} error ${problem.message}`);
57
+ }
58
+ }
43
59
  console.log(`${documents.length} file(s), ${errors} error(s)`);
44
60
  return errors ? 1 : 0;
45
61
  }
@@ -70,13 +86,13 @@ function simulate(documents, services, [question, target, state]) {
70
86
  }
71
87
  }
72
88
  /** Prints where an element and its members are implemented, or with --check every reference that is not current. */
73
- function refs(documents, services, target) {
89
+ async function refs(documents, services, target) {
74
90
  if (report(documents, console.error))
75
91
  return 1;
76
- const all = resolveReferences('.', buildGraph(documents.map(doc => doc.parseResult.value), services));
92
+ const all = await workspaceReferences('.', buildGraph(documents.map(doc => doc.parseResult.value), services));
77
93
  const line = (r) => `${r.file}:${r.start}-${r.end} ${r.qn}`;
78
94
  if (target !== '--check') {
79
- const found = all.filter(r => r.qn === target || r.qn.startsWith(`${target}.`));
95
+ const found = all.filter(r => r.qn === target || r.qn.startsWith(`${target}.`) || r.qn.startsWith(`${target}#`));
80
96
  for (const r of found)
81
97
  console.log(`${line(r)}${r.status === 'current' ? '' : ` (${r.status})`}`);
82
98
  if (!found.length)
@@ -85,14 +101,14 @@ function refs(documents, services, target) {
85
101
  }
86
102
  const stale = all.filter(r => r.status !== 'current');
87
103
  for (const r of stale) {
88
- console.log(`${line(r)}: ${r.status === 'shifted' ? `shifted from ${r.recorded.start}-${r.recorded.end}`
89
- : r.status === 'broken' ? `broken, "${r.anchor}" not found` : 'orphaned, no such element in the model'}`);
104
+ console.log(`${line(r)}: ${r.status === 'orphaned' ? 'orphaned, no such element in the model'
105
+ : r.marked ? `stale, the marker names ${r.marked}` : 'stale, the element changed since the code was written'}`);
90
106
  }
91
107
  const count = (status) => stale.filter(r => r.status === status).length;
92
- console.log(`${all.length} reference(s), ${count('shifted')} shifted, ${count('broken')} broken, ${count('orphaned')} orphaned`);
108
+ console.log(`${all.length} reference(s), ${count('stale')} stale, ${count('orphaned')} orphaned`);
93
109
  return stale.length ? 1 : 0;
94
110
  }
95
- async function generate(documents, services, mode) {
111
+ async function generate(documents, services, mode, json) {
96
112
  if (report(documents, console.error))
97
113
  return 1;
98
114
  const targets = readConfig('.').generate ?? [];
@@ -101,6 +117,20 @@ async function generate(documents, services, mode) {
101
117
  return 1;
102
118
  }
103
119
  const graph = buildGraph(documents.map(doc => doc.parseResult.value), services);
120
+ if (mode === '--coverage') {
121
+ // Plans every target without running anything: the coverage of each extension over this model
122
+ const plans = [];
123
+ for (const target of targets) {
124
+ const extension = await loadExtension(target.extension, '.');
125
+ if (plans.some(p => p.extension === extension.name))
126
+ continue;
127
+ const options = target.options ?? {};
128
+ plans.push({ extension: extension.name, input: 'model', entries: plan(graph, extension, String(options.name ?? basename(resolve(target.out))), options).entries });
129
+ }
130
+ const result = coverageReport(plans);
131
+ console.log(json ? JSON.stringify(result, null, 2) : coverageMarkdown(result, undefined, { marker: false }).trimEnd());
132
+ return 0;
133
+ }
104
134
  for (const target of targets) {
105
135
  const failed = mode === '--migrate' ? await migrateTarget(graph, target.extension, target.out, target.options ?? {})
106
136
  : mode === '--sync' ? await syncTarget(graph, target.extension, target.out, target.options ?? {})
@@ -130,8 +160,9 @@ async function syncTarget(graph, name, out, options) {
130
160
  const temp = mkdtempSync(join(tmpdir(), 'appling-sync-'));
131
161
  try {
132
162
  const next = join(temp, basename(resolve(out)));
133
- runPlan(plan(graph, extension, String(options.name ?? basename(resolve(out))), options), next, line => console.log(` ${line}`));
163
+ await runPlan(plan(graph, extension, String(options.name ?? basename(resolve(out))), options), next, line => console.log(` ${line}`));
134
164
  const report = mergeGeneration(out, next, extension.syncExclude ?? []);
165
+ recordGeneration('.', out, graph, graph.nodes.map(n => n.qn));
135
166
  for (const [label, files] of Object.entries(report))
136
167
  if (files.length)
137
168
  console.log(`${label}: ${files.join(', ')}`);
@@ -178,6 +209,9 @@ async function generateTarget(graph, name, out, options, onlyPlan) {
178
209
  console.log(`${name} -> ${out}`);
179
210
  for (const { node, step } of result.steps)
180
211
  console.log(` ${node}: ${describe(step)}`);
212
+ console.log('');
213
+ console.log(coverageTable(coverage(result.entries)));
214
+ console.log('');
181
215
  console.log(summary(result));
182
216
  return false;
183
217
  }
@@ -191,7 +225,8 @@ async function generateTarget(graph, name, out, options, onlyPlan) {
191
225
  return true;
192
226
  }
193
227
  try {
194
- runPlan(result, out, line => console.log(line));
228
+ await runPlan(result, out, line => console.log(line));
229
+ recordGeneration('.', out, graph, graph.nodes.map(n => n.qn));
195
230
  }
196
231
  catch (error) {
197
232
  console.error(error.message);
package/package.json CHANGED
@@ -1,7 +1,13 @@
1
1
  {
2
2
  "name": "@appling/cli",
3
- "version": "0.2.1",
4
- "description": "Command line tool to check, format, inspect, release and generate Appling models",
3
+ "version": "0.3.0",
4
+ "description": "Command line tool to check, format, inspect, release and generate Appling models and open them in the read only inspector",
5
+ "homepage": "https://www.appling.tools/docs/",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/alex20465/appling.git",
9
+ "directory": "packages/cli"
10
+ },
5
11
  "type": "module",
6
12
  "bin": {
7
13
  "appling": "./out/main.js"
@@ -10,10 +16,13 @@
10
16
  "out"
11
17
  ],
12
18
  "dependencies": {
13
- "@appling/codegen": "0.1.1",
14
- "@appling/lang": "0.2.1",
15
- "@appling/model": "0.1.1",
16
- "langium": "4.4.0"
19
+ "@appling/codegen": "0.1.3",
20
+ "@appling/inspect": "0.1.3",
21
+ "@appling/lang": "0.3.0",
22
+ "@appling/model": "0.1.3",
23
+ "@clack/prompts": "1.8.1",
24
+ "langium": "4.4.0",
25
+ "open": "11.0.4"
17
26
  },
18
27
  "devDependencies": {
19
28
  "@types/node": "^24.19.2",