• Stars
    star
    2,570
  • Rank 17,842 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Create Alfred workflows with ease

Alfy

Create Alfred workflows with ease

Highlights

  • Easy inputโ†”output.
  • Config and cache handling built-in.
  • Fetching remote files with optional caching.
  • Publish your workflow to npm.
  • Automatic update notifications.
  • Easily testable workflows.
  • Finds the node binary.
  • Support for top-level await.
  • Presents uncaught exceptions and unhandled Promise rejections to the user.
    No need to manually .catch() top-level promises.

Prerequisites

You need Node.js 14+ and Alfred 4 or later with the paid Powerpack upgrade.

Install

npm install alfy

Usage

IMPORTANT: Your script will be run as ESM.

  1. Create a new blank Alfred workflow.

  2. Add a Script Filter (right-click the canvas โ†’ Inputs โ†’ Script Filter), set Language to /bin/bash, and add the following script:

./node_modules/.bin/run-node index.js "$1"

We can't call node directly as GUI apps on macOS doesn't inherit the $PATH.

Tip: You can use generator-alfred to scaffold out an alfy based workflow. If so, you can skip the rest of the steps, go straight to the index.js and do your thing.

  1. Set the Keyword by which you want to invoke your workflow.

  2. Go to your new workflow directory (right-click on the workflow in the sidebar โ†’ Open in Finder).

  3. Initialize a repo with npm init.

  4. Add "type": "module" to package.json.

  5. Install Alfy with npm install alfy.

  6. In the workflow directory, create a index.js file, import alfy, and do your thing.

Example

Here we fetch some JSON from a placeholder API and present matching items to the user:

import alfy from 'alfy';

const data = await alfy.fetch('https://jsonplaceholder.typicode.com/posts');

const items = alfy
	.inputMatches(data, 'title')
	.map(element => ({
		title: element.title,
		subtitle: element.body,
		arg: element.id
	}));

alfy.output(items);

More

Some example usage in the wild: alfred-npms, alfred-emoj, alfred-ng.

Update notifications

Alfy uses alfred-notifier in the background to show a notification when an update for your workflow is available.

Caching

Alfy offers the possibility of caching data, either with the fetch or directly through the cache object.

An important thing to note is that the cached data gets invalidated automatically when you update your workflow. This offers the flexibility for developers to change the structure of the cached data between workflows without having to worry about invalid older data.

Publish to npm

By adding alfy-init as postinstall and alfy-cleanup as preuninstall script, you can publish your package to npm instead of to Packal. This way, your packages are only one simple npm install command away.

{
	"name": "alfred-unicorn",
	"version": "1.0.0",
	"description": "My awesome unicorn workflow",
	"author": {
		"name": "Sindre Sorhus",
		"email": "[email protected]",
		"url": "sindresorhus.com"
	},
	"scripts": {
		"postinstall": "alfy-init",
		"preuninstall": "alfy-cleanup"
	},
	"dependencies": {
		"alfy": "*"
	}
}

Tip: Prefix your workflow with alfred- to make them easy searchable through npm.

You can remove these properties from your info.plist file as they are being added automatically at install time.

After publishing your workflow to npm, your users can easily install or update the workflow.

npm install --global alfred-unicorn

Tip: instead of manually updating every workflow yourself, use the alfred-updater workflow to do that for you.

Testing

Workflows can easily be tested with alfy-test. Here is a small example.

import test from 'ava';
import alfyTest from 'alfy-test';

test('main', async t => {
	const alfy = alfyTest();

	const result = await alfy('workflow input');

	t.deepEqual(result, [
		{
			title: 'foo',
			subtitle: 'bar'
		}
	]);
});

Debugging

When developing your workflow it can be useful to be able to debug it when something is not working. This is when the workflow debugger comes in handy. You can find it in your workflow view in Alfred. Press the insect icon to open it. It will show you the plain text output of alfy.output() and anything you log with alfy.log():

import alfy from 'alfy';

const unicorn = getUnicorn();
alfy.log(unicorn);

Environment variables

Alfred lets users set environment variables for a workflow which can then be used by that workflow. This can be useful if you, for example, need the user to specify an API token for a service. You can access the workflow environment variables from process.env. For example process.env.apiToken.

