Skip to main content

API

Intro

Welcome to Script Kit! 👋

Script Kit provides an opinionated set of global APIs meant to streamline the process of writing scripts. Many of them (such as prompts) are meant to interact with the app, but there are also many common APIs for working with files, etc, that are simply built-in node or third-party libraries exposed as globals.

You do not need to use any of these APIs. You are free to write your scripts and add whatever npm packages you like.

If you have questions, please reach out on our Script Kit GitHub Discussions

Happy Scripting! ❤️ - John Lindquist

Play with Examples in the App

With Script Kit open, type docs and hit enter.

With any example open, press cmd+p to generate a script where you can experiment with examples contained in that section.

Prompts

arg

  • Accept text input from the user.
  • Optionally provide a list of choices filtered by the text input.
  • Optionally provide a list of actions to trigger when the user presses a shortcut.
  1. The first argument is a string or a prompt configuration object.
  2. The second argument is a list of choices, a string to render, or a function that returns choices or a string to render.

arg example

let value = await arg()

arg basic string input

let name = await arg("Enter your name")

arg with async choices object

let person = await arg("Select a person", async () => {
let response = await get("https://swapi.dev/api/people/");
// return an array of objects with "name", "value", and "description" properties
return response?.data?.results.map((person) => {
return {
name: person.name,
description: person.url,
value: person
}
});
})

arg with async choices

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);
})

arg with choices array

let name = await arg("Select a name", [
"John",
"Mindy",
"Joy",
])

arg with generated choices

let char = await arg("Type then pick a char", (input) => { 
// return an array of strings
return input.split("")
})

arg with shortcuts

let url = "https://swapi.dev/api/people"
let name = await arg({
placeholder: "Select a name",
shortcuts: [
{
name: "Explore API",
key: "cmd+e",
onPress: async () => {
open(url)
},
bar: "right"
}
]
}, async () => {
let response = await get(url);
return response?.data?.results.map((p) => p.name);
})

micro

Same API as arg, but with a tiny, adorable UI.

micro example

let name = await micro("Enter your name")

env

Load an env var if it exists, prompt to set the env var if not:

You can also prompt the user to set the env var using a prompt by nesting it in an async function:

env example

// Write write "MY_ENV_VAR" to ~/.kenv/.env
let MY_ENV_VAR = await env("MY_ENV_VAR")

env example with prompt

// Prompt the user to select from a path
let OUTPUT_DIR = await env("OUTPUT_DIR", async () => {
return await path({
hint: `Select the output directory`,
})
})

editor

The editor function opens a text editor with the given text. The editor is a full-featured "Monaco" editor with syntax highlighting, find/replace, and more. The editor is a great way to edit or update text to write a file. The default language is markdown.

editor example

let content = await editor()

editor load remote text content

let response = await get(`https://raw.githubusercontent.com/johnlindquist/kit/main/API.md`)

let content = await editor(response.data)

editor with initial content

let content = await editor("Hello world!")

div

div displays HTML. Pass a string of HTML to div to render it. div is commonly used in conjunction with md to render markdown.

  1. Just like arg, the first argument is a string or a prompt configuration object.
  2. Optional:The second argument is a string of tailwind class to apply to the container, e.g., bg-white p-4.

div example

await div(`Hello world!`)

div with markdown

await div(md(`
# example!

### Thanks for coming to my demo
* This is a list
* This is another item
* This is the last item

`))
let name = await div(md(`# Pick a Name
* [John](submit:John)
* [Mindy](submit:Mindy)
* [Joy](submit:Joy)
`))

await div(md(`# You selected ${name}`))

div with tailwind classes

await div(`Hello world!`, `bg-white text-black text-4xl p-4`)

term

The term function opens a terminal window. The terminal is a full-featured terminal, but only intended for running commands and CLI tools that require user input. term is not suitable for long-running processes (try exec instead).

  1. Optional: the first argument is a command to run with the terminal

term example

await term(`cd ~/.kenv/scripts && ls`)

term with command

await term(`cd ~/.kenv/scripts && ls`)

template

The template prompt will present the editor populated by your template. You can then tab through each variable in your template and edit it.

  1. The first argument is a string template. Add variables using $1, $2, etc. You can also use

