#!/usr/bin/env node import fs from "fs"; import path from "path"; // Parse command-line arguments import { parseArgs } from "util"; const args = parseArgs({ options: { "api-url": { type: "string", short: "a", default: process.env.JMESPATH_PLAYGROUND_API_URL || "http://localhost:3000", }, "api-key": { type: "string", short: "k", default: process.env.JMESPATH_PLAYGROUND_API_KEY || "", }, "json-file": { type: "string", short: "j", default: "", }, help: { type: "boolean", short: "h" }, }, }); // Show help message if (args.values.help) { console.log(` Usage: upload-jmespath.mjs [options] Options: -a, --api-url API base URL (default: http://localhost:3000) -k, --api-key API key for authentication -j, --json-file Path to the JSON file to upload -h, --help Show this help message `); process.exit(0); } // Read the JSON from the specfied file or from stdin if no file is provided async function readJson(filePath) { if (filePath) { const absolutePath = path.resolve(filePath); const fileContent = fs.readFileSync(absolutePath, "utf-8"); return JSON.parse(fileContent); } else { return new Promise((resolve, reject) => { let data = ""; process.stdin.on("data", (chunk) => { data += chunk; }); process.stdin.on("end", () => { try { resolve(JSON.parse(data)); } catch (error) { reject(error); } }); }); } } // Upload the JSON data to the API using built-in fetch async function uploadJson(apiUrl, apiKey, jsonData) { const response = await fetch(`${apiUrl}/api/v1/upload`, { method: "POST", headers: { "Content-Type": "application/json", ...(apiKey ? { "X-API-Key": `${apiKey}` } : {}), }, body: JSON.stringify(jsonData), }); if (!response.ok) { throw new Error(`Failed to upload JSON: ${response.status} ${response.statusText}`); } } // Main function async function main() { try { const jsonData = await readJson(args.values["json-file"]); await uploadJson(args.values["api-url"], args.values["api-key"], jsonData); console.log("JSON uploaded successfully."); } catch (error) { console.error("Error:", error.message); process.exit(1); } } main();