devanvil 0.0.0-stage → 2.1.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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +664 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +312 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +989 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +309 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +260 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +174 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +269 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +396 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +360 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +603 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +301 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +169 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +359 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +373 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +118 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +137 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +470 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +238 -0
  63. package/dist/server/plugin-loader.d.ts +61 -0
  64. package/dist/server/plugin-loader.js +305 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +147 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +441 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +299 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +262 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +100 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +448 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +291 -0
  79. package/dist/ui/app.js +290 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +719 -0
  85. package/dist/ui/tools-network.js +769 -0
  86. package/dist/ui/tools-ops.js +299 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +397 -0
  89. package/dist/ui/tools-v12.js +765 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +411 -0
  93. package/package.json +75 -4
package/dist/cli.js ADDED
@@ -0,0 +1,664 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { checkOpenApiContractDrift } from './core/contract-drift.js';
4
+ import { convertData, formatSql } from './core/converters.js';
5
+ import { describeCron, getNextCronRuns, parseTimestamp } from './core/cron.js';
6
+ import { decryptAesGcm, encryptAesGcm, generateApiKey, generateNanoId, generatePassword, generateUlid, generateUuidV4, generateUuidV7, hashText, hmacText, } from './core/crypto.js';
7
+ import { generateCodeSnippets, parseCurlCommand } from './core/curl.js';
8
+ import { diffJsonSemantic, diffText } from './core/diff.js';
9
+ import { decodeText, encodeText } from './core/encoding.js';
10
+ import { importHarArchive, importHttpFile, importPostmanCollection } from './core/importers.js';
11
+ import { decodeJwt, signJwt, verifyJwt } from './core/jwt.js';
12
+ import { analyzeLlmText, compactContextText } from './core/llm-tokens.js';
13
+ import { analyzeLogs } from './core/log-analyzer.js';
14
+ import { calculateCidr, checkColorContrast, parseChmod } from './core/network.js';
15
+ import { decodeProtobufWire, generatePkceBundle } from './core/oauth-protobuf.js';
16
+ import { openApiToMockRoutes, parseOpenApiSpec } from './core/openapi.js';
17
+ import { runPipeline } from './core/pipeline.js';
18
+ import { testRegex } from './core/regex.js';
19
+ import { formatRunReportAsJunitXml, runCollection } from './core/runner.js';
20
+ import { analyzeEnvFile, formatSecretsAsSarif, scanDirectory, scanGitStaged, scanSecrets } from './core/secrets.js';
21
+ import { safeJsonParse } from './core/security.js';
22
+ import { analyzeSqlExplain } from './core/sql-explain.js';
23
+ import { inspectPemCertificates, inspectRemoteTls } from './core/tls.js';
24
+ import { createDevAnvilServer, DEVANVIL_VERSION } from './server/app.js';
25
+ import { executeLoadTest } from './server/load-tester.js';
26
+ import { startMcpStdioServer } from './server/mcp.js';
27
+ import { PluginLoader } from './server/plugin-loader.js';
28
+ import { WorkspaceStore } from './server/workspace-store.js';
29
+ const VERSION = DEVANVIL_VERSION;
30
+ const USE_COLOR = !process.env.NO_COLOR && process.stdout.isTTY;
31
+ const c = {
32
+ bold: (s) => (USE_COLOR ? `\x1b[1m${s}\x1b[0m` : s),
33
+ amber: (s) => (USE_COLOR ? `\x1b[33m${s}\x1b[0m` : s),
34
+ cyan: (s) => (USE_COLOR ? `\x1b[36m${s}\x1b[0m` : s),
35
+ green: (s) => (USE_COLOR ? `\x1b[32m${s}\x1b[0m` : s),
36
+ red: (s) => (USE_COLOR ? `\x1b[31m${s}\x1b[0m` : s),
37
+ dim: (s) => (USE_COLOR ? `\x1b[2m${s}\x1b[0m` : s),
38
+ };
39
+ function parseArgs(argv) {
40
+ const positionals = [];
41
+ const flags = {};
42
+ for (let i = 0; i < argv.length; i++) {
43
+ const token = argv[i];
44
+ if (token === '--') {
45
+ positionals.push(...argv.slice(i + 1));
46
+ break;
47
+ }
48
+ if (token.startsWith('--')) {
49
+ const eq = token.indexOf('=');
50
+ if (eq !== -1) {
51
+ flags[token.slice(2, eq)] = token.slice(eq + 1);
52
+ }
53
+ else {
54
+ const key = token.slice(2);
55
+ const next = argv[i + 1];
56
+ if (next !== undefined && !next.startsWith('-')) {
57
+ flags[key] = next;
58
+ i++;
59
+ }
60
+ else {
61
+ flags[key] = true;
62
+ }
63
+ }
64
+ }
65
+ else if (token.startsWith('-') && token.length === 2) {
66
+ const key = token.slice(1);
67
+ const next = argv[i + 1];
68
+ if (next !== undefined && !next.startsWith('-')) {
69
+ flags[key] = next;
70
+ i++;
71
+ }
72
+ else {
73
+ flags[key] = true;
74
+ }
75
+ }
76
+ else {
77
+ positionals.push(token);
78
+ }
79
+ }
80
+ return { positionals, flags };
81
+ }
82
+ async function readStdinIfPiped() {
83
+ if (process.stdin.isTTY)
84
+ return '';
85
+ const chunks = [];
86
+ for await (const chunk of process.stdin) {
87
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
88
+ }
89
+ return Buffer.concat(chunks).toString('utf8');
90
+ }
91
+ async function readTextOrFile(arg) {
92
+ if (!arg || arg === '-')
93
+ return readStdinIfPiped();
94
+ if (existsSync(arg))
95
+ return readFileSync(arg, 'utf8');
96
+ return arg;
97
+ }
98
+ function printHelp() {
99
+ console.log(`
100
+ ${c.bold(c.amber('DevAnvil'))} ${c.dim(`v${VERSION}`)} — Local-first, zero-dependency developer workbench & CLI
101
+
102
+ ${c.bold('USAGE')}
103
+ devanvil [command] [options]
104
+
105
+ ${c.bold('COMMANDS')}
106
+ ${c.cyan('serve')} Launch Local Dev Studio Web App, Mock & Webhook Server
107
+ --port, -p <port> Port to listen on (default: 4321)
108
+ --host, -H <host> Bind host (default: 127.0.0.1; use 0.0.0.0 for Docker/LAN)
109
+ --workspace, -w <file> Persist collections, environments & mocks in Git-friendly JSON
110
+ --allow-private-proxy Allow API Studio proxy to target localhost/private IPs
111
+ --deny-iframe Send X-Frame-Options: DENY & frame-ancestors 'none'
112
+
113
+ ${c.cyan('mcp')} Start local MCP Server over stdio (Claude Code / Cursor / Windsurf)
114
+ ${c.cyan('openapi')} <specFile> [--serve] Parse OpenAPI 3.x/Swagger & optionally boot live Mock Server!
115
+ ${c.cyan('import')} <postman|har|http> <f> Convert Postman v2.1, HAR 1.2, or .http into DevAnvil JSON
116
+ ${c.cyan('scan')} [file|dir|text] Scan file, stdin, OR full directory for leaked secrets
117
+ --redact Output safe redacted text (for file/stdin)
118
+ --sarif Output SARIF 2.1.0 JSON for GitHub Code Scanning
119
+ ${c.cyan('env')} <file> [--example f] Validate .env file syntax, duplicates & .env.example drift
120
+ ${c.cyan('tokens')} [file|text] [--compact] Estimate LLM tokens & cost across Claude/GPT/Gemini/Llama
121
+ ${c.cyan('jwt')} <decode|sign|verify> Inspect, audit, sign, or verify JWT tokens
122
+ ${c.cyan('convert')} --from <f> --to <t> Convert JSON/YAML/TOML/CSV/Query -> JSON/YAML/TOML/CSV/TS/Schema
123
+ ${c.cyan('hash')} <algo> [text] Compute SHA-256/512/BLAKE2b/HMAC (--secret <key>)
124
+ ${c.cyan('aes')} <encrypt|decrypt> Authenticated AES-256-GCM encryption (--key <passphrase>)
125
+ ${c.cyan('encode')} <codec> [text] Encode (base64, base64url, hex, url, html, gzip-base64, ...)
126
+ ${c.cyan('decode')} <codec> [text] Decode using any supported codec
127
+ ${c.cyan('id')} [uuidv7|uuidv4|ulid|nanoid|apikey] [--count N]
128
+ ${c.cyan('password')} [--length 24] [--count 1] [--no-symbols]
129
+ ${c.cyan('cron')} "<expr>" [--next 5] Describe cron expression & compute upcoming UTC runs
130
+ ${c.cyan('time')} [now|epoch|iso] Inspect/convert timestamps across formats
131
+ ${c.cyan('cidr')} <ip/prefix> IPv4 CIDR subnet & binary calculator
132
+ ${c.cyan('chmod')} <755|rwxr-xr-x> Linux permission converter
133
+ ${c.cyan('contrast')} <fgHex> <bgHex> WCAG 2.1 AA/AAA color contrast checker
134
+ ${c.cyan('diff')} <fileA> <fileB> [--json] Line diff or semantic JSON structural diff
135
+ ${c.cyan('regex')} <pattern> <text> Safe timeout-guarded regex test + ReDoS analysis
136
+ ${c.cyan('sql')} [query] Format SQL query
137
+ ${c.cyan('curl')} "<curl cmd>" Parse cURL & generate Fetch/Python/Go snippets
138
+ ${c.cyan('pipe')} <op1,op2,...> [input] Run a composable transformation pipeline
139
+
140
+ ${c.bold('EXAMPLES')}
141
+ devanvil serve --port 4321 --workspace ./devanvil.json
142
+ devanvil mcp
143
+ devanvil run devanvil.json --env Staging --junit report.xml
144
+ devanvil load https://httpbin.org/get -c 10 -n 50 --max-p95 250
145
+ devanvil drift openapi.yaml GET /pets/42 response.json --status 200
146
+ devanvil pkce --endpoint https://auth.example.com/authorize --client-id my-app
147
+ devanvil proto 089601120774657374696e67
148
+ devanvil explain query-plan.json
149
+ cat app.log | devanvil logs
150
+ devanvil plugins scaffold my-formatter
151
+ devanvil tls example.com
152
+ devanvil scan --staged --sarif
153
+ devanvil openapi petstore.yaml --serve --port 4321
154
+ devanvil id uuidv7 --count 5
155
+ `);
156
+ }
157
+ async function main() {
158
+ const { positionals, flags } = parseArgs(process.argv.slice(2));
159
+ const cmd = positionals[0];
160
+ if (flags.version || flags.v || cmd === 'version') {
161
+ console.log(`devanvil v${VERSION}`);
162
+ return;
163
+ }
164
+ if (flags.help || flags.h || cmd === 'help') {
165
+ printHelp();
166
+ return;
167
+ }
168
+ if (!cmd || cmd === 'serve') {
169
+ const port = Number(flags.port ?? flags.p ?? process.env.PORT ?? 4321);
170
+ const host = String(flags.host ?? flags.H ?? process.env.HOST ?? '127.0.0.1');
171
+ const allowPrivateProxy = Boolean(flags['allow-private-proxy'] || process.env.DEVANVIL_ALLOW_PRIVATE_PROXY === '1');
172
+ const denyIframe = Boolean(flags['deny-iframe']);
173
+ const workspaceFile = typeof (flags.workspace ?? flags.w) === 'string'
174
+ ? String(flags.workspace ?? flags.w)
175
+ : process.env.DEVANVIL_WORKSPACE || undefined;
176
+ const pluginsDir = typeof flags['plugins-dir'] === 'string'
177
+ ? String(flags['plugins-dir'])
178
+ : process.env.DEVANVIL_PLUGINS_DIR || undefined;
179
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
180
+ throw new Error(`Invalid port: ${port}`);
181
+ }
182
+ const app = createDevAnvilServer({ host, port, allowPrivateProxy, denyIframe, workspaceFile, pluginsDir });
183
+ const info = await app.start();
184
+ console.log('');
185
+ console.log(` ${c.bold(c.amber('DevAnvil'))} ${c.dim(`v${VERSION}`)} ${c.green('ready')}`);
186
+ console.log(` ${c.bold('Studio UI:')} ${c.cyan(info.url)}`);
187
+ console.log(` ${c.bold('Mock Server:')} ${c.cyan(`${info.url}/mock/<path>`)}`);
188
+ console.log(` ${c.bold('Webhook Hook:')} ${c.cyan(`${info.url}/hook/<channel>`)}`);
189
+ console.log(` ${c.bold('Bind Host:')} ${info.host}`);
190
+ if (workspaceFile) {
191
+ console.log(` ${c.bold('Workspace:')} ${c.green(workspaceFile)} (Git-native persistence active)`);
192
+ }
193
+ console.log(` ${c.bold('SSRF Guard:')} ${allowPrivateProxy ? c.amber('PERMISSIVE (--allow-private-proxy)') : c.green('STRICT (private IPs blocked)')}`);
194
+ console.log(` ${c.dim('100% offline · zero telemetry · zero runtime dependencies · 18 studios')}`);
195
+ console.log('');
196
+ const shutdown = () => {
197
+ void app.stop().then(() => process.exit(0));
198
+ };
199
+ process.on('SIGINT', shutdown);
200
+ process.on('SIGTERM', shutdown);
201
+ return;
202
+ }
203
+ if (cmd === 'mcp') {
204
+ startMcpStdioServer();
205
+ return;
206
+ }
207
+ if (cmd === 'run') {
208
+ const wsPath = positionals[1] || 'devanvil.json';
209
+ if (!existsSync(wsPath)) {
210
+ throw new Error(`Workspace file not found: ${wsPath}`);
211
+ }
212
+ const store = new WorkspaceStore(wsPath);
213
+ const snap = store.getSnapshot();
214
+ const colSelector = typeof flags.collection === 'string' ? flags.collection : undefined;
215
+ const col = colSelector
216
+ ? snap.collections.find((x) => x.id === colSelector || x.name.toLowerCase() === colSelector.toLowerCase())
217
+ : snap.collections[0];
218
+ if (!col) {
219
+ throw new Error(colSelector ? `Collection "${colSelector}" not found` : 'Workspace has no collections');
220
+ }
221
+ const envSelector = typeof flags.env === 'string' ? flags.env : undefined;
222
+ const chosenEnv = envSelector
223
+ ? snap.environments.find((e) => e.id === envSelector || e.name.toLowerCase() === envSelector.toLowerCase())
224
+ : store.getActiveEnvironment();
225
+ const report = await runCollection(col, {
226
+ environmentName: chosenEnv?.name,
227
+ variables: chosenEnv?.variables ?? {},
228
+ processEnv: process.env,
229
+ allowPrivate: Boolean(flags['allow-private'] || flags['allow-private-proxy']),
230
+ timeoutMs: flags.timeout ? Number(flags.timeout) : undefined,
231
+ stopOnFailure: Boolean(flags['stop-on-failure']),
232
+ });
233
+ if (typeof flags.junit === 'string') {
234
+ writeFileSync(flags.junit, `${formatRunReportAsJunitXml(report)}\n`, 'utf8');
235
+ }
236
+ console.log(JSON.stringify(report, null, 2));
237
+ if (!report.passed) {
238
+ process.exitCode = 1;
239
+ }
240
+ return;
241
+ }
242
+ if (cmd === 'tls') {
243
+ const target = positionals[1];
244
+ if (!target) {
245
+ throw new Error('Usage: devanvil tls <domain-or-cert.pem> [--port 443] [--allow-private]');
246
+ }
247
+ if (existsSync(target) && statSync(target).isFile()) {
248
+ const pem = readFileSync(target, 'utf8');
249
+ const certs = inspectPemCertificates(pem);
250
+ console.log(JSON.stringify({ count: certs.length, certificates: certs }, null, 2));
251
+ if (certs.some((x) => x.expired))
252
+ process.exitCode = 1;
253
+ return;
254
+ }
255
+ const report = await inspectRemoteTls(target, {
256
+ port: flags.port ? Number(flags.port) : undefined,
257
+ allowPrivate: Boolean(flags['allow-private'] || flags['allow-private-proxy']),
258
+ });
259
+ console.log(JSON.stringify(report, null, 2));
260
+ if (report.leaf.expired)
261
+ process.exitCode = 1;
262
+ return;
263
+ }
264
+ if (cmd === 'load') {
265
+ const targetUrl = positionals[1];
266
+ if (!targetUrl) {
267
+ throw new Error('Usage: devanvil load <url> [-c 10] [-n 50] [--method GET] [--max-p95 250] [--min-rps 20] [--allow-private]');
268
+ }
269
+ const maxP95Ms = flags['max-p95'] !== undefined ? Number(flags['max-p95']) : undefined;
270
+ const minRps = flags['min-rps'] !== undefined ? Number(flags['min-rps']) : undefined;
271
+ const maxErrorRatePct = flags['max-error-rate'] !== undefined ? Number(flags['max-error-rate']) : undefined;
272
+ const hasThresholds = maxP95Ms !== undefined || minRps !== undefined || maxErrorRatePct !== undefined;
273
+ const report = await executeLoadTest({
274
+ method: String(flags.method ?? flags.m ?? 'GET'),
275
+ url: targetUrl,
276
+ totalRequests: Number(flags.n ?? flags.requests ?? 50),
277
+ concurrency: Number(flags.c ?? flags.concurrency ?? 10),
278
+ body: typeof flags.body === 'string' ? flags.body : undefined,
279
+ ...(hasThresholds ? { thresholds: { maxP95Ms, minRps, maxErrorRatePct } } : {}),
280
+ }, { allowPrivate: Boolean(flags['allow-private'] || flags['allow-private-proxy']) });
281
+ console.log(JSON.stringify(report, null, 2));
282
+ // If --max-error-rate threshold is explicitly provided, honor thresholdsPassed; otherwise fail on any failed request
283
+ if (!report.thresholdsPassed || (maxErrorRatePct === undefined && report.failedRequests > 0)) {
284
+ process.exitCode = 1;
285
+ }
286
+ return;
287
+ }
288
+ if (cmd === 'drift') {
289
+ const specFile = positionals[1];
290
+ const reqMethod = positionals[2];
291
+ const reqPath = positionals[3];
292
+ if (!specFile || !reqMethod || !reqPath) {
293
+ throw new Error('Usage: devanvil drift <openapi.yaml> <method> <path> [response.json-or-stdin] [--status 200]');
294
+ }
295
+ const spec = readFileSync(specFile, 'utf8');
296
+ const body = await readTextOrFile(positionals[4]);
297
+ const status = flags.status !== undefined ? Number(flags.status) : 200;
298
+ const report = checkOpenApiContractDrift({ spec, method: reqMethod, path: reqPath, status, body });
299
+ console.log(JSON.stringify(report, null, 2));
300
+ if (!report.compatible)
301
+ process.exitCode = 1;
302
+ return;
303
+ }
304
+ if (cmd === 'pkce') {
305
+ const bundle = generatePkceBundle({
306
+ verifierLength: flags.length !== undefined ? Number(flags.length) : undefined,
307
+ authorizationEndpoint: typeof flags.endpoint === 'string' ? flags.endpoint : undefined,
308
+ clientId: typeof flags['client-id'] === 'string' ? flags['client-id'] : undefined,
309
+ redirectUri: typeof flags['redirect-uri'] === 'string' ? flags['redirect-uri'] : undefined,
310
+ scope: typeof flags.scope === 'string' ? flags.scope : undefined,
311
+ });
312
+ console.log(JSON.stringify(bundle, null, 2));
313
+ return;
314
+ }
315
+ if (cmd === 'proto') {
316
+ const payload = await readTextOrFile(positionals[1]);
317
+ const protoSchema = typeof flags.schema === 'string' ? readFileSync(flags.schema, 'utf8') : undefined;
318
+ const res = decodeProtobufWire(payload, {
319
+ protoSchema,
320
+ messageName: typeof flags.message === 'string' ? flags.message : undefined,
321
+ });
322
+ console.log(JSON.stringify(res, null, 2));
323
+ return;
324
+ }
325
+ if (cmd === 'explain') {
326
+ const raw = await readTextOrFile(positionals[1]);
327
+ console.log(JSON.stringify(analyzeSqlExplain(raw), null, 2));
328
+ return;
329
+ }
330
+ if (cmd === 'logs') {
331
+ const raw = await readTextOrFile(positionals[1]);
332
+ console.log(JSON.stringify(analyzeLogs(raw), null, 2));
333
+ return;
334
+ }
335
+ if (cmd === 'plugins') {
336
+ const sub = positionals[1] ?? 'list';
337
+ const loader = new PluginLoader(typeof flags.dir === 'string' ? flags.dir : undefined);
338
+ if (sub === 'list') {
339
+ console.log(JSON.stringify({ pluginsDir: loader.getPluginsDir(), plugins: loader.listPlugins() }, null, 2));
340
+ return;
341
+ }
342
+ if (sub === 'scaffold') {
343
+ const id = positionals[2];
344
+ if (!id)
345
+ throw new Error('Usage: devanvil plugins scaffold <plugin-id> [--dir path]');
346
+ console.log(JSON.stringify(loader.scaffoldPlugin(id), null, 2));
347
+ return;
348
+ }
349
+ if (sub === 'run') {
350
+ const id = positionals[2];
351
+ if (!id)
352
+ throw new Error('Usage: devanvil plugins run <plugin-id> [input-or-file]');
353
+ const input = await readTextOrFile(positionals[3]);
354
+ console.log(JSON.stringify(loader.runPlugin(id, input), null, 2));
355
+ return;
356
+ }
357
+ throw new Error('Usage: devanvil plugins <list|scaffold|run> ...');
358
+ }
359
+ if (cmd === 'import') {
360
+ const fmt = (positionals[1] || 'auto').toLowerCase();
361
+ const raw = await readTextOrFile(positionals[2]);
362
+ let res;
363
+ if (fmt === 'postman')
364
+ res = importPostmanCollection(raw);
365
+ else if (fmt === 'har')
366
+ res = importHarArchive(raw);
367
+ else if (fmt === 'http')
368
+ res = importHttpFile(raw);
369
+ else
370
+ throw new Error('Usage: devanvil import <postman|har|http> <file> [--out file.json]');
371
+ const jsonOut = `${JSON.stringify(res, null, 2)}\n`;
372
+ if (typeof flags.out === 'string') {
373
+ writeFileSync(flags.out, jsonOut, 'utf8');
374
+ console.log(`Imported ${res.requests.length} requests & ${res.mockRoutes.length} mocks -> ${flags.out}`);
375
+ }
376
+ else {
377
+ console.log(jsonOut.trimEnd());
378
+ }
379
+ return;
380
+ }
381
+ if (cmd === 'openapi') {
382
+ const raw = await readTextOrFile(positionals[1]);
383
+ const parsed = parseOpenApiSpec(raw);
384
+ if (flags.serve) {
385
+ const port = Number(flags.port ?? flags.p ?? 4321);
386
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
387
+ throw new Error(`Invalid port: ${port}`);
388
+ }
389
+ const host = String(flags.host ?? flags.H ?? '127.0.0.1');
390
+ const app = createDevAnvilServer({ host, port });
391
+ const routes = openApiToMockRoutes(parsed);
392
+ app.mockStore.importRoutes(routes, true);
393
+ const info = await app.start();
394
+ console.log(`${c.bold(c.amber('DevAnvil OpenAPI Mock Server'))} — ${parsed.title} v${parsed.version}`);
395
+ console.log(`Mounted ${c.green(String(routes.length))} live endpoint(s) at ${c.cyan(`${info.url}/mock`)}:`);
396
+ for (const ep of parsed.endpoints) {
397
+ console.log(` ${c.cyan(ep.method.padEnd(7))} ${info.url}/mock${ep.mockPath} (${ep.responseStatus})`);
398
+ }
399
+ const shutdown = () => {
400
+ void app.stop().then(() => process.exit(0));
401
+ };
402
+ process.on('SIGINT', shutdown);
403
+ process.on('SIGTERM', shutdown);
404
+ return;
405
+ }
406
+ console.log(JSON.stringify(parsed, null, 2));
407
+ return;
408
+ }
409
+ if (cmd === 'scan') {
410
+ if (flags.staged) {
411
+ const stagedRes = scanGitStaged(positionals[1] || '.', { checkHighEntropy: !flags['no-entropy'] });
412
+ if (flags.sarif) {
413
+ console.log(JSON.stringify(formatSecretsAsSarif(stagedRes.findings, VERSION), null, 2));
414
+ }
415
+ else {
416
+ console.log(JSON.stringify(stagedRes, null, 2));
417
+ }
418
+ if (!stagedRes.clean && !flags['no-fail']) {
419
+ process.exitCode = 1;
420
+ }
421
+ return;
422
+ }
423
+ const target = positionals[1];
424
+ if (target && existsSync(target) && statSync(target).isDirectory()) {
425
+ const dirRes = scanDirectory(target, { checkHighEntropy: !flags['no-entropy'] });
426
+ if (flags.sarif) {
427
+ console.log(JSON.stringify(formatSecretsAsSarif(dirRes.findings, VERSION), null, 2));
428
+ }
429
+ else {
430
+ console.log(JSON.stringify(dirRes, null, 2));
431
+ }
432
+ if (!dirRes.clean && !flags['no-fail']) {
433
+ process.exitCode = 1;
434
+ }
435
+ return;
436
+ }
437
+ const input = await readTextOrFile(target);
438
+ const res = scanSecrets(input, { checkHighEntropy: !flags['no-entropy'] });
439
+ if (flags.redact) {
440
+ console.log(res.redactedText);
441
+ return;
442
+ }
443
+ if (flags.sarif) {
444
+ const fileLabel = target && existsSync(target) ? target : 'stdin';
445
+ const mapped = res.findings.map((f) => ({ ...f, file: fileLabel }));
446
+ console.log(JSON.stringify(formatSecretsAsSarif(mapped, VERSION), null, 2));
447
+ }
448
+ else {
449
+ console.log(JSON.stringify({ clean: res.clean, totalFindings: res.totalFindings, summary: res.summary, findings: res.findings }, null, 2));
450
+ }
451
+ if (!res.clean && !flags['no-fail']) {
452
+ process.exitCode = 1;
453
+ }
454
+ return;
455
+ }
456
+ if (cmd === 'env') {
457
+ const envRaw = await readTextOrFile(positionals[1]);
458
+ const exampleRaw = flags.example ? readFileSync(String(flags.example), 'utf8') : undefined;
459
+ const res = analyzeEnvFile(envRaw, exampleRaw);
460
+ console.log(JSON.stringify(res, null, 2));
461
+ if (res.issues.some((i) => i.severity === 'error'))
462
+ process.exitCode = 1;
463
+ return;
464
+ }
465
+ if (cmd === 'tokens') {
466
+ const input = await readTextOrFile(positionals[1]);
467
+ if (flags.compact) {
468
+ const compacted = compactContextText(input, {
469
+ stripLineComments: Boolean(flags['strip-comments']),
470
+ minifyJson: Boolean(flags['minify-json']),
471
+ });
472
+ console.log(flags.json ? JSON.stringify(compacted, null, 2) : compacted.compacted);
473
+ return;
474
+ }
475
+ console.log(JSON.stringify(analyzeLlmText(input), null, 2));
476
+ return;
477
+ }
478
+ if (cmd === 'jwt') {
479
+ const sub = positionals[1];
480
+ const stdin = await readStdinIfPiped();
481
+ if (sub === 'decode') {
482
+ const token = positionals[2] ?? stdin.trim();
483
+ console.log(JSON.stringify(decodeJwt(token), null, 2));
484
+ return;
485
+ }
486
+ if (sub === 'sign') {
487
+ const payloadRaw = positionals[2] ?? stdin.trim() ?? '{}';
488
+ const secret = String(flags.secret ?? flags.s ?? '');
489
+ const alg = String(flags.alg ?? 'HS256');
490
+ const exp = flags.exp ? Number(flags.exp) : undefined;
491
+ const payload = safeJsonParse(payloadRaw);
492
+ console.log(signJwt(payload, secret, { alg, expiresInSeconds: exp }));
493
+ return;
494
+ }
495
+ if (sub === 'verify') {
496
+ const token = positionals[2] ?? stdin.trim();
497
+ const secret = String(flags.secret ?? flags.s ?? '');
498
+ const res = verifyJwt(token, secret);
499
+ console.log(JSON.stringify(res, null, 2));
500
+ if (!res.valid)
501
+ process.exitCode = 1;
502
+ return;
503
+ }
504
+ throw new Error('Usage: devanvil jwt <decode|sign|verify> ...');
505
+ }
506
+ if (cmd === 'convert') {
507
+ const from = String(flags.from ?? flags.f ?? 'json');
508
+ const to = String(flags.to ?? flags.t ?? 'yaml');
509
+ const input = flags.file ? readFileSync(String(flags.file), 'utf8') : (positionals[1] ?? (await readStdinIfPiped()));
510
+ console.log(convertData(input, from, to, {
511
+ minify: Boolean(flags.minify),
512
+ sortKeys: Boolean(flags['sort-keys']),
513
+ }));
514
+ return;
515
+ }
516
+ if (cmd === 'hash') {
517
+ const algo = (positionals[1] ?? 'sha256');
518
+ const input = positionals[2] ?? (await readStdinIfPiped());
519
+ const secret = flags.secret ? String(flags.secret) : undefined;
520
+ const res = secret ? hmacText(input, secret, algo) : hashText(input, algo);
521
+ console.log(flags.json ? JSON.stringify(res, null, 2) : res.hex);
522
+ return;
523
+ }
524
+ if (cmd === 'aes') {
525
+ const mode = positionals[1];
526
+ const key = String(flags.key ?? flags.k ?? '');
527
+ const input = positionals[2] ?? (await readStdinIfPiped()).trim();
528
+ if (mode === 'encrypt')
529
+ console.log(encryptAesGcm(input, key));
530
+ else if (mode === 'decrypt')
531
+ console.log(decryptAesGcm(input, key));
532
+ else
533
+ throw new Error('Usage: devanvil aes <encrypt|decrypt> <text> --key <passphrase>');
534
+ return;
535
+ }
536
+ if (cmd === 'encode' || cmd === 'decode') {
537
+ const codec = (positionals[1] ?? 'base64');
538
+ const input = positionals[2] ?? (await readStdinIfPiped());
539
+ console.log(cmd === 'encode' ? encodeText(input, codec) : decodeText(input, codec));
540
+ return;
541
+ }
542
+ if (cmd === 'id' || cmd === 'uuid') {
543
+ const kind = positionals[1] ?? (flags.v4 ? 'uuidv4' : 'uuidv7');
544
+ const count = Math.min(Math.max(Number(flags.count ?? flags.n ?? 1), 1), 100);
545
+ for (let i = 0; i < count; i++) {
546
+ if (kind === 'uuidv4' || kind === 'v4')
547
+ console.log(generateUuidV4());
548
+ else if (kind === 'ulid')
549
+ console.log(generateUlid());
550
+ else if (kind === 'nanoid')
551
+ console.log(generateNanoId(Number(flags.size ?? 21)));
552
+ else if (kind === 'apikey')
553
+ console.log(generateApiKey(String(flags.prefix ?? 'da_live')));
554
+ else
555
+ console.log(generateUuidV7());
556
+ }
557
+ return;
558
+ }
559
+ if (cmd === 'password') {
560
+ const count = Math.min(Math.max(Number(flags.count ?? flags.n ?? 1), 1), 20);
561
+ const length = Number(flags.length ?? flags.l ?? 20);
562
+ for (let i = 0; i < count; i++) {
563
+ const res = generatePassword({
564
+ length,
565
+ symbols: !flags['no-symbols'],
566
+ excludeAmbiguous: Boolean(flags['no-ambiguous']),
567
+ });
568
+ console.log(flags.json ? JSON.stringify(res) : res.password);
569
+ }
570
+ return;
571
+ }
572
+ if (cmd === 'cron') {
573
+ const expr = positionals[1] ?? '*/15 * * * *';
574
+ const next = Number(flags.next ?? flags.n ?? 5);
575
+ const res = getNextCronRuns(expr, next);
576
+ if (flags.json) {
577
+ console.log(JSON.stringify(res, null, 2));
578
+ }
579
+ else {
580
+ console.log(`${c.bold('Expression:')} ${res.expression}`);
581
+ console.log(`${c.bold('Schedule:')} ${describeCron(expr)}`);
582
+ console.log(`${c.bold('Next runs (UTC):')}`);
583
+ for (const run of res.nextRuns)
584
+ console.log(` - ${run}`);
585
+ }
586
+ return;
587
+ }
588
+ if (cmd === 'time' || cmd === 'timestamp') {
589
+ const input = positionals[1] ?? 'now';
590
+ console.log(JSON.stringify(parseTimestamp(input), null, 2));
591
+ return;
592
+ }
593
+ if (cmd === 'cidr') {
594
+ const input = positionals[1] ?? '192.168.1.0/24';
595
+ console.log(JSON.stringify(calculateCidr(input), null, 2));
596
+ return;
597
+ }
598
+ if (cmd === 'chmod') {
599
+ const input = positionals[1] ?? '755';
600
+ console.log(JSON.stringify(parseChmod(input), null, 2));
601
+ return;
602
+ }
603
+ if (cmd === 'contrast') {
604
+ const fg = positionals[1] ?? '#FFFFFF';
605
+ const bg = positionals[2] ?? '#0F172A';
606
+ console.log(JSON.stringify(checkColorContrast(fg, bg), null, 2));
607
+ return;
608
+ }
609
+ if (cmd === 'diff') {
610
+ const fileA = positionals[1];
611
+ const fileB = positionals[2];
612
+ if (!fileA || !fileB)
613
+ throw new Error('Usage: devanvil diff <fileA> <fileB> [--json]');
614
+ const left = readFileSync(fileA, 'utf8');
615
+ const right = readFileSync(fileB, 'utf8');
616
+ if (flags.json) {
617
+ console.log(JSON.stringify(diffJsonSemantic(left, right), null, 2));
618
+ }
619
+ else {
620
+ console.log(diffText(left, right).unified);
621
+ }
622
+ return;
623
+ }
624
+ if (cmd === 'regex') {
625
+ const pattern = positionals[1] ?? '';
626
+ const text = positionals[2] ?? (await readStdinIfPiped());
627
+ const regexFlags = String(flags.flags ?? 'g');
628
+ console.log(JSON.stringify(testRegex(pattern, regexFlags, text), null, 2));
629
+ return;
630
+ }
631
+ if (cmd === 'sql') {
632
+ const input = positionals[1] ?? (await readStdinIfPiped());
633
+ console.log(formatSql(input));
634
+ return;
635
+ }
636
+ if (cmd === 'curl') {
637
+ const raw = positionals[1] ?? (await readStdinIfPiped());
638
+ const parsed = parseCurlCommand(raw);
639
+ const snippets = generateCodeSnippets(parsed);
640
+ console.log(JSON.stringify({ parsed, snippets }, null, 2));
641
+ return;
642
+ }
643
+ if (cmd === 'pipe') {
644
+ const opsRaw = positionals[1] ?? '';
645
+ const input = positionals[2] ?? (await readStdinIfPiped());
646
+ const steps = opsRaw
647
+ .split(',')
648
+ .map((s) => s.trim())
649
+ .filter(Boolean)
650
+ .map((op) => ({ op: op }));
651
+ const res = runPipeline(input, steps);
652
+ if (!res.succeeded) {
653
+ const failed = res.steps.find((s) => s.error);
654
+ throw new Error(`Pipeline failed at step #${(failed?.index ?? 0) + 1} (${failed?.op}): ${failed?.error}`);
655
+ }
656
+ console.log(flags.trace ? JSON.stringify(res, null, 2) : res.output);
657
+ return;
658
+ }
659
+ throw new Error(`Unknown command "${cmd}". Run "devanvil --help" to see available commands.`);
660
+ }
661
+ main().catch((err) => {
662
+ console.error(`${c.red('Error:')} ${err.message}`);
663
+ process.exit(1);
664
+ });