template example

let text = await template(`Hello $1!`)

template standard usage

let text = await template(`
Dear \${1:name},

Please meet me at \${2:address}

Sincerely, John`)

hotkey

The hotkey prompt allows you to press modifier keys, then submits once you've pressed a non-monodifier key. For example, press command then e to submit key info about the command and e keys:

{
"key": "e",
"command": true,
"shift": false,
"option": false,
"control": false,
"fn": false,
"hyper": false,
"os": false,
"super": false,
"win": false,
"shortcut": "command e",
"keyCode": "KeyE"
}

This can be useful when you want to use a palette of commands and trigger each of them by switching on a hotkey.

  1. Optional: The first argument is a string to display in the prompt.

hotkey example

let keyInfo = await hotkey()
await editor(JSON.stringify(keyInfo, null, 2))

drop

Use await drop() to prompt the user to drop a file or folder.

drop example

// Dropping text or an image from the browser returns a string
let fileInfos = await drop()

let filePaths = fileInfos.map(f => f.path).join(",")

await div(md(filePaths))

fields

The fields prompt allows you to rapidly create a form with fields.

  1. An array of labels or objects with label and field properties.

fields example

let [first, last] = await fields(["First name", "Last name"])

fields edit the keys and values of an object

let data = {
name: "John",
age: 42,
location: "USA",
};

let result = await fields(
Object.entries(data).map(([key, value]) => ({
name: key,
label: key,
value: String(value),
}))
);

let newData = Object.entries(data).map(([key], i) => ({
[key]: result[i],
}));

inspect(newData);

fields with field properties

let [name, age] = await fields([
{
name: "name",
label: "Name",
type: "text",
placeholder: "John"
},
{
name: "age",
label: "Age",
type: "number",
placeholder: "40"
}
])

form

Use an HTML form which returns an Object based on the names of the form fields.

form example

let result = await form(`
<div class="p-4">
<input type="text" name="textInput" placeholder="Text Input" />
<input type="password" name="passwordInput" placeholder="Password" />
<input type="email" name="emailInput" placeholder="Email" />
<input type="number" name="numberInput" placeholder="Number" />
<input type="date" name="dateInput" placeholder="Date" />
<input type="time" name="timeInput" placeholder="Time" />
<input type="datetime-local" name="dateTimeInput" placeholder="Date and Time" />
<input type="month" name="monthInput" placeholder="Month" />
<input type="week" name="weekInput" placeholder="Week" />
<input type="url" name="urlInput" placeholder="URL" />
<input type="search" name="searchInput" placeholder="Search" />
<input type="tel" name="telInput" placeholder="Telephone" />
<input type="color" name="colorInput" placeholder="Color" />
<textarea name="textareaInput" placeholder="Textarea"></textarea>
</div>
`)

inspect(result)

chat

A chat prompt. Use chat.addMessage() to insert messages into the chat.

Note: Manually invoke submit inside of a shortcut/action/etc to end the chat.

Also see the included "chatgpt" example for a much more advanced scenario.

chat example

await chat({
onInit: async () => {
chat.addMessage({
// Note: text and position are implemented, there are other properties that are a WIP
text: "You like Script Kit",
position: "left",
})

await wait(1000)

chat.addMessage({
text: "Yeah! It's awesome!",
position: "right",
})

await wait(1000)

chat.addMessage({
text: "I know, right?!?",
position: "left",
})

await wait(1000)

chat.addMessage({
text: `<img src="https://media0.giphy.com/media/yeE6B8nEKcTMWWvBzD/giphy.gif?cid=0b9ef2f49arnbs4aajuycirjsclpbtimvib6a76g7afizgr5&ep=v1_gifs_search&rid=giphy.gif" width="200px" />`,
position: "right",
})
},
})

selectFile

Prompt the user to select a file using the Finder dialog:

selectFile example

let filePath = await selectFile()

selectFolder

Prompt the user to select a folder using the Finder dialog:

selectFolder example

let folderPath = await selectFolder()

path

