padrone 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +105 -284
  3. package/dist/{args-CVDbyyzG.mjs → args-D5PNDyNu.mjs} +41 -18
  4. package/dist/args-D5PNDyNu.mjs.map +1 -0
  5. package/dist/chunk-CjcI7cDX.mjs +15 -0
  6. package/dist/codegen/index.d.mts +28 -3
  7. package/dist/codegen/index.d.mts.map +1 -1
  8. package/dist/codegen/index.mjs +169 -19
  9. package/dist/codegen/index.mjs.map +1 -1
  10. package/dist/command-utils-B1D-HqCd.mjs +1117 -0
  11. package/dist/command-utils-B1D-HqCd.mjs.map +1 -0
  12. package/dist/completion.d.mts +1 -1
  13. package/dist/completion.d.mts.map +1 -1
  14. package/dist/completion.mjs +77 -29
  15. package/dist/completion.mjs.map +1 -1
  16. package/dist/docs/index.d.mts +22 -2
  17. package/dist/docs/index.d.mts.map +1 -1
  18. package/dist/docs/index.mjs +94 -7
  19. package/dist/docs/index.mjs.map +1 -1
  20. package/dist/errors-BiVrBgi6.mjs +114 -0
  21. package/dist/errors-BiVrBgi6.mjs.map +1 -0
  22. package/dist/{formatter-ClUK5hcQ.d.mts → formatter-DtHzbP22.d.mts} +34 -5
  23. package/dist/formatter-DtHzbP22.d.mts.map +1 -0
  24. package/dist/help-bbmu9-qd.mjs +735 -0
  25. package/dist/help-bbmu9-qd.mjs.map +1 -0
  26. package/dist/index.d.mts +32 -3
  27. package/dist/index.d.mts.map +1 -1
  28. package/dist/index.mjs +493 -265
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/mcp-mLWIdUIu.mjs +379 -0
  31. package/dist/mcp-mLWIdUIu.mjs.map +1 -0
  32. package/dist/serve-B0u43DK7.mjs +404 -0
  33. package/dist/serve-B0u43DK7.mjs.map +1 -0
  34. package/dist/stream-BcC146Ud.mjs +56 -0
  35. package/dist/stream-BcC146Ud.mjs.map +1 -0
  36. package/dist/test.d.mts +1 -1
  37. package/dist/test.mjs +4 -15
  38. package/dist/test.mjs.map +1 -1
  39. package/dist/{types-DjIdJN5G.d.mts → types-Ch8Mk6Qb.d.mts} +310 -62
  40. package/dist/types-Ch8Mk6Qb.d.mts.map +1 -0
  41. package/dist/{update-check-EbNDkzyV.mjs → update-check-CFX1FV3v.mjs} +2 -2
  42. package/dist/{update-check-EbNDkzyV.mjs.map → update-check-CFX1FV3v.mjs.map} +1 -1
  43. package/dist/zod.d.mts +32 -0
  44. package/dist/zod.d.mts.map +1 -0
  45. package/dist/zod.mjs +50 -0
  46. package/dist/zod.mjs.map +1 -0
  47. package/package.json +10 -2
  48. package/src/args.ts +68 -40
  49. package/src/cli/docs.ts +1 -7
  50. package/src/cli/doctor.ts +195 -10
  51. package/src/cli/index.ts +1 -1
  52. package/src/cli/init.ts +2 -3
  53. package/src/cli/link.ts +2 -2
  54. package/src/codegen/discovery.ts +80 -28
  55. package/src/codegen/index.ts +2 -1
  56. package/src/codegen/parsers/bash.ts +179 -0
  57. package/src/codegen/schema-to-code.ts +2 -1
  58. package/src/colorizer.ts +126 -13
  59. package/src/command-utils.ts +380 -30
  60. package/src/completion.ts +120 -47
  61. package/src/create.ts +480 -128
  62. package/src/docs/index.ts +122 -8
  63. package/src/formatter.ts +171 -125
  64. package/src/help.ts +45 -12
  65. package/src/index.ts +29 -1
  66. package/src/interactive.ts +45 -4
  67. package/src/mcp.ts +390 -0
  68. package/src/repl-loop.ts +16 -3
  69. package/src/runtime.ts +195 -2
  70. package/src/serve.ts +442 -0
  71. package/src/stream.ts +75 -0
  72. package/src/test.ts +7 -16
  73. package/src/type-utils.ts +28 -4
  74. package/src/types.ts +212 -30
  75. package/src/wrap.ts +23 -25
  76. package/src/zod.ts +50 -0
  77. package/dist/args-CVDbyyzG.mjs.map +0 -1
  78. package/dist/chunk-y_GBKt04.mjs +0 -5
  79. package/dist/formatter-ClUK5hcQ.d.mts.map +0 -1
  80. package/dist/help-CcBe91bV.mjs +0 -1254
  81. package/dist/help-CcBe91bV.mjs.map +0 -1
  82. package/dist/types-DjIdJN5G.d.mts.map +0 -1
