agentleFS
buildosaurusbuildosaurus/scripteratops/skills/typescript-script/SKILL.md

typescript-script

Skill0 starsChanged 3 months agoMITView on GitHub

Write self-contained, portable, testable TypeScript command-line tools on Deno — pure-logic/side-effect separation (boundaries as interfaces) that `deno test` can drive with fakes, a Cliffy CLI, and a check/test/lint/fmt gate. Use as soon as the user wants a TypeScript (or JavaScript) script, CLI utility, automation tool, or "glue" code (orchestrating git, curl/fetch, file manipulation, parsing) in TS, even if they never say "Deno". Also triggers on adding tests to an existing TS tool, making one portable/testable, or porting a shell/Python script to TypeScript.

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Prefer JSR (jsr:) packages.

    line 53
  2. Very specific:

    Every tool ships co-located *_test.ts files, run by deno test.

    line 205
  3. Distinctive:

    Delete what it doesn't earn.

    line 243

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TypeScript script

Standard for all TypeScript command-line tools: a small Deno project whose logic lives in testable src/ modules, driven by a thin Cliffy CLI in main.ts, verified by deno check + deno test + deno lint + deno fmt. The goal is a self-contained tool (no node_modules, one runtime that runs, tests, lints, formats, and compiles) — the TypeScript counterpart of the python-script, swift-script, and kotlin-script skills.

Three decisions are already settled. Don't second-guess them, apply them:

  1. Runtime → Deno. It runs .ts directly (like uv run runs .py), ships the test runner, linter, formatter, type-checker, and a single-binary compiler in the box, and needs no node_modules. Bun and Node are viable but pull the batteries back apart (a separate formatter/linter, a bundler for a binary).
  2. Interface → Cliffy (@cliffy/command).
  3. Tests → deno test (Deno.test + @std/assert), made easy by an architecture that isolates side effects behind interfaces.

This file carries the decisions; the code implementing them is a complete, gate-passing project in assets/template/. Copy and adapt that project — don't retype it from here. Then delete what your tool doesn't earn.

1. Project layout

tool/
├── deno.json          # tasks, imports (pinned), fmt/lint config, strict TS
├── deno.lock          # integrity-pinned dependency graph (commit it)
├── main.ts            # Cliffy CLI → thin entry point
├── src/
│   ├── errors.ts      # ToolError subclasses (each carries its exit code)
│   ├── logic.ts       # pure transform
│   ├── boundaries.ts  # CommandRunner / HttpFetcher / EnvironmentReading interfaces
│   ├── config.ts      # Config + precedence + JSON file read
│   ├── color.ts       # ColorMode + shouldColor (pure)
│   ├── log.ts         # net-verbosity → level; stderr logger
│   ├── runner.ts      # Deno.Command subprocess boundary
│   ├── http.ts        # fetch boundary
│   ├── work.ts        # orchestration (doWork)
│   ├── signals.ts     # SIGTERM → 143
│   └── *_test.ts      # co-located deno tests
└── README.md
  • Pin every dependency in deno.json imports (jsr:@cliffy/command@1.2.1, jsr:@std/assert@1.0.19) and commit deno.lock (it records integrity hashes). Prefer JSR (jsr:) packages; npm: specifiers work when you need one.
  • fetch, subprocess (Deno.Command), files, and env are built in — reach for a dependency only for a real gain. Cliffy is usually the only one.
  • JSON is the "free" config format (JSON.parse); no dependency needed.

2. Structure

The structure is designed to make tests trivial: pure logic never touches the outside world directly. Everything that leaves the process (subprocess, network, filesystem, environment) sits behind an interface boundary, injected into the orchestration. Tests pass a fake implementation; production passes the real one.

  • Boundaries are interfaces — CommandRunner, HttpFetcher, EnvironmentReading. These are the single mock hooks. A fake is a small class.
  • Pure logic (transform) — input → output, no I/O, tested with assertEquals.
  • Config is an interface; precedence is one pure function, resolveConfig(cli, environment, file), tested without any fake.
  • Orchestration (doWork) assembles boundary calls + pure logic: data positional, behaviour flags with defaults, returns a count. It takes the boundaries as interfaces, so a test drives it with no process and no socket.
  • main.ts is thin: parse arguments, build the real boundaries, call doWork, map errors to an exit code. Nothing worth testing lives here.

2.1 Async is the norm

Deno's I/O is promise-based, so the subprocess boundary, HTTP boundary, config read, and doWork are all async. Keep pure logic synchronous — only the boundaries and the orchestration that awaits them are async.

2.2 Subprocess boundary

ProcessRunner routes all subprocess calls through Deno.Command:

  • Never a shell. Pass the program + an args array — no sh -c, so no injection from a filename or argument.
  • Always a timeout. Pass signal: AbortSignal.timeout(ms); on deadline Deno kills the child and .output() resolves (success: false, signal: "SIGTERM") — it does not throw. Check signal.aborted after the call (keep a reference to the signal) and throw TimeoutError (exit 124) yourself; otherwise a timeout falls through to the non-zero-exit path and surfaces as a generic exit 1.
  • On non-zero exit, throw CommandError(command, code, stderr).

2.3 Config and precedence

Resolve settings with an explicit, documented precedence — higher wins:

CLI flags  >  environment variables  >  config file  >  built-in defaults

resolveConfig is pure (??-chains the layers so an absent value never clobbers a lower layer). Each source is read by one boundary — readConfigFile (JSON), configFromEnvironment (through the EnvironmentReading hook). Secrets get no CLI flag (argv is world-readable via ps); a token comes from the environment or config file. Never log a raw Config — route it through redacted(…).

2.4 HTTP requests