API

alfy

input

Type: string

Input from Alfred. What the user wrote in the input box.

output(list, options?)

Return output to Alfred.

list

Type: object[]

List of object with any of the supported properties.

Example:

import alfy from 'alfy';

alfy.output([
	{
		title: 'Unicorn'
	},
	{
		title: 'Rainbow'
	}
]);
options

Type: object

rerunInterval

Type: number (seconds)
Values: 0.1...5.0

A script can be set to re-run automatically after some interval. The script will only be re-run if the script filter is still active and the user hasn't changed the state of the filter by typing and triggering a re-run. More info.

For example, it could be used to update the progress of a particular task:

import alfy from 'alfy';

alfy.output(
	[
		{
			title: 'Downloading Unicornsโ€ฆ',
			subtitle: `${progress}%`,
		}
	],
	{
		// Re-run and update progress every 3 seconds.
		rerunInterval: 3
	}
);

log(value)

Log value to the Alfred workflow debugger.

matches(input, list, item?)

Returns an string[] of items in list that case-insensitively contains input.

import alfy from 'alfy';

alfy.matches('Corn', ['foo', 'unicorn']);
//=> ['unicorn']
input

Type: string

Text to match against the list items.

list

Type: string[]

List to be matched against.

item

Type: string | Function

By default, it will match against the list items.

Specify a string to match against an object property:

import alfy from 'alfy';

const list = [
	{
		title: 'foo'
	},
	{
		title: 'unicorn'
	}
];

alfy.matches('Unicorn', list, 'title');
//=> [{title: 'unicorn'}]

Or nested property:

import alfy from 'alfy';

const list = [
	{
		name: {
			first: 'John',
			last: 'Doe'
		}
	},
	{
		name: {
			first: 'Sindre',
			last: 'Sorhus'
		}
	}
];

alfy.matches('sindre', list, 'name.first');
//=> [{name: {first: 'Sindre', last: 'Sorhus'}}]

Specify a function to handle the matching yourself. The function receives the list item and input, both lowercased, as arguments, and is expected to return a boolean of whether it matches:

import alfy from 'alfy';

const list = ['foo', 'unicorn'];

// Here we do an exact match.
// `Foo` matches the item since it's lowercased for you.
alfy.matches('Foo', list, (item, input) => item === input);
//=> ['foo']

inputMatches(list, item?)

Same as matches(), but with alfy.input as input.

error(error)

Display an error or error message in Alfred.

Note: You don't need to .catch() top-level promises. Alfy handles that for you.

error

Type: Error | string

Error or error message to be displayed.

fetch(url, options?)

Returns a Promise that returns the body of the response.

url

Type: string

URL to fetch.

options

Type: object

Any of the got options and the below options.

json

Type: boolean
Default: true

Parse response body with JSON.parse and set accept header to application/json.

maxAge

Type: number

Number of milliseconds this request should be cached.

resolveBodyOnly

Type: boolean
Default: true

Whether to resolve with only body or a full response.

import alfy from 'alfy';

await alfy.fetch('https://api.foo.com');
//=> {foo: 'bar'}

await alfy.fetch('https://api.foo.com', {
	resolveBodyOnly: false 
});
/*
{
	body: {
		foo: 'bar'
	},
	headers: {
		'content-type': 'application/json'
	}
}
*/
transform

Type: Function

Transform the response body before it gets cached.

import alfy from 'alfy';

await alfy.fetch('https://api.foo.com', {
	transform: body => {
		body.foo = 'bar';
		return body;
	}
})

Transform the response.

import alfy from 'alfy';

await alfy.fetch('https://api.foo.com', {
	resolveBodyOnly: false,
	transform: response => {
		response.body.foo = 'bar';
		return response;
	}
})

You can also return a Promise.

import alfy from 'alfy';
import xml2js from 'xml2js';
import pify from 'pify';

const parseString = pify(xml2js.parseString);

await alfy.fetch('https://api.foo.com', {
	transform: body => parseString(body)
})

config

Type: object

Persist config data.

Exports a conf instance with the correct config path set.

Example:

import alfy from 'alfy';

