# Extension Authoring Guide `create-pkgbld` ships with a small extension system that lets a third-party npm package add or remove a feature (linter, plugin, formatter, etc.) from a user's project. This document is the contract. ## Overview An extension is an ESM npm package that exports a manifest plus two operations — `setup` and `remove` — and is referenced by name from a **registry** JSON file shipped with `create-pkgbld`. ``` ┌──────────────┐ ┌────────────────────┐ ┌──────────────────┐ │ Registry │─────▶│ Core Engine │◀────▶│ Extension Pkg │ │ (JSON file) │ │ (create-pkgbld) │ │ (npm package) │ └──────────────┘ └────────────────────┘ └──────────────────┘ ``` The engine builds a virtual file `Tree` for the project root, hands it to each extension's `setup` (or `remove`) implementation, then prints the collected diff and commits to disk in one shot. --- ## Registry format A registry file is JSON shaped like this: ```json { "$schema": "./extensions-schema.json", "extensions": [ { "name": "biome", "package": "create-pkgbld-extension-biome", "description": "Biome linter and formatter", "tags": ["linter", "formatter"] } ] } ``` | Field | Required | Description | |---|---|---| | `name` | yes | Unique CLI handle (`create-pkgbld add `). | | `package` | yes | Canonically named extension package, or a PKG BLD plugin with an optional `/extension` subpath. | | `version` | no | Version range used when an official extension is downloaded to the shared cache. Defaults to `latest`. | | `description` | yes | Short one-liner shown in `list` / TUI. | | `tags` | no | Optional tags for grouping/filtering. | The shape is validated by `extensions-schema.json` (draft-07). Editors that respect `$schema` will autocomplete. Built-in registry entries are official extensions. `create-pkgbld` contains their metadata only. When an official extension is selected, its package is installed with npm into the platform-standard shared cache selected by `find-cache-directory`. It is not added to the target project's dependencies. Set `CREATE_PKGBLD_CACHE_DIR` to override the cache location. The registry is official package metadata. Project state is stored separately in `.pkgbld-lock.json`; the lock is not an extension catalog. --- ## Extension package contract Each package referenced by `package` must export the following named ESM exports: ```js export const manifest = { name: 'biome', description: 'Biome linter and formatter', tags: ['linter', 'formatter'], }; export const setup = /* declarative obj OR async (tree, options) => void */; export const remove = /* declarative obj OR async (tree, options) => void */; export async function update(tree, context, options) { /* optional migration */ } export function detect(tree) { /* boolean: is it already installed? */ } export function prompts(tree, context) { /* optional: Option[] */ } ``` `manifest`, `setup`, and `remove` are required. `detect` is optional but strongly recommended (without it, the CLI assumes "not installed"). `prompts` is optional and only used in interactive mode. When both locked and target versions have declarative `setup` objects, the engine can update their individual dependency, script, file, and package JSON resources automatically. It replaces a resource only when the project still matches the old declaration, or when the project already matches the target. A customized resource becomes a migration conflict with the target value staged for review. ### Programmatic `update` Export `update` when a version transition needs semantic migration. The target version receives the project tree, an update context, and newly collected options: ```js export async function update(tree, context, options) { const { fromVersion, toVersion, reconcileDeclarative, reportConflict } = context; reconcileDeclarative({ exclude: ['file:tool.json'] }); const current = tree.readJson('tool.json'); if (canMigrate(current, fromVersion, toVersion)) { tree.updateJson('tool.json', value => migrate(value, options)); return; } const proposed = createConfig(options); reportConflict({ resource: 'file:tool.json', current, proposed, message: 'The tool configuration needs review', }); tree.write('tool.json', `${JSON.stringify(proposed, null, 2)}\n`); } ``` `reconcileDeclarative({ exclude })` applies the guarded comparison to all ordinary resources except the listed resource IDs. IDs use `file:`, `script:`, `dependency::`, or `package-json:`. `reportConflict` records a proposed migration that the user must approve before commit. If either version uses programmatic setup and the target has no `update`, the transition is unsupported. ### Declarative `setup` ```js export const setup = { dependencies: { 'some-dep': '^1.0.0' }, devDependencies: { '@biomejs/biome': '^2.3.8' }, scripts: { lint: 'biome check ./src', 'lint:fix': 'biome check --fix ./src', }, files: { // target -> source. Source may be a template path (relative to the // extension package root) or `inline:`. 'biome.json': './templates/biome.tpl.json', '.gitignore': 'inline:dist\nnode_modules\n', }, packageJson: { type: 'module' }, // shallow merge into package.json }; ``` ### Declarative `remove` ```js export const remove = { dependencies: ['some-dep'], devDependencies: ['@biomejs/biome'], scripts: ['lint', 'lint:fix'], files: ['biome.json'], }; ``` ### Programmatic form If declarative isn't expressive enough, both `setup` and `remove` may instead be `async (tree, options) => void`: ```js export async function setup(tree, options) { const pkg = tree.readJson('package.json') ?? {}; pkg.scripts = { ...pkg.scripts, hello: `echo ${options.greeting}` }; tree.updateJson('package.json', () => pkg); if (!tree.exists('hello.txt')) tree.write('hello.txt', 'hi\n'); } ``` `options` is the `OptionsValue` collected from the extension's `prompts()` (empty `{}` if `prompts` is not exported). ### `detect(tree) -> boolean` Used by `list` and the TUI to distinguish an available extension from an installed integration. An installed integration without a lock entry is shown as unmanaged and can be explicitly adopted. Typical implementation inspects `package.json`: ```js export function detect(tree) { const pkg = tree.readJson('package.json'); return Boolean(pkg?.devDependencies?.['@biomejs/biome']) || tree.exists('biome.json'); } ``` ### `prompts(tree) -> Option[]` Returns a list of `Option` objects (same `Option` type used by the rest of `create-pkgbld`'s extension UI). Each option contributes one prompt before setup runs; the answers are passed into `setup(tree, options)`. --- ## The Tree API All file mutation in an extension goes through `Tree`. Reads are lazy (loaded from disk on first access), writes are buffered, and the engine calls `tree.commit()` once after all extensions have run. | Method | Description | |---|---| | `read(path)` | Returns file content as string, or `null` if missing. | | `write(path, content)` | Stages a CREATE or UPDATE. | | `exists(path)` | True if the file exists (in tree or on disk). | | `delete(path)` | Stages a DELETE (or cancels a pending CREATE). | | `rename(oldPath, newPath)` | Move staged content. | | `readJson(path, options?)` | Parse JSON or recognized JSONC configs. Returns `null` if missing. | | `updateJson(path, updater, options?)` | Read, run updater(data), and stage the result; JSONC edits preserve comments and formatting outside changed values. | | `addDependency(name, version, type?)` | type defaults to `'dependencies'`. | | `removeDependency(name, type?)` | | | `addScript(name, command)` | | | `removeScript(name)` | | | `resolveExtensionFile(rel)` | Resolve a path relative to the extension's package directory. | | `listChanges()` | Returns `FileChange[]` of `{ path, type, content? }`. | | `commit()` | Reserved for the engine; unavailable during extension execution. | Paths are project-root-relative. `resolveExtensionFile` is what you use inside a programmatic `setup` to read template files bundled with your extension package. JSONC is recognized for `.jsonc` files, `tsconfig.json`/`jsconfig.json` and dotted variants such as `tsconfig.base.json`, `.swcrc`, and JSON files under `.vscode`, `.cursor`, or `.zed`. For another configuration filename, pass `{ jsonc: true }`: ```js tree.updateJson('configs/base.json', config => { config.compilerOptions ??= {}; config.compilerOptions.strict = true; }, { jsonc: true }); ``` Package metadata and other `.json` files use strict JSON by default. Invalid syntax is rejected in both modes. Declarative updates compare recognized JSONC configs by their values and retain existing comments when applying the proposed values. ### Template files The engine sets the extension base directory (the directory of the resolved module file) automatically while `setup`/`remove` runs. Declarative `files: { target: './tpl.json' }` resolves `./tpl.json` relative to that base. Inside a programmatic setup, call `tree.resolveExtensionFile('./templates/foo')` to obtain the absolute path. --- ## Worked example: `create-pkgbld-extension-biome` ```js // create-pkgbld-extension-biome/src/index.js export const manifest = { name: 'biome', description: 'Biome linter and formatter', tags: ['linter', 'formatter'], }; export const setup = { devDependencies: { '@biomejs/biome': '^2.3.8' }, scripts: { lint: 'biome check ./src', 'lint:fix': 'biome check --fix ./src', }, files: { 'biome.json': './templates/biome.tpl.json' }, }; export const remove = { devDependencies: ['@biomejs/biome'], scripts: ['lint', 'lint:fix'], files: ['biome.json'], }; export function detect(tree) { const pkg = tree.readJson('package.json'); if (pkg?.devDependencies?.['@biomejs/biome'] || pkg?.dependencies?.['@biomejs/biome']) return true; return tree.exists('biome.json'); } ``` Registry entry: ```json { "name": "biome", "package": "create-pkgbld-extension-biome", "description": "Biome linter and formatter", "tags": ["linter", "formatter"] } ``` That's the entire extension. --- ## Conflict detection When multiple extensions run in the same flow (e.g. the interactive TUI), the engine records all `write`/`delete`/`addDependency`/`addScript` calls per extension and surfaces conflicts as warnings before commit: - two different file contents written to the same path - a path both written and deleted in the same run - the same dependency added at different versions - the same script name set to different commands Conflicts are warnings, not errors — commit still proceeds (last writer wins per the Tree's normal semantics). Extension authors should keep this in mind and namespace files/scripts where it matters. --- ## Tips - Keep `setup` idempotent. The engine doesn't enforce it but the diff display gets noisy if re-running the same extension produces churn. - Use `detect` to gate things you can't safely re-add, and bail in `setup` if you must, but prefer letting Tree's UPDATE semantics handle re-runs. - Don't rely on a specific working directory — always operate via the `tree` argument. - For declarative `files`, store templates as `.tpl.json` (or another `.tpl.*` extension) so that the workspace's own linters/formatters don't try to parse them. ## Package naming Use `create-pkgbld-extension-` for project setup extensions, such as `create-pkgbld-extension-biome` or `create-pkgbld-extension-dts-buddy`. These packages export the extension contract from their root. They are registered in the official `extensions.json`; the prefix does not enable automatic discovery. Reserve `pkgbld-plugin-` for build plugins automatically loaded by PKG BLD. A build plugin can additionally expose the extension contract at `/extension`, as `pkgbld-plugin-dts-buddy/extension` does. Both forms are supported by the registry resolver. CLI names can stay short: `dts-buddy` configures standalone use, while `pkgbld-dts-buddy` installs the build plugin. Build plugins do not need registry metadata or an extension export to run. `create-pkgbld` discovers their scoped and unscoped names from all project dependency fields without importing them. Such plugins can be generically removed or adopted into `.pkgbld-lock.json` when their exact installed version can be resolved. Every modern build plugin must declare a compatible `pkgbld` range in `peerDependencies`; extension-only packages should not add that peer solely for `create-pkgbld` compatibility.