The path prompt allows you to select a file or folder from the file system. You navigate with tab/shift+tab (or right/left arrows) and enter to select.

  1. Optional: The first argument is the initial directory to open with. Defaults to the home directory.

path example

let selectedFile = await path()

path example startpath

const projectPath = await path({
startPath: home("dev"),
hint: "Select a project from your dev folder",
});

await editor(projectPath);

select

select lets you choose from a list of options.

  1. The first argument is a array or a prompt configuration object.
  2. The second argument is a list of choices, a array to render, or a function that returns choices or a string to render.

select example

let multipleChoice = await select(
"Select one or more developer",
["John", "Nghia", "Mindy", "Joy"]
)

select a choice with a single keystroke

let choice = await arg({
placeholder: "Choose a color",
choices: [
{ name: "[R]ed", value: "red" },
{ name: "[G]reen", value: "green" },
{ name: "[B]lue", value: "blue" },
],
})

await div(md(`You chose ${choice}`))

select array object

const people = [
{
name: "John",
description: "Full-stack Dev",
value: "John",
},
{
name: "Nghia",
description: "Full-stackoverflow dev",
value: "Nghia",
},
{
name: "Mindy",
description: "Business Analyst",
value: "Mindy",
},
{
name: "Joy",
description: "Leader",
value: "Joy",
},
]
let multipleChoice = await select(
"Select one or more developer",
people
)

select async choices array object

let name = await select(
"GET: NAME (please wait)",
async () => {
let response = await get(
"https://swapi.dev/api/people/"
)
return response?.data?.results.map(person => {
return {
name: person.name,
description: `height: ${person.height}, mass: ${person.mass}`,
value: person,
preview: () => JSON.stringify(person),
}
})
}
)

select basic array input

let multipleChoice = await select(
"Select one or more developer",
["John", "Nghia", "Mindy", "Joy"]
)

select generated input choices

let word = await select("Type then pick a words", input => {
return input.trim().split(new RegExp("[.,;/-_\n]", "g"))
})

inspect

inspect takes an object and writes out a text file you can use to read/copy/paste the values from:

Note: It will automatically convert objects to JSON to display them in the file

inspect example

let response = await get("https://swapi.dev/api/people/1/")
await inspect(response.data)

dev

dev Opens a standalone instance of Chrome Dev Tools so you can play with JavaScript in the console. Passing in an object will set the variable x to your object in the console making it easy to inspect.

  1. Optional: the first argument is an object to set to the variable x to in the console.

dev example

dev()

dev with object

dev({
name: "John",
age: 40
})

find

A file search prompt

find example

let filePath = await find("Search in the Downloads directory", {
onlyin: home("Downloads"),
})

await revealFile(filePath)

webcam

Prompt for webcam access. Press enter to capture an image buffer:

webcam example

let buffer = await webcam()
let imagePath = tmpPath("image.jpg")
await writeFile(imagePath, buffer)
await revealFile(imagePath)

Choices

formatChoices

Formats an array of choices.

  • If a choice is not an object, it is converted to a basic choice object.
  • If a choice has a nested choices array (i.e. represents a group), then:
    1. The group header is formatted (its group property is preserved if already set, or defaulted to its name).
    2. Its sub-choices are formatted in their original order.
    3. After processing the sub‑choices, any items with an index property are re‑inserted at the appropriate positions.
  • For top‑level non-group items, if every item is non‑group, then we re‑insert the indexed items in the final array.

Parameters:

  • choices: An array of choices or simple values
  • className: An optional default className

Returns the formatted array of choices.

Advanced

onTab

onTab allows you to build a menu where prompts are organized under a tab. Press Tab/Shift+Tab to navigate between prompts.

onTab example

onTab("People", async (event) => {
await arg("Select a person", ["John", "Mindy", "Ben"]);
});

onTab("Animals", async (event) => {
await arg("Select an animal", ["Dog", "Cat", "Bird"]);
});

openActions

Manually open the actions menu

Alerts

beep

Beep the system speaker:

beep example

await beep()

say

Say something using the built-in text-to-speech:

say example

await say("Done!")

setStatus

Set the system menu bar icon and message. Each status message will be appended to a list. Clicking on the menu will display the list of messages. The status and messages will be dismissed once the tray closes, so use log if you want to persist messages.