alfy.config.set('unicorn', '๐Ÿฆ„');

alfy.config.get('unicorn');
//=> '๐Ÿฆ„'

userConfig

Type: Map

Exports a Map with the user workflow configuration. A workflow configuration allows your users to provide configuration information for the workflow. For instance, if you are developing a GitHub workflow, you could let your users provide their own API tokens.

See alfred-config for more details.

Example:

import alfy from 'alfy';

alfy.userConfig.get('apiKey');
//=> '16811cad1b8547478b3e53eae2e0f083'

cache

Type: object

Persist cache data.

Exports a modified conf instance with the correct cache path set.

Example:

import alfy from 'alfy';

alfy.cache.set('unicorn', '๐Ÿฆ„');

alfy.cache.get('unicorn');
//=> '๐Ÿฆ„'
maxAge

The set method of this instance accepts an optional third argument where you can provide a maxAge option. maxAge is the number of milliseconds the value is valid in the cache.

Example:

import alfy from 'alfy';
import delay from 'delay';

alfy.cache.set('foo', 'bar', {maxAge: 5000});

alfy.cache.get('foo');
//=> 'bar'

// Wait 5 seconds
await delay(5000);

alfy.cache.get('foo');
//=> undefined

debug

Type: boolean

Whether the user currently has the workflow debugger open.

icon

Type: object
Keys: 'info' | 'warning' | 'error' | 'alert' | 'like' | 'delete'

Get various default system icons.

The most useful ones are included as keys. The rest you can get with icon.get(). Go to /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources in Finder to see them all.

Example:

import alfy from 'alfy';

console.log(alfy.icon.error);
//=> '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns'

console.log(alfy.icon.get('Clock'));
//=> '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/Clock.icns'

meta

Type: object

Example:

{
	name: 'Emoj',
	version: '0.2.5',
	uid: 'user.workflow.B0AC54EC-601C-479A-9428-01F9FD732959',
	bundleId: 'com.sindresorhus.emoj'
}

alfred

Type: object

Alfred metadata.

version

Example: '3.0.2'

Find out which version the user is currently running. This may be useful if your workflow depends on a particular Alfred version's features.

theme

Example: 'alfred.theme.yosemite'

Current theme used.

themeBackground

Example: 'rgba(255,255,255,0.98)'

If you're creating icons on the fly, this allows you to find out the color of the theme background.

themeSelectionBackground

Example: 'rgba(255,255,255,0.98)'

The color of the selected result.

themeSubtext

Example: 3

Find out what subtext mode the user has selected in the Appearance preferences.

Usability note: This is available so developers can tweak the result text based on the user's selected mode, but a workflow's result text should not be bloated unnecessarily based on this, as the main reason users generally hide the subtext is to make Alfred look cleaner.

data

Example: '/Users/sindresorhus/Library/Application Support/Alfred/Workflow Data/com.sindresorhus.npms'

Recommended location for non-volatile data. Just use alfy.data which uses this path.

cache

Example: '/Users/sindresorhus/Library/Caches/com.runningwithcrayons.Alfred/Workflow Data/com.sindresorhus.npms'

Recommended location for volatile data. Just use alfy.cache which uses this path.

preferences

Example: '/Users/sindresorhus/Dropbox/Alfred/Alfred.alfredpreferences'

This is the location of the Alfred.alfredpreferences. If a user has synced their settings, this will allow you to find out where their settings are regardless of sync state.

preferencesLocalHash

Example: 'adbd4f66bc3ae8493832af61a41ee609b20d8705'

Non-synced local preferences are stored within Alfred.alfredpreferences under โ€ฆ/preferences/local/${preferencesLocalHash}/.

Users

Alfred workflows using Alfy

Related

Maintainers

More Repositories

1

awesome

๐Ÿ˜Ž Awesome lists about all kinds of interesting topics
270,042
star
2

awesome-nodejs

โšก Delightful Node.js packages and resources
52,854
star
3

awesome-electron

Useful resources for creating apps with Electron
25,634
star
4

quick-look-plugins

List of useful Quick Look plugins for developers
17,497
star
5

got

๐ŸŒ Human-friendly and powerful HTTP request library for Node.js
TypeScript
14,218
star
6

