// Name: Expose Script API // Description: REST API for script execution // Author: erauner12 import '@johnlindquist/kit' import express, { Express, Request, Response } from 'express' /** * Interface defining the structure of a script object. */ interface Script { name: string filePath: string} /** * Fetches all scripts available in the Script Kit environment. */ const scripts = await getScripts() /** * Filters out the 'index' script and maps the remaining scripts to choice objects for the prompt. */ const choices = scripts .filter((s: Script) => s.name !== 'index') .map((s: Script) => ({ name: s.name, value: s.filePath, description: s.filePath, })) /** * Prompts the user to select a script from the available choices. */ const selectedScript = await arg<string>('Select a script to expose via REST API', choices) /** * Extracts the script name from the selected script's file path. */ const scriptName = selectedScript.split('/').pop()?.split('.')[0] /** * Prompts the user to enter the port number for the REST API, defaulting to 3000. */ const port = await env('PORT', 'Enter the port to use for the REST API', '3000') /** * Constructs the base URL and the full endpoint URL for the REST API. */ const baseUrl = `http://localhost:${port}` const endpoint = `${baseUrl}/${scriptName}` /** * Displays a markdown-formatted div with information about the created REST API endpoint and example usage. */ await div( md(` # REST API endpoint createdEndpoint: [${endpoint}](${endpoint}) ## Example usage \`\`\`bash curl ${endpoint} \`\`\` ## How to End Long-Running Scripts Press "${cmd}+p" from the Main Menu to open the Process Manager. Select the process you want to end. ![http://res.cloudinary.com/johnlindquist/image/upload/v1689094925/clipboard/stzc2z4dsi15wrwdctao.png](http://res.cloudinary.com/johnlindquist/image/upload/v1689094925/clipboard/stzc2z4dsi15wrwdctao.png) `) ) /** * Hides the prompt window after displaying the endpoint information. */ hide() /** * Initializes an Express application. */ const app: Express = express() /** * Defines a GET endpoint for the selected script. * When this endpoint is called, it executes the selected script using the `run` function. */ app.get(`/${scriptName}`, async (req: Request, res: Response) => { try { /** * Executes the selected script. */ await run(selectedScript) /** * Sends a success response if the script executes without errors. */ res.send(`Script ${scriptName} executed successfully`) } catch (error: any) { /** * Sends an error response if there's an issue executing the script. */ res.status(500).send(`Error executing script ${scriptName}: ${error}`) } }) /** * Starts the Express server and listens on the specified port. * Returns a promise that resolves when the server starts listening. */ await new Promise<void>((resolve, reject) => { app.listen(port, () => resolve()) })