setStatus example

await setStatus({
message: "Working on it...",
status: "busy",
})

Set the system menu to a custom message/emoji with a list of scripts to run.

// Set the menu to a custom message/emoji with a list of scripts to run
await menu(`👍`, ["my-script", "another-script"])
// Reset the menu to the default icon and scripts by passing an empty string
await menu(``)

notify

Send a system notification

Note: osx notifications require permissions for "Terminal Notifier" in the system preferences. Due to the complicated nature of configuring notifications, please use a search engine to find the latest instructions for your osx version. In the Script Kit menu bar icon: "Permissions -> Request Notification Permissions" might help.

notify example

await notify("Attention!")

Widget

widget

A widget creates a new window using HTML. The HTML can be styled via Tailwind CSS class names. Templating and interactivity can be added via petite-vue.

  1. The first argument is a string of HTML to render in the window.
  2. Optional: the second argument is "Browser Window Options"

widget example

await widget(`<h1 class="p-4 text-4xl">Hello World!</h1>`)

widget clock

let clock = await widget(`<h1 class="text-7xl p-5 whitespace-nowrap">{{date}}</h1>`, {
transparent: true,
draggable: true,
hasShadow: false,
alwaysOnTop: true,
})

setInterval(()=> {
clock.setState({
date: new Date().toLocaleTimeString()
})
}, 1000)

widget events

let text = ""
let count = 0

let w = await widget(`
<div class="p-5">
<h1>Widget Events</h1>
<input autofocus type="text" class="border dark:bg-black"/>
<button id="myButton" class="border px-2 py-1">+</button>
<span>{{count}}</span>
</div>
`)

w.onClick((event) => {
if (event.targetId === "myButton") {
w.setState({count: count++})
}
})

w.onClose(async () => {
await widget(`
<div class="p-5">
<h1>You closed the other widget</h1>
<p>${text}</p>
</div>
`)
})

w.onInput((event) => {
text = event.value
})

w.onMoved(({ x, y}) => {
// e.g., save position
})

w.onResized(({ width, height }) => {
// e.g., save size
})

Commands

exec

exec uses allows you to run shell commands within your script:

Note: Execa is an alias for execaCommand from the execa npm package with "shell" and "all" true by default.

exec example

let result = await exec(`ls -la`, {
cwd: home(), // where to run the command
shell: "/bin/zsh", // if you're expecting to use specific shell features/configs
all: true, // pipe both stdout and stderr to "all"
})

inspect(result.all)

exec with prompt info

// It's extremely common to show the user what's happening while your command is running. This is often done by using `div` with `onInit` + `sumbit`:
let result = await div({
html: md(`# Loading your home directory`),
onInit: async () => {
let result = await exec(`sleep 2 && ls -la`, {
cwd: home(), // where to run the command
shell: "/bin/zsh", // use if you're expecting the command to load in your .zshrc
all: true, // pipe both stdout and stderr to "all"
})

submit(result.all)
},
})

Pro APIs

term

Opens a built-in Terminal window.

  • Can run interactive commands
  • Supports custom working directory and shell

term example

await term(`cd ~/.kenv/scripts && ls`)

term with command

await term(`cd ~/.kenv/scripts && ls`)

showLogWindow

Opens a logs window to display script output.

  • Displays output from all scripts run in the current session

showLogWindow example

await showLogWindow()

Platform APIs

scatterWindows

Evenly spaces out all open windows across the screen in a neat grid.

  • Only tested on macOS.
  • May require accessibility permissions if it's moving windows across multiple monitors.

scatterWindows example

await scatterWindows()

focusKitWindow

Brings the Script Kit window into focus.

  • Only tested on macOS.
  • May require accessibility permissions.

focusKitWindow example

await focusKitWindow()

attemptScriptFocus

Attempts to bring the Script Kit window into focus.

  • Only tested on macOS.
  • May require accessibility permissions.

attemptScriptFocus example

await attemptScriptFocus()

getKitWindows

Retrieves the Script Kit window objects.

  • Only tested on macOS.
  • May require accessibility permissions.

getKitWindows example