type-fest

A collection of essential TypeScript types
TypeScript
14,015
star
7

ky

๐ŸŒณ Tiny & elegant JavaScript HTTP client based on the Fetch API
TypeScript
13,762
star
8

pure

Pretty, minimal and fast ZSH prompt
Shell
12,391
star
9

pageres

Capture website screenshots
TypeScript
9,573
star
10

ora

Elegant terminal spinner
JavaScript
8,591
star
11

np

A better `npm publish`
JavaScript
7,529
star
12

github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
CSS
7,421
star
13

caprine

Elegant Facebook Messenger desktop app
TypeScript
7,014
star
14

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
HTML
6,891
star
15

Gifski

๐ŸŒˆ Convert videos to high-quality GIFs on your Mac
Swift
6,807
star
16

fkill-cli

Fabulously kill processes. Cross-platform.
JavaScript
6,782
star
17

query-string

Parse and stringify URL query strings
JavaScript
6,453
star
18

execa

Process execution for humans
JavaScript
6,019
star
19

modern-normalize

๐Ÿ’ Normalize browsers' default style
TypeScript
5,038
star
20

css-in-readme-like-wat

Style your readme using CSS with this simple trick
5,013
star
21

awesome-npm

Awesome npm resources and tips
4,315
star
22

promise-fun

Promise packages, patterns, chat, and tutorials
4,277
star
23

awesome-scifi

Sci-Fi worth consuming
4,268
star
24

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
JavaScript
4,165
star
25

create-dmg

Create a good-looking DMG for your macOS app in seconds
JavaScript
3,950
star
26

speed-test

Test your internet connection speed and ping using speedtest.net from the CLI
JavaScript
3,882
star
27

eslint-plugin-unicorn

More than 100 powerful ESLint rules
JavaScript
3,877
star
28

ow

Function argument validation for humans
TypeScript
3,799
star
29

file-type

Detect the file type of a file, stream, or data
JavaScript
3,632
star
30

meow

๐Ÿˆ CLI app helper
JavaScript
3,305
star
31

p-queue

Promise queue with concurrency control
TypeScript
3,202
star
32

open

Open stuff like URLs, files, executables. Cross-platform.
JavaScript
2,976
star
33

Plash

๐Ÿ’ฆ Make any website your Mac desktop wallpaper
Swift
2,735
star
34

trash

Move files and directories to the trash
JavaScript
2,512
star
35

fast-cli

Test your download and upload speed using fast.com
JavaScript
2,484
star
36

guides

A collection of succinct guides - Public Domain
2,424
star
37

globby

User-friendly glob matching
JavaScript
2,376
star
38

slugify

Slugify a string
JavaScript
2,357
star
39

emoj

Find relevant emoji from text on the command-line ๐Ÿ˜ฎ โœจ ๐Ÿ™Œ ๐Ÿด ๐Ÿ’ฅ ๐Ÿ™ˆ
JavaScript
2,311
star
40

cli-spinners

Spinners for use in the terminal
JavaScript
2,255
star
41

on-change

Watch an object or array for changes
JavaScript
1,966
star
42

devtools-detect

Detect if DevTools is open and its orientation
HTML
1,924
star
43

gulp-imagemin

Minify PNG, JPEG, GIF and SVG images
JavaScript
1,903
star
44

touch-bar-simulator

Use the Touch Bar on any Mac
Swift
1,900
star
45

notifier-for-github

Browser extension - Get notified about new GitHub notifications
JavaScript
1,828
star
46

editorconfig-sublime

Sublime Text plugin for EditorConfig - Helps developers maintain consistent coding styles between different editors
Python
1,757
star
47

emittery

Simple and modern async event emitter
JavaScript
1,721
star
48

is

Type check values
TypeScript
1,678
star
49

capture-website

Capture screenshots of websites
JavaScript
1,670
star
50

Defaults

๐Ÿ’พ Swifty and modern UserDefaults
Swift
1,661
star
51

electron-boilerplate

Boilerplate to kickstart creating an app with Electron
JavaScript
1,632
star
52

pageres-cli

Capture website screenshots
JavaScript
1,620
star
53

clipboardy

