@devicecloud.dev/dcd 5.14.1 → 5.16.0-beta.1

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 (44) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/device.d.ts +39 -0
  5. package/dist/commands/device.js +479 -101
  6. package/dist/e2e/index.d.ts +4 -0
  7. package/dist/e2e/index.js +41 -0
  8. package/dist/e2e/provider.d.ts +80 -0
  9. package/dist/e2e/provider.js +233 -0
  10. package/dist/gateways/api-gateway.d.ts +25 -3
  11. package/dist/gateways/api-gateway.js +68 -6
  12. package/dist/gateways/device-gateway.d.ts +34 -10
  13. package/dist/gateways/device-gateway.js +72 -17
  14. package/dist/mcp/bridge.d.ts +30 -16
  15. package/dist/mcp/bridge.js +201 -64
  16. package/dist/mcp/local-files.d.ts +14 -0
  17. package/dist/mcp/local-files.js +75 -0
  18. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  19. package/dist/mcp/tools/download-artifacts.js +44 -17
  20. package/dist/services/report-download.service.d.ts +32 -0
  21. package/dist/services/report-download.service.js +51 -2
  22. package/dist/services/telemetry.service.d.ts +20 -1
  23. package/dist/services/telemetry.service.js +27 -6
  24. package/dist/types/domain/device-session.types.d.ts +73 -3
  25. package/dist/types/domain/device-session.types.js +2 -0
  26. package/dist/utils/api-url.d.ts +20 -0
  27. package/dist/utils/api-url.js +49 -0
  28. package/dist/utils/app-upload.d.ts +6 -0
  29. package/dist/utils/app-upload.js +19 -0
  30. package/dist/utils/config-store.d.ts +5 -1
  31. package/dist/utils/config-store.js +18 -2
  32. package/dist/utils/device-artifacts.d.ts +5 -0
  33. package/dist/utils/device-artifacts.js +22 -0
  34. package/dist/utils/device-bundle.d.ts +39 -9
  35. package/dist/utils/device-bundle.js +153 -51
  36. package/dist/utils/device-flags.d.ts +17 -0
  37. package/dist/utils/device-flags.js +145 -0
  38. package/dist/utils/device-output.d.ts +53 -7
  39. package/dist/utils/device-output.js +148 -21
  40. package/dist/utils/device-run.d.ts +8 -3
  41. package/dist/utils/device-run.js +85 -8
  42. package/dist/utils/zip-integrity.d.ts +21 -0
  43. package/dist/utils/zip-integrity.js +45 -0
  44. package/package.json +10 -1
@@ -1,6 +1,12 @@
1
1
  import type { AuthContext } from '../types/domain/auth.types.js';
2
2
  /** The platform a local build is for, from its file name; undefined if unknown. */
3
3
  export declare function platformOfAppFile(filePath: string): 'android' | 'ios' | undefined;
