### Start Docusaurus Development Server Source: https://github.com/johnlindquist/kit-docs/blob/main/README.md After installing dependencies, run this command in the /host directory to launch a local copy of the documentation site, allowing for real-time preview of changes. ```bash cd host yarn start ``` -------------------------------- ### Editor Example Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Provides a basic example of using the `editor()` function to open Script Kit's built-in Monaco editor prompt. The content entered by the user is returned. ```js // Name: Editor Example import "@johnlindquist/kit" let result = await editor() await div(md(result)) ``` -------------------------------- ### path: With Start Path and Hint (ts) Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Configures the `path` prompt to start in a specific directory (`startPath`) and provides a descriptive `hint` to guide the user's selection. ```ts const projectPath = await path({ startPath: home("dev"), hint: "Select a project from your dev folder", }); await editor(projectPath); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/johnlindquist/kit-docs/blob/main/host/README.md Starts a local development server for live preview. Most changes are reflected live without requiring a server restart. ```shell $ yarn start ``` -------------------------------- ### Basic Input Prompt with `arg` Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows the simplest usage of the `arg` function to get string input from the user. The input is directly returned and rendered as HTML by Kit.app. ```js await arg("Start typing", input => input) ``` -------------------------------- ### Database Read/Write Example (Kit) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md An example of using Kit's database functionality to manage a list of fruits. It allows users to add new fruits and delete existing ones through interactive prompts, persisting changes to a local JSON file. The script runs in an infinite loop until manually stopped. ```typescript import "@johnlindquist/kit" let fruitDb = await db(["apple", "banana", "orange"]) while (true) { let fruitToAdd = await arg("Add a fruit", md(fruitDb.items.map(fruit => `* ${fruit}`).join("\n"))) fruitDb.items.push(fruitToAdd) await fruitDb.write() let fruitToDelete = await arg("Delete a fruit", fruitDb.items) fruitDb.items = fruitDb.items.filter(fruit => fruit !== fruitToDelete) await fruitDb.write() } ``` -------------------------------- ### Install Docusaurus Dependencies Source: https://github.com/johnlindquist/kit-docs/blob/main/README.md Navigate to the /host directory and install the necessary dependencies using Yarn to set up the local development environment for the documentation site. ```bash cd host yarn install ``` -------------------------------- ### Select from Finder Prompts Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to use `selectFile()` and `selectFolder()` to prompt the user for file and folder selections, respectively, leveraging native OS dialogs. ```js // Name: Select from Finder Prompt import "@johnlindquist/kit" let filePath = await selectFile() let folderPath = await selectFolder() await div(md(`You selected ${filePath} and ${folderPath}`)) ``` -------------------------------- ### Select a Path Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates the basic usage of the `path()` function to prompt the user to select a file or directory. The selected path is then displayed. ```js // Name: Select a Path import "@johnlindquist/kit" let filePath = await path() await div(md(`You selected ${filePath}`)) ``` -------------------------------- ### Celsius to Fahrenheit Converter with `arg` Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md An example of using the `arg` function to create an interactive converter. It takes Celsius input and displays the Fahrenheit equivalent, formatted with HTML. ```js let cToF = celsius => { return (celsius * 9) / 5 + 32 } await arg( "Enter degress in celsius", input => `
${input ? cToF(input) + "f" : `Waiting for input`}
` ) ``` -------------------------------- ### Scriptlet Placeholder Usage Example Source: https://github.com/johnlindquist/kit-docs/blob/main/SCRIPTLETS.md Demonstrates the use of scriptlet placeholders like $0, $1, etc., within codefence to prompt users for input before executing a command. This example shows how to construct a Google Images search URL dynamically. ```open # Placeholders ## Search Google Images Will prompt for 2 arguments before opening the url: ```open https://www.google.com/search?q=$0+$1 ``` ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/johnlindquist/kit-docs/blob/main/host/README.md Installs project dependencies using Yarn. This command fetches all necessary packages listed in the project's package.json file. ```shell $ yarn ``` -------------------------------- ### Display Dynamic HTML with arg() using Async Functions Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates using an asynchronous function with arg() to generate HTML. The example uses the highlight() function to apply code highlighting to markdown strings, creating dynamic, highlighted previews. ```js await arg( "Select a fruit", async input => await highlight(` ~~~js await arg("${input}") ~~~ `) ) ``` -------------------------------- ### Select From a List of Strings Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to use `await arg()` to present a list of predefined string options to the user. The selected string is then returned and can be used in the script. ```js // Name: Select From a List import "@johnlindquist/kit" let fruit = await arg("Pick a fruit", [ "Apple", "Banana", "Cherry", ]) await div(md(`You selected ${fruit}`)) ``` -------------------------------- ### Alternate Importing Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Demonstrates an alternative way to import and use Script Kit APIs. ```typescript import kit from "@johnlindquist/kit" await kit.arg("Enter your name") ``` -------------------------------- ### Get Scripts Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Provides an example of using the `getScripts` function to retrieve all available scripts. The retrieved scripts can then be used to build a selection menu using `arg`. ```ts // Get all scripts from ~/.kit/db/scripts.json const scripts = await getScripts(); const script = await arg("Select a script", scripts); await editor(JSON.stringify(script, null, 2)); ``` -------------------------------- ### Read Text File Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Reads the content of a text file from the local system using the `readFile` function. The example first downloads a README file for demonstration purposes and then displays its content in an editor. ```javascript // Name: Read a Text File import "@johnlindquist/kit" // Download a readme for the sake of the example let fileUrl = `https://raw.githubusercontent.com/johnlindquist/kit/main/README.md` let filePath = home("README.md") let buffer = await download(fileUrl) await writeFile(filePath, buffer) // Read the file let contents = await readFile(filePath, "utf-8") await editor(contents) ``` -------------------------------- ### Quick Submit from Choice Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to use `arg()` with an array of choices to provide more detailed options to the user. Each choice has a display name and a submitted value. ```js import "@johnlindquist/kit" let value = await arg("Select a food", [ { name: "[a]pple", value: "apple", }, { name: "[b]anana", value: "banana", }, { name: "[c]heese", value: "cheese", }, ]) await div(md(value)) ``` -------------------------------- ### Quick Submit from Hint Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how to use a hint with a single bracketed character in `arg()` to allow quick submission of that character. This is useful for simple yes/no prompts. ```js import "@johnlindquist/kit" let value = await arg({ placeholder: "Continue?", hint: `Another [y]/[n]`, }) if (value === "y") { say(`You pressed y`) } else { say(`You pressed n`) } ``` -------------------------------- ### Select a Path with Options Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates advanced usage of `path()` with options like `hint`, `onlyDirs`, and `onChoiceFocus`. The `onChoiceFocus` callback allows for dynamic preview updates based on the focused directory. ```js // Name: Select a Path with Options import "@johnlindquist/kit" await path({ hint: `Select a path containing JS files`, onlyDirs: true, onChoiceFocus: async (input, { focused }) => { let focusedPath = focused.value try { let files = await readdir(focusedPath) let hasJS = files.find(f => f.endsWith(".js")) setPreview( md( `${hasJS ? "✅ Found" : "🔴 Didn't find"} JS files` ) ) } catch (error) { log(error) } }, }) ``` -------------------------------- ### HTTP GET Request Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Makes an HTTP GET request to a specified URL using the `get` method, which is an alias for the Axios API. It retrieves data and displays a message from the response. ```javascript // Name: Get Example import "@johnlindquist/kit" let response = await get( "https://scriptkit.com/api/get-example" ) await div(md(response.data.message)) ``` -------------------------------- ### Load Text Into the Editor Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to load external text content into the built-in editor using the `editor()` function with the `value` and `language` options. The example fetches README content from GitHub. ```js // Name: Load Text Into the Editor import "@johnlindquist/kit" let { data } = await get( `https://raw.githubusercontent.com/johnlindquist/kit/main/README.md` ) let result = await editor({ value: data, // Supports "css", "js", "ts", "md", "properties". "md" is default. More language support coming in future releases. language: "md", footer: `Hit cmd+s to continue...`, }) await div(md(result)) ``` -------------------------------- ### Find Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Provides an example of the 'find' function, which opens a file search prompt. It allows specifying a directory to search within and returns the selected file path. ```typescript let filePath = await find("Search in the Downloads directory", { onlyin: home("Downloads"), }) await revealFile(filePath) ``` -------------------------------- ### AI Environment Variable Setup Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Provides an example of how to configure AI-related environment variables in the `~/.kenv/.env` file. These variables set the default AI provider, model, temperature, and max tokens for Script Kit's AI helpers. ```env AI_DEFAULT_PROVIDER=anthropic AI_DEFAULT_MODEL=claude-3-opus-20240229 AI_DEFAULT_TEMPERATURE=0.7 AI_DEFAULT_MAX_TOKENS=1000 ``` -------------------------------- ### Download File from URL Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Downloads a file from a given URL using the `download` utility. The downloaded content is returned as a buffer, which can then be written to a local file. ```javascript // Name: Download a File import "@johnlindquist/kit" let url = "https://www.scriptkit.com/assets/logo.png" let buffer = await download(url) let fileName = path.basename(url) let filePath = home(fileName) await writeFile(filePath, buffer) ``` -------------------------------- ### Keyboard Shortcut Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Demonstrates using the keyboard API to simulate key presses for common shortcuts like Command+A, Command+C, Command+N, and Command+V. ```ts prompt: false, }; await keyboard.tap(Key.LeftSuper, Key.A); await wait(100); await keyboard.tap(Key.LeftSuper, Key.C); await wait(100); await keyboard.tap(Key.LeftSuper, Key.N); await wait(100); await keyboard.tap(Key.LeftSuper, Key.V); ``` -------------------------------- ### Select from a Dynamic List Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates how to populate a selection prompt dynamically by providing an async function to `await arg()`. This function fetches data (e.g., from an API) and returns a list of options. ```js // Name: Select From a Dynamic List import "@johnlindquist/kit" await arg("Select a Star Wars Character", async () => { // Get a list of people from the swapi api let response = await get("https://swapi.dev/api/people/") return response?.data?.results.map(p => p.name) }) ``` -------------------------------- ### Schedule Script with Cron in Kit Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to schedule a script to run automatically using cron syntax. The example sets a schedule to display a notification every 15 minutes. It uses the `notify` function for alerts and comments to define the cron schedule. ```js // Name: Stand Up and Stretch // Schedule: */15 * * * * import "@johnlindquist/kit" notify(`Stand up and stretch`) ``` -------------------------------- ### Global Helpers: Network Request and File Write Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Script Kit provides global helper functions that abstract common Node.js or third-party library operations. This example uses `get` to fetch content from a URL and `writeFile` to save it to a local file, requiring no explicit imports. ```javascript const url = "https://raw.githubusercontent.com/johnlindquist/kit-docs/refs/heads/main/API.md"; const response = await get(url); const content = response.data; const apiPath = home("Downloads", "API.md"); await writeFile(apiPath, content); ``` -------------------------------- ### Top-Level Await Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Illustrates the use of top-level await in Script Kit, allowing asynchronous operations like file system access and network requests to be performed directly. This example reads all markdown files in a directory and displays their combined content in an editor. ```ts const downloadMarkdownPattern = home("Downloads", "*.md"); const files = await globby(downloadMarkdownPattern); let totalContent = ""; for await (const file of files) { const content = await readFile(file, "utf8"); totalContent += content; } await editor(totalContent); ``` -------------------------------- ### Quick Keys for Prompt Choices Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to use quick keys for user prompts. This can be done via a hint string or by embedding quick keys within the choice names. It also demonstrates returning a specific `value` associated with a quick key selection. ```javascript //Type "y" or "n" let confirm = await arg({ placeholder: "Eat a taco?", hint: `[y]es/[n]o`, }) console.log(confirm) //"y" or "n" ``` ```javascript // Type "a", "b", or "g" let fruit = await arg(`Pick one`, [ `An [a]pple`, `A [b]anana`, `a [g]rape`, ]) console.log(fruit) //"a", "b", or "g" ``` ```javascript // Type "c" or "a" let vegetable = await arg("Pick a veggie", [ { name: "[C]elery", value: "Celery" }, { name: "C[a]rrot", value: "Carrot" }, ]) console.log(vegetable) //"Celery" or "Carrot" ``` -------------------------------- ### Save Webpage as PDF Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how to download a webpage and save it as a PDF file. It uses `getWebpageAsPdf` to fetch the content and `writeFile` to save it to the user's home directory. ```js // Name: Save news as PDF import "@johnlindquist/kit" const pdfResults = await getWebpageAsPdf('https://legiblenews.com'); await writeFile(home('news.pdf'), pdfResults); ``` -------------------------------- ### Input Text with `arg()` Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates the basic usage of `await arg()` to prompt the user for text input. The entered text is then used in a subsequent action, like displaying a greeting. ```js // Name: Input Text import "@johnlindquist/kit" let name = await arg("Enter your name") await div(md(`Hello, ${name}`)) ``` -------------------------------- ### Use Shortcodes for Scripts in Kit Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Explains how to assign shortcodes to scripts for quick execution. By prefixing a script with `// Shortcode: `, users can type these characters in the main menu followed by a space to run the script. ```js // Shortcode: oi import "@johnlindquist/kit" say(`You pressed option i`) ``` -------------------------------- ### Preview Markdown in Editor (Kit) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md An interactive example that previews Markdown content within the Kit editor. It uses the `editor` function with an `onInput` callback to dynamically render the Markdown as it's being typed or modified, utilizing the `md` helper for conversion. ```typescript import "@johnlindquist/kit" let value = ` # Hello World ## Markdown Features Here are some examples of markdown features: - **Bold Text** - *Italic Text* - `Inline Code` 1. First item in a numbered list 2. Second item in a numbered list > Blockquote ![Image Alt Text](https://example.com/image.jpg "Image Title") ~~~javascript console.log("Code block with syntax highlighting"); ~~~ Here is a table: | Header 1 | Header 2 | | -------- | -------- | | Row 1 Col 1 | Row 1 Col 2 | | Row 2 Col 1 | Row 2 Col 2 | ` await editor({ value, onInput: async input => { setPreview(md(input)) }, }) ``` -------------------------------- ### Take Screenshot of Webpage Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to capture a screenshot of a webpage, with an option for a full-page screenshot. The resulting image data is saved as a PNG file. ```js // Name: Take screenshot of news webpage import "@johnlindquist/kit" const screenshotResults = await getScreenshotFromWebpage('https://legiblenews.com', { screenshotOptions: { fullPage: true }, }); await writeFile(home('news.png'), screenshotResults); ``` -------------------------------- ### Mic Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Shows how to record audio from the microphone using the 'mic' function. The recorded audio is returned as a buffer, which can be saved to a file and played back. ```typescript const tmpMicPath = tmpPath("mic.webm"); const buffer = await mic(); await writeFile(tmpMicPath, buffer); await playAudioFile(tmpMicPath); ``` -------------------------------- ### Progress Panel (TypeScript) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md This example demonstrates a dynamic progress panel within a prompt. It allows the user to input values sequentially, updating the panel's content after each input. The panel displays the status of each step, showing which values have been entered and which are still pending. ```ts // Name: Progress Panel // Group: Prompt import "@johnlindquist/kit" let first = "" let second = "" let third = "" let progressPanel = () => md(`# Progress: - ${first || "Waiting first value"} - ${second || "Waiting second value"} - ${third || "Waiting third value"} `) first = await arg("Enter the first value", progressPanel) second = await arg("Enter the second value", progressPanel) third = await arg("Enter the third value", progressPanel) await div( md(`# You entered: - ${first} - ${second} - ${third} `) ) ``` -------------------------------- ### Display Dynamic HTML with arg() using Functions Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how arg() can accept a function as its second argument, which returns a string. This string is then rendered as HTML, allowing for dynamic content generation based on user input. ```js await arg("Select a fruit", input => md(`You typed "${input}"`) ) ``` -------------------------------- ### Set Options using Flags with arg() Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how to add an options menu to arg() by passing an array of actions as the third argument. Each action has a name, shortcut, and an onAction handler for custom logic. ```js import "@johnlindquist/kit"; let urls = [ "https://scriptkit.com", "https://egghead.io", "https://johnlindquist.com", ]; let url = await arg(`Press 'right' to see menu`, urls, [ { name: "Open", shortcut: `${cmd}+o`, onAction: async (input, state) => { await open(state.focused.value); exit(); // Remove if you want to keep the menu open }, }, { name: "Copy", shortcut: `${cmd}+c`, onAction: async (input, state) => { await copy(state.focused.value); await notify(`Copied ${state.focused.value}`); exit(); }, }, ]); // Some default behavior await editor(url); ``` -------------------------------- ### DB Helper: Store Simple JSON Data Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates using the `db` helper to read/write JSON files in `~/.kenv/db`. It supports managing lists of items and can be used as a simple key-value store. ```javascript // Menu: Database Read/Write Example // Description: Add/remove items from a list of fruit let fruitDb = await db(["apple", "banana", "orange"]) // This will keep prompting until you hit Escape while (true) { let fruitToAdd = await arg( { placeholder: "Add a fruit", //allows to submit input not in the list strict: false, }, fruitDb.items ) fruitDb.items.push(fruitToAdd) await fruitDb.write() let fruitToDelete = await arg( "Delete a fruit", fruitDb.items ) fruitDb.items = fruitDb.items.filter( fruit => fruit !== fruitToDelete ) await fruitDb.write() } ``` ```javascript // Menu: Database Read/Write Example 2 // Description: Use 'db' helper as Key/Value Store // Open the json file with the same name as the script file, the data in the param is the default, // which will be used when the db file is opened the first time const scriptDB = await db({hello: 'World'}); // Note: This db read here should only make sure the db object has the latest content from disk. // It may be unnecessary directly after opening the db object. await scriptDB.read(); if (scriptDB.data.hello === 'World') { // change value in your db scriptDB.data.hello = 'Bob'; } else { // change value back in your db scriptDB.data.hello = 'World'; } await scriptDB.write(); ``` -------------------------------- ### Dynamic Choices with Static Preview using arg() Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Explains how to configure arg() with a preview function for static content and a dynamic function for choices. The preview is displayed regardless of input, while choices update based on user input. ```js await arg( { preview: async () => await highlight(` ## This is just information Usually to help you make a choice Just type some text to see the choices update `) }, async input => { return Array.from({ length: 10 }).map( (_, i) => `${input} ${i}` ) } ) ``` -------------------------------- ### Formatted Input Prompt with `arg` Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how to format user input using HTML within the `arg` function. This allows for richer display of the returned value, including styling. ```js await arg( "Type something", input => `
${input || `Waiting for input`}
` ) ``` -------------------------------- ### Webcam Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Demonstrates capturing an image from the webcam using the 'webcam' function. The captured image is returned as a buffer, which can then be saved or processed. ```typescript let buffer = await webcam() let imagePath = tmpPath("image.jpg") await writeFile(imagePath, buffer) await revealFile(imagePath) ``` -------------------------------- ### Watch Directory: Log Download Events Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Watches a directory (e.g., `~/Downloads/*`) for file system events using Chokidar patterns. It logs the path of added files to a `download.log` file. ```javascript // Name: Download Log // Watch: ~/Downloads/* import "@johnlindquist/kit" // These are optional and automatically set by the watcher let filePath = await arg() let event = await arg() if (event === "add") { await appendFile(home("download.log"), filePath + "\n") } ``` -------------------------------- ### Kit Module Import Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Illustrates an alternative method for importing and using the kit module's functionalities by importing the entire module and accessing its methods via dot notation. ```javascript import kit from "@johnlindquist/kit" await kit.arg("Enter your name") ``` -------------------------------- ### Importing Script Kit SDK Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Scripts in Script Kit begin by importing the SDK. This makes the global APIs available within your script. You can also import other npm libraries, and Script Kit will prompt for installation if needed. ```ts import "@johnlindquist/kit" import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai' ``` -------------------------------- ### Select From a List of Objects Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates selecting an item from a list where each item is an object. The `value` property of the selected object is destructured and used within the script. ```js // Name: Select From a List of Objects import "@johnlindquist/kit" let { size, weight } = await arg("Select a Fruit", [ { name: "Apple", description: "A shiny red fruit", // add any properties to "value" value: { size: "small", weight: 1, }, }, { name: "Banana", description: "A long yellow fruit", value: { size: "medium", weight: 2, }, }, ]) await div( md( `You selected a fruit with size: ${size} and weight: ${weight}` ) ) ``` -------------------------------- ### Kenv Path Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Shows how to use the `kenvPath` utility to construct file paths relative to the kit environment directory. It demonstrates reading the contents of a directory obtained via `kenvPath`. ```ts const scriptsPath = kenvPath("scripts"); const scripts = await readdir(scriptsPath); await editor(JSON.stringify(scripts, null, 2)); ``` -------------------------------- ### Async Prompt for Environment Variables Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates setting environment variables with an asynchronous prompt. If a variable is not found, a function passed to `env` is executed to prompt the user for input, such as selecting from a list. This allows for dynamic environment variable configuration. ```js // Name: Choose an Environment Variable import "@johnlindquist/kit" let MY_API_USER = await env("MY_API_USER", async () => { return await arg("Select a user for your API", [ "John", "Mindy", "Joy", ]) }) await div( md( `You selected ${MY_API_USER}. Running this script again will remember your choice` ) ) ``` -------------------------------- ### Create a Persisting Widget Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates the `widget` function to create a new, independent window. This window can display HTML content and persists even after the script that created it has finished execution. ```javascript await widget(`
Hello there!
`) ``` -------------------------------- ### Position Widget on Screen Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Explains how to control the size and position of a widget window. It utilizes `getActiveScreen()` to get screen dimensions and `workArea` to place the widget, for example, in the top-right corner of the current screen. ```javascript let width = 480 let height = 320 let { workArea } = await getActiveScreen() let { x, y, width: workAreaWidth } = workArea await widget( md(` # I'm in the top right of the current screen!
😘
`), { width, height, x: x + workAreaWidth - width, y: y, } ) ``` -------------------------------- ### Basic Scriptlet Example Source: https://github.com/johnlindquist/kit-docs/blob/main/SCRIPTLETS.md Demonstrates a basic scriptlet structure where a header 2 (##) defines a runnable script. The code within the code fence is executed by Script Kit. ```ts await open('https://scriptkit.com') ``` -------------------------------- ### Populate Database from API (Kit) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md Shows how to pre-populate a Kit database with data fetched from an external API (GitHub repositories in this case). It uses `get` to fetch data, maps it to a desired structure, and then allows the user to select an item (a repository URL) to open in the browser using `exec`. ```typescript // Pass in a function to generate data for the db // Because this script is named "db-basic.js" // The database is found at "~/.kenv/db/_db-basic.json" let reposDb = await db(async () => { let response = await get("https://api.github.com/users/johnlindquist/repos") return response.data.map(({ name, description, html_url }) => { return { name, description, value: html_url, } }) }) let repoUrl = await arg("Select repo to open:", reposDb.items) exec(`open "${repoUrl}"`) ``` -------------------------------- ### EyeDropper Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Illustrates using the 'eyeDropper' function to pick a color from the desktop. The function returns color information in various formats, shown here being displayed in an editor. ```typescript const result = await eyeDropper(); await editor(JSON.stringify(result, null, 2)); ``` -------------------------------- ### Append Text to Editor (Kit) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md This example demonstrates appending text to the Kit editor asynchronously. It uses `setInterval` to add words from a sentence one by one with a delay, and then opens the editor with specified configurations like line numbers and font family. ```typescript import "@johnlindquist/kit" let sentence = `This is a sentence that will be appended to the editor.` let words = sentence.split(" ") setInterval(() => { let word = words.shift() if (word) { editor.append(word + " ") } }, 100) await editor({ lineNumbers: "on", fontFamily: "Menlo", }) ``` -------------------------------- ### Clone Git Repositories with `degit` Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Utilizes the `degit` utility to clone a Git repository template into a specified directory. It prompts for a project name and then opens the cloned directory for editing. ```js let projectName = await arg("Name your project") let targetDir = home("projects", projectName) await degit(`https://github.com/sveltejs/template`).clone( targetDir ) edit(targetDir) ``` -------------------------------- ### Display HTML Beneath Input with arg() Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how the arg() function can display HTML content directly beneath the input prompt when the second argument is a string. This allows for rich previews or contextual information. ```js await arg( "Select a fruit", md(`I recommend typing "Apple"`) // "md" converts strings to HTML ) ``` -------------------------------- ### AI Provider Switching Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Demonstrates how to switch between different AI providers by specifying the provider and model ID in the `model` option. Supported providers include openai, anthropic, google, xai, and openrouter. ```typescript const result = await ai("Say hello", { model: "anthropic:claude-3-opus-20240229" }) // Supported providers: // - openai // - anthropic // - google // - xai // - openrouter ``` -------------------------------- ### Add Kit CLI to PATH Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Explains how to add the Kit CLI's binary directory to the system's PATH environment variable. This allows running the `kit` command directly from any terminal location instead of specifying the full path. ```bash ~/.kit/bin/kit ``` ```bash kit ``` -------------------------------- ### Manage Environment Variables with Kit Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates how to access environment variables using the `env` helper. It reads a variable from `~/.kenv/.env` and prompts the user to create it if it's not found. The loaded variable is then displayed in a markdown div. ```js // Name: Env Example import "@johnlindquist/kit" let KEY = await env("MY_KEY") await div(md(`You loaded ${KEY} from ~/.kenv/.env`)) ``` -------------------------------- ### Dev Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Shows the basic usage of the 'dev' function, which opens a standalone Chrome Dev Tools instance. This is useful for debugging and inspecting JavaScript execution. ```typescript dev() ``` -------------------------------- ### Return to the Main Script on Escape (TypeScript) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md This example demonstrates how to use keyboard shortcuts within a Kit prompt. Specifically, it configures the 'escape' key to trigger a call to `mainScript()`, allowing the user to return to the primary script flow from a modal or sub-prompt. ```ts // Name: Return to the Main Script on Escape // Group: Prompt import "@johnlindquist/kit" await div({ html: md(`# Hello`), shortcuts: [ { key: "escape", onPress: async () => { await mainScript() }, }, ], }) ``` -------------------------------- ### Invoke Scripts from Other Apps Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Explains how to run Script Kit scripts from external applications like Keyboard Maestro, Better Touch Tool, or Raycast using the `kar` executable. It details how to pass arguments to scripts. ```bash ~/.kit/kar center-app ``` ```bash ~/.kit/kar center-app 50 ``` -------------------------------- ### Add Global Keyboard Shortcut Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates how to assign a global keyboard shortcut to a script using the `// Shortcut:` metadata. This allows users to trigger the script directly via a key combination. ```js // Shortcut: cmd shift j import "@johnlindquist/kit" say(`You pressed command shift j`) ``` ```js // Shortcut: opt i import "@johnlindquist/kit" say(`You pressed option i`) ``` -------------------------------- ### Global Helpers for File and Network Operations Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Showcases Script Kit's global helper functions that simplify common tasks without requiring explicit imports. This example fetches content from a URL and writes it to a local file. ```ts const url = "https://raw.githubusercontent.com/johnlindquist/kit-docs/refs/heads/main/API.md"; const response = await get(url); const content = response.data; const apiPath = home("Downloads", "API.md"); await writeFile(apiPath, content); ``` -------------------------------- ### View Log Files Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Provides shell commands to monitor log files generated by Kit scripts. `tail -f` is used to view the live output of specific script logs or the main Kit log file. ```sh tail -f ~/.kenv/logs/my-script.log ``` ```sh tail -f ~/.kit/logs/kit.log ``` -------------------------------- ### Scrape Content from Webpage Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Illustrates web scraping using `scrapeSelector` to extract specific data from a webpage based on CSS selectors. It can transform the scraped elements into structured data and handles Playwright installation. ```js // Name: Scrape John's pinned Github repositories import "@johnlindquist/kit" const items = await scrapeSelector( 'https://github.com/johnlindquist', // CSS Selector to target elements '.pinned-item-list-item-content > div > a', // [Optional] function to transform the elements, if omitted then `element.innerText` is returned (element) => ({ title: element.innerText, link: element.href, }), // [Optional] options { headless: false, timeout: 60000, } ); let filePath = home(`pinned-repos.md`) // `ensureReadFile` will create the file with the content // if it doesn't exist let content = await ensureReadFile(filePath, items.map(({title, link}) => `- [${title}](${link})`).join('\n')) ``` -------------------------------- ### Display Preview When Focusing Choice Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Shows how to enhance list selections by providing a `preview` function for each choice. This function generates HTML content (e.g., an image) that is displayed when a user hovers over or focuses on a specific choice. ```js // Name: Display a Preview When Focusing a Choice import "@johnlindquist/kit" let heights = [320, 480, 640] let choices = heights.map(h => { return { name: `Kitten height: ${h}`, preview: () => ``, value: h, } }) let height = await arg("Select a Kitten", choices) await div(md(`You selected ${height}`)) ``` -------------------------------- ### Import Script Kit SDK Source: https://github.com/johnlindquist/kit-docs/blob/main/API.md Demonstrates the basic import statement required to use Script Kit's global APIs in your scripts. It also shows how to import other npm packages, which Script Kit will prompt you to install if needed. ```ts import "@johnlindquist/kit" import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai' ``` -------------------------------- ### Get Active App on Mac (Kit) Source: https://github.com/johnlindquist/kit-docs/blob/main/TIPS.md A macOS-specific snippet that retrieves information about the currently active application using Kit's `getActiveAppInfo`. It includes an example of conditionally executing an action (simulating a keyboard shortcut) if the active app is Google Chrome. ```typescript // MAC ONLY! import "@johnlindquist/kit" // Always hide immmediately if you're not going to show a prompt await hide() // Note: This uses "https://www.npmjs.com/package/@johnlindquist/mac-frontmost" inside Kit.app, // but you can import that package directly (or another similar package) if you prefer let info = await getActiveAppInfo() if (info.bundleIdentifier === "com.google.Chrome") { await keyboard.pressKey(Key.LeftSuper, Key.T) await keyboard.releaseKey(Key.LeftSuper, Key.T) } ``` -------------------------------- ### Tmp Path Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Demonstrates the `tmpPath` utility for creating paths within the system's temporary directory, specifically linked to the kit environment. It shows writing content to a temporary file and then reading it back. ```ts const tmpTestTxtPath = tmpPath("test.txt"); const content = await ensureReadFile(tmpTestTxtPath, "Hello World"); await editor( JSON.stringify( { tmpTestTxtPath, content, }, null, 2 ) ); ``` -------------------------------- ### Submit from Live Data with setInterval Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Demonstrates how to handle asynchronous operations like `setInterval` when submitting data from UI elements. It uses `Promise.then` to avoid blocking the script and `clearInterval` to manage the interval's lifecycle. ```javascript let intervalId = 0 div(md(`Click a value`)).then(async value => { clearInterval(intervalId) await div(md(value)) }) intervalId = setInterval(() => { let value = Math.random() setPanel( md(` [${value}](submit:${value}) `) ) }, 1000) ``` -------------------------------- ### Watch File: Speak File Content Source: https://github.com/johnlindquist/kit-docs/blob/main/GUIDE.md Monitors a specific file (`~/speak.txt`) for changes and reads its content to be spoken aloud using the `say` command. It includes basic error handling and a length check to prevent overly long spoken outputs. ```javascript // Name: Speak File // Watch: ~/speak.txt import "@johnlindquist/kit" let speakPath = home("speak.txt") try { let content = await readFile(speakPath, "utf-8") if (content.length < 60) { // We don't want `say` to run too long 😅 say(content) } } catch (error) { log(error) } ``` -------------------------------- ### get Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md An alias for making HTTP GET requests, typically using the axios library. It simplifies fetching data from URLs. ```APIDOC get(url: string, config?: AxiosRequestConfig): Promise Performs an HTTP GET request. Parameters: url: The URL to fetch. config: Optional Axios request configuration. Returns: A Promise resolving to the Axios response object. Example: const result = await get("https://jsonplaceholder.typicode.com/todos/1"); await editor(JSON.stringify(result.data)); ``` -------------------------------- ### Prompting with `arg` and Async Choices Array Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md This example demonstrates using `arg` to prompt the user with a list of choices fetched asynchronously. The function returns an array of strings, which `arg` then displays as selectable options. ```javascript let name = await arg("Select a name", async () => { let response = await get("https://swapi.dev/api/people/"); return response?.data?.results.map((p) => p.name); }) ``` -------------------------------- ### Exit Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Illustrates how to use the `exit` function to terminate the script execution. This example includes a `setTimeout` to ensure the script exits after a delay, even if other asynchronous operations are pending. ```ts // Prevent the script from running for more than 1 second setTimeout(() => { exit(); }, 1000); await arg("I will exit in 1 second"); ``` -------------------------------- ### Build Static Website Source: https://github.com/johnlindquist/kit-docs/blob/main/host/README.md Generates static website content into the `build` directory. This output can be served using any static content hosting service. ```shell $ yarn build ``` -------------------------------- ### Install npm package (Deprecated) Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Installs an npm package. This function is deprecated and users are advised to use standard `import` statements instead. Tested on macOS, may require additional permissions or configurations. ```ts await npm("lodash") ``` -------------------------------- ### Open Script Kit Tutorials Source: https://github.com/johnlindquist/kit-docs/blob/main/KIT.md Opens the official Script Kit tutorials website. These tutorials are designed to enhance scripting skills with Script Kit, AI, and more. ```javascript // Description: Watch and read official tutorials // Value: cli/tutorials.js // Enter: Open scriptkit.com // Example usage (conceptual, as this refers to an external action): // await run("cli/tutorials.js"); ``` -------------------------------- ### Metadata Object Example Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md An example demonstrating how to define script metadata using a JavaScript object. This object can include properties like name, description, author, and more, influencing how the script appears and behaves in the Script Kit UI. ```javascript metadata = { name: "Metadata Example", description: "This is an example of how to use metadata in a script", author: "John Lindquist", }; ``` -------------------------------- ### Top-Level Await Example: File Processing Source: https://github.com/johnlindquist/kit-docs/blob/main/API-GENERATED.md Script Kit scripts support top-level await, allowing asynchronous operations to be written sequentially. This example demonstrates fetching multiple markdown files using `globby`, reading their content, concatenating it, and opening it in an editor. ```javascript const downloadMarkdownPattern = home("Downloads", "*.md"); const files = await globby(downloadMarkdownPattern); let totalContent = ""; for await (const file of files) { const content = await readFile(file, "utf8"); totalContent += content; } await editor(totalContent); ```