`)
```
--------------------------------
### 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);
```