Writing a Patchwork Tool #
This is a practical reference for writing a tool (and, if needed, a matching datatype) for Patchwork. Everything here is grounded directly in the source of inkandswitch/patchwork-system (core/plugins, core/filesystem, packages/providers, packages/e2e/fixtures) — not the public docs, since there aren't much of those yet. (That repo used to be called inkandswitch/patchwork — GitHub redirects the old name. The sibling repo of real, in-the-wild tool examples, patchwork-experiments, was similarly once called patchwork-tools; you'll see the old name in some in-repo docs and env-var comments.)
The short version #
A tool is a plain function with this shape:
(handle: DocHandle<T>, element: ToolElement) => () => void
// ^ returns a cleanup function
You get an Automerge document handle and a real HTMLElement to mount into. What you put inside — vanilla DOM, React, Solid, whatever — is entirely up to you. Patchwork's tool contract is not opinionated about framework at all. There is no createReactTool() helper, no special React adapter for mounting — I checked, and there's no ReactDOM/createRoot call anywhere in the whole patchwork monorepo. React and Solid are both pulled in as first-class dependencies (for their official Automerge hook packages), but mounting them into a tool's element is just you calling the framework's own standard mount API inside that function. Vanilla JS is exactly as first-class as either.
1. The package shape #
A Patchwork package is a small npm-style package: a package.json plus one or more
JS files, exporting a plugins array. Nothing more is required.
// package.json
{
"name": "my-patchwork-tool",
"version": "1.0.0",
"main": "./index.js"
}
// index.js
export const plugins = [
/* one or more datatype / tool descriptors, see below */
];
That minimal shape is genuinely all Patchwork needs. But it's worth seeing what a real, actively-published tool's package.json looks like, since it reveals conventions the minimal example doesn't. Here's @chee/patchwork-sideboard (fetched live from its published package.json, referenced below):
{
"name": "@chee/patchwork-sideboard",
"private": true,
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"exports": {
".": {
"import": "./dist/index.js",
"patchwork": "./dist/index.js",
"types": "./dist/index.d.ts",
"source": "./src/index.tsx"
},
"./tools/sideboard": {
"import": "./dist/sideboard/sideboard.js",
"patchwork": "./dist/sideboard/sideboard.js",
"source": "./src/sideboard/sideboard.tsx"
},
"./styles.css": "./dist/index.css"
},
"scripts": {
"build": "node esbuild/build.ts",
"dev": "node esbuild/watch.ts",
"register": "pw-modules add \"$MODULE_SETTINGS_DOC_URL\" \"$(pushwork url)\""
}
}
Notes on what's actually going on here, beyond name/main:
exportscan be a full conditional map, not justmain. Patchwork resolvesexports/mainthe same way Node does, so subpath exports (./tools/sideboardabove) work for splitting a package with multiple tools/datatypes into separately-importable entry points — useful if you only want one tool's descriptor to trigger loading its implementation, rather than the whole package.- There's a
"patchwork"export condition alongside the standard"import"one. In this package they point at the same file, so it's not doing anything exotic today, but it means the loader is written to recognize a"patchwork"condition specifically (in case a package ever wants to ship a Patchwork-specific build distinct from its Node/browser one). - A subpath can point straight at a plain asset (
"./styles.css": "./dist/index.css") — not every export needs animport/typesobject. "private": trueand"version": "0.0.0"are normal here — these packages aren't meant for the public npm registry; they're published to Automerge instead (see below), and npm-registry semver just isn't the relevant versioning story.
It can live in two places:
- Hosted anywhere on the web with a
package.jsonreachable overhttps:(CORS must allow it — Patchwork fetchespackage.jsonand resolvesexports/mainitself, same as Node's resolution algorithm). - Inside your own Patchwork workspace, as a folder doc — package.json and the JS file(s) are just entries in an Automerge "directory" document. This is the "code as data" path: the package is itself synced, versioned, and — if you keep editing it — hot-reloaded live by the
ModuleWatcher, no rebuild step.
To install it: open the Packages panel in the Patchwork UI, paste the package's URL (automerge:... or https://...) into the search field, and click "Add to my package list." That's a real, built-in flow — not something you need to build yourself.
2. Writing a tool #
Description fields #
type ToolDescription = {
id: string; // unique within the "patchwork:tool" registry
type: "patchwork:tool";
name: string; // shown in menus
supportedDatatypes: "*" | string[]; // datatype id(s) this tool can open, or "*" for any
icon?: string; // icon-font name
tags?: string[];
unlisted?: boolean; // hide from pickers (still usable if explicitly set)
forTitleBar?: boolean; // render as a title-bar action instead of a full view
importUrl?: string; // set automatically by the loader, don't set by hand
};
Plus either a synchronous-looking loader:
{ load: () => Promise<ToolImplementation<T>> }
or a URL to dynamically import() at load time:
{ import: string }
Use load() when the implementation lives in the same module as the descriptor
(the common case — see examples below). Use import if you want the descriptor
listed in one place and the implementation code-split elsewhere.
The implementation itself #
type ToolElement = HTMLElement & {
repo: Repo; // the live Automerge Repo, in case you need it
hive?: AutomergeRepoKeyhive; // present if the site runs keyhive
};
type ToolRender<T = unknown> = (
handle: DocHandle<T>,
element: ToolElement
) => () => void; // teardown/cleanup
type ToolImplementation<T = unknown> = ToolRender<T>;
handle is a standard automerge-repo DocHandle<T> — handle.doc() for the current snapshot, handle.change(fn) to mutate, handle.on("change", cb) / handle.off("change", cb) to subscribe, handle.url for its automerge: address.
Vanilla JS example (real, working — this is the actual e2e test fixture) #
export const plugins = [
{
type: "patchwork:datatype",
id: "counter",
name: "Counter",
async load() {
return {
init(doc) {
doc.count = 0;
},
getTitle: () => "Counter",
};
},
},
{
type: "patchwork:tool",
id: "counter-viewer",
name: "Counter Viewer",
supportedDatatypes: ["counter"],
async load() {
return (handle, element) => {
const root = document.createElement("div");
const count = document.createElement("output");
const button = document.createElement("button");
button.textContent = "increment";
button.onclick = () => {
handle.change((doc) => {
doc.count = (doc.count ?? 0) + 1;
});
};
const render = () => {
count.textContent = String(handle.doc()?.count ?? 0);
};
handle.on("change", render);
render();
root.append(count, button);
element.append(root);
return () => handle.off("change", render); // cleanup
};
},
},
];
3. Writing a tool with React #
There's no special helper — you mount React yourself, the same way you would into any plain DOM node, and unmount it in the returned cleanup function. React 18's createRoot API is what Patchwork itself pins (react/react-dom 18.3.1 in its own workspace), so that's the safe target.
import { createRoot } from "react-dom/client";
import { useDocument } from "@automerge/automerge-repo-react-hooks";
function CounterView({ handle }) {
const [doc, changeDoc] = useDocument(handle.url);
return (
<div>
<output>{doc?.count ?? 0}</output>
<button onClick={() => changeDoc((d) => { d.count = (d.count ?? 0) + 1; })}>
increment
</button>
</div>
);
}
export const plugins = [
{
type: "patchwork:datatype",
id: "counter",
name: "Counter",
async load() {
return { init: (doc) => { doc.count = 0; }, getTitle: () => "Counter" };
},
},
{
type: "patchwork:tool",
id: "counter-viewer-react",
name: "Counter Viewer (React)",
supportedDatatypes: ["counter"],
async load() {
return (handle, element) => {
const root = createRoot(element);
root.render(<CounterView handle={handle} />);
return () => root.unmount();
};
},
},
];
@automerge/automerge-repo-react-hooks is a real dependency Patchwork itself depends on (pinned to 2.6.0-subduction.46, their fork tag), so useDocument / useDocHandle are safe to build on rather than hand-rolling handle.on("change") subscriptions yourself.
A caveat on JSX/TSX specifically: I found no evidence of an in-browser JSX/TypeScript transpiler anywhere in this pipeline — the working example fixture is plain .js. That means:
- If you're hosting your package on the web, bundle/transpile JSX → plain
React.createElement(...)calls (or plain JS output) before publishing it, same as you would for any production React bundle. - If you're writing it as a folder doc inside your workspace (the "code as data" path), you'd want to paste already-compiled JS into the
index.jsentry rather than raw.jsx— I didn't find a build step in the Packages UI that would compile JSX for you.
Bundling with Vite (real example) #
The sideboard package (sections 1 and 6) builds with a hand-rolled esbuild script, but Vite works too — the real todo tool in patchwork-experiments builds with it, and its vite.config.ts is worth copying from directly:
import { defineConfig } from 'vite';
import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import external from '@inkandswitch/patchwork-bootloader/externals';
import path from 'path';
export default defineConfig({
base: './',
plugins: [react(), tailwindcss(), cssInjectedByJsPlugin({ relativeCSSInjection: true })],
resolve: {
alias: {
// Force all react imports (including from linked packages) to resolve to the same instance
react: path.resolve(__dirname, 'node_modules/react'),
'react-dom': path.resolve(__dirname, 'node_modules/react-dom'),
'react/jsx-runtime': path.resolve(__dirname, 'node_modules/react/jsx-runtime'),
'react/jsx-dev-runtime': path.resolve(__dirname, 'node_modules/react/jsx-dev-runtime'),
},
},
build: {
cssCodeSplit: true,
minify: false,
rollupOptions: {
external,
input: './src/index.ts',
output: {
format: 'es',
entryFileNames: '[name].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name][extname]',
},
preserveEntrySignatures: 'strict',
},
},
});
Three things here matter beyond "it's Vite config":
externalfrom@inkandswitch/patchwork-bootloader/externals— this is a list of packages the Patchwork bootloader already provides at runtime via an import map (Automerge,@keyhive/keyhive,solid-jsand its subpaths, CodeMirror@codemirror/*). Marking themexternalinrollupOptionsmeans your bundle doesn't duplicate them — it imports the host's shared copies instead. React is not in that list — the bootloader doesn't supply a shared React, so React-based tools do bundle their own copy.- The
resolve.aliasblock forces a single React instance. Because a tool bundles its own React while running inside a host page that may have its own React elsewhere, two different copies of React in the same page will break hooks (the classic "Invalid hook call" symptom). Pinning all React entry points to onenode_modules/reactresolves that within your own bundle; it doesn't fix cross-tool duplication, but it's the right first defense. - Output must be plain ESM (
format: 'es') with a single, deterministic entry filename —preserveEntrySignatures: 'strict'stops Rollup from renaming or splitting your named exports (plugins) away from the entry file thatmain/exportsinpackage.jsonpoints at. cssInjectedByJsPlugininlines CSS straight into the JS bundle at runtime instead of emitting a separate stylesheet — useful if you don't want to also wire up a"./styles.css"export likesideboarddoes; either approach is fine, just pick one.
4. Writing a tool with Solid, or nothing at all #
Same story as React — Patchwork ships @automerge/automerge-repo-solid-primitives (same pinned tag) as an equally first-class option, but there's no special adapter for it either:
import { render } from "solid-js/web";
import { createSignal } from "solid-js";
function CounterView(props) {
const [count, setCount] = createSignal(props.handle.doc()?.count ?? 0);
props.handle.on("change", () => setCount(props.handle.doc()?.count ?? 0));
return (
<div>
<output>{count()}</output>
<button onClick={() => props.handle.change((d) => { d.count = (d.count ?? 0) + 1; })}>
increment
</button>
</div>
);
}
// inside load():
return (handle, element) => {
const dispose = render(() => <CounterView handle={handle} />, element);
return dispose;
};
Since the contract is just "give me an element, give me back a cleanup function," Vue, Svelte, Lit, or plain document.createElement calls all work exactly the same way — there's genuinely nothing React- or Solid-specific baked into Patchwork's loader or registry.
5. Writing a datatype (if your tool needs a new document type) #
You only need this if your tool's data doesn't fit an existing datatype.
type DatatypeDescription = {
id: string;
type: "patchwork:datatype";
name: string;
icon: string;
unlisted?: boolean;
importUrl?: string; // set by the loader
};
type DatatypeImplementation<D = unknown> = {
init(doc: D, repo: Repo): void; // called once, on document creation
getTitle(doc: D): string; // used in lists/tabs
setTitle?(doc: D, title: string): void; // optional, if titles are renamable
};
A document created from your datatype gets tagged automatically — doc["@patchwork"] = { type: yourDatatypeId, suggestedImportUrl: ... } — Patchwork writes this for you via createDocOfDatatype2; you don't set it by hand.
6. Publishing at scale: pushwork + pw-modules #
Section 1 covers the two ways anyone can install a package: paste a URL into the Packages UI, one at a time. Real tool authors in patchwork-experiments use a second, CLI-driven path for publishing and deploying many tools onto a site — this is how a Patchwork site operator curates the fixed set of tools that site boots with, as opposed to an individual user's personal package list.
The site-level piece is a module-settings doc: an Automerge document whose modules array holds the Automerge URLs of every tool module to load. A Patchwork site booted with MODULE_SETTINGS_DOC_URL=<url> fetches that doc and loads everything listed inside (ModuleSettingsDoc, defined in core/filesystem/src/module-watcher.ts).
Two CLIs manage this, used together:
pushwork— publishes a built package into Automerge and hands back itsautomerge:URL.pushwork init .— one-time, initializes sync for a package directory.pushwork sync— builds/pushes the package's current contents.pushwork url— prints the package'sautomerge:URL.pushwork watch— dev-mode: rebuilds and republishes on file change.
pw-modules(aliaspatchwork-modules) — lives inscripts/module-settings/ofpatchwork-system; edits the module-settings doc itself.pw-modules init— creates a new module-settings doc, prints its URL.pw-modules add <settings-url> <module-url>— appends a module (idempotent).pw-modules remove <settings-url> <module-url>— removes one.
A published tool's package.json conventionally wires these into push/sync and register scripts (see the sideboard example above), so publishing a tool after editing it is just:
pnpm run build && pushwork sync # or: pnpm run push / pnpm run sync
pw-modules add "$MODULE_SETTINGS_DOC_URL" "$(pushwork url)"
To deploy every tool under a directory at once (e.g. all of patchwork-experiments), loop over every package with a register script, running pushwork init . once per package, then push/sync + register — registration is idempotent, so re-running the loop after adding new tools is safe.
This path exists alongside, not instead of, the Packages-UI flow in section 1 — use the UI for "I want to try this one tool in my own workspace," use pushwork/pw-modules for "I run a Patchwork site and want to manage its fixed tool set as code."
7. Field reference #
| Field | Applies to | Meaning |
|---|---|---|
id |
both | Unique within its registry (patchwork:tool and patchwork:datatype are separate namespaces — a tool and a datatype can share an id) |
supportedDatatypes |
tool | "*" = any datatype, or an array of specific datatype ids. Multiple tools can support the same datatype; the "create new" / "open with" pickers list them all |
unlisted |
both | Hide from the picker UI without disabling it — still resolvable if referenced directly |
forTitleBar |
tool | Renders as a title-bar action rather than the main view |
icon |
both | Name from the icon font, shown in menus |
8. Minimal checklist #
- Write
index.jsexportingplugins: [...](datatype and/or tool descriptors). - Write
package.jsonwith at leastname+main(example: https://patchwork.inkandswitch.com/packages/sideboard/package.json — the real one dissected in section 1, above). - Host it — either as a folder doc in your own workspace (
repo.create()+handle.change()to writepackage.json/index.jsas file entries with@patchwork: { type: "directory" }), anywhere over HTTPS with CORS enabled, or published to Automerge viapushwork sync(section 6) if you're managing a site's fixed tool set rather than your own workspace. - Grab the resulting
automerge:orhttps:URL. - Either open Packages in Patchwork and paste the URL under "Add to my package list" (personal use), or run
pw-modules addagainst a site's module-settings doc (site deployment — section 6). - Your datatype appears in "create new"; your tool renders it. Editing the folder doc's
index.jsafterward hot-reloads automatically if you went the workspace route.