let windows = await getKitWindows()

focusWindow

Brings a specific window into focus.

  • Only tested on macOS.
  • May require accessibility permissions.

focusWindow example

await focusWindow(12345)

focusAppWindow

Brings a specific application window into focus.

  • Only tested on macOS.
  • May require accessibility permissions.

focusAppWindow example

await focusAppWindow("Google Chrome", "Script Kit - Google Chrome")

setWindowPosition

Sets the position of a specific window.

  • Only tested on macOS.
  • May require accessibility permissions.

setWindowPosition example

await setWindowPosition(12345, 100, 200)

setWindowPositionByIndex

Sets the position of a window based on its index.

  • Only tested on macOS.
  • May require accessibility permissions.

setWindowPositionByIndex example

await setWindowPositionByIndex(0, 100, 200)

scatterWindows

Evenly spaces out all open windows across the screen in a neat grid.

  • Only tested on macOS.
  • May require accessibility permissions if it's moving windows across multiple monitors.

scatterWindows example

await scatterWindows()

organizeWindows

Organizes windows in a specific way.

  • Only tested on macOS.
  • May require accessibility permissions.

organizeWindows example

await organizeWindows({
direction?: "horizontal" | "vertical",
padding?: number,
...
}): Promise<string>

tileWindow

Tiles a specific window.

  • Only tested on macOS.
  • May require accessibility permissions.

tileWindow example

await tileWindow(12345, {
direction: "horizontal",
padding: 10
})

scrapeSelector

Scrapes a webpage using a CSS selector.

scrapeSelector example

let text = await scrapeSelector("https://example.com", "#main-content")

scrapeAttribute

Scrapes a webpage and extracts an attribute value.

scrapeAttribute example

let src = await scrapeAttribute("https://example.com", "img", "src")

getScreenshotFromWebpage

Captures a screenshot of a webpage.

getScreenshotFromWebpage example

let buffer = await getScreenshotFromWebpage("https://example.com", {
width?: number,
height?: number,
...
}): Promise<Buffer>

getWebpageAsPdf

Converts a webpage to a PDF.

getWebpageAsPdf example

let buffer = await getWebpageAsPdf("https://example.com", {
width: 800,
height: 600
})

applescript

Executes an applescript string

  • Only tested on macOS
  • May require additional permissions or configurations

applescript example

let result = await applescript(`
tell application "Finder"
return name of every disk
end tell
`)

lock

Locks the screen.

  • Only tested on macOS
  • May require additional permissions or configurations

lock example

await lock()

logout

Logs out the current user.

  • Only tested on macOS
  • May require additional permissions or configurations

logout example

await logout()

shutdown

Shuts down the computer.

  • Only tested on macOS
  • May require additional permissions or configurations

shutdown example

await shutdown()

shutdown

Shuts down the computer.

  • Only tested on macOS
  • May require additional permissions or configurations

shutdown example

await shutdown()

sleep

Puts the computer to sleep.

  • Only tested on macOS
  • May require additional permissions or configurations

sleep example

await sleep()

sleep

Puts the computer to sleep.

  • Only tested on macOS
  • May require additional permissions or configurations

sleep example

await sleep()

sleep

Puts the computer to sleep.

  • Only tested on macOS
  • May require additional permissions or configurations

sleep example

await sleep()

fileSearch

Searches for files on the filesystem.

  • Only tested on macOS
  • May require additional permissions or configurations

fileSearch example

async function fileSearch(query: string, options?: {
onlyin?: string,
...
}): Promise<string[]>

copyPathAsImage

Copies a file path as an image to the clipboard.

  • Only tested on macOS
  • May require additional permissions or configurations

copyPathAsImage example

await copyPathAsImage("/path/to/file.txt")

copyPathAsImage

Copies a file path as an image to the clipboard.

  • Only tested on macOS
  • May require additional permissions or configurations

copyPathAsImage example

await copyPathAsImage("/path/to/file.txt")

copyPathAsImage

Copies a file path as an image to the clipboard.

  • Only tested on macOS
  • May require additional permissions or configurations

copyPathAsImage example

await copyPathAsImage("/path/to/file.txt")

getWindows