Access the system clipboard (copy/paste)
JavaScript
1,598
star
54

gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` โ†’ `unicorn-d41d8cd98f.css`
JavaScript
1,538
star
55

pify

Promisify a callback-style function
JavaScript
1,494
star
56

boxen

Create boxes in the terminal
JavaScript
1,467
star
57

Actions

โš™๏ธ Supercharge your shortcuts
Swift
1,437
star
58

multiline

Multiline strings in JavaScript
JavaScript
1,424
star
59

hyper-snazzy

Elegant Hyper theme with bright colors
JavaScript
1,412
star
60

amas

Awesome & Marvelous Amas
1,392
star
61

LaunchAtLogin

Add โ€œLaunch at Loginโ€ functionality to your macOS app in seconds
Swift
1,346
star
62

del

Delete files and directories
JavaScript
1,316
star
63

refined-twitter

Browser extension that simplifies the Twitter interface and adds useful features
JavaScript
1,313
star
64

KeyboardShortcuts

โŒจ๏ธ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
Swift
1,313
star
65

iterm2-snazzy

Elegant iTerm2 theme with bright colors
1,313
star
66

electron-context-menu

Context menu for your Electron app
JavaScript
1,297
star
67

p-limit

Run multiple promise-returning & async functions with limited concurrency
JavaScript
1,294
star
68

Settings

โš™ Add a settings window to your macOS app in minutes
Swift
1,282
star
69

trash-cli

Move files and folders to the trash
JavaScript
1,244
star
70

electron-util

Useful utilities for Electron apps and modules
JavaScript
1,188
star
71

is-online

Check if the internet connection is up
JavaScript
1,181
star
72

ponyfill

๐Ÿฆ„ Like polyfill but with pony pureness
1,136
star
73

conf

Simple config handling for your app or module
TypeScript
1,109
star
74

anatine

[DEPRECATED] ๐Ÿฆ Pristine Twitter app
JavaScript
1,097
star
75

electron-dl

Simplified file downloads for your Electron app
JavaScript
1,087
star
76

log-update

Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.
JavaScript
1,027
star
77

pretty-bytes

Convert bytes to a human readable string: 1337 โ†’ 1.34 kB
JavaScript
1,022
star
78

grunt-sass

Compile Sass to CSS
JavaScript
1,020
star
79

mem

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
TypeScript
1,019
star
80

DockProgress

Show progress in your app's Dock icon
Swift
1,003
star
81

wallpaper

Manage the desktop wallpaper
JavaScript
996
star
82

p-map

Map over promises concurrently
JavaScript
996
star
83

public-ip

Get your public IP address - very fast!
JavaScript
979
star
84

gulp-app

[DEPRECATED] Gulp as an app
JavaScript
961
star
85

grunt-shell

Run shell commands
JavaScript
952
star
86

load-grunt-tasks

Load multiple grunt tasks using globbing patterns
JavaScript
940
star
87

hasha

Hashing made simple. Get the hash of a buffer/string/stream/file.
JavaScript
934
star
88

pretty-ms

Convert milliseconds to a human readable string: `1337000000` โ†’ `15d 11h 23m 20s`
JavaScript
929
star
89

terminal-image

Display images in the terminal
JavaScript
923
star
90

object-assign

ES2015 Object.assign() ponyfill
JavaScript
922
star
91

copy-text-to-clipboard

Copy text to the clipboard in modern browsers (0.2 kB)
JavaScript
858
star
92

System-Color-Picker

๐ŸŽจ The macOS color picker as an app with more features
Swift
842
star
93

normalize-url

Normalize a URL
JavaScript
818
star
94

get-port

Get an available TCP port
JavaScript
817
star
95

atom-editorconfig

Helps developers maintain consistent coding styles between different editors
JavaScript
811
star
96

grunt-concurrent

Run grunt tasks concurrently
JavaScript
799
star
97

dot-prop

Get, set, or delete a property from a nested object using a dot path
JavaScript
777
star
98

p-progress

Create a promise that reports progress
TypeScript
751
star
99

gulp-changed

Only pass through changed files
JavaScript
747
star
100

generator-nm

Scaffold out a node module
JavaScript
742
star