FetchClient wraps the global fetch in one boundary:

  • Set an explicit timeout with AbortSignal.timeout(ms).
  • Raise on non-2xx yourself. fetch only rejects on transport failure, not on 4xx/5xx, so check response.ok and throw HttpError; cancel the body first to avoid a leak.
  • Inject a fake HttpFetcher to test offline.

2.5 Colorized logging

Logging uses the template's own Log, constructed once in main.ts and writing to stderr (never stdout — stdout is for program data). Color:

  • shouldColor(mode, isTty, env) is a pure decision — precedence --color=always/never > NO_COLOR/FORCE_COLOR > TTY (and not TERM=dumb).
  • TTY detection in main.ts uses Deno.stderr.isTerminal().

2.6 Robustness, signals & permissions

  • Bound every subprocess and HTTP call with a timeout (§2.2, §2.4).
  • Signals: SIGTERM → Deno.exit(143) (installed in signals.ts); SIGINT keeps Deno's default (130). Deno surfaces a closed downstream pipe as a write error, not a SIGPIPE kill — no handler needed.
  • Permissions are the Deno-specific bit. Deno is deny-by-default: the tool needs --allow-run (subprocess), --allow-net (fetch), --allow-env, and --allow-read (config + ls). The deno.json tasks encode these, and deno compile bakes them into the binary. Grant only what the tool earns.
  • Preflight external tools for glue scripts (a which-style check up front), throwing ConfigError listing every missing tool.

2.7 Subcommands (if needed)

Cliffy handles this natively: a root Command with .command("name", subCmd), each its own Command. No manual dispatch.

2.8 Man page (optional)

Cliffy has no built-in man generator. Generate one from the CLI's own --help with help2man:

help2man --no-info --name "tool" "./tool" > tool.1
sudo install -m 644 tool.1 /usr/local/share/man/man1/tool.1

(Compile the binary first — §2.9 — so help2man can invoke it.)

2.9 Build & install (optional, for tools you distribute)

The README carries the environment set-up, not just the gates: a Prerequisites section with per-platform install of Deno (macOS/Linux/Windows) and the dependency list, pointing to deno.json + deno.lock as the pinned source. For a distributed binary (deno compile), an optional --dependencies flag printing the pinned versions is a nice touch — skip it for source-run tools.

  • Single binary: deno task compile runs deno compile … -o tool main.ts → one self-contained executable with the permissions baked in; no runtime needed afterwards. Install it onto PATH (install -m 755 tool ~/.local/bin/).
  • Run from source: deno task run <args> (no build step, like uv run).
  • Limits: the compiled binary is per-OS — compile on each platform (or use deno compile --target to cross-compile).

3. CLI contract

Cliffy gives most of the baseline for free:

  • -h/--help and -V/--version are automatic (.version("…")).
  • Verbosity: .option("-v, --verbose", …, { collect: true }) collects occurrences into an array; .length is the count (same for quiet). Map the net count to a level with logLevelForVerbosity(verbose - quiet).
  • --color is an EnumType(["auto","always","never"]) option with a default.
  • --dry-run short-circuits before output, announced at warning level.
  • Group the help once flags pile up (the same rule as the other skills): .group("Config sources") / .group("Behaviour") / .group("General") before each block; Cliffy renders each as its own --help heading.
  • Stream discipline: program data → stdout (console.log); logs, progress, diagnostics → stderr (the Log).

Exit codes

Map typed errors to a code in main.ts's catch (Deno.exit(e.exitCode)):

CodeMeaning
0Success (also --help/--version)
1Runtime error (a ToolError); Cliffy also uses non-zero for usage errors
124A subprocess exceeded its timeout (TimeoutError)
130Interrupted — SIGINT / Ctrl-C (Deno default)
143Terminated — SIGTERM / kill (signals.ts)

ToolError.exitCode keeps the code with the failure category. As with Clikt, Cliffy maps usage errors to its own non-zero default rather than the 2 of argparse/ArgumentParser.

4. Tests with deno test

Every tool ships co-located *_test.ts files, run by deno test.

  • Never test subprocess or network for real — inject a fake implementing the boundary interface. That's what the interface is for.
  • Fakes are tiny classes (class FakeRunner implements CommandRunner), not a mocking framework. Return Promise.resolve(…) — don't mark them async without an await (deno lint's require-await flags that).
  • Pure logic and precedence are tested by direct call — no fakes at all.
  • Assert with @std/assert (assertEquals, assert, assertFalse).

Coverage priority: pure logic and orchestration first, then config precedence, then arg parsing.

5. Quality gates

Four gates, all one tool — no separate type checker, linter, or formatter to install:

deno check main.ts    # types (uses tsc under the hood; the type gate)
deno test <perms>     # deno test
deno lint             # lint
deno fmt --check      # format

(The template wraps these as deno task check|test|lint|fmt:check.) Notes:

  • A first run downloads and caches the pinned deps — slow once, then cached.
  • Indentation is 2-space (deno fmt default; set in deno.json).
  • deno test type-checks the test files too; deno check main.ts covers src/.

Summary of what to produce

Faced with a TypeScript tool request, produce:

  1. A Deno project copied from assets/template/: logic + boundaries in src/, a thin Cliffy main.ts, pinned deno.json/deno.lock, the §2 structure, the §3 CLI contract and exit codes, and the robustness rules the tool's job earns (shelling out earns the timeout + preflight; the network earns the HTTP boundary + timeout; holding config/secrets earns precedence + redaction). Delete what it doesn't earn.
  2. Co-located *_test.ts covering pure logic, config precedence, orchestration (with fakes), and any boundary the tool ships.
  3. In one line: how to run it (deno task run <args>), and that the four gates — check + test + lint + fmt:check — are green (needs only Deno).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.