Retrieves information about open windows.

  • Only tested on macOS
  • May require additional permissions or configurations

getWindows example

let windows = await getWindows()

getWindowsBounds

Retrieves the bounds of open windows.

  • Only tested on macOS
  • May require additional permissions or configurations

getWindowsBounds example

let bounds = await getWindowsBounds()

Utils

edit

Open a file using the KIT_EDITOR env variable

(For example, set KIT_EDITOR=/usr/local/bin/cursor)

edit example

const zshrcPath = home(".zshrc");
await edit(zshrcPath);

browse

Open a URL in the default browser.

browse example

// When executing a command without UI, "hide" allows you to instantly hide the UI rather than waiting for the command to finish
await hide();
await browse("https://scriptkit.com");

formatDate

Formats a date

trash

Moves files or directories to the trash.

  • Only tested on macOS
  • May require additional permissions or configurations

trash example

await trash("/path/to/file.txt")

git

Git utility functions.

  • Only tested on macOS
  • May require additional permissions or configurations

git example

await git.clone("https://github.com/user/repo.git", "/path/to/repo")

degit

Clones a GitHub repository using degit.

  • Only tested on macOS
  • May require additional permissions or configurations

degit example

await degit("https://github.com/user/repo.git", "/path/to/repo")

openApp

Opens an application.

  • Only tested on macOS
  • May require additional permissions or configurations

openApp example

await openApp("Google Chrome")

createGist

Creates a GitHub gist.

  • Only tested on macOS
  • May require additional permissions or configurations

createGist example

let gistUrl = await createGist({
description: "My awesome gist",
public: true,
files: {
"hello.txt": {
content: "Hello, world!"
}
}
})

npm

Deprecated: Use standard import instead.

Installs an npm package.

  • Only tested on macOS
  • May require additional permissions or configurations

npm example

await npm("lodash")

attemptImport

Attempts to import a module.

attemptImport example

let module = await attemptImport("lodash")

silentAttemptImport

Attempts to import a module silently.

  • Only tested on macOS
  • May require additional permissions or configurations

silentAttemptImport example

let module = await silentAttemptImport("lodash")

store

Stores data in a persistent key-value store.

  • Only tested on macOS
  • May require additional permissions or configurations

store example

await store.set("myKey", "myValue")
let value = await store.get("myKey")

db

An extremely simple database that persists to a file.

db hello world

// Pre-populate the database with some items

const peopleDb = await db({
people: [
{
name: "John",
age: 30,
city: "San Francisco",
},
{
name: "Jane",
age: 25,
city: "New York",
},
] as Person[],
});

const person = await arg<Person>("Select a person", peopleDb.people);
// Do something with the person...

const [name, age, city] = await fields({
fields: ["name", "age", "city"],
enter: "Add",
description: "Add a new person to the database",
});

peopleDb.people.push({ name, age: parseInt(age), city });

await peopleDb.write();

await editor(JSON.stringify(peopleDb.people, null, 2));

type Person = {
name: string;
age: number;
city: string;
};

db populate

// 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}"`);

db store

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()
}

memoryMap

Manages a memory map of objects.

memoryMap example

memoryMap.set("myKey", { myObject: true })
let value = memoryMap.get("myKey")

show

Shows the main prompt.

show example

await show()

hide

Hides the main prompt.

hide example

await hide()

setPanel

Sets the panel content.

setPanel example

await setPanel("<h1>Hello, world!</h1>")

setPrompt

Sets the prompt content.

setPrompt example

await setPrompt("<h1>Enter your name:</h1>")

setPreview

Sets the preview content.

setPreview example

await setPreview("<h1>Preview</h1>")

setIgnoreBlur

Sets whether to ignore blur events.

setIgnoreBlur example

await setIgnoreBlur(true)

removeClipboardItem

Removes an item from the clipboard.

removeClipboardItem example

await removeClipboardItem(item)

clearClipboardHistory

Clears the clipboard history.

clearClipboardHistory example

await clearClipboardHistory()

setScoredChoices

Sets scored choices for a prompt.

setScoredChoices example