4
+ /**
5
+ * The platform a build at a URL is for, from the file name in its path:
6
+ * install from a URL takes an Android .apk or a zipped iOS simulator .app.
7
+ * Undefined when the path names neither (a signed link with no file name).
8
+ */
9
+ export declare function platformOfAppUrl(url: string): 'android' | 'ios' | undefined;
4
10
  export interface UploadLocalAppOptions {
5
11
  apiUrl: string;
6
12
  auth: AuthContext;
@@ -14,6 +14,25 @@ export function platformOfAppFile(filePath) {
14
14
  return 'ios';
15
15
  return undefined;
16
16
  }
17
+ /**
18
+ * The platform a build at a URL is for, from the file name in its path:
19
+ * install from a URL takes an Android .apk or a zipped iOS simulator .app.
20
+ * Undefined when the path names neither (a signed link with no file name).
21
+ */
22
+ export function platformOfAppUrl(url) {
23
+ let pathname;
24
+ try {
25
+ pathname = decodeURIComponent(new URL(url).pathname).toLowerCase();
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ if (pathname.endsWith('.apk'))
31
+ return 'android';
32
+ if (pathname.endsWith('.zip'))
33
+ return 'ios';
34
+ return undefined;
35
+ }
17
36
  /**
18
37
  * Upload a local build the way `dcd upload` does, and return its binary id:
19
38
  * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and the
@@ -21,13 +21,17 @@ export declare function getConfigPath(): string;
21
21
  export declare function readConfig(): StoredConfig | null;
22
22
  /**
23
23
  * Resolve the API URL a command should talk to. Precedence:
24
- * 1. explicit --api-url flag
24
+ * 1. explicit --api-url flag (or DCD_API_URL, for the MCP server)
25
25
  * 2. api_url stored by `dcd login` (honors the env the user logged into)
26
26
  * 3. prod default
27
27
  *
28
28
  * Without this, session commands default to prod and a dev/staging Bearer
29
29
  * token is rejected with a misleading "Invalid or expired JWT". `switch-org`
30
30
  * has always done this; this helper extends it to every command.
31
+ *
32
+ * An explicit URL is checked first, since the credentials go to it
33
+ * (checkApiUrl): plain http is refused except to this machine, and a host
34
+ * other than devicecloud.dev gets a warning on stderr, once.
31
35
  */
32
36
  export declare function resolveApiUrl(flag: string | undefined): string;
33
37
  export declare function writeConfig(config: StoredConfig): void;
@@ -11,6 +11,8 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync
11
11
  import { homedir } from 'node:os';
12
12
  import * as path from 'node:path';
13
13
  import { ENVIRONMENTS } from '../config/environments.js';
14
+ import { checkApiUrl } from './api-url.js';
15
+ import { CliError } from './cli.js';
14
16
  export const CONFIG_SCHEMA_VERSION = 1;
15
17
  export function getConfigDir() {
16
18
  if (process.env.DCD_CONFIG_DIR)
@@ -45,20 +47,34 @@ export function readConfig() {
45
47
  return null;
46
48
  }
47
49
  }
50
+ /** Hosts already warned about in this process: the MCP server resolves its URL again and again. */
51
+ const warnedHosts = new Set();
48
52
  /**
49
53
  * Resolve the API URL a command should talk to. Precedence:
50
- * 1. explicit --api-url flag
54
+ * 1. explicit --api-url flag (or DCD_API_URL, for the MCP server)
51
55
  * 2. api_url stored by `dcd login` (honors the env the user logged into)
52
56
  * 3. prod default
53
57
  *
54
58
  * Without this, session commands default to prod and a dev/staging Bearer
55
59
  * token is rejected with a misleading "Invalid or expired JWT". `switch-org`
56
60
  * has always done this; this helper extends it to every command.
61
+ *
62
+ * An explicit URL is checked first, since the credentials go to it
63
+ * (checkApiUrl): plain http is refused except to this machine, and a host
64
+ * other than devicecloud.dev gets a warning on stderr, once.
57
65
  */
58
66
  export function resolveApiUrl(flag) {
59
67
  const explicit = flag?.trim();
60
- if (explicit)
68
+ if (explicit) {
69
+ const check = checkApiUrl(explicit);
70
+ if (!check.ok)
71
+ throw new CliError(check.reason);
72
+ if (check.warning && !warnedHosts.has(check.origin)) {
73
+ warnedHosts.add(check.origin);
74
+ process.stderr.write(`Warning: ${check.warning}\n`);
75
+ }
61
76
  return explicit;
77
+ }
62
78
  return readConfig()?.api_url ?? ENVIRONMENTS.prod.apiUrl;
63
79
  }
64
80
  export function writeConfig(config) {
@@ -43,6 +43,11 @@ export interface DownloadArtifactOptions {
43
43
  /** How many times to try each file before reporting it failed. */
44
44
  attempts?: number;
45
45
  }
46
+ /**
47
+ * Download one link to `target`, tried twice, making its folder. A failed
48
+ * download leaves no partial file behind.
49
+ */
50
+ export declare function downloadFile(url: string, target: string, options?: DownloadArtifactOptions): Promise<void>;
46
51
  /**
47
52
  * Download every file with a link into `dir`, four at a time. Each file is
48
53
  * tried twice (a stalled CDN response usually succeeds on a second
@@ -165,6 +165,28 @@ async function downloadOnce(url, target, idleMs, totalMs) {
165
165
  clearTimeout(total);
166
166
  }
167
167
  }
168
+ /**
169
+ * Download one link to `target`, tried twice, making its folder. A failed
170
+ * download leaves no partial file behind.
171
+ */
172
+ export async function downloadFile(url, target, options = {}) {
173
+ const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
174
+ const totalMs = options.totalTimeoutMs ?? DEFAULT_TOTAL_TIMEOUT_MS;
175
+ const attempts = Math.max(1, options.attempts ?? DEFAULT_ATTEMPTS);
176
+ await mkdir(path.dirname(target), { recursive: true });
177
+ let lastError;
178
+ for (let attempt = 1; attempt <= attempts; attempt++) {
179
+ try {
180
+ await downloadOnce(url, target, idleMs, totalMs);
181
+ return;
182
+ }
183
+ catch (error) {
184
+ lastError = error;
185
+ }
186
+ }
187
+ await rm(target, { force: true }).catch(() => { });
188
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
189
+ }
168
190
  /**
169
191
  * Download every file with a link into `dir`, four at a time. Each file is
170
192
  * tried twice (a stalled CDN response usually succeeds on a second
@@ -3,17 +3,45 @@ import type { DeviceFlowBundle } from '../types/domain/device-session.types.js';
3
3
  /** The API's limit on a bundle (dcd plan 2.5b). */
4
4
  export declare const MAX_BUNDLE_BYTES: number;
5
5
  /**
6
- * The files under `dir` a bundle needs, relative to it, in a stable order:
7
- * every YAML file (flows, subflows, config), the files the flows use
8
- * (runScript, addMedia, assertScreenshot and the like), and config's
9
- * includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
10
- * and .zip files with its flows.
6
+ * The files a flow reaches: the flow, the files it uses (runFlow, runScript,
7
+ * addMedia, assertScreenshot and the like), and the files those use in turn.
8
+ * Absolute paths, the flow first. `problems` are the files it names that do
9
+ * not exist. A flow that can't be read throws; a YAML file it uses that is
10
+ * not a flow (a data file) is taken as it is.
11
+ */
12
+ export declare function reachableFiles(flow: string): {
13
+ files: string[];
14
+ problems: string[];
15
+ };
16
+ /**
17
+ * For a single flow file that uses other files (runFlow, runScript, addMedia
18
+ * and the like): the folder to upload as a bundle, and the file's path
19
+ * inside it. Sent as yaml on its own, the flow would fail on the device with
20
+ * an invalid file path, because the files it uses would not be there. The
21
+ * folder is the closest one that holds every file the flow reaches; only
22
+ * those files are uploaded. Null when the flow uses no other files, or can't
23
+ * be read (the device reports that itself).
24
+ */
25
+ export declare function flowFileBundle(file: string): {
26
+ dir: string;
27
+ entry: string;
28
+ } | null;
29
+ /** A path inside a bundle as the API takes it: forward slashes on every platform. */
30
+ export declare function bundlePath(relative: string): string;
31
+ /**
32
+ * The files under `dir` a bundle needs, relative to it, in a stable order.
33
+ *
34
+ * With an `entry`, the one flow that will run: that flow and the files it
35
+ * reaches (reachableFiles), which must all be inside `dir`. Nothing else is
36
+ * read or sent, so a folder high above the flow (a home directory, say)
37
+ * costs nothing and gives nothing away.
11
38
  *
12
- * `entry` is the one flow that will run. Its files must all be inside `dir`.
13
- * Without an entry every flow may run, so that goes for all of them. Another
14
- * flow's missing file doesn't stop the entry running, so it is left out.
39
+ * Without one, every flow may run: every YAML file (flows, subflows, config)
40
+ * and the files they use. Either way, config's includedPaths too, and nothing
41
+ * else: an agent's samples folder sent 265 MB of .apk and .zip files with
42
+ * its flows.
15
43
  */
16
- export declare function bundleFiles(dir: string, entry?: string, warn?: (message: string) => void): string[];
44
+ export declare function bundleFiles(dir: string, entry?: string, warn?: (message: string) => void, confineTo?: string): string[];
17
45
  export interface UploadFlowBundleOptions {
18
46
  apiUrl: string;
19
47
  auth: AuthContext;
@@ -21,6 +49,8 @@ export interface UploadFlowBundleOptions {
21
49
  /** The one flow that will run, a path inside `dir`. Omitted, all of them. */
22
50
  entry?: string;
23
51
  log: (message: string) => void;
52
+ /** Send nothing that resolves outside this folder (links included). */
53
+ confineTo?: string;
24
54
  }
25
55
  /**
26
56
  * Zip the files a directory's flows need (bundleFiles) and upload them as a
@@ -1,48 +1,126 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readdirSync } from 'node:fs';
2
+ import { existsSync, readdirSync, realpathSync } from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { DeviceGateway } from '../gateways/device-gateway.js';
5
5
  import { compressFilesFromRelativePath } from '../methods.js';
6
6
  import { resolveIncludedPaths } from '../services/execution-plan.service.js';
7
+ import { computeCommonRoot } from '../services/flow-paths.js';
7
8
  import { isWorkspaceConfigFile, loadWorkspaceConfig, processDependencies, readTestYamlFileAsJson, } from '../services/execution-plan.utils.js';
8
9
  import { CliError } from './cli.js';
9
10
  import { fetchCompatibilityData } from './compatibility.js';
10
11
  import { checkKekForEncryption, encryptFlowBuffer, resolveEncryption, resolveKekPublicKey, } from './envelope.js';
11
12
  /** The API's limit on a bundle (dcd plan 2.5b). */
12
13
  export const MAX_BUNDLE_BYTES = 50 * 1024 * 1024;
13
- /** Never bundled: version control, dependencies, and other dot-folders. */
14
- function skipped(relativePath) {
15
- return relativePath
16
- .split(path.sep)
17
- .some((part) => part === 'node_modules' || (part.startsWith('.') && part !== '.'));
14
+ /**
15
+ * Never walked for flows: dependencies, version control and other tools'
16
+ * dot-folders and dot-files. `.maestro`, where Maestro keeps flows by
17
+ * convention, is walked.
18
+ */
19
+ function skipped(name) {
20
+ return name === 'node_modules' || (name.startsWith('.') && name !== '.maestro');
18
21
  }
19
22
  const YAML_FILE = /\.ya?ml$/i;
20
- /** Every file under `dir`, relative to it. */
23
+ /** Every file under `dir`, relative to it, without going into the folders `skipped` names. */
21
24
  function allFiles(dir) {
22
- return readdirSync(dir, { recursive: true, withFileTypes: true })
23
- .filter((entry) => entry.isFile())
24
- .map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)))
25
- .filter((file) => !skipped(file));
25
+ const files = [];
26
+ const walk = (relative) => {
27
+ for (const entry of readdirSync(path.join(dir, relative), { withFileTypes: true })) {
28
+ if (skipped(entry.name))
29
+ continue;
30
+ const child = relative ? path.join(relative, entry.name) : entry.name;
31
+ if (entry.isDirectory())
32
+ walk(child);
33
+ else if (entry.isFile())
34
+ files.push(child);
35
+ }
36
+ };
37
+ walk('');
38
+ return files;
39
+ }
40
+ /**
41
+ * The files a flow reaches: the flow, the files it uses (runFlow, runScript,
42
+ * addMedia, assertScreenshot and the like), and the files those use in turn.
43
+ * Absolute paths, the flow first. `problems` are the files it names that do
44
+ * not exist. A flow that can't be read throws; a YAML file it uses that is
45
+ * not a flow (a data file) is taken as it is.
46
+ */
47
+ export function reachableFiles(flow) {
48
+ const first = path.resolve(flow);
49
+ const files = [];
50
+ const problems = [];
51
+ const queue = [first];
52
+ const seen = new Set();
53
+ while (queue.length > 0) {
54
+ const file = queue.shift();
55
+ if (seen.has(file))
56
+ continue;
57
+ seen.add(file);
58
+ files.push(file);
59
+ if (!YAML_FILE.test(file) || (file !== first && isWorkspaceConfigFile(file)))
60
+ continue;
61
+ let deps;
62
+ try {
63
+ const { config, testSteps } = readTestYamlFileAsJson(file);
64
+ deps = processDependencies({ config, input: file, testSteps });
65
+ }
66
+ catch (error) {
67
+ if (file === first)
68
+ throw new CliError(error.message);
69
+ continue;
70
+ }
71
+ problems.push(...deps.allErrors);
72
+ for (const dep of deps.allFiles) {
73
+ if (existsSync(dep))
74
+ queue.push(path.normalize(dep));
75
+ }
76
+ }
77
+ return { files, problems };
78
+ }
79
+ /**
80
+ * For a single flow file that uses other files (runFlow, runScript, addMedia
81
+ * and the like): the folder to upload as a bundle, and the file's path
82
+ * inside it. Sent as yaml on its own, the flow would fail on the device with
83
+ * an invalid file path, because the files it uses would not be there. The
84
+ * folder is the closest one that holds every file the flow reaches; only
85
+ * those files are uploaded. Null when the flow uses no other files, or can't
86
+ * be read (the device reports that itself).
87
+ */
88
+ export function flowFileBundle(file) {
89
+ const absolute = path.resolve(file);
90
+ let reached;
91
+ try {
92
+ reached = reachableFiles(absolute);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ // A missing file goes this way too, so the upload names it.
98
+ if (reached.files.length === 1 && reached.problems.length === 0)
99
+ return null;
100
+ const dir = computeCommonRoot([absolute], reached.files.slice(1)) || path.dirname(absolute);
101
+ return { dir, entry: path.relative(dir, absolute) };
102
+ }
103
+ /** A path inside a bundle as the API takes it: forward slashes on every platform. */
104
+ export function bundlePath(relative) {
105
+ return relative.split(path.sep).join('/');
26
106
  }
27
107
  /**
28
- * The files under `dir` a bundle needs, relative to it, in a stable order:
29
- * every YAML file (flows, subflows, config), the files the flows use
30
- * (runScript, addMedia, assertScreenshot and the like), and config's
31
- * includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
32
- * and .zip files with its flows.
108
+ * The files under `dir` a bundle needs, relative to it, in a stable order.
33
109
  *
34
- * `entry` is the one flow that will run. Its files must all be inside `dir`.
35
- * Without an entry every flow may run, so that goes for all of them. Another
36
- * flow's missing file doesn't stop the entry running, so it is left out.
110
+ * With an `entry`, the one flow that will run: that flow and the files it
111
+ * reaches (reachableFiles), which must all be inside `dir`. Nothing else is
112
+ * read or sent, so a folder high above the flow (a home directory, say)
113
+ * costs nothing and gives nothing away.
114
+ *
115
+ * Without one, every flow may run: every YAML file (flows, subflows, config)
116
+ * and the files they use. Either way, config's includedPaths too, and nothing
117
+ * else: an agent's samples folder sent 265 MB of .apk and .zip files with
118
+ * its flows.
37
119
  */
38
- export function bundleFiles(dir, entry, warn = () => { }) {
120
+ export function bundleFiles(dir, entry, warn = () => { }, confineTo) {
39
121
  const root = path.resolve(dir);
40
- const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file));
41
- const entryFile = entry === undefined ? undefined : path.normalize(entry);
42
- if (entryFile !== undefined && !yamlFiles.includes(entryFile)) {
43
- throw new CliError(`No flow ${entry} in ${dir}.`);
44
- }
45
- const needed = new Set(yamlFiles);
122
+ const configs = ['config.yaml', 'config.yml'].filter((name) => existsSync(path.join(root, name)));
123
+ const needed = new Set();
46
124
  const problems = [];
47
125
  const add = (absolute, strict, from) => {
48
126
  const relative = path.relative(root, absolute);
@@ -53,36 +131,60 @@ export function bundleFiles(dir, entry, warn = () => { }) {
53
131
  }
54
132
  needed.add(relative);
55
133
  };
56
- for (const file of yamlFiles) {
57
- const absolute = path.join(root, file);
58
- const strict = entryFile === undefined || entryFile === file;
59
- if (isWorkspaceConfigFile(absolute))
60
- continue;
61
- let deps;
62
- try {
63
- const { config, testSteps } = readTestYamlFileAsJson(absolute);
64
- deps = processDependencies({ config, input: absolute, testSteps });
65
- }
66
- catch (error) {
67
- // Not a flow (a data file, say), or one Maestro will report itself.
68
- if (entryFile === file)
69
- throw new CliError(error.message);
70
- continue;
71
- }
72
- if (strict)
134
+ if (entry === undefined) {
135
+ const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file));
136
+ for (const file of yamlFiles)
137
+ needed.add(file);
138
+ for (const file of yamlFiles) {
139
+ const absolute = path.join(root, file);
140
+ if (isWorkspaceConfigFile(absolute))
141
+ continue;
142
+ let deps;
143
+ try {
144
+ const { config, testSteps } = readTestYamlFileAsJson(absolute);
145
+ deps = processDependencies({ config, input: absolute, testSteps });
146
+ }
147
+ catch {
148
+ // Not a flow (a data file, say), or one Maestro will report itself.
149
+ continue;
150
+ }
73
151
  problems.push(...deps.allErrors);
74
- for (const dep of deps.allFiles) {
75
- if (existsSync(dep))
76
- add(dep, strict, file);
152
+ for (const dep of deps.allFiles) {
153
+ if (existsSync(dep))
154
+ add(dep, true, file);
155
+ }
77
156
  }
78
157
  }
79
- for (const name of ['config.yaml', 'config.yml']) {
80
- if (!yamlFiles.includes(name))
81
- continue;
158
+ else {
159
+ const entryFile = path.resolve(root, path.normalize(entry));
160
+ const inside = path.relative(root, entryFile);
161
+ if (inside.startsWith('..') || path.isAbsolute(inside) || !YAML_FILE.test(entryFile) || !existsSync(entryFile)) {
162
+ throw new CliError(`No flow ${entry} in ${dir}.`);
163
+ }
164
+ const reached = reachableFiles(entryFile);
165
+ problems.push(...reached.problems);
166
+ for (const file of reached.files)
167
+ add(file, true, entry);
168
+ for (const name of configs)
169
+ needed.add(name);
170
+ }
171
+ for (const name of configs) {
82
172
  const config = loadWorkspaceConfig(path.join(root, name), warn);
83
173
  for (const file of resolveIncludedPaths(config, root, warn))
84
174
  add(file, true, name);
85
175
  }
176
+ // For an agent's call (the dcd mcp bridge): a file that is a link to one
177
+ // outside the folder it may read would send that file's contents.
178
+ if (confineTo !== undefined) {
179
+ const allowed = realpathSync(confineTo);
180
+ for (const file of needed) {
181
+ const real = realpathSync(path.join(root, file));
182
+ const relative = path.relative(allowed, real);
183
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
184
+ problems.push(`${file} is a link to a file outside ${confineTo}, which is not sent.`);
185
+ }
186
+ }
187
+ }
86
188
  if (problems.length > 0)
87
189
  throw new CliError(problems.join('\n'));
88
190
  return [...needed].sort();
@@ -118,8 +220,8 @@ async function put(url, body) {
118
220
  * `flow` is a path inside it, e.g. `login.yaml`.
119
221
  */
120
222
  export async function uploadFlowBundle(opts) {
121
- const { apiUrl, auth, dir, entry, log } = opts;
122
- const files = bundleFiles(dir, entry, log);
223
+ const { apiUrl, auth, confineTo, dir, entry, log } = opts;
224
+ const files = bundleFiles(dir, entry, log, confineTo);
123
225
  if (!files.some((f) => YAML_FILE.test(f))) {
124
226
  throw new CliError(`No flow files (.yaml) in ${dir}.`);
125
227
  }
@@ -0,0 +1,17 @@
1
+ import type { ArgsDef, CommandDef } from 'citty';
2
+ import { CliError } from './cli.js';
3
+ /** The edit distance between two words, a swap of neighbours counting as one edit. */
4
+ export declare function editDistance(a: string, b: string): number;
5
+ /**
6
+ * The flags in `rawArgs` that `args` does not define, each as typed. A
7
+ * value after a flag that takes one is skipped, so `--yaml "- launchApp"`
8
+ * and `--longitude -0.1278` are read as values. `--` ends the flags.
9
+ */
10
+ export declare function unknownFlags(rawArgs: string[], args: ArgsDef): string[];
11
+ /** The usage error for unknown flags, or null when there are none. */
12
+ export declare function unknownFlagsError(rawArgs: string[], args: ArgsDef): CliError | null;
13
+ /**
14
+ * A `dcd device` subcommand that refuses unknown flags before it runs: with
15
+ * --json the refusal is the usual envelope, exit 1.
16
+ */
17
+ export declare function strictFlags<T extends ArgsDef>(sub: CommandDef<T>): CommandDef<T>;
@@ -0,0 +1,145 @@
1
+ import { CliError } from './cli.js';
2
+ import { DEVICE_EXIT, runDeviceCommand } from './device-output.js';
3
+ /*
4
+ * citty accepts any flag and ignores the ones a command does not define. For
5
+ * `dcd device` that is unsafe: `type --text hunter2 --sensetive` typed a
6
+ * password in plain text and exited 0, and `--wiat` started a session
7
+ * without waiting. So every `dcd device` subcommand refuses a flag it does
8
+ * not know, and suggests the one that was meant.
9
+ */
10
+ const camel = (name) => name.replaceAll(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
11
+ const kebab = (name) => name.replaceAll(/([a-z0-9])([A-Z])/g, '$1-$2').replaceAll(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase();
12
+ function flagSpecs(args) {
13
+ return Object.entries(args)
14
+ .filter(([, def]) => def.type !== 'positional')
15
+ .map(([name, def]) => {
16
+ const alias = def.alias;
17
+ const aliases = Array.isArray(alias) ? alias : alias ? [alias] : [];
18
+ const names = new Set();
19
+ for (const n of [name, ...aliases]) {
20
+ names.add(n);
21
+ names.add(camel(n));
22
+ names.add(kebab(n));
23
+ }
24
+ return { names, primary: name, takesValue: def.type === 'string' || def.type === 'enum' };
25
+ });
26
+ }
27
+ /** The edit distance between two words, a swap of neighbours counting as one edit. */
28
+ export function editDistance(a, b) {
29
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
30
+ for (let i = 1; i <= a.length; i++) {
31
+ for (let j = 1; j <= b.length; j++) {
32
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
33
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
34
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
35
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
36
+ }
37
+ }
38
+ }
39
+ return d[a.length][b.length];
40
+ }
41
+ /** Words other tools use for a flag of ours. */
42
+ const SYNONYMS = { secret: 'sensitive', secure: 'sensitive' };
43
+ /** Flags people carry over from `dcd live` and the MCP tools, for the session id. */
44
+ const SESSION_FLAGS = new Set(['id', 'session', 'session-id', 'sessionId', 'session_id']);
45
+ /** What to say about one unknown flag: the flag meant, when it is clear. */
46
+ function hint(given, specs, positionals) {
47
+ const bare = given.replace(/^-+/, '').replace(/=.*$/, '');
48
+ if (SESSION_FLAGS.has(bare) && positionals.includes('id')) {
49
+ return ' The session id is an argument, not a flag: `dcd device <command> <id>`.';
50
+ }
51
+ const negated = bare.startsWith('no-');
52
+ const base = kebab(negated ? bare.slice(3) : bare);
53
+ const synonym = SYNONYMS[base];
54
+ if (synonym && specs.some((s) => s.primary === synonym))
55
+ return ` Did you mean --${negated ? 'no-' : ''}${synonym}?`;
56
+ let best = null;
57
+ for (const spec of specs) {
58
+ const distance = editDistance(base, spec.primary);
59
+ if (!best || distance < best.distance)
60
+ best = { distance, name: spec.primary };
61
+ }
62
+ // Close enough to be a slip of the keys, not another word.
63
+ if (best && best.distance <= 2 && best.distance < base.length / 2) {
64
+ return ` Did you mean --${negated ? 'no-' : ''}${best.name}?`;
65
+ }
66
+ return '';
67
+ }
68
+ /**
69
+ * The flags in `rawArgs` that `args` does not define, each as typed. A
70
+ * value after a flag that takes one is skipped, so `--yaml "- launchApp"`
71
+ * and `--longitude -0.1278` are read as values. `--` ends the flags.
72
+ */
73
+ export function unknownFlags(rawArgs, args) {
74
+ const specs = flagSpecs(args);
75
+ const find = (name) => specs.find((s) => s.names.has(name) || s.names.has(camel(name)));
76
+ const unknown = [];
77
+ for (let i = 0; i < rawArgs.length; i++) {
78
+ const token = rawArgs[i];
79
+ if (token === '--')
80
+ break;
81
+ if (!token.startsWith('-') || token === '-' || /^-\d/.test(token))
82
+ continue;
83
+ const eq = token.indexOf('=');
84
+ const name = (eq === -1 ? token : token.slice(0, eq)).replace(/^-{1,2}/, '');
85
+ if (token.startsWith('--')) {
86
+ const spec = find(name) ?? (name.startsWith('no-') ? find(name.slice(3)) : undefined);
87
+ if (!spec)
88
+ unknown.push(token.slice(0, eq === -1 ? undefined : eq));
89
+ else if (spec.takesValue && eq === -1 && !name.startsWith('no-'))
90
+ i++;
91
+ continue;
92
+ }
93
+ // Short flags, e.g. -o file or -f: each letter must be one of ours, and
94
+ // one that takes a value ends the group (its value is the rest, or the
95
+ // next token).
96
+ for (let k = 0; k < name.length; k++) {
97
+ const spec = find(name[k]);
98
+ if (!spec) {
99
+ unknown.push(`-${name[k]}`);
100
+ break;
101
+ }
102
+ if (spec.takesValue) {
103
+ if (k === name.length - 1 && eq === -1)
104
+ i++;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ return unknown;
110
+ }
111
+ /** The usage error for unknown flags, or null when there are none. */
112
+ export function unknownFlagsError(rawArgs, args) {
113
+ const unknown = unknownFlags(rawArgs, args);
114
+ if (unknown.length === 0)
115
+ return null;
116
+ const specs = flagSpecs(args);
117
+ const positionals = Object.entries(args)
118
+ .filter(([, def]) => def.type === 'positional')
119
+ .map(([name]) => name);
120
+ const lines = unknown.map((flag) => `Unknown flag ${flag}.${hint(flag, specs, positionals)}`);
121
+ return new CliError(`${lines.join(' ')} See --help for the flags this command takes.`, DEVICE_EXIT.usage);
122
+ }
123
+ /**
124
+ * A `dcd device` subcommand that refuses unknown flags before it runs: with
125
+ * --json the refusal is the usual envelope, exit 1.
126
+ */
127
+ export function strictFlags(sub) {
128
+ const { run } = sub;
129
+ if (!run)
130
+ return sub;
131
+ return {
132
+ ...sub,
133
+ async run(context) {
134
+ const args = (sub.args ?? {});
135
+ const problem = unknownFlagsError(context.rawArgs ?? [], args);
136
+ if (problem) {
137
+ await runDeviceCommand(Boolean(context.args.json), async () => {
138
+ throw problem;
139
+ });
140
+ return;
141
+ }
142
+ return run(context);
143
+ },
144
+ };
145
+ }