UNPKG

json2zod

Version:

A CLI tool and library to convert JSON to Zod schemas with optional OpenAPI examples.

153 lines (148 loc) 5.42 kB
#!/usr/bin/env node "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); const generator_1 = require("./generator"); // Import the core generator function const path = __importStar(require("path")); /** * Main function for the CLI tool. * Reads JSON input, processes arguments, and prints the generated Zod schema. */ async function main() { const args = process.argv.slice(2); let jsonString; let addOpenApiExamples = false; // Default behavior changed to NOT include OpenAPI examples // Parse command line arguments for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === '--add-openapi-examples') { // Flag to ENABLE OpenAPI examples addOpenApiExamples = true; } else if (arg === '--help' || arg === '-h') { printHelp(); process.exit(0); } else if (arg.startsWith('-')) { console.error(`Error: Unknown option "${arg}"`); printHelp(); process.exit(1); } else if (!jsonString) { // Assume the first non-flag argument is the JSON string jsonString = arg; } else { console.error("Error: Too many arguments provided. Expected a single JSON string or input via stdin."); printHelp(); process.exit(1); } } // If no JSON string is provided via arguments, try reading from stdin if (!jsonString) { // Check if stdin is a TTY (interactive terminal). If so, prompt the user. // If not (e.g., piped input), it will just wait for stdin. if (process.stdin.isTTY) { console.log("Enter JSON (Ctrl+D to finish, Ctrl+C to exit):"); } jsonString = await readFromStdin(); } if (!jsonString) { console.error("Error: No JSON input provided."); printHelp(); process.exit(1); } try { const parsedJson = JSON.parse(jsonString); // Call the core generator function with the parsed JSON and options const zodSchemaOutput = (0, generator_1.generateZodSchema)(parsedJson, { addOpenApiExamples }); console.log(zodSchemaOutput); } catch (e) { if (e instanceof SyntaxError) { console.error(`Error: Invalid JSON input. ${e.message}`); } else { console.error(`An unexpected error occurred: ${e.message}`); } process.exit(1); } } /** * Reads all data from standard input (stdin) until EOF. * @returns A promise that resolves with the accumulated input string. */ function readFromStdin() { return new Promise((resolve, reject) => { let data = ''; process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { let chunk; while ((chunk = process.stdin.read()) !== null) { data += chunk; } }); process.stdin.on('end', () => { resolve(data); }); process.stdin.on('error', (err) => { reject(err); }); }); } /** * Prints the help message for the CLI tool. */ function printHelp() { const scriptName = path.basename(process.argv[1] || 'json2zod'); console.log(` Usage: ${scriptName} [options] [json_string] Generate a Zod schema from a JSON string. If no JSON string is provided, input is read from stdin. Options: --add-openapi-examples Include .openapi({ example: ... }) in the generated schema. By default, examples are NOT included. -h, --help Show this help message and exit. Examples: # Pass JSON as a string argument (no OpenAPI examples by default) ${scriptName} '{"name": "Alice", "age": 30}' # Pipe JSON from a file with OpenAPI examples cat data.json | ${scriptName} --add-openapi-examples # Pipe JSON from stdin without OpenAPI examples (default) echo '{"item": "pen"}' | ${scriptName} `); } // Execute the main CLI function main(); //# sourceMappingURL=cli.js.map