await setScoredChoices([
{ name: "John", score: 0.9 },
{ name: "Mindy", score: 0.8 },
{ name: "Joy", score: 0.7 }
])

setSelectedChoices

Sets selected choices for a prompt.

setSelectedChoices example

await setSelectedChoices(["John", "Mindy"])

groupChoices

Groups choices for a prompt.

groupChoices example

await groupChoices([
{ name: "Group 1", choices: ["John", "Mindy"] },
{ name: "Group 2", choices: ["Joy"] }
])

preload

Preloads data for a prompt.

preload example

await preload({
name: "John",
age: 40
})

select

Prompts the user to select one or more options.

select example

let multipleChoice = await select(
"Select one or more developer",
["John", "Nghia", "Mindy", "Joy"]
)

select a choice with a single keystroke

let choice = await arg({
placeholder: "Choose a color",
choices: [
{ name: "[R]ed", value: "red" },
{ name: "[G]reen", value: "green" },
{ name: "[B]lue", value: "blue" },
],
})

await div(md(`You chose ${choice}`))

select array object

const people = [
{
name: "John",
description: "Full-stack Dev",
value: "John",
},
{
name: "Nghia",
description: "Full-stackoverflow dev",
value: "Nghia",
},
{
name: "Mindy",
description: "Business Analyst",
value: "Mindy",
},
{
name: "Joy",
description: "Leader",
value: "Joy",
},
]
let multipleChoice = await select(
"Select one or more developer",
people
)

select async choices array object

let name = await select(
"GET: NAME (please wait)",
async () => {
let response = await get(
"https://swapi.dev/api/people/"
)
return response?.data?.results.map(person => {
return {
name: person.name,
description: `height: ${person.height}, mass: ${person.mass}`,
value: person,
preview: () => JSON.stringify(person),
}
})
}
)

select basic array input

let multipleChoice = await select(
"Select one or more developer",
["John", "Nghia", "Mindy", "Joy"]
)

select generated input choices

let word = await select("Type then pick a words", input => {
return input.trim().split(new RegExp("[.,;/-_\n]", "g"))
})

grid

Prompts the user to select one or more options in a grid layout.

grid example

let multipleChoice = await grid(
"Select one or more developer",
["John", "Nghia", "Mindy", "Joy"]
)

mini

Prompts the user for input in a compact format.

mini example

let name = await mini("Enter your name")

micro

Prompts the user for input in a tiny, adorable format.

micro example

let name = await micro("Enter your name")

getMediaDevices

Retrieves available media devices.

getMediaDevices example

let devices = await getMediaDevices()

getTypedText

Retrieves typed text from the user.

getTypedText example

let text = await getTypedText()

toast

Displays a small pop-up notification inside the Script Kit window.

toast example

await toast("Hello from Script Kit!", {
autoClose: 3000, // close after 3 seconds
pauseOnFocusLoss: false
})

metadata

Define additional information and capabilities for your script:

The metadata object can include:

  • author: Creator's name
  • name: Display name in Script Kit UI (defaults to filename)
  • description: Brief script summary
  • enter: Text shown on Enter button
  • alias: Alternative search term
  • image: Path to script icon
  • shortcut: Global keyboard shortcut
  • shortcode: Execute when typed + space in menu
  • trigger: Execute when typed in menu
  • expand: Text expansion trigger (replaces deprecated snippet)
  • keyword: Search keyword for menu
  • pass: Pass menu input as arg (true/string/RegExp)
  • group: Menu organization category
  • exclude: Hide from menu
  • watch: File/dir to watch for changes
  • log: Disable logging if false
  • background: Run as background process
  • timeout: Auto-terminate after seconds
  • system: Trigger on system events (sleep/wake/etc)
  • schedule: Cron expression for timing
  • access: REST API access level (public/key/private)
  • response: Allow REST API response
  • index: Order within group

metadata example

metadata = {
name: "Metadata Example",
description: "This is an example of how to use metadata in a script",
author: "John Lindquist",
};

SDK Utils

kitPath

Create a path relative to the kit directory.

Closing Thoughts

Alternate Importing

Also, you can import kit and access the APIs like so:

import kit from "@johnlindquist/kit"

await kit.arg("Enter your name")