BarefootJS 模板适配器开发
add-adapter
新增 BarefootJS 模板适配器包的操作指南(IR → 目标模板语言 + 原生运行时)。适用场景:为新模板引擎或后端语言添加适配器、将 bf helpers / ParsedExpr 求值器移植到新语言,或将适配器接入一致性、兼容性、CI、发布和文档流程。
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 26
- Forks
- 0
01 前言 Front Matter
- name
- add-adapter
- metadata
- { "short-description": "Add a new BarefootJS adapter end-to-end" }
- description
- Playbook for adding a new BarefootJS template adapter package (IR → target template language + native runtime). Use when: adding an adapter for a new template engine or backend language, porting the bf helpers / ParsedExpr evaluator to a new language, or wiring an adapter into conformance, compat, CI, release, and docs.
02 资源文件 1
- 参考文档requires.yaml48 B
03 SKILL.md 正文
Add a New Adapter
This is the end-to-end playbook for adding a packages/adapter-<name> package. It exists
because the task is long (a full adapter lands ~30 files, ~6k lines) and the failure mode is
predictable: writing lots of adapter code before the conformance loop is running, or finishing
the package but missing the repo-wide integration points. Follow the phases in order — each
one ends with something that compiles and a test loop that stays green.
Read first (in this order, before writing any code)
spec/compiler.md— "Adapter API" and "Implementing a New Adapter" sections (theTemplateAdaptercontract,TemplateSections, per-kind emitter pattern, capability flags).spec/adapter-architecture.md— the constitution: IR carries semantics, adapters never parse/regex expression strings, thin adapter object + pure domain modules overEmitContext.docs/core/adapters/custom-adapter.md— step-by-step coding walkthrough of each render method.spec/template-helpers.md— thebfhelper catalogue the native runtime must implement.- Skim the newest comparable adapter's initial commit for the authoritative file list:
git log --oneline --grep 'adapter' -- packages/adapter-blade packages/adapter-rust(e.g.9da1880blade,0e6aeebrust — both land nearly self-contained in one package).
Phase 0 — Scoping decisions (write these down before coding)
Pick the closest existing adapter and copy its skeleton; do not design from scratch:
| Target runtime | Copy from | Base class |
|---|---|---|
| Full JS engine template (can run JS at SSR) | packages/adapter-hono |
JsxAdapter |
| String-template DSL, compiled language | packages/adapter-go-template, adapter-rust |
BaseAdapter (Go), DslTemplateAdapter (Rust) |
| String-template DSL, dynamic language | packages/adapter-erb, adapter-jinja, adapter-twig, adapter-blade |
DslTemplateAdapter |
| Perl family | packages/adapter-mojolicious, adapter-xslate, adapter-perl |
DslTemplateAdapter |
DslTemplateAdapter (packages/jsx/src/adapters/dsl-template-adapter.ts) owns generate() and
the per-compile state it resets; the adapter supplies its diagnostic name, its reserved-name
spelling, any extra state (resetAdapterState), its script registrations and its two seeds.
Decide and record:
- Runtime model: JS-engine (
clientShimSource,acceptsTemplateCall) vs DSL (templatePrimitivesmap only, both othersundefined). templatesPerComponentand the template fileextension.- Where the native runtime lives: in-package (like
adapter-erb/lib,adapter-go-template/runtime) or shared with a sibling (like blade reusingadapter-php's runtime). - Helper naming convention for lowering-node dispatch (
bf_*Go,bf->*Perl/Mojo,$bf.*Xslate,bf.*Ruby/Jinja-family) — stay consistent with the language's idiom.
Phase 1 — Package skeleton (compiles, empty adapter)
Create packages/adapter-<name>/ by copying the chosen reference. The invariant shape:
package.json # exports: "." , "./adapter" (src), "./vite", "./test-render" ("bun" condition ONLY)
tsconfig.json
src/index.ts # re-exports adapter + conformancePins
src/vite.ts # barefoot() — composes core @barefootjs/vite's plugin with this adapter's
# TemplateAdapter instance; the user's vite.config.ts imports this, not a
# barefoot.config.ts factory (that pipeline is gone — see PR 7a-7c)
src/conformance-pins.ts # ConformancePins — per-fixture BF101/BF103 refusals (also consumed by bf compat)
src/test-render.ts # spawns the REAL backend toolchain; Bun-only, behind the "bun" export condition
src/__tests__/<name>-adapter.test.ts # the single runAdapterConformanceTests(...) call
src/adapter/
<name>-adapter.ts # thin orchestrator: TemplateAdapter impl, CompileState, dispatch methods
emit-context.ts # the seam domain modules depend on (never the concrete class)
analysis/component-tree.ts
expr/{emitters,array-method,operand}.ts # ParsedExpr → target language
lib/{constants,ir-scope,<lang>-naming,types}.ts
memo/seed.ts props/… spread/spread-codegen.ts value/…
<native runtime dir> # lib/ (gem), runtime/ (go module), php/, … with its own tests
The workspace glob (packages/*) picks the package up automatically. Deps: @barefootjs/shared
as dependency, @barefootjs/jsx as peer + dev, @barefootjs/adapter-tests as dev.
Checkpoint: bun install && tsgo --noEmit -p packages/adapter-<name> passes.
Phase 2 — Adapter core
Implement TemplateAdapter (packages/jsx/src/adapters/interface.ts). Non-negotiables:
- Emit via the shared dispatchers — implement
ParsedExprEmitter/IRNodeEmitter<Ctx>/AttrValueEmittervisitor interfaces. Never write your ownswitch (kind)with a permissivedefault: the shared dispatchers'assertNeveris the drift-defence that turns a new IR kind into a compile error in your adapter. - No expression parsing.
parseExpression,ts.createSourceFile, and regex over expression strings are forbidden in adapter code — the IR suppliesParsedExpr(MemoInfo.parsed,IRExpression.parsed,parsedCondition,ExpressionAttr.parsed). If a field you need isn't carried yet, extend the shared layer per "How to add a unit" inspec/adapter-architecture.md. - Sections, not post-processing: return
AdapterOutput.sections(imports/types/component/ defaultExport/moduleConstants); the compiler concatenates and never parses your template. - Hydration markers:
renderScopeMarker/renderSlotMarker/renderCondMarkeremitbf-s/bf/bf-c; the marker-conformance suite asserts the ids match the IR's. - Lowering nodes (
packages/jsx/src/lowering-registry.ts): ingenerate()bind matchers once withprepareLoweringMatchers(ir.metadata)and store them inCompileState. When lowering a call, try the matchers; render aLoweringNodewith one renderer per node kind, dispatching on thehelperid (guarded byisValidHelperId) mapped to your runtime naming (e.g.query→bf_query). Reference:packages/adapter-go-template/src/adapter/expr/url-builder.ts. Never render an unmapped helper verbatim, and never special-case a built-in likequeryHrefoutside this path (see AGENTS.md "Structural lowering registration"). - Keep the object thin: per-compile state in
CompileStatereset pergenerate(), logic in pure functions overemit-context.ts, stateless helpers inlib/.
Checkpoint: the simplest shared fixture compiles to a plausible template (drive it from a scratch test before wiring the full suite).
Phase 3 — Native runtime + golden vectors
The target language needs a runtime package shipping:
- The
bftemplate helpers perspec/template-helpers.md(incl. thequeryhelper matching clientqueryHrefsemantics exactly — guards, emptiness, array append). - A ParsedExpr evaluator porting
packages/adapter-tests/vectors/eval-reference.tssemantics. - Golden-vector replay tests in the target language for both
packages/adapter-tests/vectors/vectors.jsonandeval-vectors.json, plus a hand-maintainedvector-divergences.jsonin your package (auto-discovered bypackages/adapter-tests/src/__tests__/divergences.test.ts— and note itsEXPECTED_BACKENDSlist must gain your language). - Dev-reload support if the scaffold story needs it (pattern:
lib/barefoot_js/dev_reload.rb,runtime/bfdev/).
Follow packages/adapter-tests/vectors/README.md "Adding a new backend".
Checkpoint: native-language test suite green locally (skip gracefully when the toolchain is
missing — see onRenderError in existing conformance tests).
Phase 4 — The conformance loop (this is most of the work)
Wire runAdapterConformanceTests (packages/adapter-tests/src/run-adapter-conformance.ts) in
your src/__tests__/ with: name, factory, render (your test-render.ts spawning the real
backend), onRenderError, expectedDiagnostics: conformancePins, and initially-broad skipJsx.
Then iterate: pick one failing fixture at a time, make it pass, shrink the skip list, commit. ~190 shared fixtures exist; do not try to clear them in one pass and do not edit shared fixtures to fit your adapter. Rules for what remains skipped/pinned at the end:
- A genuine capability refusal (target language can't express it) becomes an
expectedDiagnosticspin inconformance-pins.tswhoselimitationfield cites the registry entry (packages/adapter-tests/limitations/<id>.ts) it is an instance of — add the entry (or add your fixture to an existing one) in the same PR; the join test refuses an unknown id. skipJsx(derived fromrenderDivergences, which cites an entry the same way) /skipTemplatePrimitives/skipMarkerConformanceentries likewise each carry a limitation pointer. An unexplained skip is a review blocker.
Also verify: no-bun-coupling.test.ts (published sources Bun-free except the "bun"-gated
./test-render), marker conformance, and the CSR conformance suite (adapter-independent — you
should never need to touch csr-conformance.test.ts).
Checkpoint: bun test packages/adapter-<name> and bun test packages/adapter-tests green;
tsgo --noEmit and bun run lint (biome) clean.
Phase 5 — Repo integration checklist (every line, in this order)
The initial package commit is nearly self-contained, but these cross-cutting registrations are easy to miss — check off each one:
- [ ]
packages/adapter-tests/src/__tests__/divergences.test.ts— add the language toEXPECTED_BACKENDS(only if this is a new backend language). - [ ]
packages/adapter-tests/src/__tests__/import-map-injection.contract.test.ts— add the adapter toADAPTERS. - [ ]
packages/compat/src/adapter-registry.ts— add{ pkg, className }toCOMPAT_ADAPTERS(the ONE enumeration of TemplateAdapter packages); add the workspace devDependency inpackages/compat/package.json; regenerateui/compat.lock.jsonviabun run compat:lock(CI fails on drift). - [ ] Publish set — nothing to edit:
scripts/lib/workspace-packages.tsderives it (every non-privatepackages/*not in.changeset/config.json's ignore list, dependencies first), andscripts/lib/__tests__/publishable-packages.test.tspins that. Run that test to see the new package listed for npm, and — if it has TSsrcexports — for JSR. - [ ] Create the package on each registry before the release that first ships it. Trusted
Publishing (OIDC) can only publish to a package that already exists, so the release
workflow refuses to publish anything until these exist (
scripts/release-preflight.tsprints the exact steps; the summary): - npm: publish the first version by hand with a token (bun pm pack+npm publish <tarball> --access public), then on npmjs.com → package → Settings → Trusted Publisher → GitHub Actions (piconic-ai/barefootjs,release.yml) with the "npm publish" permission — without it the next publish fails with "OIDC permission denied for this action". - JSR (TS packages only): create it athttps://jsr.io/new?scope=barefootjs&package=<name>and link the GitHub repository in its settings. No manual publish needed. - Native registry (CPAN / PyPI / RubyGems / crates.io / Packagist): whatever that registry's trusted-publishing setup requires — see the matching job inrelease.yml. - [ ]
.github/workflows/ci-<name>.yml— new workflow, path-filtered onpackages/{client,shared,jsx,adapter-<name>,adapter-tests}/**, installing the language toolchain, running native runtime tests thenbun test packages/adapter-<name>(copy the closestci-*.yml). It belongs to the heavy set: keep the copiedpull_requesttrigger'sbranches: [main]and its default activity types (noedited), and do not add it toEVERY_PR_WORKFLOWSinscripts/lib/heavy-gate.ts. The lintbun test scripts/lib/__tests__/heavy-gate.test.tsfails otherwise (AGENTS.md, "CI on stacked PRs"). - [ ]
.github/workflows/release.yml— per-language registry publish job (gem/crates/PyPI/CPAN/ Packagist…), following the existing Trusted-Publishing patterns. - [ ] Add a changeset (
.changeset/) — CI enforces it. - [ ] Optional, separate PRs:
bf initscaffold (ADAPTERSmap inpackages/cli/src/lib/templates.ts+packages/cli/src/lib/adapters/<name>.ts+ scaffold/dev-reload contract tests), anintegrations/<framework>/example app (+integrations/README.md,docker-compose.ymlmounts), site landing demo backends (site/core/landing/generate-demo-outputs.tsBACKENDS— every demo must compile there).
Phase 6 — Docs
- [ ]
docs/core/adapters.md— "Available Adapters" table (generated) and the runtime-model paragraph. - [ ] New
docs/core/adapters/<lang>-adapter.mdpage (pattern:ruby-adapter.md), plus its entry insite/core/lib/navigation.tsandsite/core/components/mobile-menu.tsx. - [ ]
spec/compiler.md— "Available Adapters" list. - [ ]
spec/template-helpers.md— helper naming column, if a new convention. - [ ]
packages/adapter-tests/vectors/README.md— runners table. - [ ]
AGENTS.md— Architecture adapter list. - [ ]
docs/core/llms.txtindex.
Working discipline (how to run this as a long task)
- One phase per commit (minimum). Within Phase 4, commit every time the skip list shrinks. Each commit message states which fixtures went green.
- Keep a scratch checklist of the Phase 5/6 boxes from the start; tick them as you go rather than reconstructing at the end.
- Verify with the suite, not by eye: the conformance runner comparing against the reference adapter's frozen snapshots is the ground truth. When output differs, diff the emitted template against the closest sibling adapter's output for the same fixture before touching code.
- When blocked on a fixture: check the registry (
packages/adapter-tests/limitations/) first — a sibling adapter may already have pinned the same case; mirror its pin and cite the same limitation id. - Never edit shared fixtures, frozen snapshots, or the shared dispatchers to make your adapter pass; if the shared layer genuinely needs a new IR-carried field, that is its own stacked, byte-identical-for-existing-adapters PR (spec/adapter-architecture.md "How to add a unit").
- Final gate before the PR:
bun run build,bun test,tsgo --noEmit,bun run lint,bun run compat:lockdrift check, and re-read this checklist top to bottom.
Kickoff prompt template
Paste this (filled in) to start the task in a fresh session:
Add a new BarefootJS adapter for <TEMPLATE ENGINE / LANGUAGE> as packages/adapter-<name>.
Follow .agents/skills/add-adapter/SKILL.md exactly, phase by phase — read its "Read first"
list before writing code. Scoping answers: runtime model = <DSL | JS-engine>; copy skeleton
from packages/adapter-<closest>; native runtime lives <in-package | shared with X>; helper
naming = <bf_* | bf.* | …>.
Work in small commits: package skeleton first, then the adapter core, then the native runtime
with golden-vector replay, then grind the conformance suite one fixture at a time (skip list
shrinks every commit; every surviving skip/pin cites a registry limitation id). Finish
with the Phase 5 integration checklist and Phase 6 docs — every box, none skipped. Do not edit
shared fixtures, snapshots, or dispatchers. Gate on: bun run build, bun test, tsgo --noEmit,
bun run lint, bun run compat:lock.
04 同仓库更多 Skills
BarefootJS UI 组件开发
barefootjs
使用 @barefootjs/cli 构建、检查和调试 UI 组件。适用于:创建/编辑/审查组件、排查信号(signal)依赖关系、调试响应式更新、搭建新组件脚手架,或查询组件 API。
PR 收尾打磨
polish-pr
通过验证当前 HEAD 版本并处理 CI 失败和 Pullfrog 审查意见,完成 BarefootJS 的拉取请求(PR),并进行最后一次人工通知。适用于 PR 打磨或消除阻塞,不适用于只读审查或状态查询。
GitHub 议题转 PR 实现
implement-issues
通过经过测试的拉取请求(PR)实现 BarefootJS 的 GitHub 议题或已记录的已知限制。适用于从议题到 PR 的工作;对于已有 PR 的 CI 和审查后续处理,请使用 polish-pr。
BarefootJS 模板引擎开发
barefootjs
暂无简介