@@ -0,0 +1,404 @@
1
+ import { t as generateHelp } from "./help-bbmu9-qd.mjs";
2
+ import { E as serializeArgsToFlags, i as collectEndpoints, n as buildInputSchema } from "./command-utils-B1D-HqCd.mjs";
3
+ import { a as ValidationError, i as RoutingError } from "./errors-BiVrBgi6.mjs";
4
+ //#region src/serve.ts
5
+ /** Convert an endpoint dot-path to a URL path segment. */
6
+ function toUrlPath(name) {
7
+ return name.replace(/\./g, "/");
8
+ }
9
+ /** Convert a URL path segment back to a command path (slash → space). */
10
+ function toCommandPath(urlPath) {
11
+ return urlPath.replace(/\//g, " ");
12
+ }
13
+ function jsonResponse(body, status = 200, headers) {
14
+ return new Response(JSON.stringify(body), {
15
+ status,
16
+ headers: {
17
+ "Content-Type": "application/json",
18
+ ...headers
19
+ }
20
+ });
21
+ }
22
+ function errorToStatus(error) {
23
+ if (error instanceof RoutingError) return 404;
24
+ if (error instanceof ValidationError) return 400;
25
+ return 500;
26
+ }
27
+ function errorToResponse(error) {
28
+ const status = errorToStatus(error);
29
+ if (error instanceof ValidationError) return jsonResponse({
30
+ ok: false,
31
+ error: "validation",
32
+ message: error.message,
33
+ issues: error.issues.map((i) => ({
34
+ path: i.path?.map(String),
35
+ message: i.message
36
+ }))
37
+ }, status);
38
+ if (error instanceof RoutingError) return jsonResponse({
39
+ ok: false,
40
+ error: "not_found",
41
+ message: error.message,
42
+ suggestions: error.suggestions
43
+ }, status);
44
+ return jsonResponse({
45
+ ok: false,
46
+ error: "action_error",
47
+ message: error instanceof Error ? error.message : String(error)
48
+ }, status);
49
+ }
50
+ /** Generate an OpenAPI 3.1.0 spec from the command tree. */
51
+ function buildOpenApiSpec(existingCommand, endpoints, basePath) {
52
+ const paths = {};
53
+ const responseSchema = {
54
+ "200": {
55
+ description: "Successful response",
56
+ content: { "application/json": { schema: {
57
+ type: "object",
58
+ properties: {
59
+ ok: {
60
+ type: "boolean",
61
+ const: true
62
+ },
63
+ result: {}
64
+ }
65
+ } } }
66
+ },
67
+ "400": {
68
+ description: "Validation error",
69
+ content: { "application/json": { schema: {
70
+ type: "object",
71
+ properties: {
72
+ ok: {
73
+ type: "boolean",
74
+ const: false
75
+ },
76
+ error: {
77
+ type: "string",
78
+ const: "validation"
79
+ },
80
+ message: { type: "string" },
81
+ issues: {
82
+ type: "array",
83
+ items: {
84
+ type: "object",
85
+ properties: {
86
+ path: { type: "array" },
87
+ message: { type: "string" }
88
+ }
89
+ }
90
+ }
91
+ }
92
+ } } }
93
+ },
94
+ "404": {
95
+ description: "Command not found",
96
+ content: { "application/json": { schema: {
97
+ type: "object",
98
+ properties: {
99
+ ok: {
100
+ type: "boolean",
101
+ const: false
102
+ },
103
+ error: {
104
+ type: "string",
105
+ const: "not_found"
106
+ },
107
+ message: { type: "string" }
108
+ }
109
+ } } }
110
+ },
111
+ "500": {
112
+ description: "Action error",
113
+ content: { "application/json": { schema: {
114
+ type: "object",
115
+ properties: {
116
+ ok: {
117
+ type: "boolean",
118
+ const: false
119
+ },
120
+ error: {
121
+ type: "string",
122
+ const: "action_error"
123
+ },
124
+ message: { type: "string" }
125
+ }
126
+ } } }
127
+ }
128
+ };
129
+ for (const { name, command: cmd } of endpoints) {
130
+ const urlPath = `${basePath}${toUrlPath(name)}`;
131
+ const inputSchema = buildInputSchema(cmd);
132
+ const description = cmd.description || cmd.title || `Run the "${name}" command`;
133
+ const pathItem = {};
134
+ const postOp = {
135
+ summary: cmd.title || name,
136
+ description,
137
+ operationId: `post_${name.replace(/\./g, "_")}`,
138
+ requestBody: { content: { "application/json": { schema: inputSchema } } },
139
+ responses: responseSchema
140
+ };
141
+ if (cmd.mutation) pathItem.post = postOp;
142
+ else {
143
+ const properties = inputSchema.properties ?? {};
144
+ const queryParams = Object.entries(properties).map(([key, schema]) => ({
145
+ name: key,
146
+ in: "query",
147
+ schema,
148
+ required: inputSchema.required?.includes(key) ?? false
149
+ }));
150
+ pathItem.get = {
151
+ summary: cmd.title || name,
152
+ description,
153
+ operationId: `get_${name.replace(/\./g, "_")}`,
154
+ parameters: queryParams,
155
+ responses: responseSchema
156
+ };
157
+ pathItem.post = postOp;
158
+ }
159
+ paths[urlPath] = pathItem;
160
+ }
161
+ return {
162
+ openapi: "3.1.0",
163
+ info: {
164
+ title: existingCommand.title || existingCommand.name,
165
+ description: existingCommand.description,
166
+ version: existingCommand.version ?? "0.0.0"
167
+ },
168
+ paths
169
+ };
170
+ }
171
+ function scalarDocsHtml(openapiUrl, title) {
172
+ return `<!doctype html>
173
+ <html>
174
+ <head>
175
+ <title>${title} — API Docs</title>
176
+ <meta charset="utf-8" />
177
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
178
+ </head>
179
+ <body>
180
+ <script id="api-reference" data-url="${openapiUrl}"><\/script>
181
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
182
+ </body>
183
+ </html>`;
184
+ }
185
+ /** Create the serve request handler. */
186
+ function createServeHandler(existingCommand, evalCommand, prefs) {
187
+ const basePath = (prefs?.basePath ?? "/").replace(/\/$/, "/");
188
+ const corsOrigin = prefs?.cors !== false ? prefs?.cors ?? "*" : void 0;
189
+ const builtins = {
190
+ health: true,
191
+ help: true,
192
+ schema: true,
193
+ docs: true,
194
+ ...prefs?.builtins
195
+ };
196
+ const endpoints = collectEndpoints(existingCommand.commands, "");
197
+ if (existingCommand.action || existingCommand.argsSchema) endpoints.unshift({
198
+ name: "",
199
+ command: existingCommand
200
+ });
201
+ const routeMap = /* @__PURE__ */ new Map();
202
+ for (const ep of endpoints) routeMap.set(toUrlPath(ep.name), ep);
203
+ let cachedOpenApiSpec;
204
+ const getOpenApiSpec = () => cachedOpenApiSpec ??= buildOpenApiSpec(existingCommand, endpoints, basePath);
205
+ function addCorsHeaders(res) {
206
+ if (!corsOrigin) return res;
207
+ const headers = new Headers(res.headers);
208
+ headers.set("Access-Control-Allow-Origin", corsOrigin);
209
+ headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
210
+ headers.set("Access-Control-Allow-Headers", "Content-Type");
211
+ return new Response(res.body, {
212
+ status: res.status,
213
+ statusText: res.statusText,
214
+ headers
215
+ });
216
+ }
217
+ async function evalAndRespond(commandString, request) {
218
+ const output = [];
219
+ const errors = [];
220
+ const result = await evalCommand(commandString || void 0, {
221
+ autoOutput: false,
222
+ runtime: {
223
+ output: (...args) => output.push(args.map(String).join(" ")),
224
+ error: (text) => errors.push(text),
225
+ interactive: "unsupported",
226
+ format: "json"
227
+ }
228
+ });
229
+ if (result.error) return prefs?.onError ? prefs.onError(result.error, request) : errorToResponse(result.error);
230
+ if (result.argsResult?.issues) return jsonResponse({
231
+ ok: false,
232
+ error: "validation",
233
+ issues: result.argsResult.issues.map((i) => ({
234
+ path: i.path?.map(String),
235
+ message: i.message
236
+ }))
237
+ }, 400);
238
+ return jsonResponse({
239
+ ok: true,
240
+ result: result.result ?? null
241
+ });
242
+ }
243
+ return async function handleRequest(req) {
244
+ if (req.method === "OPTIONS") return addCorsHeaders(new Response(null, { status: corsOrigin ? 204 : 405 }));
245
+ if (prefs?.onRequest) {
246
+ const hookResponse = await prefs.onRequest(req);
247
+ if (hookResponse) return addCorsHeaders(hookResponse);
248
+ }
249
+ const url = new URL(req.url, "http://localhost");
250
+ let pathname = url.pathname;
251
+ if (basePath !== "/" && pathname.startsWith(basePath)) pathname = pathname.slice(basePath.length - 1);
252
+ const routePath = pathname.replace(/^\//, "");
253
+ if (req.method === "GET") {
254
+ if (builtins.health && routePath === "_health") return addCorsHeaders(jsonResponse({ status: "ok" }));
255
+ if (builtins.schema && routePath === "_schema") {
256
+ const schemaMap = {};
257
+ for (const ep of endpoints) schemaMap[toUrlPath(ep.name) || "/"] = buildInputSchema(ep.command);
258
+ return addCorsHeaders(jsonResponse(schemaMap));
259
+ }
260
+ if (builtins.schema && routePath.startsWith("_schema/")) {
261
+ const cmdPath = routePath.slice(8);
262
+ const ep = routeMap.get(cmdPath);
263
+ if (!ep) return addCorsHeaders(jsonResponse({
264
+ ok: false,
265
+ error: "not_found",
266
+ message: `Command not found: ${cmdPath}`
267
+ }, 404));
268
+ return addCorsHeaders(jsonResponse(buildInputSchema(ep.command)));
269
+ }
270
+ if (builtins.help && routePath === "_help") {
271
+ const format = (req.headers.get("accept") ?? "").includes("application/json") ? "json" : "markdown";
272
+ const helpText = generateHelp(existingCommand, existingCommand, {
273
+ format,
274
+ detail: "full"
275
+ });
276
+ if (format === "json") return addCorsHeaders(jsonResponse(JSON.parse(helpText)));
277
+ return addCorsHeaders(new Response(helpText, {
278
+ status: 200,
279
+ headers: { "Content-Type": "text/markdown" }
280
+ }));
281
+ }
282
+ if (builtins.help && routePath.startsWith("_help/")) {
283
+ const cmdPath = routePath.slice(6);
284
+ const ep = routeMap.get(cmdPath);
285
+ if (!ep) return addCorsHeaders(jsonResponse({
286
+ ok: false,
287
+ error: "not_found",
288
+ message: `Command not found: ${cmdPath}`
289
+ }, 404));
290
+ const format = (req.headers.get("accept") ?? "").includes("application/json") ? "json" : "markdown";
291
+ const helpText = generateHelp(existingCommand, ep.command, {
292
+ format,
293
+ detail: "full"
294
+ });
295
+ if (format === "json") return addCorsHeaders(jsonResponse(JSON.parse(helpText)));
296
+ return addCorsHeaders(new Response(helpText, {
297
+ status: 200,
298
+ headers: { "Content-Type": "text/markdown" }
299
+ }));
300
+ }
301
+ if (builtins.docs && routePath === "_openapi") return addCorsHeaders(jsonResponse(getOpenApiSpec()));
302
+ if (builtins.docs && routePath === "_docs") {
303
+ const html = scalarDocsHtml(`${basePath}_openapi`, existingCommand.title || existingCommand.name);
304
+ return addCorsHeaders(new Response(html, {
305
+ status: 200,
306
+ headers: { "Content-Type": "text/html" }
307
+ }));
308
+ }
309
+ }
310
+ const endpoint = routeMap.get(routePath);
311
+ if (!endpoint) return addCorsHeaders(jsonResponse({
312
+ ok: false,
313
+ error: "not_found",
314
+ message: `Command not found: ${routePath || "/"}`
315
+ }, 404));
316
+ if (endpoint.command.mutation && req.method === "GET") return addCorsHeaders(new Response(JSON.stringify({
317
+ ok: false,
318
+ error: "method_not_allowed",
319
+ message: "Mutation commands only accept POST"
320
+ }), {
321
+ status: 405,
322
+ headers: {
323
+ "Content-Type": "application/json",
324
+ Allow: "POST"
325
+ }
326
+ }));
327
+ if (req.method !== "GET" && req.method !== "POST") return addCorsHeaders(new Response(null, {
328
+ status: 405,
329
+ headers: { Allow: endpoint.command.mutation ? "POST" : "GET, POST" }
330
+ }));
331
+ const commandPath = toCommandPath(routePath);
332
+ let argParts;
333
+ if (req.method === "POST") try {
334
+ argParts = serializeArgsToFlags(await req.json());
335
+ } catch {
336
+ return addCorsHeaders(jsonResponse({
337
+ ok: false,
338
+ error: "bad_request",
339
+ message: "Invalid JSON body"
340
+ }, 400));
341
+ }
342
+ else {
343
+ argParts = [];
344
+ for (const [key, value] of url.searchParams.entries()) if (key === "_") argParts.push(value);
345
+ else argParts.push(value === "" ? `--${key}` : `--${key}=${value}`);
346
+ }
347
+ return addCorsHeaders(await evalAndRespond([commandPath, ...argParts].filter(Boolean).join(" "), req));
348
+ };
349
+ }
350
+ /** Start the serve HTTP server. */
351
+ async function startServeServer(_program, existingCommand, evalCommand, prefs) {
352
+ const handler = createServeHandler(existingCommand, evalCommand, prefs);
353
+ const http = await import("node:http");
354
+ const port = prefs?.port ?? 3e3;
355
+ const host = prefs?.host ?? "127.0.0.1";
356
+ const basePath = (prefs?.basePath ?? "/").replace(/\/$/, "/");
357
+ const server = http.createServer(async (req, res) => {
358
+ const url = `http://${host}:${port}${req.url}`;
359
+ const headers = new Headers();
360
+ for (const [key, value] of Object.entries(req.headers)) if (value) headers.set(key, Array.isArray(value) ? value.join(", ") : value);
361
+ const response = await handler(new Request(url, {
362
+ method: req.method,
363
+ headers,
364
+ body: req.method !== "GET" && req.method !== "HEAD" ? await readBody(req) : void 0
365
+ }));
366
+ const resHeaders = {};
367
+ response.headers.forEach((v, k) => {
368
+ resHeaders[k] = v;
369
+ });
370
+ res.writeHead(response.status, resHeaders);
371
+ const body = await response.text();
372
+ res.end(body);
373
+ });
374
+ const { getCommandRuntime } = await import("./command-utils-B1D-HqCd.mjs").then((n) => n.o);
375
+ const runtime = getCommandRuntime(existingCommand);
376
+ return new Promise((resolve, reject) => {
377
+ server.listen(port, host, () => {
378
+ runtime.error(`REST server listening on http://${host}:${port}${basePath}`);
379
+ if ({
380
+ health: true,
381
+ help: true,
382
+ schema: true,
383
+ docs: true,
384
+ ...prefs?.builtins
385
+ }.docs) runtime.error(`API docs: http://${host}:${port}${basePath}_docs`);
386
+ });
387
+ server.on("error", reject);
388
+ const onSignal = () => {
389
+ server.close(() => resolve());
390
+ };
391
+ process.on("SIGINT", onSignal);
392
+ process.on("SIGTERM", onSignal);
393
+ });
394
+ }
395
+ /** Read the full body from a Node.js IncomingMessage. */
396
+ async function readBody(req) {
397
+ const chunks = [];
398
+ for await (const chunk of req) chunks.push(chunk);
399
+ return Buffer.concat(chunks).toString("utf-8");
400
+ }
401
+ //#endregion
402
+ export { startServeServer };
403
+
404
+ //# sourceMappingURL=serve-B0u43DK7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-B0u43DK7.mjs","names":[],"sources":["../src/serve.ts"],"sourcesContent":["import { buildInputSchema, type CollectedEndpoint, collectEndpoints, serializeArgsToFlags } from './command-utils.ts';\nimport { RoutingError, ValidationError } from './errors.ts';\nimport { generateHelp } from './help.ts';\nimport type { AnyPadroneCommand, AnyPadroneProgram } from './types.ts';\n\nexport type PadroneServePreferences = {\n /** Port to listen on. Default: 3000 */\n port?: number;\n /** Host to bind to. Default: '127.0.0.1' */\n host?: string;\n /** Base path prefix for all routes. Default: '/' */\n basePath?: string;\n /** CORS allowed origin. Default: '*'. Set to `false` to disable CORS headers. */\n cors?: string | false;\n /** Control built-in utility endpoints. All enabled by default. */\n builtins?: {\n /** GET /_health — returns 200 OK. */\n health?: boolean;\n /** GET /_help and GET /_help/:command — returns help text. */\n help?: boolean;\n /** GET /_schema and GET /_schema/:command — returns JSON Schema. */\n schema?: boolean;\n /** GET /_docs — Scalar OpenAPI docs viewer. */\n docs?: boolean;\n };\n /** Hook to run before each request. Return a Response to short-circuit. */\n onRequest?: (req: Request) => Response | void | Promise<Response | void>;\n /** Transform errors into responses. */\n onError?: (error: unknown, req: Request) => Response;\n};\n\n/** Convert an endpoint dot-path to a URL path segment. */\nfunction toUrlPath(name: string): string {\n return name.replace(/\\./g, '/');\n}\n\n/** Convert a URL path segment back to a command path (slash → space). */\nfunction toCommandPath(urlPath: string): string {\n return urlPath.replace(/\\//g, ' ');\n}\n\nfunction jsonResponse(body: unknown, status = 200, headers?: Record<string, string>): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json', ...headers },\n });\n}\n\nfunction errorToStatus(error: unknown): number {\n if (error instanceof RoutingError) return 404;\n if (error instanceof ValidationError) return 400;\n return 500;\n}\n\nfunction errorToResponse(error: unknown): Response {\n const status = errorToStatus(error);\n if (error instanceof ValidationError) {\n return jsonResponse(\n {\n ok: false,\n error: 'validation',\n message: error.message,\n issues: error.issues.map((i) => ({ path: i.path?.map(String), message: i.message })),\n },\n status,\n );\n }\n if (error instanceof RoutingError) {\n return jsonResponse({ ok: false, error: 'not_found', message: error.message, suggestions: error.suggestions }, status);\n }\n const message = error instanceof Error ? error.message : String(error);\n return jsonResponse({ ok: false, error: 'action_error', message }, status);\n}\n\n/** Generate an OpenAPI 3.1.0 spec from the command tree. */\nfunction buildOpenApiSpec(existingCommand: AnyPadroneCommand, endpoints: CollectedEndpoint[], basePath: string): Record<string, unknown> {\n const paths: Record<string, unknown> = {};\n\n const responseSchema = {\n '200': {\n description: 'Successful response',\n content: { 'application/json': { schema: { type: 'object', properties: { ok: { type: 'boolean', const: true }, result: {} } } } },\n },\n '400': {\n description: 'Validation error',\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: false },\n error: { type: 'string', const: 'validation' },\n message: { type: 'string' },\n issues: { type: 'array', items: { type: 'object', properties: { path: { type: 'array' }, message: { type: 'string' } } } },\n },\n },\n },\n },\n },\n '404': {\n description: 'Command not found',\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: false },\n error: { type: 'string', const: 'not_found' },\n message: { type: 'string' },\n },\n },\n },\n },\n },\n '500': {\n description: 'Action error',\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: false },\n error: { type: 'string', const: 'action_error' },\n message: { type: 'string' },\n },\n },\n },\n },\n },\n };\n\n for (const { name, command: cmd } of endpoints) {\n const urlPath = `${basePath}${toUrlPath(name)}`;\n const inputSchema = buildInputSchema(cmd);\n const description = cmd.description || cmd.title || `Run the \"${name}\" command`;\n const pathItem: Record<string, unknown> = {};\n\n const postOp = {\n summary: cmd.title || name,\n description,\n operationId: `post_${name.replace(/\\./g, '_')}`,\n requestBody: { content: { 'application/json': { schema: inputSchema } } },\n responses: responseSchema,\n };\n\n if (cmd.mutation) {\n pathItem.post = postOp;\n } else {\n // GET: args as query parameters\n const properties = (inputSchema.properties ?? {}) as Record<string, Record<string, unknown>>;\n const queryParams = Object.entries(properties).map(([key, schema]) => ({\n name: key,\n in: 'query',\n schema,\n required: (inputSchema.required as string[] | undefined)?.includes(key) ?? false,\n }));\n pathItem.get = {\n summary: cmd.title || name,\n description,\n operationId: `get_${name.replace(/\\./g, '_')}`,\n parameters: queryParams,\n responses: responseSchema,\n };\n pathItem.post = postOp;\n }\n\n paths[urlPath] = pathItem;\n }\n\n return {\n openapi: '3.1.0',\n info: {\n title: existingCommand.title || existingCommand.name,\n description: existingCommand.description,\n version: existingCommand.version ?? '0.0.0',\n },\n paths,\n };\n}\n\nfunction scalarDocsHtml(openapiUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n<head>\n <title>${title} — API Docs</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n</head>\n<body>\n <script id=\"api-reference\" data-url=\"${openapiUrl}\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n</body>\n</html>`;\n}\n\n/** Create the serve request handler. */\nexport function createServeHandler(\n existingCommand: AnyPadroneCommand,\n evalCommand: AnyPadroneProgram['eval'],\n prefs?: PadroneServePreferences,\n): (req: Request) => Promise<Response> {\n const basePath = (prefs?.basePath ?? '/').replace(/\\/$/, '/');\n const corsOrigin = prefs?.cors !== false ? (prefs?.cors ?? '*') : undefined;\n const builtins = { health: true, help: true, schema: true, docs: true, ...prefs?.builtins };\n\n const endpoints = collectEndpoints(existingCommand.commands, '');\n if (existingCommand.action || existingCommand.argsSchema) {\n endpoints.unshift({ name: '', command: existingCommand });\n }\n\n const routeMap = new Map<string, CollectedEndpoint>();\n for (const ep of endpoints) {\n routeMap.set(toUrlPath(ep.name), ep);\n }\n\n let cachedOpenApiSpec: Record<string, unknown> | undefined;\n const getOpenApiSpec = () => (cachedOpenApiSpec ??= buildOpenApiSpec(existingCommand, endpoints, basePath));\n\n function addCorsHeaders(res: Response): Response {\n if (!corsOrigin) return res;\n const headers = new Headers(res.headers);\n headers.set('Access-Control-Allow-Origin', corsOrigin);\n headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n headers.set('Access-Control-Allow-Headers', 'Content-Type');\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n }\n\n async function evalAndRespond(commandString: string, request: Request): Promise<Response> {\n const output: string[] = [];\n const errors: string[] = [];\n const result = await evalCommand(commandString || (undefined as any), {\n autoOutput: false,\n runtime: {\n output: (...args: unknown[]) => output.push(args.map(String).join(' ')),\n error: (text: string) => errors.push(text),\n interactive: 'unsupported',\n format: 'json',\n },\n });\n\n if (result.error) {\n return prefs?.onError ? prefs.onError(result.error, request) : errorToResponse(result.error);\n }\n\n if (result.argsResult?.issues) {\n const issues = (result.argsResult.issues as { path?: PropertyKey[]; message: string }[]).map((i) => ({\n path: i.path?.map(String),\n message: i.message,\n }));\n return jsonResponse({ ok: false, error: 'validation', issues }, 400);\n }\n\n return jsonResponse({ ok: true, result: result.result ?? null });\n }\n\n return async function handleRequest(req: Request): Promise<Response> {\n // CORS preflight\n if (req.method === 'OPTIONS') {\n return addCorsHeaders(new Response(null, { status: corsOrigin ? 204 : 405 }));\n }\n\n // onRequest hook\n if (prefs?.onRequest) {\n const hookResponse = await prefs.onRequest(req);\n if (hookResponse) return addCorsHeaders(hookResponse);\n }\n\n const url = new URL(req.url, 'http://localhost');\n let pathname = url.pathname;\n\n // Strip basePath prefix\n if (basePath !== '/' && pathname.startsWith(basePath)) {\n pathname = pathname.slice(basePath.length - 1);\n }\n // Remove leading slash for route matching\n const routePath = pathname.replace(/^\\//, '');\n\n // Built-in endpoints\n if (req.method === 'GET') {\n if (builtins.health && routePath === '_health') {\n return addCorsHeaders(jsonResponse({ status: 'ok' }));\n }\n\n if (builtins.schema && routePath === '_schema') {\n const schemaMap: Record<string, unknown> = {};\n for (const ep of endpoints) {\n schemaMap[toUrlPath(ep.name) || '/'] = buildInputSchema(ep.command);\n }\n return addCorsHeaders(jsonResponse(schemaMap));\n }\n\n if (builtins.schema && routePath.startsWith('_schema/')) {\n const cmdPath = routePath.slice('_schema/'.length);\n const ep = routeMap.get(cmdPath);\n if (!ep) return addCorsHeaders(jsonResponse({ ok: false, error: 'not_found', message: `Command not found: ${cmdPath}` }, 404));\n return addCorsHeaders(jsonResponse(buildInputSchema(ep.command)));\n }\n\n if (builtins.help && routePath === '_help') {\n const accept = req.headers.get('accept') ?? '';\n const format = accept.includes('application/json') ? 'json' : 'markdown';\n const helpText = generateHelp(existingCommand, existingCommand, { format, detail: 'full' });\n if (format === 'json') return addCorsHeaders(jsonResponse(JSON.parse(helpText)));\n return addCorsHeaders(new Response(helpText, { status: 200, headers: { 'Content-Type': 'text/markdown' } }));\n }\n\n if (builtins.help && routePath.startsWith('_help/')) {\n const cmdPath = routePath.slice('_help/'.length);\n const ep = routeMap.get(cmdPath);\n if (!ep) return addCorsHeaders(jsonResponse({ ok: false, error: 'not_found', message: `Command not found: ${cmdPath}` }, 404));\n const accept = req.headers.get('accept') ?? '';\n const format = accept.includes('application/json') ? 'json' : 'markdown';\n const helpText = generateHelp(existingCommand, ep.command, { format, detail: 'full' });\n if (format === 'json') return addCorsHeaders(jsonResponse(JSON.parse(helpText)));\n return addCorsHeaders(new Response(helpText, { status: 200, headers: { 'Content-Type': 'text/markdown' } }));\n }\n\n if (builtins.docs && routePath === '_openapi') {\n return addCorsHeaders(jsonResponse(getOpenApiSpec()));\n }\n\n if (builtins.docs && routePath === '_docs') {\n const openapiUrl = `${basePath}_openapi`;\n const title = existingCommand.title || existingCommand.name;\n const html = scalarDocsHtml(openapiUrl, title);\n return addCorsHeaders(new Response(html, { status: 200, headers: { 'Content-Type': 'text/html' } }));\n }\n }\n\n // Route to command\n const endpoint = routeMap.get(routePath);\n if (!endpoint) {\n return addCorsHeaders(jsonResponse({ ok: false, error: 'not_found', message: `Command not found: ${routePath || '/'}` }, 404));\n }\n\n // Enforce method based on mutation flag\n if (endpoint.command.mutation && req.method === 'GET') {\n return addCorsHeaders(\n new Response(JSON.stringify({ ok: false, error: 'method_not_allowed', message: 'Mutation commands only accept POST' }), {\n status: 405,\n headers: { 'Content-Type': 'application/json', Allow: 'POST' },\n }),\n );\n }\n\n if (req.method !== 'GET' && req.method !== 'POST') {\n return addCorsHeaders(new Response(null, { status: 405, headers: { Allow: endpoint.command.mutation ? 'POST' : 'GET, POST' } }));\n }\n\n // Build command string from request\n const commandPath = toCommandPath(routePath);\n let argParts: string[];\n\n if (req.method === 'POST') {\n try {\n const body = (await req.json()) as Record<string, unknown>;\n argParts = serializeArgsToFlags(body);\n } catch {\n return addCorsHeaders(jsonResponse({ ok: false, error: 'bad_request', message: 'Invalid JSON body' }, 400));\n }\n } else {\n // GET: query string → flags\n argParts = [];\n for (const [key, value] of url.searchParams.entries()) {\n if (key === '_') {\n // Positional args\n argParts.push(value);\n } else {\n argParts.push(value === '' ? `--${key}` : `--${key}=${value}`);\n }\n }\n }\n\n const commandString = [commandPath, ...argParts].filter(Boolean).join(' ');\n const response = await evalAndRespond(commandString, req);\n return addCorsHeaders(response);\n };\n}\n\n/** Start the serve HTTP server. */\nexport async function startServeServer(\n _program: AnyPadroneProgram,\n existingCommand: AnyPadroneCommand,\n evalCommand: AnyPadroneProgram['eval'],\n prefs?: PadroneServePreferences,\n): Promise<void> {\n const handler = createServeHandler(existingCommand, evalCommand, prefs);\n const http = await import('node:http');\n\n const port = prefs?.port ?? 3000;\n const host = prefs?.host ?? '127.0.0.1';\n const basePath = (prefs?.basePath ?? '/').replace(/\\/$/, '/');\n\n const server = http.createServer(async (req, res) => {\n const url = `http://${host}:${port}${req.url}`;\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) headers.set(key, Array.isArray(value) ? value.join(', ') : value);\n }\n\n const fetchReq = new Request(url, {\n method: req.method,\n headers,\n body: req.method !== 'GET' && req.method !== 'HEAD' ? await readBody(req) : undefined,\n });\n\n const response = await handler(fetchReq);\n const resHeaders: Record<string, string> = {};\n response.headers.forEach((v, k) => {\n resHeaders[k] = v;\n });\n res.writeHead(response.status, resHeaders);\n const body = await response.text();\n res.end(body);\n });\n\n const { getCommandRuntime } = await import('./command-utils.ts');\n const runtime = getCommandRuntime(existingCommand);\n\n return new Promise<void>((resolve, reject) => {\n server.listen(port, host, () => {\n runtime.error(`REST server listening on http://${host}:${port}${basePath}`);\n const builtins = { health: true, help: true, schema: true, docs: true, ...prefs?.builtins };\n if (builtins.docs) runtime.error(`API docs: http://${host}:${port}${basePath}_docs`);\n });\n server.on('error', reject);\n const onSignal = () => {\n server.close(() => resolve());\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n });\n}\n\n/** Read the full body from a Node.js IncomingMessage. */\nasync function readBody(req: import('node:http').IncomingMessage): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const ch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sC;EACxC,MAAM,aAAqC,EAAE;AAC7C,WAAS,QAAQ,SAAS,GAAG,MAAM;AACjC,cAAW,KAAK;IAChB;AACF,MAAI,UAAU,SAAS,QAAQ,WAAW;EAC1C,MAAM,OAAO,MAAM,SAAS,MAAM;AAClC,MAAI,IAAI,KAAK;GACb;CAEF,MAAM,EAAE,sBAAsB,MAAM,OAAO,gCAAA,MAAA,MAAA,EAAA,EAAA;CAC3C,MAAM,UAAU,kBAAkB,gBAAgB;AAElD,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,SAAO,OAAO,MAAM,YAAY;AAC9B,WAAQ,MAAM,mCAAmC,KAAK,GAAG,OAAO,WAAW;AAE3E,OADiB;IAAE,QAAQ;IAAM,MAAM;IAAM,QAAQ;IAAM,MAAM;IAAM,GAAG,OAAO;IAAU,CAC9E,KAAM,SAAQ,MAAM,oBAAoB,KAAK,GAAG,OAAO,SAAS,OAAO;IACpF;AACF,SAAO,GAAG,SAAS,OAAO;EAC1B,MAAM,iBAAiB;AACrB,UAAO,YAAY,SAAS,CAAC;;AAE/B,UAAQ,GAAG,UAAU,SAAS;AAC9B,UAAQ,GAAG,WAAW,SAAS;GAC/B;;;AAIJ,eAAe,SAAS,KAA2D;CACjF,MAAM,SAAmB,EAAE;AAC3B,YAAW,MAAM,SAAS,IACxB,QAAO,KAAK,MAAgB;AAE9B,QAAO,OAAO,OAAO,OAAO,CAAC,SAAS,QAAQ"}
@@ -0,0 +1,56 @@
1
+ //#region src/stream.ts
2
+ let asyncStreamIdCounter = 1;
3
+ const asyncStreamRegistry = /* @__PURE__ */ new Map();
4
+ /**
5
+ * Returns metadata to mark a schema field as an async stream via `.meta()`.
6
+ *
7
+ * When used with `stdin`, padrone pipes stdin data as an `AsyncIterable` instead of
8
+ * buffering it. Each line is validated against the item schema (if provided) as it arrives.
9
+ *
10
+ * @param itemSchema - Optional item schema for per-item validation.
11
+ * Non-string schemas cause each stdin line to be `JSON.parse`'d before validation.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { asyncStream } from 'padrone';
16
+ *
17
+ * // String lines
18
+ * z.object({ lines: z.custom<AsyncIterable<string>>().meta(asyncStream()) })
19
+ *
20
+ * // Typed items — each line JSON.parse'd and validated
21
+ * z.object({ records: z.custom<AsyncIterable<{ name: string }>>().meta(asyncStream(recordSchema)) })
22
+ * ```
23
+ */
24
+ function asyncStream(itemSchema) {
25
+ const id = asyncStreamIdCounter++;
26
+ const meta = itemSchema ? {
27
+ asyncStream: id,
28
+ itemSchema
29
+ } : { asyncStream: id };
30
+ asyncStreamRegistry.set(id, meta);
31
+ return meta;
32
+ }
33
+ /**
34
+ * Creates an `AsyncIterable` from a stdin source, optionally validating each item.
35
+ * When no stdin is available (TTY / undefined), yields nothing.
36
+ *
37
+ * - No item schema: yields raw string lines
38
+ * - With item schema: `JSON.parse`s each line, validates, then yields
39
+ */
40
+ function createStdinStream(stdin, itemSchema) {
41
+ if (!stdin) return emptyAsyncIterable;
42
+ if (!itemSchema) return stdin.lines();
43
+ return { async *[Symbol.asyncIterator]() {
44
+ for await (const line of stdin.lines()) {
45
+ const result = itemSchema["~standard"].validate(line);
46
+ const resolved = result instanceof Promise ? await result : result;
47
+ if ("issues" in resolved && resolved.issues) throw new Error(`Stream item validation failed: ${resolved.issues.map((i) => i.message).join(", ")}`);
48
+ yield resolved.value;
49
+ }
50
+ } };
51
+ }
52
+ const emptyAsyncIterable = { async *[Symbol.asyncIterator]() {} };
53
+ //#endregion
54
+ export { asyncStreamRegistry as n, createStdinStream as r, asyncStream as t };
55
+
56
+ //# sourceMappingURL=stream-BcC146Ud.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-BcC146Ud.mjs","names":[],"sources":["../src/stream.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { PadroneSchema } from './types.ts';\n\nexport interface AsyncStreamMeta {\n [x: string]: unknown;\n readonly asyncStream: number;\n readonly itemSchema?: StandardSchemaV1;\n}\n\nlet asyncStreamIdCounter = 1;\nexport const asyncStreamRegistry = new Map<number, AsyncStreamMeta>();\n\n/**\n * Returns metadata to mark a schema field as an async stream via `.meta()`.\n *\n * When used with `stdin`, padrone pipes stdin data as an `AsyncIterable` instead of\n * buffering it. Each line is validated against the item schema (if provided) as it arrives.\n *\n * @param itemSchema - Optional item schema for per-item validation.\n * Non-string schemas cause each stdin line to be `JSON.parse`'d before validation.\n *\n * @example\n * ```ts\n * import { asyncStream } from 'padrone';\n *\n * // String lines\n * z.object({ lines: z.custom<AsyncIterable<string>>().meta(asyncStream()) })\n *\n * // Typed items — each line JSON.parse'd and validated\n * z.object({ records: z.custom<AsyncIterable<{ name: string }>>().meta(asyncStream(recordSchema)) })\n * ```\n */\nexport function asyncStream<T = string>(itemSchema?: PadroneSchema<T>): AsyncStreamMeta {\n const id = asyncStreamIdCounter++;\n const meta: AsyncStreamMeta = itemSchema ? { asyncStream: id, itemSchema } : { asyncStream: id };\n asyncStreamRegistry.set(id, meta);\n return meta;\n}\n\n/** Stdin interface matching PadroneRuntime.stdin */\ninterface StdinSource {\n isTTY?: boolean;\n text(): Promise<string>;\n lines(): AsyncIterable<string>;\n}\n\n/**\n * Creates an `AsyncIterable` from a stdin source, optionally validating each item.\n * When no stdin is available (TTY / undefined), yields nothing.\n *\n * - No item schema: yields raw string lines\n * - With item schema: `JSON.parse`s each line, validates, then yields\n */\nexport function createStdinStream(stdin: StdinSource | undefined, itemSchema?: StandardSchemaV1): AsyncIterable<unknown> {\n if (!stdin) return emptyAsyncIterable;\n\n if (!itemSchema) return stdin.lines();\n\n return {\n async *[Symbol.asyncIterator]() {\n for await (const line of stdin.lines()) {\n const result = itemSchema['~standard'].validate(line);\n const resolved = result instanceof Promise ? await result : result;\n if ('issues' in resolved && resolved.issues) {\n throw new Error(`Stream item validation failed: ${resolved.issues.map((i) => i.message).join(', ')}`);\n }\n yield (resolved as { value: unknown }).value;\n }\n },\n };\n}\n\nconst emptyAsyncIterable: AsyncIterable<never> = {\n async *[Symbol.asyncIterator]() {},\n};\n"],"mappings":";AASA,IAAI,uBAAuB;AAC3B,MAAa,sCAAsB,IAAI,KAA8B;;;;;;;;;;;;;;;;;;;;;AAsBrE,SAAgB,YAAwB,YAAgD;CACtF,MAAM,KAAK;CACX,MAAM,OAAwB,aAAa;EAAE,aAAa;EAAI;EAAY,GAAG,EAAE,aAAa,IAAI;AAChG,qBAAoB,IAAI,IAAI,KAAK;AACjC,QAAO;;;;;;;;;AAiBT,SAAgB,kBAAkB,OAAgC,YAAuD;AACvH,KAAI,CAAC,MAAO,QAAO;AAEnB,KAAI,CAAC,WAAY,QAAO,MAAM,OAAO;AAErC,QAAO,EACL,QAAQ,OAAO,iBAAiB;AAC9B,aAAW,MAAM,QAAQ,MAAM,OAAO,EAAE;GACtC,MAAM,SAAS,WAAW,aAAa,SAAS,KAAK;GACrD,MAAM,WAAW,kBAAkB,UAAU,MAAM,SAAS;AAC5D,OAAI,YAAY,YAAY,SAAS,OACnC,OAAM,IAAI,MAAM,kCAAkC,SAAS,OAAO,KAAK,MAAM,EAAE,QAAQ,CAAC,KAAK,KAAK,GAAG;AAEvG,SAAO,SAAgC;;IAG5C;;AAGH,MAAM,qBAA2C,EAC/C,QAAQ,OAAO,iBAAiB,IACjC"}
package/dist/test.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { b as PadroneRuntime, n as AnyPadroneCommand } from "./types-DjIdJN5G.mjs";
1
+ import { L as PadroneRuntime, n as AnyPadroneCommand } from "./types-Ch8Mk6Qb.mjs";
2
2
 
3
3
  //#region src/test.d.ts
4
4
  /**
package/dist/test.mjs CHANGED
@@ -35,21 +35,9 @@ function testCli(program) {
35
35
  configFiles,
36
36
  stdinData
37
37
  });
38
- const testProgram = program.runtime(runtime);
39
- try {
40
- return toTestResult(await testProgram.eval(runInput ?? input ?? "", { autoOutput: false }), stdout, stderr);
41
- } catch (err) {
42
- stderr.push(err instanceof Error ? err.message : String(err));
43
- return {
44
- command: void 0,
45
- args: void 0,
46
- result: void 0,
47
- issues: void 0,
48
- stdout,
49
- stderr,
50
- error: err
51
- };
52
- }
38
+ const evalResult = await program.runtime(runtime).eval(runInput ?? input ?? "", { autoOutput: false });
39
+ if (evalResult.error) stderr.push(evalResult.error instanceof Error ? evalResult.error.message : String(evalResult.error));
40
+ return toTestResult(evalResult, stdout, stderr);
53
41
  },
54
42
  async repl(inputs) {
55
43
  const stdout = [];
@@ -85,6 +73,7 @@ function toTestResult(evalResult, stdout, stderr) {
85
73
  command: evalResult.command,
86
74
  args: evalResult.args,
87
75
  result: evalResult.result,
76
+ error: evalResult.error,
88
77
  issues: evalResult.argsResult?.issues,
89
78
  stdout,
90
79
  stderr
package/dist/test.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"test.mjs","names":[],"sources":["../src/test.ts"],"sourcesContent":["import type { InteractivePromptConfig, PadroneRuntime } from './runtime.ts';\nimport type { AnyPadroneCommand, PadroneCommandResult } from './types.ts';\n\n/**\n * Result from a single command execution in test mode.\n * Extends the standard PadroneCommandResult with captured I/O.\n */\nexport type TestCliResult = {\n /** The matched command. */\n command: AnyPadroneCommand;\n /** Validated arguments (undefined if validation failed). */\n args: unknown;\n /** Action handler return value (undefined if validation failed or no action). */\n result: unknown;\n /** Validation issues, if any. */\n issues: { message: string; path?: PropertyKey[] }[] | undefined;\n /** All values passed to `runtime.output()`. */\n stdout: unknown[];\n /** All strings passed to `runtime.error()`. */\n stderr: string[];\n /** The thrown error, if the command threw (routing error, action error, etc.). */\n error?: unknown;\n};\n\n/**\n * Result from a REPL test session.\n */\nexport type TestReplResult = {\n /** One entry per successfully executed command (validation errors are captured in stderr, not here). */\n results: Omit<TestCliResult, 'stdout' | 'stderr'>[];\n /** All output from the entire REPL session. */\n stdout: unknown[];\n /** All errors from the entire REPL session. */\n stderr: string[];\n};\n\n/**\n * Fluent builder for setting up CLI test scenarios.\n */\nexport type TestCliBuilder = {\n /** Set the CLI input string (e.g. `'deploy --env production'`). */\n args(input: string): TestCliBuilder;\n /** Set environment variables visible to the command. */\n env(vars: Record<string, string | undefined>): TestCliBuilder;\n /** Provide mock answers for interactive prompts. Keys are field names. */\n prompt(answers: Record<string, unknown>): TestCliBuilder;\n /** Provide mock config files. Keys are file paths, values are parsed config objects. */\n config(files: Record<string, Record<string, unknown>>): TestCliBuilder;\n /** Provide mock stdin data (simulates piped input). */\n stdin(data: string): TestCliBuilder;\n /**\n * Execute a single command via `eval()` and return the result with captured I/O.\n * @param input - Optional CLI input string. Overrides `.args()` if provided.\n */\n run(input?: string): Promise<TestCliResult>;\n /**\n * Run a REPL session with the given sequence of inputs.\n * Each string in the array is fed as one line of input.\n * The session ends after all inputs are consumed (EOF).\n */\n repl(inputs: string[]): Promise<TestReplResult>;\n};\n\n/**\n * Creates a fluent test builder for a Padrone program.\n * Captures all I/O and provides a clean interface for assertions.\n *\n * Works with any test framework (bun:test, vitest, jest, node:test, etc.).\n *\n * @example\n * ```ts\n * import { testCli } from 'padrone/test'\n *\n * const result = await testCli(myProgram)\n * .args('deploy --env production')\n * .env({ API_KEY: 'xxx' })\n * .run()\n *\n * expect(result.result).toBe('Deployed')\n * expect(result.stdout).toContain('Deploying...')\n * ```\n *\n * @example\n * ```ts\n * // Shorthand: pass input directly to run()\n * const result = await testCli(myProgram).run('deploy --env production')\n * ```\n *\n * @example\n * ```ts\n * // Test interactive prompts\n * const result = await testCli(myProgram)\n * .args('init')\n * .prompt({ name: 'myapp', template: 'react' })\n * .run()\n *\n * expect(result.args).toEqual({ name: 'myapp', template: 'react' })\n * ```\n *\n * @example\n * ```ts\n * // Test REPL sessions\n * const { results } = await testCli(myProgram)\n * .repl(['greet World', 'add --a=2 --b=3'])\n *\n * expect(results[0].result).toBe('Hello, World!')\n * expect(results[1].result).toBe(5)\n * ```\n */\n/**\n * Any program-like object that has `eval`, `runtime`, and `repl` methods.\n * Avoids strict variance issues with `AnyPadroneProgram`.\n */\ntype TestableProgram = {\n eval: (input: string, prefs?: { autoOutput?: boolean }) => any;\n runtime: (runtime: PadroneRuntime) => TestableProgram;\n repl: (options?: { greeting?: false; hint?: false }) => AsyncIterable<any>;\n};\n\nexport function testCli(program: TestableProgram): TestCliBuilder {\n let input: string | undefined;\n let envVars: Record<string, string | undefined> | undefined;\n let promptAnswers: Record<string, unknown> | undefined;\n let configFiles: Record<string, Record<string, unknown>> | undefined;\n let stdinData: string | undefined;\n\n const builder: TestCliBuilder = {\n args(args: string) {\n input = args;\n return builder;\n },\n env(vars) {\n envVars = vars;\n return builder;\n },\n prompt(answers) {\n promptAnswers = answers;\n return builder;\n },\n config(files) {\n configFiles = files;\n return builder;\n },\n stdin(data: string) {\n stdinData = data;\n return builder;\n },\n\n async run(runInput?: string) {\n const stdout: unknown[] = [];\n const stderr: string[] = [];\n\n const runtime = buildRuntime(stdout, stderr, { envVars, promptAnswers, configFiles, stdinData });\n const testProgram = program.runtime(runtime);\n\n try {\n const evalResult = await testProgram.eval(runInput ?? input ?? '', { autoOutput: false });\n return toTestResult(evalResult, stdout, stderr);\n } catch (err) {\n stderr.push(err instanceof Error ? err.message : String(err));\n return {\n command: undefined as unknown as AnyPadroneCommand,\n args: undefined,\n result: undefined,\n issues: undefined,\n stdout,\n stderr,\n error: err,\n };\n }\n },\n\n async repl(inputs: string[]) {\n const stdout: unknown[] = [];\n const stderr: string[] = [];\n\n const runtime = buildRuntime(stdout, stderr, {\n envVars,\n promptAnswers,\n configFiles,\n readLine: createMockReadLine(inputs),\n });\n\n const testProgram = program.runtime(runtime);\n const results: Omit<TestCliResult, 'stdout' | 'stderr'>[] = [];\n\n for await (const r of testProgram.repl({ greeting: false, hint: false })) {\n results.push({\n command: r.command,\n args: r.args,\n result: r.result,\n issues: r.argsResult?.issues as TestCliResult['issues'],\n });\n }\n\n return { results, stdout, stderr };\n },\n };\n\n return builder;\n}\n\nfunction toTestResult(evalResult: PadroneCommandResult, stdout: unknown[], stderr: string[]): TestCliResult {\n return {\n command: evalResult.command,\n args: evalResult.args,\n result: evalResult.result,\n issues: evalResult.argsResult?.issues as TestCliResult['issues'],\n stdout,\n stderr,\n };\n}\n\nfunction buildRuntime(\n stdout: unknown[],\n stderr: string[],\n opts: {\n envVars?: Record<string, string | undefined>;\n promptAnswers?: Record<string, unknown>;\n configFiles?: Record<string, Record<string, unknown>>;\n readLine?: (prompt: string) => Promise<string | null>;\n stdinData?: string;\n },\n): PadroneRuntime {\n const runtime: PadroneRuntime = {\n output: (...args: unknown[]) => stdout.push(...args),\n error: (text: string) => stderr.push(text),\n };\n\n if (opts.envVars) {\n runtime.env = () => opts.envVars!;\n }\n\n if (opts.promptAnswers) {\n runtime.interactive = 'supported';\n runtime.prompt = async (config: InteractivePromptConfig) => opts.promptAnswers![config.name];\n }\n\n if (opts.configFiles) {\n runtime.loadConfigFile = (path: string) => opts.configFiles![path];\n runtime.findFile = (names: string[]) => names.find((n) => n in opts.configFiles!);\n }\n\n if (opts.readLine) {\n runtime.readLine = opts.readLine;\n }\n\n if (opts.stdinData !== undefined) {\n runtime.stdin = {\n isTTY: false,\n async text() {\n return opts.stdinData!;\n },\n async *lines() {\n const lines = opts.stdinData!.split('\\n');\n // Remove trailing empty line from final newline (matches readline behavior)\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n for (const line of lines) {\n yield line;\n }\n },\n };\n } else {\n // No stdin data: simulate a TTY (no piped input) to avoid reading from process.stdin\n runtime.stdin = {\n isTTY: true,\n async text() {\n return '';\n },\n async *lines() {\n // no lines\n },\n };\n }\n\n return runtime;\n}\n\nfunction createMockReadLine(inputs: string[]): (prompt: string) => Promise<string | null> {\n let index = 0;\n return async (_prompt: string): Promise<string | null> => {\n if (index >= inputs.length) return null;\n return inputs[index++] ?? null;\n };\n}\n"],"mappings":";AAuHA,SAAgB,QAAQ,SAA0C;CAChE,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,UAA0B;EAC9B,KAAK,MAAc;AACjB,WAAQ;AACR,UAAO;;EAET,IAAI,MAAM;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Q,WAAW,YAAY;EAC/B;EACA;EACD;;AAGH,SAAS,aACP,QACA,QACA,MAOgB;CAChB,MAAM,UAA0B;EAC9B,SAAS,GAAG,SAAoB,OAAO,KAAK,GAAG,KAAK;EACpD,QAAQ,SAAiB,OAAO,KAAK,KAAK;EAC3C;AAED,KAAI,KAAK,QACP,SAAQ,YAAY,KAAK;AAG3B,KAAI,KAAK,eAAe;AACtB,UAAQ,cAAc;AACtB,UAAQ,SAAS,OAAO,WAAoC,KAAK,cAAe,OAAO;;AAGzF,KAAI,KAAK,aAAa;AACpB,UAAQ,kBAAkB,SAAiB,KAAK,YAAa;AAC7D,UAAQ,YAAY,UAAoB,MAAM,MAAM,MAAM,KAAK,KAAK,YAAa;;AAGnF,KAAI,KAAK,SACP,SAAQ,WAAW,KAAK;AAG1B,KAAI,KAAK,cAAc,KAAA,EACrB,SAAQ,QAAQ;EACd,OAAO;EACP,MAAM,OAAO;AACX,UAAO,KAAK;;EAEd,OAAO,QAAQ;GACb,MAAM,QAAQ,KAAK,UAAW,MAAM,KAAK;AAEzC,OAAI,MAAM,SAAS,KAAK,MAAM,MAAM,SAAS,OAAO,GAAI,OAAM,KAAK;AACnE,QAAK,MAAM,QAAQ,MACjB,OAAM;;EAGX;KAGD,SAAQ,QAAQ;EACd,OAAO;EACP,MAAM,OAAO;AACX,UAAO;;EAET,OAAO,QAAQ;EAGhB;AAGH,QAAO;;AAGT,SAAS,mBAAmB,QAA8D;CACxF,IAAI,QAAQ;AACZ,QAAO,OAAO,YAA4C;AACxD,MAAI,SAAS,OAAO,OAAQ,QAAO;AACnC,SAAO,OAAO,YAAY"}
1
+ {"version":3,"file":"test.mjs","names":[],"sources":["../src/test.ts"],"sourcesContent":["import type { InteractivePromptConfig, PadroneRuntime } from './runtime.ts';\nimport type { AnyPadroneCommand, PadroneCommandResult } from './types.ts';\n\n/**\n * Result from a single command execution in test mode.\n * Extends the standard PadroneCommandResult with captured I/O.\n */\nexport type TestCliResult = {\n /** The matched command. */\n command: AnyPadroneCommand;\n /** Validated arguments (undefined if validation failed). */\n args: unknown;\n /** Action handler return value (undefined if validation failed or no action). */\n result: unknown;\n /** Validation issues, if any. */\n issues: { message: string; path?: PropertyKey[] }[] | undefined;\n /** All values passed to `runtime.output()`. */\n stdout: unknown[];\n /** All strings passed to `runtime.error()`. */\n stderr: string[];\n /** The thrown error, if the command threw (routing error, action error, etc.). */\n error?: unknown;\n};\n\n/**\n * Result from a REPL test session.\n */\nexport type TestReplResult = {\n /** One entry per successfully executed command (validation errors are captured in stderr, not here). */\n results: Omit<TestCliResult, 'stdout' | 'stderr'>[];\n /** All output from the entire REPL session. */\n stdout: unknown[];\n /** All errors from the entire REPL session. */\n stderr: string[];\n};\n\n/**\n * Fluent builder for setting up CLI test scenarios.\n */\nexport type TestCliBuilder = {\n /** Set the CLI input string (e.g. `'deploy --env production'`). */\n args(input: string): TestCliBuilder;\n /** Set environment variables visible to the command. */\n env(vars: Record<string, string | undefined>): TestCliBuilder;\n /** Provide mock answers for interactive prompts. Keys are field names. */\n prompt(answers: Record<string, unknown>): TestCliBuilder;\n /** Provide mock config files. Keys are file paths, values are parsed config objects. */\n config(files: Record<string, Record<string, unknown>>): TestCliBuilder;\n /** Provide mock stdin data (simulates piped input). */\n stdin(data: string): TestCliBuilder;\n /**\n * Execute a single command via `eval()` and return the result with captured I/O.\n * @param input - Optional CLI input string. Overrides `.args()` if provided.\n */\n run(input?: string): Promise<TestCliResult>;\n /**\n * Run a REPL session with the given sequence of inputs.\n * Each string in the array is fed as one line of input.\n * The session ends after all inputs are consumed (EOF).\n */\n repl(inputs: string[]): Promise<TestReplResult>;\n};\n\n/**\n * Creates a fluent test builder for a Padrone program.\n * Captures all I/O and provides a clean interface for assertions.\n *\n * Works with any test framework (bun:test, vitest, jest, node:test, etc.).\n *\n * @example\n * ```ts\n * import { testCli } from 'padrone/test'\n *\n * const result = await testCli(myProgram)\n * .args('deploy --env production')\n * .env({ API_KEY: 'xxx' })\n * .run()\n *\n * expect(result.result).toBe('Deployed')\n * expect(result.stdout).toContain('Deploying...')\n * ```\n *\n * @example\n * ```ts\n * // Shorthand: pass input directly to run()\n * const result = await testCli(myProgram).run('deploy --env production')\n * ```\n *\n * @example\n * ```ts\n * // Test interactive prompts\n * const result = await testCli(myProgram)\n * .args('init')\n * .prompt({ name: 'myapp', template: 'react' })\n * .run()\n *\n * expect(result.args).toEqual({ name: 'myapp', template: 'react' })\n * ```\n *\n * @example\n * ```ts\n * // Test REPL sessions\n * const { results } = await testCli(myProgram)\n * .repl(['greet World', 'add --a=2 --b=3'])\n *\n * expect(results[0].result).toBe('Hello, World!')\n * expect(results[1].result).toBe(5)\n * ```\n */\n/**\n * Any program-like object that has `eval`, `runtime`, and `repl` methods.\n * Avoids strict variance issues with `AnyPadroneProgram`.\n */\ntype TestableProgram = {\n eval: (input: string, prefs?: { autoOutput?: boolean }) => any;\n runtime: (runtime: PadroneRuntime) => TestableProgram;\n repl: (options?: { greeting?: false; hint?: false }) => AsyncIterable<any>;\n};\n\nexport function testCli(program: TestableProgram): TestCliBuilder {\n let input: string | undefined;\n let envVars: Record<string, string | undefined> | undefined;\n let promptAnswers: Record<string, unknown> | undefined;\n let configFiles: Record<string, Record<string, unknown>> | undefined;\n let stdinData: string | undefined;\n\n const builder: TestCliBuilder = {\n args(args: string) {\n input = args;\n return builder;\n },\n env(vars) {\n envVars = vars;\n return builder;\n },\n prompt(answers) {\n promptAnswers = answers;\n return builder;\n },\n config(files) {\n configFiles = files;\n return builder;\n },\n stdin(data: string) {\n stdinData = data;\n return builder;\n },\n\n async run(runInput?: string) {\n const stdout: unknown[] = [];\n const stderr: string[] = [];\n\n const runtime = buildRuntime(stdout, stderr, { envVars, promptAnswers, configFiles, stdinData });\n const testProgram = program.runtime(runtime);\n\n const evalResult = await testProgram.eval(runInput ?? input ?? '', { autoOutput: false });\n if (evalResult.error) {\n stderr.push(evalResult.error instanceof Error ? evalResult.error.message : String(evalResult.error));\n }\n return toTestResult(evalResult, stdout, stderr);\n },\n\n async repl(inputs: string[]) {\n const stdout: unknown[] = [];\n const stderr: string[] = [];\n\n const runtime = buildRuntime(stdout, stderr, {\n envVars,\n promptAnswers,\n configFiles,\n readLine: createMockReadLine(inputs),\n });\n\n const testProgram = program.runtime(runtime);\n const results: Omit<TestCliResult, 'stdout' | 'stderr'>[] = [];\n\n for await (const r of testProgram.repl({ greeting: false, hint: false })) {\n results.push({\n command: r.command!,\n args: r.args,\n result: r.result,\n issues: r.argsResult?.issues as TestCliResult['issues'],\n });\n }\n\n return { results, stdout, stderr };\n },\n };\n\n return builder;\n}\n\nfunction toTestResult(evalResult: PadroneCommandResult, stdout: unknown[], stderr: string[]): TestCliResult {\n return {\n command: evalResult.command!,\n args: evalResult.args,\n result: evalResult.result,\n error: evalResult.error,\n issues: evalResult.argsResult?.issues as TestCliResult['issues'],\n stdout,\n stderr,\n };\n}\n\nfunction buildRuntime(\n stdout: unknown[],\n stderr: string[],\n opts: {\n envVars?: Record<string, string | undefined>;\n promptAnswers?: Record<string, unknown>;\n configFiles?: Record<string, Record<string, unknown>>;\n readLine?: (prompt: string) => Promise<string | null>;\n stdinData?: string;\n },\n): PadroneRuntime {\n const runtime: PadroneRuntime = {\n output: (...args: unknown[]) => stdout.push(...args),\n error: (text: string) => stderr.push(text),\n };\n\n if (opts.envVars) {\n runtime.env = () => opts.envVars!;\n }\n\n if (opts.promptAnswers) {\n runtime.interactive = 'supported';\n runtime.prompt = async (config: InteractivePromptConfig) => opts.promptAnswers![config.name];\n }\n\n if (opts.configFiles) {\n runtime.loadConfigFile = (path: string) => opts.configFiles![path];\n runtime.findFile = (names: string[]) => names.find((n) => n in opts.configFiles!);\n }\n\n if (opts.readLine) {\n runtime.readLine = opts.readLine;\n }\n\n if (opts.stdinData !== undefined) {\n runtime.stdin = {\n isTTY: false,\n async text() {\n return opts.stdinData!;\n },\n async *lines() {\n const lines = opts.stdinData!.split('\\n');\n // Remove trailing empty line from final newline (matches readline behavior)\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n for (const line of lines) {\n yield line;\n }\n },\n };\n } else {\n // No stdin data: simulate a TTY (no piped input) to avoid reading from process.stdin\n runtime.stdin = {\n isTTY: true,\n async text() {\n return '';\n },\n async *lines() {\n // no lines\n },\n };\n }\n\n return runtime;\n}\n\nfunction createMockReadLine(inputs: string[]): (prompt: string) => Promise<string | null> {\n let index = 0;\n return async (_prompt: string): Promise<string | null> => {\n if (index >= inputs.length) return null;\n return inputs[index++] ?? null;\n };\n}\n"],"mappings":";AAuHA,SAAgB,QAAQ,SAA0C;CAChE,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,UAA0B;EAC9B,KAAK,MAAc;AACjB,WAAQ;AACR,UAAO;;EAET,IAAI,MAAM;AACR,aAAU;AACV,UAAO;;EAET,OAAO,SAAS;AACd,mBAAgB;AAChB,UAAO;;EAET,OAAO,OAAO;AACZ,iBAAc;AACd,UAAO;;EAET,MAAM,MAAc;AAClB,eAAY;AACZ,UAAO;;EAGT,MAAM,IAAI,UAAmB;GAC3B,MAAM,SAAoB,EAAE;GAC5B,MAAM,SAAmB,EAAE;GAE3B,MAAM,UAAU,aAAa,QAAQ,QAAQ;IAAE;IAAS;IAAe;IAAa;IAAW,CAAC;GAGhG,MAAM,aAAa,MAFC,QAAQ,QAAQ,QAAQ,CAEP,KAAK,YAAY,SAAS,IAAI,EAAE,YAAY,OAAO,CAAC;AACzF,OAAI,WAAW,MACb,QAAO,KAAK,WAAW,iBAAiB,QAAQ,WAAW,MAAM,UAAU,OAAO,WAAW,MAAM,CAAC;AAEtG,UAAO,aAAa,YAAY,QAAQ,OAAO;;EAGjD,MAAM,KAAK,QAAkB;GAC3B,MAAM,SAAoB,EAAE;GAC5B,MAAM,SAAmB,EAAE;GAE3B,MAAM,UAAU,aAAa,QAAQ,QAAQ;IAC3C;IACA;IACA;IACA,UAAU,mBAAmB,OAAO;IACrC,CAAC;GAEF,MAAM,cAAc,QA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